PageRenderTime 50ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 0ms

/video/plugins/video_s3/filesystem/video_s3.inc

#
Pascal | 320 lines | 131 code | 22 blank | 167 comment | 14 complexity | 4c102ac94e605a54136cca7ee6317833 MD5 | raw file
Possible License(s): GPL-2.0
  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. protected $params = array();
  9. protected $name = 'Amazon S3';
  10. protected $value = 'video_s3';
  11. public function __construct() {
  12. }
  13. public function load_file($video) {
  14. $transcoder = variable_get('vid_convertor', 'video_ffmpeg');
  15. module_load_include('lib.inc', 'video_s3');
  16. $s3 = new video_amazon_s3();
  17. if ($amazon = $s3->get($video->fid)) {
  18. foreach ($video->files as $key => &$file) {
  19. $s3->connect();
  20. $file->url = $s3->getVideoUrl($file->filepath);
  21. // For old video's (pre-4.5), the filename property is actually a path
  22. // and no ffmpeg converted files were saved to S3.
  23. if (strpos('/', $amazon->filename) !== FALSE && $transcoder == 'video_ffmpeg') {
  24. $file->url = $s3->getVideoUrl($amazon->filename);
  25. }
  26. }
  27. }
  28. }
  29. /**
  30. * Interface Implementations
  31. * @see sites/all/modules/video/includes/filesystem_interface#get_name()
  32. */
  33. public function get_name() {
  34. return $this->name;
  35. }
  36. /**
  37. * Interface Implementations
  38. * @see sites/all/modules/video/includes/filesystem_interface#get_help()
  39. */
  40. public function get_help() {
  41. 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/')));
  42. }
  43. /**
  44. * Interface Implementations
  45. * @see sites/all/modules/video/includes/filesystem_interface#get_value()
  46. */
  47. public function get_value() {
  48. return $this->value;
  49. }
  50. public function admin_settings() {
  51. $form = array();
  52. $form['amazon_s3_ssl'] = array(
  53. '#type' => 'checkbox',
  54. '#title' => t('Use HTTPS file links'),
  55. '#default_value' => variable_get('amazon_s3_ssl', FALSE),
  56. '#description' => t('If you would like to use SSL when transfering your files enable this option.'),
  57. );
  58. $form['amazon_s3_delete_local'] = array(
  59. '#type' => 'checkbox',
  60. '#title' => t('Delete local file after uploading to S3'),
  61. '#default_value' => variable_get('amazon_s3_delete_local', FALSE),
  62. '#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.'),
  63. );
  64. $form['amazon_s3_private'] = array(
  65. '#type' => 'checkbox',
  66. '#title' => t('Enable private file storage'),
  67. '#default_value' => variable_get('amazon_s3_private', FALSE),
  68. '#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.'),
  69. );
  70. $form['amazon_s3_lifetime'] = array(
  71. '#type' => 'textfield',
  72. '#title' => t('Private URL lifetime'),
  73. '#default_value' => variable_get('amazon_s3_lifetime', 1800),
  74. '#size' => 5,
  75. '#description' => t('The number of seconds a URL to a private file is valid.'),
  76. );
  77. $form['amazon_s3_access_key'] = array(
  78. '#type' => 'textfield',
  79. '#title' => t('Access Key ID'),
  80. '#default_value' => variable_get('amazon_s3_access_key', ''),
  81. '#size' => 50,
  82. '#element_validate' => array('_video_s3_fsadmin_validate'),
  83. );
  84. $form['amazon_s3_secret_access_key'] = array(
  85. '#type' => 'password',
  86. '#title' => t('Secret Access Key'),
  87. '#default_value' => variable_get('amazon_s3_secret_access_key', ''),
  88. '#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.'),
  89. '#size' => 50,
  90. '#element_validate' => array('_video_s3_fsadmin_validate_secret', '_video_s3_fsadmin_validate'),
  91. );
  92. //@todo Maybe move this to the admin settings page instead of global?
  93. $form['amazon_s3_bucket'] = array(
  94. '#type' => 'textfield',
  95. '#title' => t('Bucket'),
  96. '#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.'),
  97. '#default_value' => variable_get('amazon_s3_bucket', ''),
  98. '#size' => 50,
  99. '#element_validate' => array('_video_s3_fsadmin_validate'),
  100. );
  101. // cloud front
  102. $form['amazon_s3_cf_domain'] = array(
  103. '#type' => 'textfield',
  104. '#title' => t('CloudFront domain name'),
  105. '#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.'),
  106. '#default_value' => variable_get('amazon_s3_cf_domain', ''),
  107. '#size' => 50,
  108. );
  109. // Cloud Front and private files do not work together
  110. if (variable_get('amazon_s3_private', FALSE)) {
  111. $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.');
  112. $form['amazon_s3_cf_domain']['#disabled'] = TRUE;
  113. }
  114. $form['headers_fset'] = array(
  115. '#type' => 'fieldset',
  116. '#title' => t('Headers'),
  117. );
  118. $form['headers_fset']['amazon_s3_expires_offset'] = array(
  119. '#type' => 'select',
  120. '#title' => t('Expires header'),
  121. '#options' => array(
  122. 'none' => t('(none)'),
  123. '0' => t('File is always expired (Unix epoch, 1 Jan 1970, 00:00:00 UTC)'),
  124. ),
  125. '#default_value' => variable_get('amazon_s3_expires_offset', 604800),
  126. '#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.'),
  127. );
  128. $form['headers_fset']['amazon_s3_cache_control_max_age'] = array(
  129. '#type' => 'select',
  130. '#title' => t('max-age parameter of Cache-Control header'),
  131. '#options' => array(
  132. 'none' => t('(none)'),
  133. ),
  134. '#default_value' => variable_get('amazon_s3_cache_control_max_age', 'none'),
  135. '#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.'),
  136. );
  137. foreach (array(
  138. 300, // 5 min
  139. 600, // 10 min
  140. 1800, // 30 min
  141. 3600, // 1 hr
  142. 14400, // 4 hr
  143. 28800, // 8 hr
  144. 43200, // 12 hr
  145. 86400, // 1 day
  146. 172800, // 2 day
  147. 604800, // 1 wk
  148. 1209600, // 2 wk
  149. 2419200, // 4 wk
  150. 4838400, // 8 wk
  151. 14515200, // 24 wk
  152. 31536000, // 1 yr (365 day)
  153. 63072000, // 2 yr
  154. 157680000, // 5 yr
  155. 315360000, // 10 yr
  156. ) as $time) {
  157. $interval = format_interval($time, 1);
  158. $form['headers_fset']['amazon_s3_expires_offset']['#options'][$time] = $interval;
  159. if ($time >= 3600) {
  160. // The minimum Cache-Control; max-age value Amazon will accept is one hour.
  161. $form['headers_fset']['amazon_s3_cache_control_max_age']['#options'][$time] = $interval;
  162. }
  163. }
  164. //lets show our buckets in table format with a delete link.
  165. //@todo add permissions
  166. //were enabled, that means they have successfully connected and created a bucket.
  167. if (variable_get('amazon_s3_access_key', false) && _video_s3_is_active_fs()) {
  168. module_load_include('lib.inc', 'video_s3');
  169. $s3 = new video_amazon_s3();
  170. $s3->connect();
  171. $buckets = $s3->s3->get_bucket_list();
  172. // Setup our header.
  173. $header = array(t('Bucket Name'), t('Actions'));
  174. $rows = array();
  175. foreach ($buckets as $bucket) {
  176. if (!$this->isValidBucketName($bucket)) {
  177. $rows[] = array($bucket, t('Unsupported bucket name'));
  178. }
  179. else {
  180. $title = $bucket;
  181. if ($bucket == variable_get('amazon_s3_bucket', '')) {
  182. $title = '<strong>'. $title .' ('. t('active bucket') .')</strong>';
  183. }
  184. $actions = l(t('Delete'), 'admin/settings/video/amazon_s3/bucket/' . $bucket . '/delete');
  185. $rows[] = array($title, $actions);
  186. }
  187. }
  188. $form['amazon_info'] = array(
  189. '#type' => 'fieldset',
  190. '#title' => t('Amazon S3 Information'),
  191. '#collapsible' => TRUE,
  192. '#collapsed' => TRUE,
  193. );
  194. $form['amazon_info']['buckets'] = array(
  195. '#type' => 'markup',
  196. '#value' => theme('table', $header, $rows),
  197. );
  198. }
  199. return $form;
  200. }
  201. public function admin_settings_validate($form, &$form_state) {
  202. // Check for CURL
  203. if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll')) {
  204. form_set_error('amazon_s3', t('The CURL extension is not loaded.'));
  205. return;
  206. }
  207. $bucket = $form_state['values']['amazon_s3_bucket'];
  208. // S3 buckets must contain only lower case alphanumeric characters, dots and dashes.
  209. if (!$this->isValidBucketName($bucket)) {
  210. form_set_error('amazon_s3_bucket', t('S3 bucket names must contain only lower case alphanumeric characters, dots and dashes.'));
  211. }
  212. $ssl = isset($form_state['values']['amazon_s3_ssl']) && $form_state['values']['amazon_s3_ssl'];
  213. $access_key = $form_state['values']['amazon_s3_access_key'];
  214. $secret_key = $form_state['values']['amazon_s3_secret_access_key'];
  215. if (empty($access_key) || empty($secret_key)) {
  216. // There is no point in continuing if there is no access info
  217. return;
  218. }
  219. // Lets verify our credentials and verify our bucket exists, if not attempt to create it.
  220. module_load_include('lib.inc', 'video_s3');
  221. $s3 = new video_amazon_s3();
  222. $s3->connect($access_key, $secret_key, $ssl);
  223. $buckets = $s3->s3->get_bucket_list();
  224. if (!in_array($bucket, $buckets)) {
  225. // Create a bucket with public read access
  226. // TODO: region selection
  227. $response = $s3->s3->create_bucket($bucket, AmazonS3::REGION_US_E1, AmazonS3::ACL_PUBLIC);
  228. if ($response->isOK()) {
  229. drupal_set_message(t('Successfully created the bucket %bucket.', array('%bucket' => $bucket)));
  230. }
  231. else {
  232. form_set_error('amazon_s3_bucket', t('Could not verify or create the bucket %bucket.', array('%bucket' => $bucket)));
  233. $bucket = null;
  234. }
  235. }
  236. // Always check the access rights, in case the bucket was created
  237. // outside of Drupal or before the Zencoder module was active.
  238. if ($bucket != null && module_exists('video_zencoder')) {
  239. if ($s3->setZencoderAccessPolicy($bucket)) {
  240. drupal_set_message(t('Successfully granted write access for bucket %bucket to Zencoder.', array('%bucket' => $bucket)));
  241. }
  242. }
  243. }
  244. private function isValidBucketName($name) {
  245. return preg_match('/^[a-z0-9.-]+$/', $name);
  246. }
  247. }
  248. /**
  249. * Replace the empty form value with the variable value.
  250. *
  251. * Used for the access secret.
  252. *
  253. * @param array $element
  254. * @param array $form_state
  255. */
  256. function _video_s3_fsadmin_validate_secret($element, &$form_state) {
  257. $key = end($element['#parents']);
  258. $val = $form_state['values'][$key];
  259. $existing = variable_get($key, NULL);
  260. if ($val === '' && $existing !== NULL) {
  261. $form_state['values'][$key] = $existing;
  262. }
  263. }
  264. /**
  265. * Handle required fields that are only required when
  266. * video_s3 is the selected file system.
  267. *
  268. * @param array $element
  269. * @param array $form_state
  270. */
  271. function _video_s3_fsadmin_validate($element, $form_state) {
  272. if ($form_state['values']['vid_filesystem'] != 'video_s3') {
  273. return;
  274. }
  275. $key = end($element['#parents']);
  276. $val = $form_state['values'][$key];
  277. if (empty($val)) {
  278. form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
  279. }
  280. }