8 * See http://drupal.org/project/media for more details.
11 /* ***************************************** */
13 /* ***************************************** */
15 // A registry of variable_get defaults.
16 require_once (dirname(__FILE__
) .
'/includes/media.variables.inc');
18 // Define media related file types and how to display them.
19 require_once (dirname(__FILE__
) .
'/includes/media.types.inc');
21 // Code relating to using media as a field.
22 require_once (dirname(__FILE__
) .
'/includes/media.fields.inc');
24 // Functions for working with [[inline tags]] and wysiwyg editors.
25 require_once (dirname(__FILE__
) .
'/includes/media.filter.inc');
27 /* ***************************************** */
28 /* Hook Implementations */
29 /* ***************************************** */
32 * Implements hook_hook_info().
34 function media_hook_info() {
36 'media_display_types',
37 'media_display_types_alter',
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',
49 return array_fill_keys($hooks, array('group' => 'media'));
53 * Implements hook_help().
55 function media_help($path, $arg) {
57 case
'admin/help#media':
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>';
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>';
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');
80 * Implements hook_entity_info_alter().
82 * Add view modes to the file entity type, appropriate for displaying media.
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
);
93 * Implement of hook_menu().
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',
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',
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',
127 // $items['admin/config/media/types/manage/%media_type/settings'] = array(
128 // 'title' => 'Settings',
129 // 'type' => MENU_DEFAULT_LOCAL_TASK,
133 // Administrative screens for managing media.
134 $items['admin/content/media'] = array(
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',
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',
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',
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',
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',
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',
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'),
210 'file' => 'includes/media.filter.inc',
211 'theme callback' => 'media_dialog_get_theme_name',
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',
222 $items['media/%file/view'] = array(
224 'type' => MENU_DEFAULT_LOCAL_TASK
,
228 $items['media/%file/edit'] = array(
230 'page callback' => 'media_page_edit',
231 'page arguments' => array(1),
232 'access callback' => 'media_access',
233 'access arguments' => array('edit'),
235 'type' => MENU_LOCAL_TASK
,
236 'context' => MENU_CONTEXT_PAGE
| MENU_CONTEXT_INLINE
,
237 'file' => 'includes/media.pages.inc',
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'),
247 'file' => 'includes/media.pages.inc',
250 $items['media/%file/delete'] = array(
252 'page callback' => 'media_page_delete',
253 'page arguments' => array(1),
254 'access callback' => 'media_access',
255 'access arguments' => array('edit'),
257 'type' => MENU_LOCAL_TASK
,
258 'context' => MENU_CONTEXT_PAGE
| MENU_CONTEXT_INLINE
,
259 'file' => 'includes/media.pages.inc',
266 * Implements hook_admin_paths().
268 function media_admin_paths() {
270 'media/*/edit' => TRUE
,
271 'media/*/multiedit' => TRUE
,
272 'media/*/delete' => TRUE
,
278 * Implements hook_permission().
280 function media_permission() {
282 'administer media' => array(
283 'title' => t('Administer media'),
284 'description' => t('Add, edit or delete media files and administer settings.'),
286 'import media' => array(
287 'title' => t('Import media files from the local filesystem'),
288 'description' => t('Simple file importer'),
290 'view media' => array(
291 'title' => t('View media'),
292 'description' => t('View all media files.'), // @TODO better description
294 'edit media' => array(
295 'title' => t('Edit media'),
296 'description' => t('Edit all media files.'), // @TODO better description
302 * Implements hook_theme().
304 * @TODO: Needs a major cleanup.
306 function media_theme() {
309 // The default media file list form element.
310 'media_file_list' => array(
311 'variables' => array('element' => NULL
),
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',
320 // A preview of the uploaded file.
321 'media_thumbnail' => array(
322 'render element' => 'element',
323 'file' => 'includes/media.theme.inc',
326 // Administrative thumbnail previews.
327 'media_admin_thumbnail' => array(
328 'variables' => array('file' => array(), 'style_name' => 'thumbnail'),
329 'file' => 'includes/media.theme.inc',
332 // Administrative thumbnail previews.
333 'media_admin_thumbnail_operations' => array(
334 'variables' => array('file' => NULL
),
335 'file' => 'includes/media.theme.inc',
338 // Tabs in the media browser.
339 'media_browser_tabs' => array(
340 'file' => 'includes/media.theme.inc',
344 'media_dialog_page' => array(
345 'render element' => 'page',
346 'template' => 'templates/media-dialog-page',
347 'file' => 'includes/media.theme.inc',
351 'media_element' => array(
352 'render element' => 'element',
353 'file' => 'includes/media.theme.inc',
356 'media_formatter_large_icon' => array(
357 'variables' => array('file' => NULL
, 'attributes' => array()),
358 'file' => 'includes/media.theme.inc',
364 * Implements hook_image_default_styles().
366 function media_image_default_styles() {
368 $styles['square_thumbnail'] = array(
371 'name' => 'image_scale_and_crop',
372 'data' => array('width' => 180, 'height' => 180),
381 * Implements hook_file_update().
383 function media_file_update($file) {
384 media_filter_invalidate_caches($file->fid
);
388 * Implements hook_file_delete().
390 function media_file_delete($file) {
391 db_delete('media_filter_usage')->condition('fid', $file->fid
)->execute();
395 * Implements hook_image_style_flush().
397 * This hook is invoked by Drupal core when cached image derivatives are no
400 * @see media_styles_style_flush()
401 * @see media_file_style_flush()
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();
409 * Implements hook_file_style_flush().
411 * This hook is invoked by the File Styles module in Styles 1.x.
413 * @see media_styles_style_flush()
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();
421 * Implements hook_styles_style_flush().
423 * This hook is invoked by the Styles module in Styles 2.x.
425 * @see media_file_style_flush()
427 function media_styles_style_flush($style) {
428 // When a style is flushed, clear the filter and field caches.
429 media_filter_invalidate_caches();
433 * Implements hook_page_alter().
435 * This is used to use our alternate template when ?render=media-popup is passed
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
);
448 if (isset($_GET['render']) && $_GET['render'] == 'media-popup') {
449 $page['#theme'] = 'media_dialog_page';
451 // Disable administration modules from adding output to the popup.
452 // @see http://drupal.org/node/914786
453 module_invoke_all('suppress');
455 foreach (element_children($page) as
$key) {
456 if ($key != 'content') {
464 * Implements hook_element_info_alter().
466 function media_element_info_alter(&$types) {
467 $types['text_format']['#pre_render'][] = 'media_pre_render_text_format';
471 * Implements hook_forms().
473 function media_forms($form_id, $args) {
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',
487 * Implements hook_form_FIELD_UI_FIELD_SETTINGS_FORM_alter().
489 * @todo: Respect field settings in 7.x-2.x and handle them in the media widget UI
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
;
503 * Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
505 * @todo: Respect field settings in 7.x-2.x and handle them in the media widget UI
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;
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.
528 * Implements hook_form_FORM_ID_alter().
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');
537 /* ***************************************** */
539 /* ***************************************** */
542 * Load callback for %media_multi placeholder in menu paths.
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'].
550 * An array of corresponding file entities.
552 function media_multi_load($fids) {
553 return file_load_multiple(explode(" ", $fids));
557 * Access callback for media assets.
559 function media_access($op) {
560 return (user_access('administer media') || user_access($op .
' media'));
564 * Implements hook_file_download_access().
566 function media_file_download_access($field, $entity_type, $entity) {
567 if ($entity_type == 'media') {
568 return media_access('view');
573 * Returns the type of the media file to be used as a page title.
575 function media_type_page_title($type) {
576 return t('@type media type settings', array('@type' => $type->label
));
580 * Get all display types.
582 function media_display_types() {
583 $types = &drupal_static(__FUNCTION__
);
585 $types = module_invoke_all('media_display_types');
586 drupal_alter('media_display_types', $types);
592 /* ***************************************** */
594 /* ***************************************** */
597 * Process callback for the media_browser element.
605 function media_file_list_element_process($element, $edit, $form_state, $form) {
606 $element['list'] = array(
608 '#options' => $element['#options'],
609 '#size' => media_variable_get('file_list_size'),
615 if (!function_exists('file_uri_to_object')) {
616 // @todo: get this committed http://drupal.org/node/685818
619 * Returns a file object which can be passed to file_save().
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.
628 * A file object, or FALSE on error.
630 function file_uri_to_object($uri, $use_existing = FALSE
) {
632 $query = db_select('file_managed', 'f')
633 ->fields('f', array('fid'))
634 ->condition('uri', $uri)
637 if (!empty($query)) {
638 $file = file_load(array_shift($query));
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);
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
;
661 * Implements hook_library().
663 function media_library() {
664 $path = drupal_get_path('module', 'media');
665 $info = system_get_info('module', 'media');
668 'website' => 'http://drupal.org/project/media',
669 'version' => !empty($info['version']) ?
$info['version'] : '7.x-1.x',
673 * Contains libraries common to other media modules.
675 $libraries['media_base'] = array(
676 'title' => 'Media base',
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
),
683 $path .
'/css/media.css',
688 * Includes resources needed to launch the media browser. Should be included
689 * on pages where the media browser needs to be launched from.
691 $libraries['media_browser'] = array(
692 'title' => 'Media Browser popup libraries',
694 $path .
'/js/media.popups.js' => array('group' => JS_DEFAULT
),
696 'dependencies' => array(
697 array('media', 'media_base'),
698 array('system', 'ui.resizable'),
699 array('system', 'ui.draggable'),
700 array('system', 'ui.dialog'),
705 * Resources needed in the media browser itself.
707 $libraries['media_browser_page'] = array(
708 'title' => 'Media browser',
710 $path .
'/js/media.browser.js' => array('group' => JS_DEFAULT
),
713 $path .
'/css/media.browser.css' => array('group' => CSS_DEFAULT
),
715 'dependencies' => array(
716 array('media', 'media_base'),
717 array('system', 'ui.tabs'),
718 array('system', 'ui.draggable'),
719 array('system', 'ui.dialog'),
723 foreach ($libraries as
&$library) {
730 * Theme callback used to identify when we are in a popup dialog.
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.
737 function media_dialog_get_theme_name() {
738 return media_variable_get('dialog_theme', variable_get('admin_theme'));
742 * A wrapper around simplexml to retrieve a given XML file.
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.
750 * Optional; if TRUE, then we'll force a new load of the XML. Otherwise,
751 * a cached version will be retrieved if possible.
753 * A fully populated object, or FALSE on an error.
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);
761 * This will parse a url or embedded code into a unique URI.
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.
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.
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.
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.
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.
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.
797 * The unique URI for the file, based on its stream wrapper, or NULL.
799 * @see media_parse_to_file()
800 * @see media_add_from_url_validate()
802 function media_parse_to_uri($url) {
803 // Trim any whitespace before parsing.
805 foreach (module_implements('media_parse') as
$module) {
806 $success = module_invoke($module, 'media_parse', $url);
807 if (isset($success)) {
814 * Parse a URL or embed code and return a file object.
816 * If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
817 * then we'll copy the file locally.
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.
822 * @see media_parse_to_uri()
823 * @see media_add_from_url_submit()
825 function media_parse_to_file($url) {
827 $uri = media_parse_to_uri($url);
829 catch (Exception
$e) {
830 // Pass the error along.
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);
842 $fid = $select->execute()->fetchCol();
844 $file = file_load(array_pop($fid));
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);
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);
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
);
874 * Implements hook_element_info().
876 function media_element_info() {
878 $types['media'] = array(
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(
889 'types' => array(), // Example: array('image', 'audio');
890 'schemes' => array(), // Example: array('http', 'ftp', 'flickr');
893 '#attributes' => array(
894 'class' => array('media-widget'),
896 '#attached' => array(
898 array('media', 'media_browser'),
906 * #process callback for the media form element.
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');
913 $element['title'] = array(
915 '#title' => $element['#title'],
917 '#description' => $element['#description'],
918 '#required' => $element['#required'],
921 //@TODO: This should be loaded from the JS in case of a failed form submission.
924 $preview = media_get_thumbnail_preview($file);
925 $markup = drupal_render($preview);
927 $element['preview'] = array(
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>',
935 * This section handles fields on media when media is added as a field.
936 * It is pretty unpolished, so hiding it for now.
938 // $element['more_fields_wrapper'] = array(
939 // '#type' => 'fieldset',
940 // '#collapsible' => TRUE,
941 // '#collapsed' => TRUE,
942 // '#title' => t('Meta-data'),
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')))),
950 // // Oh god, there must be a better way to add a wrapper.
951 // $parents = $element['#parents'];
952 // array_push($parents, 'more_fields');
955 // $element['more_fields_wrapper']['more_fields'] = file_view($file, 'media_preview');
956 // unset($element['more_fields_wrapper']['more_fields']['file']);
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')),
968 // Media browser attach code.
969 $element['#attached']['js'][] = drupal_get_path('module', 'media') .
'/js/media.js';
972 $setting['media']['elements'][$element['#id']] = $element['#media_options'];
974 $element['#attached']['js'][] = array(
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?
982 module_load_include('inc', 'media', 'includes/media.browser');
983 media_attach_browser_js($element);
986 // @todo: make this work for file and image fields
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.
993 function media_element_validate(&$element, &$form_state) {
994 if ($element['#required']) {
995 $field_name = $element['#field_name'];
996 $lang = $element['#language'];
999 foreach ($form_state['values'][$field_name][$lang] as
$value) {
1000 if ($value['fid']) {
1005 form_error($element, t('%element_title is required.', array('%element_title' => $element['#title'])));
1011 * Implements hook_filter_info().
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.
1020 * @see media_filter_invalidate_caches()
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',
1028 'tips callback' => 'media_filter_tips', // @TODO not implemented
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.');
1040 * Sets the status to FILE_STATUS_PERMANENT.
1045 function _media_save_file_permanently($file) {
1046 if ($file->status
< FILE_STATUS_PERMANENT
) {
1047 $file->status
= FILE_STATUS_PERMANENT
;
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.
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);
1067 $preview = file_view_file($file, 'media_preview');
1068 $preview['#show_names'] = TRUE
;
1069 $preview['#add_link'] = $link;
1070 $preview['#theme_wrappers'][] = 'media_thumbnail';
1075 * Check that the media is one of the selected types.
1078 * A Drupal file object.
1080 * An array of media type names
1082 * An array. If the file type is not allowed, it will contain an error
1085 * @see hook_file_validate()
1087 function media_file_validate_types(stdClass
$file, $types) {
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)));
1097 * Implements hook_flush_caches().
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();
1111 * Implements hook_ctools_plugin_api().
1113 * Lets CTools know which plugin APIs are implemented by Media module.
1115 function media_ctools_plugin_api($owner, $api) {
1116 static
$api_versions = array(
1117 'file_entity' => array(
1118 'file_default_displays' => 1,
1121 if (isset($api_versions[$owner][$api])) {
1122 return array('version' => $api_versions[$owner][$api]);
1127 * Helper function to get a list of hidden stream wrappers.
1129 * This is used in several places to filter queries for media so that files in
1130 * temporary:// don't show up.
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
));
1137 * Helper function to get a list of local stream wrappers.
1139 function media_get_local_stream_wrappers() {
1140 return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL
);
1144 * Helper function to get a list of remote stream wrappers.
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
));
1154 * Implements hook_views_api().
1156 function media_views_api() {
1159 'path' => drupal_get_path('module', 'media') .
'/includes',