[ Index ]

PHP Cross Reference of Drupal 6 (yi-drupal)

title

Body

[close]

/sites/all/modules/video/plugins/video_s3/filesystem/ -> video_s3.inc (source)

   1  <?php
   2  /*
   3   * @file
   4   * Class file used to store videos in Amazon S3.
   5   *
   6   */
   7  class video_s3 implements filesystem_interface {
   8  
   9    protected $params = array();
  10    protected $name = 'Amazon S3';
  11    protected $value = 'video_s3';
  12  
  13    public function __construct() {
  14  
  15    }
  16  
  17    public function load_file($video) {
  18      $transcoder = variable_get('vid_convertor', 'video_ffmpeg');
  19  
  20      module_load_include('lib.inc', 'video_s3');
  21      $s3 = new video_amazon_s3();
  22  
  23      if ($amazon = $s3->get($video->fid)) {
  24        foreach ($video->files as $key => &$file) {
  25          $s3->connect();
  26          $file->url = $s3->getVideoUrl($file->filepath);
  27  
  28          // For old video's (pre-4.5), the filename property is actually a path
  29          // and no ffmpeg converted files were saved to S3.
  30          if (strpos('/', $amazon->filename) !== FALSE && $transcoder == 'video_ffmpeg') {
  31            $file->url = $s3->getVideoUrl($amazon->filename);
  32          }
  33        }
  34      }
  35    }
  36  
  37    /**
  38     * Interface Implementations
  39     * @see sites/all/modules/video/includes/filesystem_interface#get_name()
  40     */
  41    public function get_name() {
  42      return $this->name;
  43    }
  44  
  45    /**
  46     * Interface Implementations
  47     * @see sites/all/modules/video/includes/filesystem_interface#get_help()
  48     */
  49    public function get_help() {
  50      return t('Amazon Simple Storage Service (!s3) to store your video files. This free\'s up bandwidth from your site, providing a faster experience for your users. Simply enable this and enter your authentication details and your done!', array('!s3' => l(t('Amazon S3'), 'http://aws.amazon.com/s3/')));
  51    }
  52  
  53    /**
  54     * Interface Implementations
  55     * @see sites/all/modules/video/includes/filesystem_interface#get_value()
  56     */
  57    public function get_value() {
  58      return $this->value;
  59    }
  60  
  61    public function admin_settings() {
  62      $form = array();
  63  
  64      $form['amazon_s3_ssl'] = array(
  65        '#type' => 'checkbox',
  66        '#title' => t('Use HTTPS file links'),
  67        '#default_value' => variable_get('amazon_s3_ssl', FALSE),
  68        '#description' => t('If you would like to use SSL when transfering your files enable this option.'),
  69      );
  70  
  71      $form['amazon_s3_delete_local'] = array(
  72        '#type' => 'checkbox',
  73        '#title' => t('Delete local file after uploading to S3'),
  74        '#default_value' => variable_get('amazon_s3_delete_local', FALSE),
  75        '#description' => t('Replaces the original file on the local file system with an empty file to reduce disk space usage. The file is not removed as Drupal and FileField expect a file to be present.'),
  76      );
  77  
  78      $form['amazon_s3_private'] = array(
  79        '#type' => 'checkbox',
  80        '#title' => t('Enable private file storage'),
  81        '#default_value' => variable_get('amazon_s3_private', FALSE),
  82        '#description' => t('If you would like to use private file storage for your files enable this option. Videos are displayed using temporary URLs that expire after an amount of time that is configurable below.'),
  83      );
  84  
  85      $form['amazon_s3_lifetime'] = array(
  86        '#type' => 'textfield',
  87        '#title' => t('Private URL lifetime'),
  88        '#default_value' => variable_get('amazon_s3_lifetime', 1800),
  89        '#size' => 5,
  90        '#description' => t('The number of seconds a URL to a private file is valid.'),
  91      );
  92  
  93      $form['amazon_s3_access_key'] = array(
  94        '#type' => 'textfield',
  95        '#title' => t('Access Key ID'),
  96        '#default_value' => variable_get('amazon_s3_access_key', ''),
  97        '#size' => 50,
  98        '#element_validate' => array('_video_s3_fsadmin_validate'),
  99      );
 100  
 101      $form['amazon_s3_secret_access_key'] = array(
 102        '#type' => 'password',
 103        '#title' => t('Secret Access Key'),
 104        '#default_value' => variable_get('amazon_s3_secret_access_key', ''),
 105        '#description' => t('Once saved, you do not need to re-enter your secret key.  If you need to update your key, then fill this out to update it.'),
 106        '#size' => 50,
 107        '#element_validate' => array('_video_s3_fsadmin_validate_secret', '_video_s3_fsadmin_validate'),
 108      );
 109  
 110      //@todo Maybe move this to the admin settings page instead of global?
 111      $form['amazon_s3_bucket'] = array(
 112        '#type' => 'textfield',
 113        '#title' => t('Bucket'),
 114        '#description' => t('Enter the bucket you wish to store your videos in.  If the bucket doesn\'t exist the system will attempt to create it.'),
 115        '#default_value' => variable_get('amazon_s3_bucket', ''),
 116        '#size' => 50,
 117        '#element_validate' => array('_video_s3_fsadmin_validate'),
 118      );
 119  
 120      // cloud front
 121      $form['amazon_s3_cf_domain'] = array(
 122        '#type' => 'textfield',
 123        '#title' => t('CloudFront domain name'),
 124        '#description' => t('If you are using Amazon CloudFront with this bucket, enter the CloudFront domain name. This will probably be something like <em>X.cloudfront.net</em> where <em>X</em> is a series of random-looking numbers and letters. Do not include <em>http://</em> at the beginning.'),
 125        '#default_value' => variable_get('amazon_s3_cf_domain', ''),
 126        '#size' => 50,
 127      );
 128  
 129      // Cloud Front and private files do not work together
 130      if (variable_get('amazon_s3_private', FALSE)) {
 131        $form['amazon_s3_cf_domain']['#description'] = t('Amazon CloudFront and S3 private file storage cannot be used together. Disable private files to enable this setting.');
 132        $form['amazon_s3_cf_domain']['#disabled'] = TRUE;
 133      }
 134  
 135      $form['headers_fset'] = array(
 136        '#type' => 'fieldset',
 137        '#title' => t('Headers'),
 138      );
 139  
 140      $form['headers_fset']['amazon_s3_expires_offset'] = array(
 141        '#type' => 'select',
 142        '#title' => t('Expires header'),
 143        '#options' => array(
 144          'none' => t('(none)'),
 145          '0' => t('File is always expired (Unix epoch, 1 Jan 1970, 00:00:00 UTC)'),
 146        ),
 147        '#default_value' => variable_get('amazon_s3_expires_offset', 604800),
 148        '#description' => t('Amazon S3 can be told to send an Expires header (<a href="http://developer.yahoo.com/performance/rules.html#expires">learn more</a>) with served files. This will induce most browsers to cache the file longer, reducing the frequency that it is re-downloaded from the server. This can save on bandwidth charges and provide a faster experience for visitors. However, files which will be frequently updated with the same filename should use a low Expires offset, or else visitors won\'t see &quot;fresh&quot; data. Also, Expires headers will be updated for currently-uploaded files on cron runs, so the interval set here should be greater than or equal to your server\'s cron run interval for best results.'),
 149      );
 150  
 151      $form['headers_fset']['amazon_s3_cache_control_max_age'] = array(
 152        '#type' => 'select',
 153        '#title' => t('max-age parameter of Cache-Control header'),
 154        '#options' => array(
 155          'none' => t('(none)'),
 156        ),
 157        '#default_value' => variable_get('amazon_s3_cache_control_max_age', 'none'),
 158        '#description' => t('When using Amazon CloudFront, the max-age parameter of the Cache-Control header (<a href="http://condor.depaul.edu/~dmumaugh/readings/handouts/SE435/HTTP/node24.html">learn more</a>) tells CloudFront\'s edge servers how frequently they should check the Amazon S3 bucket to see if the files they have cached have been changed or deleted. If you need to ensure that files on edge servers are updated quickly after a video is changed or deleted, set this to a low value; if videos are rarely changed or deleted, or visitors seeing stale data is not a problem, set this to a high value for speed and/or to save on the cost of transferring files from your S3 server to the edge servers. If no value is selected, Amazon\'s default of one day will be used.'),
 159      );
 160      foreach (array(
 161                300, // 5 min
 162                600, // 10 min
 163                1800, // 30 min
 164                3600, // 1 hr
 165                14400, // 4 hr
 166                28800, // 8 hr
 167                43200, // 12 hr
 168                86400, // 1 day
 169                172800, // 2 day
 170                604800, // 1 wk
 171                1209600, // 2 wk
 172                2419200, // 4 wk
 173                4838400, // 8 wk
 174                14515200, // 24 wk
 175                31536000, // 1 yr (365 day)
 176                63072000, // 2 yr
 177                157680000, // 5 yr
 178                315360000, // 10 yr
 179      ) as $time) {
 180        $interval = format_interval($time, 1);
 181        $form['headers_fset']['amazon_s3_expires_offset']['#options'][$time] = $interval;
 182        if ($time >= 3600) {
 183          // The minimum Cache-Control; max-age value Amazon will accept is one hour.
 184          $form['headers_fset']['amazon_s3_cache_control_max_age']['#options'][$time] = $interval;
 185        }
 186      }
 187  
 188      //lets show our buckets in table format with a delete link.
 189      //@todo add permissions
 190      //were enabled, that means they have successfully connected and created a bucket.
 191      if (variable_get('amazon_s3_access_key', false) && _video_s3_is_active_fs()) {
 192        module_load_include('lib.inc', 'video_s3');
 193        $s3 = new video_amazon_s3();
 194        $s3->connect();
 195        $buckets = $s3->s3->get_bucket_list();
 196  
 197        // Setup our header.
 198        $header = array(t('Bucket Name'), t('Actions'));
 199        $rows = array();
 200        foreach ($buckets as $bucket) {
 201          if (!$this->isValidBucketName($bucket)) {
 202            $rows[] = array($bucket, t('Unsupported bucket name'));
 203          }
 204          else {
 205            $title = $bucket;
 206            
 207            if ($bucket == variable_get('amazon_s3_bucket', '')) {
 208              $title = '<strong>'. $title .' ('. t('active bucket') .')</strong>';
 209            }
 210  
 211            $actions = l(t('Delete'), 'admin/settings/video/amazon_s3/bucket/' . $bucket . '/delete');
 212            $rows[] = array($title, $actions);
 213          }
 214        }
 215        $form['amazon_info'] = array(
 216          '#type' => 'fieldset',
 217          '#title' => t('Amazon S3 Information'),
 218          '#collapsible' => TRUE,
 219          '#collapsed' => TRUE,
 220        );
 221        $form['amazon_info']['buckets'] = array(
 222          '#type' => 'markup',
 223          '#value' => theme('table', $header, $rows),
 224        );
 225      }
 226      return $form;
 227    }
 228  
 229    public function admin_settings_validate($form, &$form_state) {
 230      // Check for CURL
 231      if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll')) {
 232        form_set_error('amazon_s3', t('The CURL extension is not loaded.'));
 233        return;
 234      }
 235      
 236      $bucket = $form_state['values']['amazon_s3_bucket'];
 237      // S3 buckets must contain only lower case alphanumeric characters, dots and dashes.
 238      if (!$this->isValidBucketName($bucket)) {
 239        form_set_error('amazon_s3_bucket', t('S3 bucket names must contain only lower case alphanumeric characters, dots and dashes.'));
 240      }
 241  
 242      $ssl = isset($form_state['values']['amazon_s3_ssl']) && $form_state['values']['amazon_s3_ssl'];
 243      $access_key = $form_state['values']['amazon_s3_access_key'];
 244      $secret_key = $form_state['values']['amazon_s3_secret_access_key'];
 245  
 246      if (empty($access_key) || empty($secret_key)) {
 247        // There is no point in continuing if there is no access info
 248        return;
 249      }
 250  
 251      // Lets verify our credentials and verify our bucket exists, if not attempt to create it.
 252      module_load_include('lib.inc', 'video_s3');
 253      $s3 = new video_amazon_s3();
 254      $s3->connect($access_key, $secret_key, $ssl);
 255      $buckets = $s3->s3->get_bucket_list();
 256  
 257      if (!in_array($bucket, $buckets)) {
 258        // Create a bucket with public read access
 259        // TODO: region selection
 260        $response = $s3->s3->create_bucket($bucket, AmazonS3::REGION_US_E1, AmazonS3::ACL_PUBLIC);
 261        if ($response->isOK()) {
 262          drupal_set_message(t('Successfully created the bucket %bucket.', array('%bucket' => $bucket)));
 263        }
 264        else {
 265          form_set_error('amazon_s3_bucket', t('Could not verify or create the bucket %bucket.', array('%bucket' => $bucket)));
 266          $bucket = null;
 267        }
 268      }
 269  
 270      // Always check the access rights, in case the bucket was created
 271      // outside of Drupal or before the Zencoder module was active.
 272      if ($bucket != null && module_exists('video_zencoder')) {
 273        if ($s3->setZencoderAccessPolicy($bucket)) {
 274          drupal_set_message(t('Successfully granted write access for bucket %bucket to Zencoder.', array('%bucket' => $bucket)));
 275        }
 276      }
 277    }
 278  
 279    private function isValidBucketName($name) {
 280      return preg_match('/^[a-z0-9.-]+$/', $name);
 281    }
 282  }
 283  
 284  /**
 285   * Replace the empty form value with the variable value.
 286   * 
 287   * Used for the access secret.
 288   * 
 289   * @param array $element
 290   * @param array $form_state
 291   */
 292  function _video_s3_fsadmin_validate_secret($element, &$form_state) {
 293    $key = end($element['#parents']);
 294    $val = $form_state['values'][$key];
 295    $existing = variable_get($key, NULL);
 296    
 297    if ($val === '' && $existing !== NULL) {
 298      $form_state['values'][$key] = $existing;
 299    }
 300  }
 301  
 302  /**
 303   * Handle required fields that are only required when
 304   * video_s3 is the selected file system.
 305   * 
 306   * @param array $element
 307   * @param array $form_state
 308   */
 309  function _video_s3_fsadmin_validate($element, $form_state) {
 310    if ($form_state['values']['vid_filesystem'] != 'video_s3') {
 311      return;
 312    }
 313  
 314    $key = end($element['#parents']);
 315    $val = $form_state['values'][$key];
 316  
 317    if (empty($val)) {
 318      form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
 319    }
 320  }


Generated: Mon Jul 9 18:01:44 2012 Cross-referenced by PHPXref 0.7