Issue #1268268: Marked the media_url_filter() and related functions that are not...
[project/media.git] / media.module
1 <?php
2
3 /**
4 * @file
5 * Media API
6 *
7 * The core Media API.
8 * See http://drupal.org/project/media for more details.
9 */
10
11 /* ***************************************** */
12 /* INCLUDES */
13 /* ***************************************** */
14
15 // A registry of variable_get defaults.
16 require_once (dirname(__FILE__) . '/includes/media.variables.inc');
17
18 // Define media related file types and how to display them.
19 require_once (dirname(__FILE__) . '/includes/media.types.inc');
20
21 // Code relating to using media as a field.
22 require_once (dirname(__FILE__) . '/includes/media.fields.inc');
23
24 // Functions for working with [[inline tags]] and wysiwyg editors.
25 require_once (dirname(__FILE__) . '/includes/media.filter.inc');
26
27 /* ***************************************** */
28 /* Hook Implementations */
29 /* ***************************************** */
30
31 /**
32 * Implements hook_hook_info().
33 */
34 function media_hook_info() {
35 $hooks = array(
36 'media_display_types',
37 'media_display_types_alter',
38 'media_parse',
39 'media_operations',
40 'media_browser_plugin_info',
41 'media_browser_plugin_view',
42 'media_browser_plugins_alter',
43 'media_browser_params_alter',
44 'media_wysiwyg_allowed_view_modes_alter',
45 'media_format_form_prepare_alter',
46 'media_token_to_markup_alter',
47 );
48
49 return array_fill_keys($hooks, array('group' => 'media'));
50 }
51
52 /**
53 * Implements hook_help().
54 */
55 function media_help($path, $arg) {
56 switch ($path) {
57 case 'admin/help#media':
58 $output = '';
59 $output .= '<h3>' . t('About') . '</h3>';
60 $output .= '<p>' . t('The Media module is a File Browser to the Internet, media provides a framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site. It replaces the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Media module also provides rich integration with WYSIWYG module to let content creators access media assets in rich text editor. Javascript is required to use the Media module. For more information check <a href="@media_faq">Media Module page</a>', array('@media_faq' => 'http://drupal.org/project/media')) . '.</p>';
61 $output .= '<h3>' . t('Uses') . '</h3>';
62 $output .= '<dl>';
63 $output .= '<dt>' . t('Media Repository') . '</dt>';
64 $output .= '<dd>' . t('Media module allows you to maintain a <a href="@mediarepo">media asset repository</a> where in you can add, remove, reuse your media assets. You can add the media file using upload form or from a url and also do bulk operations on the media assets.', array('@mediarepo' => url('admin/content/media'))) . '</dd>';
65 $output .= '<dt>' . t('Attaching media assets to content types') . '</dt>';
66 $output .= '<dd>' . t('Media assets can be attached to content types as fields. To add a media field to a <a href="@content-type">content type</a>, go to the content type\'s <em>manage fields</em> page, and add a new field of type <em>Multimedia Asset</em>.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
67 $output .= '<dt>' . t('Using media assets in WYSIWYG') . '</dt>';
68 $output .= '<dd>' . t('Media module provides rich integration with WYSIWYG editors, using Media Browser plugin you can select media asset from library to add to the rich text editor moreover you can add media asset from the media browser itself using either upload method or add from url method. To configure media with WYSIWYG you need two steps of configuration:');
69 $output .= '<ul><li>' . t('Enable WYSIWYG plugin on your desired <a href="@wysiwyg-profile">WYSIWYG profile</a>. Please note that you will need to have <a href="@wysiwyg">WYSIWYG</a> module enabled.', array('@wysiwyg-profile' => url('admin/config/content/wysiwyg'), '@wysiwyg' => 'http://drupal.org/project/wysiwyg')) . '</li>';
70 $output .= '<li>' . t('Add Media Filter to the WYSIWYG enabled <a href="@input-format">Input format</a>', array('@input-format' => url('admin/config/content/formats'))) . '</li></ul></dd>';
71 return $output;
72 case 'admin/config/media/file-types/manage/%/display/media_preview':
73 case 'admin/config/media/file-types/manage/%/file-display/media_preview':
74 drupal_set_message(t('Changing the Preview view mode could have unintended side effects such as breaking the Media browser or WYSIWYG integration. Only change these display settings if you know what you are doing.'), 'warning');
75 break;
76 }
77 }
78
79 /**
80 * Implements hook_entity_info_alter().
81 *
82 * Add view modes to the file entity type, appropriate for displaying media.
83 */
84 function media_entity_info_alter(&$entity_info) {
85 $entity_info['file']['view modes']['media_link'] = array('label' => t('Link'), 'custom settings' => TRUE);
86 $entity_info['file']['view modes']['media_preview'] = array('label' => t('Preview'), 'custom settings' => TRUE);
87 $entity_info['file']['view modes']['media_small'] = array('label' => t('Small'), 'custom settings' => TRUE);
88 $entity_info['file']['view modes']['media_large'] = array('label' => t('Large'), 'custom settings' => TRUE);
89 $entity_info['file']['view modes']['media_original'] = array('label' => t('Original'), 'custom settings' => TRUE);
90 }
91
92 /**
93 * Implement of hook_menu().
94 */
95 function media_menu() {
96 // For managing different types of media and the fields associated with them.
97 $items['admin/config/media/browser'] = array(
98 'title' => 'Media browser settings',
99 'description' => 'Configure the behavior and display of the media browser.',
100 'page callback' => 'drupal_get_form',
101 'page arguments' => array('media_admin_config_browser'),
102 'access arguments' => array('administer media'),
103 'file' => 'includes/media.admin.inc',
104 );
105 // For managing different types of media and the fields associated with them.
106 $items['admin/config/media/rebuild_types'] = array(
107 'title' => 'Rebuild type information for media',
108 'description' => 'In case there are files in file_managed w/o a type, this function rebuilds them',
109 'page callback' => 'drupal_get_form',
110 'page arguments' => array('media_admin_rebuild_types_form'),
111 'access arguments' => array('administer media'),
112 'file' => 'includes/media.admin.inc',
113 );
114
115 // Settings used for determining the type of media a file is.
116 // @todo Find a new home for this that integrates with the file_entity module.
117 // $items['admin/config/media/types/manage/%media_type'] = array(
118 // 'title' => 'Manage media',
119 // 'title callback' => 'media_type_page_title',
120 // 'title arguments' => array(5),
121 // 'description' => 'Manage files used on your site.',
122 // 'page callback' => 'drupal_get_form',
123 // 'page arguments' => array('media_admin_type_manage_form', 5),
124 // 'access arguments' => array('administer media'),
125 // 'file' => 'includes/media.admin.inc',
126 // );
127 // $items['admin/config/media/types/manage/%media_type/settings'] = array(
128 // 'title' => 'Settings',
129 // 'type' => MENU_DEFAULT_LOCAL_TASK,
130 // 'weight' => -1,
131 // );
132
133 // Administrative screens for managing media.
134 $items['admin/content/media'] = array(
135 'title' => 'Media',
136 'description' => 'Manage files used on your site.',
137 'page callback' => 'drupal_get_form',
138 'page arguments' => array('media_admin'),
139 'access arguments' => array('administer media'),
140 'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
141 'file' => 'includes/media.admin.inc',
142 );
143
144 // Used to import files from a local filesystem into Drupal.
145 $items['admin/content/media/import'] = array(
146 'title' => 'Import media',
147 'description' => 'Import files into your media library.',
148 'page callback' => 'drupal_get_form',
149 'page arguments' => array('media_import'),
150 'access arguments' => array('import media'),
151 'type' => MENU_LOCAL_ACTION,
152 'file' => 'includes/media.admin.inc',
153 );
154
155 $items['media/browser'] = array(
156 'title' => 'Media browser',
157 'description' => 'Media Browser for picking media and uploading new media',
158 'page callback' => 'media_browser',
159 'access callback' => 'media_access',
160 'access arguments' => array('view'),
161 'type' => MENU_CALLBACK,
162 'file' => 'includes/media.browser.inc',
163 'theme callback' => 'media_dialog_get_theme_name',
164 );
165
166 // A testbed to try out the media browser with different launch commands.
167 $items['media/browser/testbed'] = array(
168 'title' => 'Media Browser test',
169 'description' => 'Make it easier to test media browser',
170 'page callback' => 'drupal_get_form',
171 'page arguments' => array('media_browser_testbed'),
172 'access arguments' => array('administer media'),
173 'type' => MENU_CALLBACK,
174 'file' => 'includes/media.browser.inc',
175 );
176
177
178 /**
179 * Browser callbacks
180 * @var unknown_type
181 */
182 $items['media/browser/list'] = array(
183 'title' => 'Media browser list',
184 'description' => 'Ajax Callback for getting media',
185 'page callback' => 'media_browser_list',
186 'access callback' => 'media_access',
187 'access arguments' => array('view'),
188 'type' => MENU_CALLBACK,
189 'file' => 'includes/media.browser.inc',
190 );
191
192 $items['media/browser/library'] = array(
193 'title' => 'Media browser library',
194 'description' => 'Media Browser for picking media and uploading new media',
195 'page callback' => 'media_browser_library',
196 'access callback' => 'media_access',
197 'access arguments' => array('view'),
198 'type' => MENU_CALLBACK,
199 'file' => 'includes/media.browser.inc',
200 );
201
202 $items['media/%file/format-form'] = array(
203 'title' => 'Style selector',
204 'description' => 'Choose a format for a piece of media',
205 'page callback' => 'drupal_get_form',
206 'page arguments' => array('media_format_form', 1),
207 'access callback' => 'media_access',
208 'access arguments' => array('view'),
209 'weight' => 0,
210 'file' => 'includes/media.filter.inc',
211 'theme callback' => 'media_dialog_get_theme_name',
212 );
213
214 $items['media/%file'] = array(
215 'page callback' => 'media_view_page',
216 'page arguments' => array(1),
217 'access callback' => 'media_access',
218 'access arguments' => array('view'),
219 'file' => 'includes/media.pages.inc',
220 );
221
222 $items['media/%file/view'] = array(
223 'title' => 'View',
224 'type' => MENU_DEFAULT_LOCAL_TASK,
225 'weight' => -10,
226 );
227
228 $items['media/%file/edit'] = array(
229 'title' => 'Edit',
230 'page callback' => 'media_page_edit',
231 'page arguments' => array(1),
232 'access callback' => 'media_access',
233 'access arguments' => array('edit'),
234 'weight' => 0,
235 'type' => MENU_LOCAL_TASK,
236 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
237 'file' => 'includes/media.pages.inc',
238 );
239
240 $items['media/%media_multi/multiedit'] = array(
241 'title' => 'Multi Edit',
242 'page callback' => 'media_page_multiedit',
243 'page arguments' => array(1),
244 'access callback' => 'media_access',
245 'access arguments' => array('edit'),
246 'weight' => 0,
247 'file' => 'includes/media.pages.inc',
248 );
249
250 $items['media/%file/delete'] = array(
251 'title' => 'Delete',
252 'page callback' => 'media_page_delete',
253 'page arguments' => array(1),
254 'access callback' => 'media_access',
255 'access arguments' => array('edit'),
256 'weight' => 1,
257 'type' => MENU_LOCAL_TASK,
258 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
259 'file' => 'includes/media.pages.inc',
260 );
261
262 return $items;
263 }
264
265 /**
266 * Implements hook_admin_paths().
267 */
268 function media_admin_paths() {
269 $paths = array(
270 'media/*/edit' => TRUE,
271 'media/*/multiedit' => TRUE,
272 'media/*/delete' => TRUE,
273 );
274 return $paths;
275 }
276
277 /**
278 * Implements hook_permission().
279 */
280 function media_permission() {
281 return array(
282 'administer media' => array(
283 'title' => t('Administer media'),
284 'description' => t('Add, edit or delete media files and administer settings.'),
285 ),
286 'import media' => array(
287 'title' => t('Import media files from the local filesystem'),
288 'description' => t('Simple file importer'),
289 ),
290 'view media' => array(
291 'title' => t('View media'),
292 'description' => t('View all media files.'), // @TODO better description
293 ),
294 'edit media' => array(
295 'title' => t('Edit media'),
296 'description' => t('Edit all media files.'), // @TODO better description
297 ),
298 );
299 }
300
301 /**
302 * Implements hook_theme().
303 *
304 * @TODO: Needs a major cleanup.
305 */
306 function media_theme() {
307 return array(
308
309 // The default media file list form element.
310 'media_file_list' => array(
311 'variables' => array('element' => NULL),
312 ),
313
314 // A link for a file w/ an icon to the media/$fid page.
315 'media_link' => array(
316 'variables' => array('file' => NULL),
317 'file' => 'includes/media.theme.inc',
318 ),
319
320 // A preview of the uploaded file.
321 'media_thumbnail' => array(
322 'render element' => 'element',
323 'file' => 'includes/media.theme.inc',
324 ),
325
326 // Administrative thumbnail previews.
327 'media_admin_thumbnail' => array(
328 'variables' => array('file' => array(), 'style_name' => 'thumbnail'),
329 'file' => 'includes/media.theme.inc',
330 ),
331
332 // Administrative thumbnail previews.
333 'media_admin_thumbnail_operations' => array(
334 'variables' => array('file' => NULL),
335 'file' => 'includes/media.theme.inc',
336 ),
337
338 // Tabs in the media browser.
339 'media_browser_tabs' => array(
340 'file' => 'includes/media.theme.inc',
341 ),
342
343 // Dialog page.
344 'media_dialog_page' => array(
345 'render element' => 'page',
346 'template' => 'templates/media-dialog-page',
347 'file' => 'includes/media.theme.inc',
348 ),
349
350 //
351 'media_element' => array(
352 'render element' => 'element',
353 'file' => 'includes/media.theme.inc',
354 ),
355
356 'media_formatter_large_icon' => array(
357 'variables' => array('file' => NULL, 'attributes' => array()),
358 'file' => 'includes/media.theme.inc',
359 ),
360 );
361 }
362
363 /**
364 * Implements hook_image_default_styles().
365 */
366 function media_image_default_styles() {
367 $styles = array();
368 $styles['square_thumbnail'] = array(
369 'effects' => array(
370 array(
371 'name' => 'image_scale_and_crop',
372 'data' => array('width' => 180, 'height' => 180),
373 'weight' => 0,
374 ),
375 )
376 );
377 return $styles;
378 }
379
380 /**
381 * Implements hook_file_update().
382 */
383 function media_file_update($file) {
384 media_filter_invalidate_caches($file->fid);
385 }
386
387 /**
388 * Implements hook_file_delete().
389 */
390 function media_file_delete($file) {
391 db_delete('media_filter_usage')->condition('fid', $file->fid)->execute();
392 }
393
394 /**
395 * Implements hook_image_style_flush().
396 *
397 * This hook is invoked by Drupal core when cached image derivatives are no
398 * longer valid.
399 *
400 * @see media_styles_style_flush()
401 * @see media_file_style_flush()
402 */
403 function media_image_style_flush($style) {
404 // When a image style is flushed, clear the filter and field caches.
405 media_filter_invalidate_caches();
406 }
407
408 /**
409 * Implements hook_file_style_flush().
410 *
411 * This hook is invoked by the File Styles module in Styles 1.x.
412 *
413 * @see media_styles_style_flush()
414 */
415 function media_file_style_flush($style) {
416 // When a file style is flushed, clear the filter and field caches.
417 media_filter_invalidate_caches();
418 }
419
420 /**
421 * Implements hook_styles_style_flush().
422 *
423 * This hook is invoked by the Styles module in Styles 2.x.
424 *
425 * @see media_file_style_flush()
426 */
427 function media_styles_style_flush($style) {
428 // When a style is flushed, clear the filter and field caches.
429 media_filter_invalidate_caches();
430 }
431
432 /**
433 * Implements hook_page_alter().
434 *
435 * This is used to use our alternate template when ?render=media-popup is passed
436 * in the URL.
437 */
438 function media_page_alter(&$page) {
439 // Show a nagging message when the media installation needs to be completed.
440 if (user_access('administer media') && media_variable_get('show_file_type_rebuild_nag')
441 // Prevent form submissions from creating duplicate messages.
442 && ($_SERVER['REQUEST_METHOD'] == 'GET')
443 // Show on all the admin pages, except the batch and the rebuild form.
444 && path_is_admin(current_path()) && (arg(0) != 'batch') && (current_path() != 'admin/config/media/rebuild_types')) {
445 drupal_set_message(t('Media module install is not complete. <a href="@type_rebuild_link">Finish the install</a>.', array('@type_rebuild_link' => url('admin/config/media/rebuild_types'))), 'warning', FALSE);
446 }
447
448 if (isset($_GET['render']) && $_GET['render'] == 'media-popup') {
449 $page['#theme'] = 'media_dialog_page';
450
451 // Disable administration modules from adding output to the popup.
452 // @see http://drupal.org/node/914786
453 module_invoke_all('suppress');
454
455 foreach (element_children($page) as $key) {
456 if ($key != 'content') {
457 unset($page[$key]);
458 }
459 }
460 }
461 }
462
463 /**
464 * Implements hook_element_info_alter().
465 */
466 function media_element_info_alter(&$types) {
467 $types['text_format']['#pre_render'][] = 'media_pre_render_text_format';
468 }
469
470 /**
471 * Implements hook_forms().
472 */
473 function media_forms($form_id, $args) {
474 $forms = array();
475 // To support the multiedit form, each form has to have a unique ID.
476 // So we name all the forms media_edit_N where the first requested form is
477 // media_edit_0, 2nd is media_edit_1, etc.
478 if ($form_id != 'media_edit' && (strpos($form_id, 'media_edit') === 0)) {
479 $forms[$form_id] = array(
480 'callback' => 'media_edit',
481 );
482 }
483 return $forms;
484 }
485
486 /**
487 * Implements hook_form_FIELD_UI_FIELD_SETTINGS_FORM_alter().
488 *
489 * @todo: Respect field settings in 7.x-2.x and handle them in the media widget UI
490 */
491 function media_form_field_ui_field_settings_form_alter(&$form, &$form_state) {
492 // On file fields that use the media widget we need remove specific fields
493 if ($form['field']['type']['#value'] == 'file') {
494 $fields = field_info_instances($form['#entity_type'], $form['#bundle']);
495 if ($fields[$form['field']['field_name']['#value']]['widget']['type'] == 'media_generic') {
496 $form['field']['settings']['display_field']['#access'] = FALSE;
497 $form['field']['settings']['display_default']['#access'] = FALSE;
498 }
499 }
500 }
501
502 /**
503 * Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
504 *
505 * @todo: Respect field settings in 7.x-2.x and handle them in the media widget UI
506 */
507 function media_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
508 // On file fields that use the media widget we need remove specific fields
509 if ($form['#field']['type'] == 'file' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
510 $form['field']['settings']['display_field']['#access'] = FALSE;
511 $form['field']['settings']['display_default']['#access'] = FALSE;
512 $form['instance']['settings']['description_field']['#access'] = FALSE;
513 $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
514 $form['instance']['settings']['file_extensions']['#maxlength'] = 255;
515 }
516
517 // On image fields using the media widget we remove the alt/title fields
518 if ($form['#field']['type'] == 'image' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
519 $form['instance']['settings']['alt_field']['#access'] = FALSE;
520 $form['instance']['settings']['title_field']['#access'] = FALSE;
521 $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
522 // Do not increase maxlength of file extensions for image fields, since
523 // presumably they will not need a long list of extensions.
524 }
525 }
526
527 /**
528 * Implements hook_form_FORM_ID_alter().
529 */
530 function media_form_wysiwyg_profile_form_alter(&$form, &$form_state) {
531 // Add warnings if the media filter is disabled for the WYSIWYG's text format.
532 $form['buttons']['drupal']['media']['#element_validate'][] = 'media_wysiwyg_button_element_validate';
533 $form['buttons']['drupal']['media']['#after_build'][] = 'media_wysiwyg_button_element_validate';
534 form_load_include($form_state, 'inc', 'media', 'wysiwyg_plugins/media');
535 }
536
537 /* ***************************************** */
538 /* API FUNCTIONS */
539 /* ***************************************** */
540
541 /**
542 * Load callback for %media_multi placeholder in menu paths.
543 *
544 * @param string $fids
545 * Separated by space (e.g., "3 6 12 99"). This often appears as "+" within
546 * URLs (e.g., "3+6+12+99"), but Drupal automatically decodes paths when
547 * intializing $_GET['q'].
548 *
549 * @return array
550 * An array of corresponding file entities.
551 */
552 function media_multi_load($fids) {
553 return file_load_multiple(explode(" ", $fids));
554 }
555
556 /**
557 * Access callback for media assets.
558 */
559 function media_access($op) {
560 return (user_access('administer media') || user_access($op . ' media'));
561 }
562
563 /**
564 * Implements hook_file_download_access().
565 */
566 function media_file_download_access($field, $entity_type, $entity) {
567 if ($entity_type == 'media') {
568 return media_access('view');
569 }
570 }
571
572 /**
573 * Returns the type of the media file to be used as a page title.
574 */
575 function media_type_page_title($type) {
576 return t('@type media type settings', array('@type' => $type->label));
577 }
578
579 /**
580 * Get all display types.
581 */
582 function media_display_types() {
583 $types = &drupal_static(__FUNCTION__);
584 if (!$types) {
585 $types = module_invoke_all('media_display_types');
586 drupal_alter('media_display_types', $types);
587 }
588 return $types;
589 }
590
591
592 /* ***************************************** */
593 /* Callbacks */
594 /* ***************************************** */
595
596 /**
597 * Process callback for the media_browser element.
598 *
599 * @param $element
600 * @param $edit
601 * @param $form_state
602 * @param $form
603 * @return array
604 */
605 function media_file_list_element_process($element, $edit, $form_state, $form) {
606 $element['list'] = array(
607 '#type' => 'select',
608 '#options' => $element['#options'],
609 '#size' => media_variable_get('file_list_size'),
610 );
611
612 return $element;
613 }
614
615 if (!function_exists('file_uri_to_object')) {
616 // @todo: get this committed http://drupal.org/node/685818
617
618 /**
619 * Returns a file object which can be passed to file_save().
620 *
621 * @param $uri
622 * A string containing the URI, path, or filename.
623 * @param $use_existing
624 * (Optional) If TRUE and there's an existing file in the {file_managed}
625 * table with the passed in URI, then that file object is returned.
626 * Otherwise, a new file object is returned.
627 * @return
628 * A file object, or FALSE on error.
629 */
630 function file_uri_to_object($uri, $use_existing = FALSE) {
631 if ($use_existing) {
632 $query = db_select('file_managed', 'f')
633 ->fields('f', array('fid'))
634 ->condition('uri', $uri)
635 ->execute()
636 ->fetchCol();
637 if (!empty($query)) {
638 $file = file_load(array_shift($query));
639 }
640 }
641 if (!isset($file)) {
642 global $user;
643 $uri = file_stream_wrapper_uri_normalize($uri);
644 $wrapper = file_stream_wrapper_get_instance_by_uri($uri);
645 $file = new StdClass;
646 $file->uid = $user->uid;
647 $file->filename = basename($uri);
648 $file->uri = $uri;
649 $file->filemime = file_get_mimetype($uri);
650 // This is gagged because some uris will not support it.
651 $file->filesize = @filesize($uri);
652 $file->timestamp = REQUEST_TIME;
653 $file->status = FILE_STATUS_PERMANENT;
654 $file->is_new = TRUE;
655 }
656 return $file;
657 }
658 }
659
660 /**
661 * Implements hook_library().
662 */
663 function media_library() {
664 $path = drupal_get_path('module', 'media');
665 $info = system_get_info('module', 'media');
666
667 $common = array(
668 'website' => 'http://drupal.org/project/media',
669 'version' => !empty($info['version']) ? $info['version'] : '7.x-1.x',
670 );
671
672 /**
673 * Contains libraries common to other media modules.
674 */
675 $libraries['media_base'] = array(
676 'title' => 'Media base',
677 'js' => array(
678 $path . '/js/media.core.js' => array('group' => JS_LIBRARY, 'weight' => - 5),
679 $path . '/js/util/json2.js' => array('group' => JS_LIBRARY),
680 $path . '/js/util/ba-debug.min.js' => array('group' => JS_LIBRARY),
681 ),
682 'css' => array(
683 $path . '/css/media.css',
684 ),
685 );
686
687 /**
688 * Includes resources needed to launch the media browser. Should be included
689 * on pages where the media browser needs to be launched from.
690 */
691 $libraries['media_browser'] = array(
692 'title' => 'Media Browser popup libraries',
693 'js' => array(
694 $path . '/js/media.popups.js' => array('group' => JS_DEFAULT),
695 ),
696 'dependencies' => array(
697 array('media', 'media_base'),
698 array('system', 'ui.resizable'),
699 array('system', 'ui.draggable'),
700 array('system', 'ui.dialog'),
701 ),
702 );
703
704 /**
705 * Resources needed in the media browser itself.
706 */
707 $libraries['media_browser_page'] = array(
708 'title' => 'Media browser',
709 'js' => array(
710 $path . '/js/media.browser.js' => array('group' => JS_DEFAULT),
711 ),
712 'css' => array(
713 $path . '/css/media.browser.css' => array('group' => CSS_DEFAULT),
714 ),
715 'dependencies' => array(
716 array('media', 'media_base'),
717 array('system', 'ui.tabs'),
718 array('system', 'ui.draggable'),
719 array('system', 'ui.dialog'),
720 ),
721 );
722
723 foreach ($libraries as &$library) {
724 $library += $common;
725 }
726 return $libraries;
727 }
728
729 /**
730 * Theme callback used to identify when we are in a popup dialog.
731 *
732 * We do this because most times the default theme will look terrible in the
733 * browser. So this will default to the administration theme, unless set otherwise.
734 *
735 * @return string
736 */
737 function media_dialog_get_theme_name() {
738 return media_variable_get('dialog_theme', variable_get('admin_theme'));
739 }
740
741 /**
742 * A wrapper around simplexml to retrieve a given XML file.
743 *
744 * @param $url
745 * The URL to the XML to retrieve.
746 * @param $display_errors
747 * Optional; if TRUE, then we'll display errors to the end user. They'll be
748 * logged to the watchdog in any case.
749 * @param $refresh
750 * Optional; if TRUE, then we'll force a new load of the XML. Otherwise,
751 * a cached version will be retrieved if possible.
752 * @return
753 * A fully populated object, or FALSE on an error.
754 */
755 function media_retrieve_xml($url, $display_errors = FALSE, $refresh = FALSE) {
756 module_load_include('inc', 'media', 'includes/media.xml');
757 return _media_retrieve_xml($url, $display_errors, $refresh);
758 }
759
760 /**
761 * This will parse a url or embedded code into a unique URI.
762 *
763 * The function will call all modules implementing hook_media_parse($url),
764 * which should return either a string containing a parsed URI or NULL.
765 *
766 * @NOTE The implementing modules may throw an error, which will not be caught
767 * here; it's up to the calling function to catch any thrown errors.
768 *
769 * @NOTE In emfield, we originally also accepted an array of regex patterns
770 * to match against. However, that module used a registration for providers,
771 * and simply stored the match in the database keyed to the provider object.
772 * However, other than the stream wrappers, there is currently no formal
773 * registration for media handling. Additionally, few, if any, stream wrappers
774 * will choose to store a straight match from the parsed URL directly into
775 * the URI. Thus, we leave both the matching and the final URI result to the
776 * implementing module in this implementation.
777 *
778 * An alternative might be to do the regex pattern matching here, and pass a
779 * successful match back to the implementing module. However, that would
780 * require either an overloaded function or a new hook, which seems like more
781 * overhead than it's worth at this point.
782 *
783 * @TODO Once hook_module_implements_alter() is in core (see the issue at
784 * http://drupal.org/node/692950) we may want to implement media_media_parse()
785 * to ensure we were passed a valid URL, rather than an unsupported or
786 * malformed embed code that wasn't caught earlier. It will needed to be
787 * weighted so it's called after all other streams have a go, as the fallback,
788 * and will need to throw an error.
789 *
790 * @param string $url
791 * The original URL or embed code to parse.
792 * @param optional string $form_field
793 * The field from FAPI when being validated, suitable for
794 * form_set_error(). If this is set, then a particular implementation
795 * may throw an error if it believes the URL to be malformed.
796 * @return
797 * The unique URI for the file, based on its stream wrapper, or NULL.
798 *
799 * @see media_parse_to_file()
800 * @see media_add_from_url_validate()
801 */
802 function media_parse_to_uri($url) {
803 // Trim any whitespace before parsing.
804 $url = trim($url);
805 foreach (module_implements('media_parse') as $module) {
806 $success = module_invoke($module, 'media_parse', $url);
807 if (isset($success)) {
808 return $success;
809 }
810 }
811 }
812
813 /**
814 * Parse a URL or embed code and return a file object.
815 *
816 * If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
817 * then we'll copy the file locally.
818 *
819 * @NOTE The implementing modules may throw an error, which will not be caught
820 * here; it's up to the calling function to catch any thrown errors.
821 *
822 * @see media_parse_to_uri()
823 * @see media_add_from_url_submit()
824 */
825 function media_parse_to_file($url) {
826 try {
827 $uri = media_parse_to_uri($url);
828 }
829 catch (Exception $e) {
830 // Pass the error along.
831 throw $e;
832 return;
833 }
834
835 if (isset($uri)) {
836 // Attempt to load an existing file from the unique URI.
837 $select = db_select('file_managed', 'f')
838 ->extend('PagerDefault')
839 ->fields('f', array('fid'))
840 ->condition('uri', $uri);
841
842 $fid = $select->execute()->fetchCol();
843 if (!empty($fid)) {
844 $file = file_load(array_pop($fid));
845 return $file;
846 }
847 }
848
849 if (isset($uri)) {
850 // The URL was successfully parsed to a URI, but does not yet have an
851 // associated file: save it!
852 $file = file_uri_to_object($uri);
853 file_save($file);
854 }
855 else {
856 // The URL wasn't parsed. We'll try to save a remote file.
857 // Copy to temporary first.
858 $source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
859 if (!@copy(@$url, $source_uri)) {
860 throw new Exception('Unable to add file ' . $url);
861 return;
862 }
863 $source_file = file_uri_to_object($source_uri);
864 $scheme = variable_get('file_default_scheme', 'public') . '://';
865 $uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);
866 // Now to its new home.
867 $file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
868 }
869
870 return $file;
871 }
872
873 /**
874 * Implements hook_element_info().
875 */
876 function media_element_info() {
877 $types = array();
878 $types['media'] = array(
879 '#input' => TRUE,
880 '#process' => array('media_element_process'),
881 //'#value_callback' => 'media_element_value',
882 '#element_validate' => array('media_element_validate'),
883 '#theme_wrappers' => array('container'),
884 '#progress_indicator' => 'throbber',
885 '#extended' => FALSE,
886 '#required' => FALSE,
887 '#media_options' => array(
888 'global' => array(
889 'types' => array(), // Example: array('image', 'audio');
890 'schemes' => array(), // Example: array('http', 'ftp', 'flickr');
891 ),
892 ),
893 '#attributes' => array(
894 'class' => array('media-widget'),
895 ),
896 '#attached' => array(
897 'library' => array(
898 array('media', 'media_browser'),
899 ),
900 ),
901 );
902 return $types;
903 }
904
905 /**
906 * #process callback for the media form element.
907 */
908 function media_element_process(&$element, &$form_state, $form) {
909 $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
910 $file = file_load($fid);
911 $path = drupal_get_path('module', 'media');
912
913 $element['title'] = array(
914 '#type' => 'item',
915 '#title' => $element['#title'],
916 '#markup' => '',
917 '#description' => $element['#description'],
918 '#required' => $element['#required'],
919 );
920
921 //@TODO: This should be loaded from the JS in case of a failed form submission.
922 $markup = '';
923 if (!empty($file)) {
924 $preview = media_get_thumbnail_preview($file);
925 $markup = drupal_render($preview);
926 }
927 $element['preview'] = array(
928 '#type' => 'item',
929 '#markup' => $markup,
930 '#prefix' => '<div class="preview launcher">',
931 '#suffix' => '</div><a class="button launcher" href="#">' . media_variable_get('field_select_media_text') . '</a><a class="button remove" href="#">' . media_variable_get('field_remove_media_text') . '</a>',
932 );
933
934 /**
935 * This section handles fields on media when media is added as a field.
936 * It is pretty unpolished, so hiding it for now.
937 */
938 // $element['more_fields_wrapper'] = array(
939 // '#type' => 'fieldset',
940 // '#collapsible' => TRUE,
941 // '#collapsed' => TRUE,
942 // '#title' => t('Meta-data'),
943 // );
944 //
945 // $element['more_fields_wrapper']['edit'] = array(
946 // '#type' => 'markup',
947 // '#markup' => l(t('Edit'), 'media/' . $fid . '/edit', array('query' => array('render' => 'media-popup'), 'attributes' => array('class'=> array('media-edit-link')))),
948 // );
949 //
950 // // Oh god, there must be a better way to add a wrapper.
951 // $parents = $element['#parents'];
952 // array_push($parents, 'more_fields');
953 //
954 // if ($file) {
955 // $element['more_fields_wrapper']['more_fields'] = file_view($file, 'media_preview');
956 // unset($element['more_fields_wrapper']['more_fields']['file']);
957 // }
958
959 //@HACK: @todo: this is so I can find it in media.js without putting every field in a settings variable.
960 // If I make it hidden (which it should be) it will go to the top of the form... I know this sucks.
961 // This is hidden in media.css
962 $element['fid'] = array(
963 '#type' => 'textfield',
964 '#default_value' => $fid,
965 '#attributes' => array('class' => array('fid')),
966 );
967
968 // Media browser attach code.
969 $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
970
971 $setting = array();
972 $setting['media']['elements'][$element['#id']] = $element['#media_options'];
973
974 $element['#attached']['js'][] = array(
975 'type' => 'setting',
976 'data' => $setting,
977 );
978
979 // hmm... Might need to think about this.
980 // All settings would likely apply to all media in a multi-value, but what about passing the existing fid?
981
982 module_load_include('inc', 'media', 'includes/media.browser');
983 media_attach_browser_js($element);
984
985 return $element;
986 // @todo: make this work for file and image fields
987 }
988
989 /**
990 * Validate media form elements. The file type is validated during the upload process, but this is
991 * necessary in order to respect the #required property.
992 */
993 function media_element_validate(&$element, &$form_state) {
994 if ($element['#required']) {
995 $field_name = $element['#field_name'];
996 $lang = $element['#language'];
997
998 $has_value = FALSE;
999 foreach ($form_state['values'][$field_name][$lang] as $value) {
1000 if ($value['fid']) {
1001 $has_value = TRUE;
1002 }
1003 }
1004 if (!$has_value) {
1005 form_error($element, t('%element_title is required.', array('%element_title' => $element['#title'])));
1006 }
1007 }
1008 }
1009
1010 /**
1011 * Implements hook_filter_info().
1012 *
1013 * For performance, the media filter is allowed to be cached by default. See
1014 * media_filter_invalidate_caches() for details. Some sites may use advanced
1015 * media styles with rendering implentations that differs per theme or based on
1016 * other runtime information. For these sites, it may be necessary to implement
1017 * a module with a hook_filter_info_alter() implementation that sets
1018 * $info['media_filter']['cache'] to FALSE.
1019 *
1020 * @see media_filter_invalidate_caches()
1021 */
1022 function media_filter_info() {
1023 $filters['media_filter'] = array(
1024 'title' => t('Convert Media tags to markup'),
1025 'description' => t('This filter will convert [[{type:media... ]] tags into markup.'),
1026 'process callback' => 'media_filter',
1027 'weight' => 2,
1028 'tips callback' => 'media_filter_tips', // @TODO not implemented
1029 );
1030
1031 // If the WYSIWYG module is enabled, add additional help.
1032 if (module_exists('wysiwyg')) {
1033 $filters['media_filter']['description'] .= ' ' . t('This must be enabled for the Media WYSIWYG integration to work with this input format.');
1034 }
1035
1036 return $filters;
1037 }
1038
1039 /**
1040 * Sets the status to FILE_STATUS_PERMANENT.
1041 *
1042 * @param $file
1043 * A file object.
1044 */
1045 function _media_save_file_permanently($file) {
1046 if ($file->status < FILE_STATUS_PERMANENT) {
1047 $file->status = FILE_STATUS_PERMANENT;
1048 file_save($file);
1049 }
1050 }
1051
1052 /**
1053 * Returns a renderable array with the necessary classes to support a media
1054 * thumbnail. Also provides default fallback images if no image is available.
1055 *
1056 * @param $file
1057 *
1058 * @return array
1059 * Renderable array.
1060 */
1061 function media_get_thumbnail_preview($file, $link = NULL) {
1062 // If a file has an invalid type, allow file_view_file() to work.
1063 if (!file_info_file_types($file->type)) {
1064 $file->type = media_get_type($file);
1065 }
1066
1067 $preview = file_view_file($file, 'media_preview');
1068 $preview['#show_names'] = TRUE;
1069 $preview['#add_link'] = $link;
1070 $preview['#theme_wrappers'][] = 'media_thumbnail';
1071 return $preview;
1072 }
1073
1074 /**
1075 * Check that the media is one of the selected types.
1076 *
1077 * @param $file
1078 * A Drupal file object.
1079 * @param $types
1080 * An array of media type names
1081 * @return
1082 * An array. If the file type is not allowed, it will contain an error
1083 * message.
1084 *
1085 * @see hook_file_validate()
1086 */
1087 function media_file_validate_types(stdClass $file, $types) {
1088 $errors = array();
1089 if (!in_array(media_get_type($file), $types)) {
1090 $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
1091 }
1092
1093 return $errors;
1094 }
1095
1096 /**
1097 * Implements hook_flush_caches().
1098 */
1099 function media_flush_caches() {
1100 // Garbage collection for the {media_filter_usage} table. If an fid was last
1101 // recorded four months ago (minimum three months due to logic in
1102 // media_filter_track_usage()), remove it from this table while the filter
1103 // and field caches are being cleared. If the fid is still in use, it will
1104 // be added back to the table the next time check_markup() runs on that
1105 // content. This prevents fids from staying in this table indefinitely,
1106 // even if the post that references them is edited or deleted.
1107 db_delete('media_filter_usage')->condition('timestamp', REQUEST_TIME - 86400 * 120, '<')->execute();
1108 }
1109
1110 /**
1111 * Implements hook_ctools_plugin_api().
1112 *
1113 * Lets CTools know which plugin APIs are implemented by Media module.
1114 */
1115 function media_ctools_plugin_api($owner, $api) {
1116 static $api_versions = array(
1117 'file_entity' => array(
1118 'file_default_displays' => 1,
1119 ),
1120 );
1121 if (isset($api_versions[$owner][$api])) {
1122 return array('version' => $api_versions[$owner][$api]);
1123 }
1124 }
1125
1126 /**
1127 * Helper function to get a list of hidden stream wrappers.
1128 *
1129 * This is used in several places to filter queries for media so that files in
1130 * temporary:// don't show up.
1131 */
1132 function media_get_hidden_stream_wrappers() {
1133 return array_diff_key(file_get_stream_wrappers(STREAM_WRAPPERS_ALL), file_get_stream_wrappers(STREAM_WRAPPERS_VISIBLE));
1134 }
1135
1136 /**
1137 * Helper function to get a list of local stream wrappers.
1138 */
1139 function media_get_local_stream_wrappers() {
1140 return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
1141 }
1142
1143 /**
1144 * Helper function to get a list of remote stream wrappers.
1145 */
1146 function media_get_remote_stream_wrappers() {
1147 $wrappers = file_get_stream_wrappers();
1148 $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
1149 $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
1150 return $wrappers;
1151 }
1152
1153 /**
1154 * Implements hook_views_api().
1155 */
1156 function media_views_api() {
1157 return array(
1158 'api' => 3,
1159 'path' => drupal_get_path('module', 'media') . '/includes',
1160 );
1161 }