Projet

Général

Profil

Paste
Télécharger (45,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / media.module @ ba09eb79

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
// Code relating to using media as a field.
12
require_once dirname(__FILE__) . '/includes/media.fields.inc';
13

    
14
/**
15
 * Implements hook_hook_info().
16
 */
17
function media_hook_info() {
18
  $hooks = array(
19
    'media_parse',
20
    'media_browser_plugin_info',
21
    'media_browser_plugin_info_alter',
22
    'media_browser_plugins_alter',
23
    'media_browser_params_alter',
24
    'query_media_browser_alter',
25
  );
26

    
27
  return array_fill_keys($hooks, array('group' => 'media'));
28
}
29

    
30
/**
31
 * Implements hook_help().
32
 */
33
function media_help($path, $arg) {
34
  switch ($path) {
35
    case 'admin/help#media':
36
      $output = '';
37
      $output .= '<h3>' . t('About') . '</h3>';
38
      $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>';
39
      $output .= '<h3>' . t('Uses') . '</h3>';
40
      $output .= '<dl>';
41
      $output .= '<dt>' . t('Media Repository') . '</dt>';
42
      $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>';
43
      $output .= '<dt>' . t('Attaching media assets to content types') . '</dt>';
44
      $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>';
45
      $output .= '<dt>' . t('Using media assets in WYSIWYG') . '</dt>';
46
      $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:');
47
      $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>';
48
      $output .= '<li>' . t('Enable the <em>Convert Media tags to markup</em> filter on the <a href="@input-format">Input format</a> you are using with the WYSIWYG profile.', array('@input-format' => url('admin/config/content/formats'))) . '</li></ul></dd>';
49
      return $output;
50
  }
51
}
52

    
53
/**
54
 * Implements hook_entity_info_alter().
55
 */
56
function media_entity_info_alter(&$entity_info) {
57
  // For sites that updated from Media 1.x, continue to provide these deprecated
58
  // view modes.
59
  // @see http://drupal.org/node/1051090
60
  if (variable_get('media_show_deprecated_view_modes', FALSE)) {
61
    $entity_info['file']['view modes']['media_link'] = array(
62
      'label' => t('Link'),
63
      'custom settings' => TRUE,
64
    );
65
    $entity_info['file']['view modes']['media_original'] = array(
66
      'label' => t('Original'),
67
      'custom settings' => TRUE,
68
    );
69
  }
70

    
71
  if (module_exists('entity_translation')) {
72
    $entity_info['file']['translation']['entity_translation']['class'] = 'MediaEntityTranslationHandler';
73
  }
74
}
75

    
76
/**
77
 * Implements hook_menu().
78
 */
79
function media_menu() {
80
  // For managing different types of media and the fields associated with them.
81
  $items['admin/config/media/browser'] = array(
82
    'title' => 'Media browser settings',
83
    'description' => 'Configure the behavior and display of the media browser.',
84
    'page callback' => 'drupal_get_form',
85
    'page arguments' => array('media_admin_config_browser'),
86
    'access arguments' => array('administer media browser'),
87
    'file' => 'includes/media.admin.inc',
88
  );
89

    
90
  // Administrative screens for managing media.
91
  $items['admin/content/file/thumbnails'] = array(
92
    'title' => 'Thumbnails',
93
    'description' => 'Manage files used on your site.',
94
    'page callback' => 'drupal_get_form',
95
    'page arguments' => array('file_entity_admin_file'),
96
    'access arguments' => array('administer files'),
97
    'type' => MENU_LOCAL_TASK,
98
    'file' => 'file_entity.admin.inc',
99
    'file path' => drupal_get_path('module', 'file_entity'),
100
    'weight' => 10,
101
  );
102

    
103
  $items['media/ajax'] = array(
104
    'page callback' => 'media_ajax_upload',
105
    'delivery callback' => 'ajax_deliver',
106
    'access arguments' => array('access content'),
107
    'theme callback' => 'ajax_base_page_theme',
108
    'type' => MENU_CALLBACK,
109
  );
110

    
111
  $items['media/browser'] = array(
112
    'title' => 'Media browser',
113
    'description' => 'Media Browser for picking media and uploading new media',
114
    'page callback' => 'media_browser',
115
    'access arguments' => array('access media browser'),
116
    'type' => MENU_CALLBACK,
117
    'file' => 'includes/media.browser.inc',
118
    'theme callback' => 'media_dialog_get_theme_name',
119
  );
120

    
121
  // A testbed to try out the media browser with different launch commands.
122
  $items['media/browser/testbed'] = array(
123
    'title' => 'Media Browser test',
124
    'description' => 'Make it easier to test media browser',
125
    'page callback' => 'drupal_get_form',
126
    'page arguments' => array('media_browser_testbed'),
127
    'access arguments' => array('administer files'),
128
    'type' => MENU_CALLBACK,
129
    'file' => 'includes/media.browser.inc',
130
  );
131

    
132
  // We could re-use the file/%file/edit path for the modal callback, but
133
  // it is just easier to use our own namespace here.
134
  $items['media/%file/edit/%ctools_js'] = array(
135
    'title' => 'Edit',
136
    'page callback' => 'drupal_get_form',
137
    'page arguments' => array('media_file_edit_modal', 1, 3),
138
    'access callback' => 'file_entity_access',
139
    'access arguments' => array('update', 1),
140
    'theme callback' => 'ajax_base_page_theme',
141
    'file' => 'includes/media.pages.inc',
142
    'type' => MENU_CALLBACK,
143
  );
144

    
145
  return $items;
146
}
147

    
148
/**
149
 * Implements hook_menu_local_tasks_alter().
150
 */
151
function media_menu_local_tasks_alter(&$data, $router_item, $root_path) {
152
  // Add action link to 'file/add' on 'admin/content/file/thumbnails' page.
153
  if ($root_path == 'admin/content/file/thumbnails') {
154
    $item = menu_get_item('file/add');
155
    if (!empty($item['access'])) {
156
      $data['actions']['output'][] = array(
157
        '#theme' => 'menu_local_action',
158
        '#link' => $item,
159
        '#weight' => $item['weight'],
160
      );
161
    }
162
  }
163
}
164

    
165
/**
166
 * Implements hook_admin_paths().
167
 */
168
function media_admin_paths() {
169
  $paths['media/*/edit/*'] = TRUE;
170
  $paths['media/*/format-form'] = TRUE;
171

    
172
  // If the media browser theme is set to the admin theme, ensure it gets set
173
  // as an admin path as well.
174
  $dialog_theme = variable_get('media_dialog_theme', '');
175
  if (empty($dialog_theme) || $dialog_theme == variable_get('admin_theme')) {
176
    $paths['media/browser'] = TRUE;
177
    $paths['media/browser/*'] = TRUE;
178
  }
179

    
180
  return $paths;
181
}
182

    
183
/**
184
 * Implements hook_permission().
185
 */
186
function media_permission() {
187
  return array(
188
    'administer media browser' => array(
189
      'title' => t('Administer media browser'),
190
      'description' => t('Access media browser settings.'),
191
    ),
192
    'access media browser' => array(
193
      'title' => t('Use the media browser'),
194
    ),
195
  );
196
}
197

    
198
/**
199
 * Implements hook_theme().
200
 */
201
function media_theme() {
202
  return array(
203
    // media.module.
204
    'media_element' => array(
205
      'render element' => 'element',
206
    ),
207

    
208
    // media.field.inc.
209
    'media_widget' => array(
210
      'render element' => 'element',
211
    ),
212
    'media_widget_multiple' => array(
213
      'render element' => 'element',
214
    ),
215
    'media_upload_help' => array(
216
      'variables' => array('description' => NULL),
217
    ),
218

    
219
    // media.theme.inc.
220
    'media_thumbnail' => array(
221
      'render element' => 'element',
222
      'file' => 'includes/media.theme.inc',
223
    ),
224
    'media_formatter_large_icon' => array(
225
      'variables' => array('file' => NULL, 'attributes' => array(), 'style_name' => 'media_thumbnail'),
226
      'file' => 'includes/media.theme.inc',
227
    ),
228
    'media_dialog_page' => array(
229
      'render element' => 'page',
230
      'template' => 'templates/media-dialog-page',
231
      'file' => 'includes/media.theme.inc',
232
    ),
233
  );
234
}
235

    
236
/**
237
 * Menu callback; Shared Ajax callback for media attachment and deletions.
238
 *
239
 * This rebuilds the form element for a particular field item. As long as the
240
 * form processing is properly encapsulated in the widget element the form
241
 * should rebuild correctly using FAPI without the need for additional callbacks
242
 * or processing.
243
 */
244
function media_ajax_upload() {
245
  $form_parents = func_get_args();
246
  $form_build_id = (string) array_pop($form_parents);
247

    
248
  if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
249
    // Invalid request.
250
    drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
251
    $commands = array();
252
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
253
    return array('#type' => 'ajax', '#commands' => $commands);
254
  }
255

    
256
  list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
257

    
258
  if (!$form) {
259
    // Invalid form_build_id.
260
    drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
261
    $commands = array();
262
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
263
    return array('#type' => 'ajax', '#commands' => $commands);
264
  }
265

    
266
  // Get the current element and count the number of files.
267
  $current_element = $form;
268
  foreach ($form_parents as $parent) {
269
    $current_element = $current_element[$parent];
270
  }
271
  $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
272

    
273
  // Process user input. $form and $form_state are modified in the process.
274
  drupal_process_form($form['#form_id'], $form, $form_state);
275

    
276
  // Retrieve the element to be rendered.
277
  foreach ($form_parents as $parent) {
278
    $form = $form[$parent];
279
  }
280

    
281
  // Add the special Ajax class if a new file was added.
282
  if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
283
    $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
284
  }
285
  // Otherwise just add the new content class on a placeholder.
286
  else {
287
    $form['#suffix'] .= '<span class="ajax-new-content"></span>';
288
  }
289

    
290
  $output = theme('status_messages') . drupal_render($form);
291
  $js = drupal_add_js();
292
  $settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
293

    
294
  $commands[] = ajax_command_replace(NULL, $output, $settings);
295
  return array('#type' => 'ajax', '#commands' => $commands);
296
}
297

    
298
/**
299
 * Implements hook_image_default_styles().
300
 */
301
function media_image_default_styles() {
302
  $styles = array();
303
  $styles['media_thumbnail'] = array(
304
    'label' => 'Media thumbnail (100x100)',
305
    'effects' => array(
306
      array(
307
        'name' => 'image_scale_and_crop',
308
        'data' => array('width' => 100, 'height' => 100),
309
        'weight' => 0,
310
      ),
311
    ),
312
  );
313
  return $styles;
314
}
315

    
316
/**
317
 * Implements hook_page_alter().
318
 *
319
 * This is used to use our alternate template when ?render=media-popup is passed
320
 * in the URL.
321
 */
322
function media_page_alter(&$page) {
323
  if (isset($_GET['render']) && $_GET['render'] == 'media-popup') {
324
    $page['#theme'] = 'media_dialog_page';
325

    
326
    // Disable administration modules from adding output to the popup.
327
    // @see http://drupal.org/node/914786
328
    module_invoke_all('suppress', TRUE);
329

    
330
    foreach (element_children($page) as $key) {
331
      if ($key != 'content') {
332
        unset($page[$key]);
333
      }
334
    }
335
  }
336
}
337

    
338
/**
339
 * Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
340
 *
341
 * @todo: Respect field settings in 7.x-2.x and handle them in the media widget
342
 * UI.
343
 */
344
function media_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
345
  // On file fields that use the media widget we need remove specific fields.
346
  if ($form['#field']['type'] == 'file' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
347
    $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
348
    $form['instance']['settings']['file_extensions']['#maxlength'] = 255;
349
  }
350

    
351
  // On image fields using the media widget we remove the alt/title fields.
352
  if ($form['#field']['type'] == 'image' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
353
    $form['instance']['settings']['alt_field']['#access'] = FALSE;
354
    $form['instance']['settings']['title_field']['#access'] = FALSE;
355
    $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
356
    // Do not increase maxlength of file extensions for image fields, since
357
    // presumably they will not need a long list of extensions.
358
  }
359

    
360
  // Add a validation function to any field instance which uses the media widget
361
  // to ensure that the upload destination scheme is one of the allowed schemes.
362
  if ($form['instance']['widget']['type']['#value'] == 'media_generic') {
363
    $form['#validate'][] = 'media_field_instance_validate';
364
  }
365

    
366
  if ($form['#instance']['entity_type'] == 'file') {
367
    $form['instance']['settings']['wysiwyg_override'] = array(
368
      '#type' => 'checkbox',
369
      '#title' => t('Override in WYSIWYG'),
370
      '#description' => t('If checked, then this field may be overridden in the WYSIWYG editor.'),
371
      '#default_value' => isset($form['#instance']['settings']['wysiwyg_override']) ? $form['#instance']['settings']['wysiwyg_override'] : TRUE,
372
    );
373
  }
374
}
375

    
376
/**
377
 * Validation handler; ensure that the upload destination scheme is one of the
378
 * allowed schemes.
379
 */
380
function media_field_instance_validate($form, &$form_state) {
381
  $allowed_schemes = $form_state['values']['instance']['widget']['settings']['allowed_schemes'];
382
  $upload_destination = $form_state['values']['field']['settings']['uri_scheme'];
383

    
384
  if (!in_array($upload_destination, array_filter($allowed_schemes))) {
385
    form_set_error('allowed_schemes', t('The upload destination must be one of the allowed schemes.'));
386
  }
387
}
388

    
389
/**
390
 * Implements hook_form_alter().
391
 */
392
function media_form_alter(&$form, &$form_state, $form_id) {
393
  // If we're in the media browser, set the #media_browser key to true
394
  // so that if an ajax request gets sent to a different path, the form
395
  // still uses the media_browser_form_submit callback.
396
  if (current_path() == 'media/browser' && $form_id != 'views_exposed_form') {
397
    $form_state['#media_browser'] = TRUE;
398
  }
399

    
400
  // If the #media_browser key isset and is true we are using the browser
401
  // popup, so add the media_browser submit handler.
402
  if (!empty($form_state['#media_browser'])) {
403
    $form['#submit'][] = 'media_browser_form_submit';
404
  }
405
}
406

    
407
/**
408
 * Submit handler; direction form submissions in the media browser.
409
 */
410
function media_browser_form_submit($form, &$form_state) {
411
  $url = NULL;
412
  $parameters = array();
413

    
414
  // Single upload.
415
  if (!empty($form_state['file'])) {
416
    $file = $form_state['file'];
417
    $url = 'media/browser';
418
    $parameters = array('query' => array('render' => 'media-popup', 'fid' => $file->fid));
419
  }
420

    
421
  // If $url is set, we had some sort of upload, so redirect the form.
422
  if (!empty($url)) {
423
    $form_state['redirect'] = array($url, $parameters);
424
  }
425
}
426

    
427
/**
428
 * Implements hook_library().
429
 */
430
function media_library() {
431
  $path = drupal_get_path('module', 'media');
432
  $info = system_get_info('module', 'media');
433

    
434
  $common = array(
435
    'website' => 'http://drupal.org/project/media',
436
    'version' => !empty($info['version']) ? $info['version'] : '7.x-2.x',
437
  );
438

    
439
  // Contains libraries common to other media modules.
440
  $libraries['media_base'] = array(
441
    'title' => 'Media base',
442
    'js' => array(
443
      $path . '/js/media.core.js' => array('group' => JS_LIBRARY, 'weight' => -5),
444
      $path . '/js/util/json2.js' => array('group' => JS_LIBRARY),
445
      $path . '/js/util/ba-debug.min.js' => array('group' => JS_LIBRARY),
446
    ),
447
    'css' => array(
448
      $path . '/css/media.css',
449
    ),
450
  );
451

    
452
  // Includes resources needed to launch the media browser.  Should be included
453
  // on pages where the media browser needs to be launched from.
454
  $libraries['media_browser'] = array(
455
    'title' => 'Media Browser popup libraries',
456
    'js' => array(
457
      $path . '/js/media.popups.js' => array('group' => JS_DEFAULT),
458
    ),
459
    'dependencies' => array(
460
      array('system', 'ui.resizable'),
461
      array('system', 'ui.draggable'),
462
      array('system', 'ui.dialog'),
463
      array('media', 'media_base'),
464
    ),
465
  );
466

    
467
  // Resources needed in the media browser itself.
468
  $libraries['media_browser_page'] = array(
469
    'title' => 'Media browser',
470
    'js' => array(
471
      $path . '/js/media.browser.js'  => array('group' => JS_DEFAULT),
472
    ),
473
    'dependencies' => array(
474
      array('system', 'ui.tabs'),
475
      array('system', 'ui.draggable'),
476
      array('system', 'ui.dialog'),
477
      array('media', 'media_base'),
478
    ),
479
  );
480

    
481
  foreach ($libraries as &$library) {
482
    $library += $common;
483
  }
484
  return $libraries;
485
}
486

    
487
/**
488
 * Theme callback used to identify when we are in a popup dialog.
489
 *
490
 * Generally the default theme will look terrible in the media browser. This
491
 * will default to the administration theme, unless set otherwise.
492
 */
493
function media_dialog_get_theme_name() {
494
  return variable_get('media_dialog_theme', variable_get('admin_theme'));
495
}
496

    
497
/**
498
 * This will parse a url or embedded code into a unique URI.
499
 *
500
 * The function will call all modules implementing hook_media_parse($url),
501
 * which should return either a string containing a parsed URI or NULL.
502
 *
503
 * @NOTE The implementing modules may throw an error, which will not be caught
504
 * here; it's up to the calling function to catch any thrown errors.
505
 *
506
 * @NOTE In emfield, we originally also accepted an array of regex patterns
507
 * to match against. However, that module used a registration for providers,
508
 * and simply stored the match in the database keyed to the provider object.
509
 * However, other than the stream wrappers, there is currently no formal
510
 * registration for media handling. Additionally, few, if any, stream wrappers
511
 * will choose to store a straight match from the parsed URL directly into
512
 * the URI. Thus, we leave both the matching and the final URI result to the
513
 * implementing module in this implementation.
514
 *
515
 * An alternative might be to do the regex pattern matching here, and pass a
516
 * successful match back to the implementing module. However, that would
517
 * require either an overloaded function or a new hook, which seems like more
518
 * overhead than it's worth at this point.
519
 *
520
 * @TODO Once hook_module_implements_alter() is in core (see the issue at
521
 * http://drupal.org/node/692950) we may want to implement media_media_parse()
522
 * to ensure we were passed a valid URL, rather than an unsupported or
523
 * malformed embed code that wasn't caught earlier. It will needed to be
524
 * weighted so it's called after all other streams have a go, as the fallback,
525
 * and will need to throw an error.
526
 *
527
 * @param string $url
528
 *   The original URL or embed code to parse.
529
 *
530
 * @return string
531
 *   The unique URI for the file, based on its stream wrapper, or NULL.
532
 *
533
 * @see media_parse_to_file()
534
 * @see media_add_from_url_validate()
535
 */
536
function media_parse_to_uri($url) {
537
  // Trim any whitespace before parsing.
538
  $url = trim($url);
539
  foreach (module_implements('media_parse') as $module) {
540
    $success = module_invoke($module, 'media_parse', $url);
541
    if (isset($success)) {
542
      return $success;
543
    }
544
  }
545
}
546

    
547
/**
548
 * Parse a URL or embed code and return a file object.
549
 *
550
 * If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
551
 * then we'll copy the file locally.
552
 *
553
 * @NOTE The implementing modules may throw an error, which will not be caught
554
 * here; it's up to the calling function to catch any thrown errors.
555
 *
556
 * @see media_parse_to_uri()
557
 * @see media_add_from_url_submit()
558
 */
559
function media_parse_to_file($url) {
560
  try {
561
    $uri = media_parse_to_uri($url);
562
  }
563
  catch (Exception $e) {
564
    // Pass the error along.
565
    throw $e;
566
    return;
567
  }
568

    
569
  if (isset($uri)) {
570
    // Attempt to load an existing file from the unique URI.
571
    $select = db_select('file_managed', 'f')
572
    ->extend('PagerDefault')
573
    ->fields('f', array('fid'))
574
    ->condition('uri', $uri);
575

    
576
    $fid = $select->execute()->fetchCol();
577
    if (!empty($fid)) {
578
      $file = file_load(array_pop($fid));
579
      return $file;
580
    }
581
  }
582

    
583
  if (isset($uri)) {
584
    // The URL was successfully parsed to a URI, but does not yet have an
585
    // associated file: save it!
586
    $file = file_uri_to_object($uri);
587
    file_save($file);
588
  }
589
  else {
590
    // The URL wasn't parsed. We'll try to save a remote file.
591
    // Copy to temporary first.
592
    $source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
593
    if (!@copy(@$url, $source_uri)) {
594
      throw new Exception('Unable to add file ' . $url);
595
      return;
596
    }
597
    $source_file = file_uri_to_object($source_uri);
598
    $scheme = variable_get('file_default_scheme', 'public') . '://';
599
    $uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);
600
    // Now to its new home.
601
    $file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
602
  }
603

    
604
  return $file;
605
}
606

    
607
/**
608
 * Utility function to recursively run check_plain on an array.
609
 *
610
 * @todo There is probably something in core I am not aware of that does this.
611
 */
612
function media_recursive_check_plain(&$value, $key) {
613
  $value = check_plain($value);
614
}
615

    
616
/**
617
 * Implements hook_element_info().
618
 */
619
function media_element_info() {
620
  $types['media'] = array(
621
    '#input' => TRUE,
622
    '#process' => array('media_element_process'),
623
    '#value_callback' => 'media_file_value',
624
    '#element_validate' => array('media_element_validate'),
625
    '#pre_render' => array('media_element_pre_render'),
626
    '#theme' => 'media_element',
627
    '#theme_wrappers' => array('form_element'),
628
    '#size' => 22,
629
    '#extended' => FALSE,
630
    '#media_options' => array(
631
      'global' => array(
632
        // Example: array('image', 'audio');
633
        'types' => array(),
634
        // Example: array('http', 'ftp', 'flickr');
635
        'schemes' => array(),
636
      ),
637
    ),
638
    '#attached' => array(
639
      'library' => array(
640
        array('media', 'media_browser'),
641
      ),
642
    ),
643
  );
644

    
645
  $setting = array();
646
  $setting['media']['global'] = $types['media']['#media_options'];
647

    
648
  $types['media']['#attached']['js'][] = array(
649
    'type' => 'setting',
650
    'data' => $setting,
651
  );
652

    
653
  return $types;
654
}
655

    
656
/**
657
 * Process callback for the media form element.
658
 */
659
function media_element_process($element, &$form_state, $form) {
660
  ctools_include('modal');
661
  ctools_include('ajax');
662
  ctools_modal_add_js();
663
  $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
664

    
665
  // Set some default element properties.
666
  $element['#file'] = $fid ? file_load($fid) : FALSE;
667
  $element['#tree'] = TRUE;
668

    
669
  $ajax_settings = array(
670
    'path' => 'media/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
671
    'wrapper' => $element['#id'] . '-ajax-wrapper',
672
    'effect' => 'fade',
673
  );
674

    
675
  // Set up the buttons first since we need to check if they were clicked.
676
  $element['attach_button'] = array(
677
    '#name' => implode('_', $element['#parents']) . '_attach_button',
678
    '#type' => 'submit',
679
    '#value' => t('Attach'),
680
    '#validate' => array(),
681
    '#submit' => array('media_file_submit'),
682
    '#limit_validation_errors' => array($element['#parents']),
683
    '#ajax' => $ajax_settings,
684
    '#attributes' => array('class' => array('attach')),
685
    '#weight' => -1,
686
  );
687

    
688
  $element['preview'] = array(
689
    'content' => array(),
690
    '#prefix' => '<div class="preview">',
691
    '#suffix' => '</div>',
692
    '#ajax' => $ajax_settings,
693
    '#weight' => -10,
694
  );
695

    
696
  // Substitute the JS preview for a true file thumbnail once the file is
697
  // attached.
698
  if ($fid && $element['#file']) {
699
    $element['preview']['content'] = media_get_thumbnail_preview($element['#file']);
700
  }
701

    
702
  // The file ID field itself.
703
  $element['upload'] = array(
704
    '#name' => 'media[' . implode('_', $element['#parents']) . ']',
705
    '#type' => 'textfield',
706
    '#title' => t('Enter the ID of an existing file'),
707
    '#title_display' => 'invisible',
708
    '#field_prefix' => t('File ID'),
709
    '#size' => $element['#size'],
710
    '#theme_wrappers' => array(),
711
    '#attributes' => array('class' => array('upload')),
712
    '#weight' => -9,
713
  );
714

    
715
  $element['browse_button'] = array(
716
    '#type' => 'link',
717
    '#href' => '',
718
    '#title' => t('Browse'),
719
    '#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
720
    '#options' => array('fragment' => FALSE, 'external' => TRUE),
721
    '#weight' => -8,
722
  );
723

    
724
  // Force the progress indicator for the remove button to be either 'none' or
725
  // 'throbber', even if the upload button is using something else.
726
  $ajax_settings['progress']['type'] = 'throbber';
727
  $ajax_settings['progress']['message'] = NULL;
728
  $ajax_settings['effect'] = 'none';
729
  $element['edit'] = array(
730
    '#type' => 'link',
731
    '#href' => 'media/' . $fid . '/edit/nojs',
732
    '#title' => t('Edit'),
733
    '#attributes' => array(
734
      'class' => array(
735
        // Required for CTools modal to work.
736
        'ctools-use-modal', 'use-ajax',
737
        'ctools-modal-media-file-edit', 'button', 'edit',
738
      ),
739
    ),
740
    '#weight' => 20,
741
    '#access' => $element['#file'] ? file_entity_access('update', $element['#file']) : FALSE,
742
  );
743
  $element['remove_button'] = array(
744
    '#name' => implode('_', $element['#parents']) . '_remove_button',
745
    '#type' => 'submit',
746
    '#value' => t('Remove'),
747
    '#validate' => array(),
748
    '#submit' => array('media_file_submit'),
749
    '#limit_validation_errors' => array($element['#parents']),
750
    '#ajax' => $ajax_settings,
751
    '#attributes' => array('class' => array('remove')),
752
    '#weight' => 0,
753
  );
754

    
755
  $element['fid'] = array(
756
    '#type' => 'hidden',
757
    '#value' => $fid,
758
    '#attributes' => array('class' => array('fid')),
759
  );
760

    
761
  // Media browser attach code.
762
  $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
763

    
764
  // Add the media options to the page as JavaScript settings.
765
  $element['browse_button']['#attached']['js'] = array(
766
    array(
767
      'type' => 'setting',
768
      'data' => array('media' => array('elements' => array('#' . $element['#id'] => $element['#media_options'])))
769
    )
770
  );
771

    
772
  module_load_include('inc', 'media', 'includes/media.browser');
773
  media_attach_browser_js($element);
774

    
775
  // Prefix and suffix used for Ajax replacement.
776
  $element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
777
  $element['#suffix'] = '</div>';
778

    
779
  return $element;
780
}
781

    
782
/**
783
 * Implements hook_form_FORM_ID_alter().
784
 */
785
function media_form_file_entity_edit_alter(&$form, &$form_state) {
786
  // Make adjustments to the file edit form when used in a CTools modal.
787
  if (!empty($form_state['ajax'])) {
788
    // Remove the preview and the delete button.
789
    $form['preview']['#access'] = FALSE;
790
    $form['actions']['delete']['#access'] = FALSE;
791

    
792
    // Convert the cancel link to a button which triggers a modal close.
793
    $form['actions']['cancel']['#attributes']['class'][] = 'button';
794
    $form['actions']['cancel']['#attributes']['class'][] = 'button-no';
795
    $form['actions']['cancel']['#attributes']['class'][] = 'ctools-close-modal';
796
  }
797
}
798

    
799
/**
800
 * The #value_callback for a media type element.
801
 */
802
function media_file_value(&$element, $input = FALSE, $form_state = NULL) {
803
  $fid = 0;
804

    
805
  // Find the current value of this field from the form state.
806
  $form_state_fid = $form_state['values'];
807
  foreach ($element['#parents'] as $parent) {
808
    $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
809
  }
810

    
811
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
812
    $fid = $form_state_fid['fid'];
813
  }
814
  elseif (is_numeric($form_state_fid)) {
815
    $fid = $form_state_fid;
816
  }
817

    
818
  // Process any input and attach files.
819
  if ($input !== FALSE) {
820
    $return = $input;
821

    
822
    // Attachments take priority over all other values.
823
    if ($file = media_attach_file($element)) {
824
      $fid = $file->fid;
825
    }
826
    else {
827
      // Check for #filefield_value_callback values.
828
      // Because FAPI does not allow multiple #value_callback values like it
829
      // does for #element_validate and #process, this fills the missing
830
      // functionality to allow File fields to be extended through FAPI.
831
      if (isset($element['#file_value_callbacks'])) {
832
        foreach ($element['#file_value_callbacks'] as $callback) {
833
          $callback($element, $input, $form_state);
834
        }
835
      }
836
      // Load file if the FID has changed to confirm it exists.
837
      if (isset($input['fid']) && $file = file_load($input['fid'])) {
838
        $fid = $file->fid;
839
      }
840
    }
841
  }
842

    
843
  // If there is no input, set the default value.
844
  else {
845
    if ($element['#extended']) {
846
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
847
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
848
    }
849
    else {
850
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
851
      $return = array('fid' => 0);
852
    }
853

    
854
    // Confirm that the file exists when used as a default value.
855
    if ($default_fid && $file = file_load($default_fid)) {
856
      $fid = $file->fid;
857
    }
858
  }
859

    
860
  $return['fid'] = $fid;
861

    
862
  return $return;
863
}
864

    
865
/**
866
 * Validate media form elements.
867
 *
868
 * The file type is validated during the upload process, but this is necessary
869
 * necessary in order to respect the #required property.
870
 */
871
function media_element_validate(&$element, &$form_state) {
872
  $clicked_button = end($form_state['triggering_element']['#parents']);
873

    
874
  // Check required property based on the FID.
875
  if ($element['#required'] && empty($element['fid']['#value']) && !in_array($clicked_button, array('attach_button', 'remove_button'))) {
876
    form_error($element['browse_button'], t('!name field is required.', array('!name' => $element['#title'])));
877
  }
878

    
879
  // Consolidate the array value of this field to a single FID.
880
  if (!$element['#extended']) {
881
    form_set_value($element, $element['fid']['#value'], $form_state);
882
  }
883
}
884

    
885
/**
886
 * Form submission handler for attach / remove buttons of media elements.
887
 *
888
 * @see media_element_process()
889
 */
890
function media_file_submit($form, &$form_state) {
891
  // Determine whether it was the attach or remove button that was clicked, and
892
  // set $element to the managed_file element that contains that button.
893
  $parents = $form_state['triggering_element']['#array_parents'];
894
  $button_key = array_pop($parents);
895
  $element = drupal_array_get_nested_value($form, $parents);
896

    
897
  // No action is needed here for the attach button, because all media
898
  // attachments on the form are processed by media_file_value() regardless of
899
  // which button was clicked. Action is needed here for the remove button,
900
  // because we only remove a file in response to its remove button being
901
  // clicked.
902
  if ($button_key == 'remove_button') {
903
    // If it's a temporary file we can safely remove it immediately, otherwise
904
    // it's up to the implementing module to clean up files that are in use.
905
    if ($element['#file'] && $element['#file']->status == 0) {
906
      file_delete($element['#file']);
907
    }
908
    // Update both $form_state['values'] and $form_state['input'] to reflect
909
    // that the file has been removed, so that the form is rebuilt correctly.
910
    // $form_state['values'] must be updated in case additional submit handlers
911
    // run, and for form building functions that run during the rebuild, such as
912
    // when the media element is part of a field widget.
913
    // $form_state['input'] must be updated so that media_file_value() has
914
    // correct information during the rebuild.
915
    $values_element = $element['#extended'] ? $element['fid'] : $element;
916
    form_set_value($values_element, NULL, $form_state);
917
    drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
918
  }
919

    
920
  // Set the form to rebuild so that $form is correctly updated in response to
921
  // processing the file removal. Since this function did not change $form_state
922
  // if the upload button was clicked, a rebuild isn't necessary in that
923
  // situation and setting $form_state['redirect'] to FALSE would suffice.
924
  // However, we choose to always rebuild, to keep the form processing workflow
925
  // consistent between the two buttons.
926
  $form_state['rebuild'] = TRUE;
927
}
928

    
929
/**
930
 * Attaches any files that have been referenced by a media element.
931
 *
932
 * @param $element
933
 *   The FAPI element whose files are being attached.
934
 *
935
 * @return
936
 *   The file object representing the file that was attached, or FALSE if no
937
 *   file was attached.
938
 */
939
function media_attach_file($element) {
940
  $upload_name = implode('_', $element['#parents']);
941
  if (empty($_POST['media'][$upload_name])) {
942
    return FALSE;
943
  }
944

    
945
  if (!$file = file_load($_POST['media'][$upload_name])) {
946
    watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
947
    form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
948
    return FALSE;
949
  }
950

    
951
  return $file;
952
}
953

    
954
/**
955
 * Returns HTML for a managed file element.
956
 *
957
 * @param $variables
958
 *   An associative array containing:
959
 *   - element: A render element representing the file.
960
 *
961
 * @ingroup themeable
962
 */
963
function theme_media_element($variables) {
964
  $element = $variables['element'];
965

    
966
  $attributes = array();
967
  if (isset($element['#id'])) {
968
    $attributes['id'] = $element['#id'];
969
  }
970
  if (!empty($element['#attributes']['class'])) {
971
    $attributes['class'] = (array) $element['#attributes']['class'];
972
  }
973
  $attributes['class'][] = 'form-media';
974

    
975
  // This wrapper is required to apply JS behaviors and CSS styling.
976
  $output = '';
977
  $output .= '<div' . drupal_attributes($attributes) . '>';
978
  $output .= drupal_render_children($element);
979
  $output .= '</div>';
980
  return $output;
981
}
982

    
983
/**
984
 * #pre_render callback to hide display of the browse/attach or remove controls.
985
 *
986
 * Browse/attach controls are hidden when a file is already attached.
987
 * Remove controls are hidden when there is no file attached. Controls are
988
 * hidden here instead of in media_element_process(), because #access for these
989
 * buttons depends on the media element's #value. See the documentation of
990
 * form_builder() for more detailed information about the relationship between
991
 * #process, #value, and #access.
992
 *
993
 * Because #access is set here, it affects display only and does not prevent
994
 * JavaScript or other untrusted code from submitting the form as though access
995
 * were enabled. The form processing functions for these elements should not
996
 * assume that the buttons can't be "clicked" just because they are not
997
 * displayed.
998
 *
999
 * @see media_element_process()
1000
 * @see form_builder()
1001
 */
1002
function media_element_pre_render($element) {
1003
  // If we already have a file, we don't want to show the browse and attach
1004
  // controls.
1005
  if (!empty($element['#value']['fid'])) {
1006
    $element['upload']['#access'] = FALSE;
1007
    $element['browse_button']['#access'] = FALSE;
1008
    $element['attach_button']['#access'] = FALSE;
1009
  }
1010
  // If we don't already have a file, there is nothing to remove.
1011
  else {
1012
    $element['remove_button']['#access'] = FALSE;
1013
  }
1014
  return $element;
1015
}
1016

    
1017
/**
1018
 * Media thumbnail render function.
1019
 *
1020
 * Returns a renderable array with the necessary classes to support a media
1021
 * thumbnail. Also provides default fallback images if no image is available.
1022
 *
1023
 * @param object $file
1024
 *   A Drupal file object.
1025
 *
1026
 * @return array
1027
 *   Renderable array.
1028
 */
1029
function media_get_thumbnail_preview($file, $link = NULL) {
1030
  // If a file has an invalid type, allow file_view_file() to work.
1031
  if (!file_type_is_enabled($file->type)) {
1032
    $file->type = file_get_type($file);
1033
  }
1034

    
1035
  $preview = file_view_file($file, 'preview');
1036
  $preview['#show_names'] = TRUE;
1037
  $preview['#add_link'] = $link;
1038
  $preview['#theme_wrappers'][] = 'media_thumbnail';
1039
  $preview['#attached']['css'][] = drupal_get_path('module', 'media') . '/css/media.css';
1040
  return $preview;
1041
}
1042

    
1043
/**
1044
 * Check that the media is one of the selected types.
1045
 *
1046
 * @param object $file
1047
 *   A Drupal file object.
1048
 * @param array $types
1049
 *   An array of media type names
1050
 *
1051
 * @return array
1052
 *   If the file type is not allowed, it will contain an error message.
1053
 *
1054
 * @see hook_file_validate()
1055
 */
1056
function media_file_validate_types($file, $types) {
1057
  $errors = array();
1058
  if (!in_array(file_get_type($file), $types)) {
1059
    $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
1060
  }
1061

    
1062
  return $errors;
1063
}
1064

    
1065
/**
1066
 * Implements hook_file_displays_alter().
1067
 */
1068
function media_file_displays_alter(&$displays, $file, $view_mode) {
1069
  if ($view_mode == 'preview' && empty($displays)) {
1070
    // We re in the media browser and this file has no formatters enabled.
1071
    // Instead of letting it go through theme_file_link(), pass it through
1072
    // theme_media_formatter_large_icon() to get our cool file icon instead.
1073
    $displays['file_field_media_large_icon'] = array(
1074
      'weight' => 0,
1075
      'status' => 1,
1076
      'settings' => NULL,
1077
    );
1078
  }
1079

    
1080
  // Override the fields of the file when requested by the WYSIWYG.
1081
  if (isset($file->override) && isset($file->override['fields'])) {
1082
    $instance = field_info_instances('file', $file->type);
1083
    foreach ($file->override['fields'] as $field_name => $value) {
1084
      if (!isset($instance[$field_name]['settings']) || !isset($instance[$field_name]['settings']['wysiwyg_override']) || $instance[$field_name]['settings']['wysiwyg_override']) {
1085
        $file->{$field_name} = $value;}
1086
    }
1087
  }
1088

    
1089
  // Alt and title are special.
1090
  // @see file_entity_file_load
1091
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
1092
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
1093

    
1094
  $replace_options = array(
1095
    'clear' => TRUE,
1096
    'sanitize' => FALSE,
1097
  );
1098

    
1099
  // Load alt and title text from fields.
1100
  if (!empty($alt)) {
1101
    $file->alt = token_replace($alt, array('file' => $file), $replace_options);
1102
  }
1103
  if (!empty($title)) {
1104
    $file->title = token_replace($title, array('file' => $file), $replace_options);
1105
  }
1106
}
1107

    
1108
/**
1109
 * For sanity in grammar.
1110
 *
1111
 * @see media_set_browser_params()
1112
 */
1113
function media_get_browser_params() {
1114
  return media_set_browser_params();
1115
}
1116

    
1117
/**
1118
 * Provides a singleton of the params passed to the media browser.
1119
 *
1120
 * This is useful in situations like form alters because callers can pass
1121
 * id="wysiywg_form" or whatever they want, and a form alter could pick this up.
1122
 * We may want to change the hook_media_browser_plugin_view() implementations to
1123
 * use this function instead of being passed params for consistency.
1124
 *
1125
 * It also offers a chance for some meddler to meddle with them.
1126
 *
1127
 * @see media_browser()
1128
 */
1129
function media_set_browser_params() {
1130
  $params = &drupal_static(__FUNCTION__, array());
1131

    
1132
  if (empty($params)) {
1133
    // Build out browser settings. Permissions- and security-related behaviors
1134
    // should not rely on these parameters, since they come from the HTTP query.
1135
    // @TODO make sure we treat parameters as user input.
1136
    $params = drupal_get_query_parameters() + array(
1137
        'types' => array(),
1138
        'multiselect' => FALSE,
1139
      );
1140

    
1141
    // Transform text 'true' and 'false' to actual booleans.
1142
    foreach ($params as $k => $v) {
1143
      if ($v === 'true') {
1144
        $params[$k] = TRUE;
1145
      }
1146
      elseif ($v === 'false') {
1147
        $params[$k] = FALSE;
1148
      }
1149
    }
1150

    
1151
    array_walk_recursive($params, 'media_recursive_check_plain');
1152

    
1153
    // Allow modules to alter the parameters.
1154
    drupal_alter('media_browser_params', $params);
1155
  }
1156

    
1157
  return $params;
1158
}
1159

    
1160
/**
1161
 * Implements hook_ctools_plugin_api().
1162
 *
1163
 * Lets CTools know which plugin APIs are implemented by Media module.
1164
 */
1165
function media_ctools_plugin_api($module, $api) {
1166
  if ($module == 'file_entity' && $api == 'file_default_displays') {
1167
    return array(
1168
      'version' => 1,
1169
    );
1170
  }
1171
}
1172

    
1173
/**
1174
 * Implements hook_form_FORM_ID_alter().
1175
 *
1176
 * This alter enhances the default admin/content/file page, addding JS and CSS.
1177
 * It also makes modifications to the thumbnail view by replacing the existing
1178
 * checkboxes and table with thumbnails.
1179
 */
1180
function media_form_file_entity_admin_file_alter(&$form, $form_state) {
1181
  if (!empty($form_state['values']['operation'])) {
1182
    // The form is being rebuilt because an operation requiring confirmation
1183
    // We don't want to be messing with it in this case.
1184
    return;
1185
  }
1186

    
1187
  // Add the "Add file" local action, and notify users if they have files
1188
  // selected and they try to switch between the "Thumbnail" and "List" local
1189
  // tasks.
1190
  $path = drupal_get_path('module', 'media');
1191
  $form['#attributes']['class'][] = 'file-entity-admin-file-form';
1192
  $form['#attached']['js'][] = $path . '/js/media.admin.js';
1193
  $form['#attached']['css'][] = $path . '/css/media.css';
1194

    
1195
  // By default, this form contains a table select element called "files". For
1196
  // the 'thumbnails' tab, Media generates a thumbnail for each file and
1197
  // replaces the tableselect with a grid of thumbnails.
1198
  if (arg(3) == 'thumbnails') {
1199
    if (empty($form['admin']['files']['#options'])) {
1200
      // Display empty text if there are no files.
1201
      $form['admin']['files'] = array(
1202
        '#markup' => '<p>' . $form['admin']['files']['#empty'] . '</p>',
1203
      );
1204
    }
1205
    else {
1206
      $files = file_load_multiple(array_keys($form['admin']['files']['#options']));
1207

    
1208
      $form['admin']['files'] = array(
1209
        '#tree' => TRUE,
1210
        '#prefix' => '<div class="media-display-thumbnails media-clear clearfix"><ul id="media-browser-library-list" class="media-list-thumbnails">',
1211
        '#suffix' => '</ul></div>',
1212
      );
1213

    
1214
      foreach ($files as $file) {
1215
        $preview = media_get_thumbnail_preview($file, TRUE);
1216
        $form['admin']['files'][$file->fid] = array(
1217
          '#type' => 'checkbox',
1218
          '#title' => '',
1219
          '#prefix' => '<li>' . drupal_render($preview),
1220
          '#suffix' => '</li>',
1221
        );
1222
      }
1223
    }
1224
  }
1225
}
1226

    
1227
/**
1228
 * Implements hook_views_api().
1229
 */
1230
function media_views_api() {
1231
  return array(
1232
    'api' => 3,
1233
    'path' => drupal_get_path('module', 'media'),
1234
  );
1235
}
1236

    
1237
/**
1238
 * Implements hook_views_default_views().
1239
 */
1240
function media_views_default_views() {
1241
  return media_load_all_exports('media', 'views', 'view.inc', 'view');
1242
}
1243

    
1244
/**
1245
 * Fetches an array of exportables from files.
1246
 *
1247
 * @param string $module
1248
 *   The module invoking this request. (Can be called by other modules.)
1249
 * @param string $directory
1250
 *   The subdirectory in the custom module.
1251
 * @param string $extension
1252
 *   The file extension.
1253
 * @param string $name
1254
 *   The name of the variable found in each file. Defaults to the same as
1255
 *   $extension.
1256
 *
1257
 * @return array
1258
 *   Array of $name objects.
1259
 */
1260
function media_load_all_exports($module, $directory, $extension, $name = NULL) {
1261
  if (!$name) {
1262
    $name = $extension;
1263
  }
1264

    
1265
  $return = array();
1266
  // Find all the files in the directory with the correct extension.
1267
  $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
1268
  foreach ($files as $path => $file) {
1269
    require $path;
1270
    if (isset($$name)) {
1271
      $return[$$name->name] = $$name;
1272
    }
1273
  }
1274

    
1275
  return $return;
1276
}
1277

    
1278
/**
1279
 * Returns metadata describing Media browser plugins.
1280
 *
1281
 * @see hook_media_browser_plugin_info()
1282
 * @see hook_media_browser_plugin_info_alter()
1283
 */
1284
function media_get_browser_plugin_info() {
1285
  $info = &drupal_static(__FUNCTION__);
1286

    
1287
  if (!isset($info)) {
1288
    $cid = 'media:browser:plugin:info:' . $GLOBALS['language']->language;
1289
    if ($cache = cache_get($cid)) {
1290
      $info = $cache->data;
1291
    }
1292
    else {
1293
      $info = module_invoke_all('media_browser_plugin_info');
1294
      drupal_alter('media_browser_plugin_info', $info);
1295
      cache_set($cid, $info);
1296
    }
1297
  }
1298

    
1299
  return $info;
1300
}
1301

    
1302
/**
1303
 * Gets the MIME type mapped to a given extension.
1304
 *
1305
 * @param string $extension
1306
 *   A file extension.
1307
 *
1308
 * @return string
1309
 *   The MIME type associated with the extension or FALSE if the extension does
1310
 *   not have an associated MIME type.
1311
 *
1312
 * @see file_mimetype_mapping()
1313
 */
1314
function media_get_extension_mimetype($extension) {
1315
  include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
1316
  $mimetype_mappings = file_mimetype_mapping();
1317

    
1318
  if (isset($mimetype_mappings['extensions'][$extension])) {
1319
    $id = $mimetype_mappings['extensions'][$extension];
1320
    return $mimetype_mappings['mimetypes'][$id];
1321
  }
1322
  else {
1323
    return FALSE;
1324
  }
1325
}
1326

    
1327
/**
1328
 * Helper function to get a list of local stream wrappers.
1329
 */
1330
function media_get_local_stream_wrappers() {
1331
  return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
1332
}
1333

    
1334
/**
1335
 * Helper function to get a list of remote stream wrappers.
1336
 */
1337
function media_get_remote_stream_wrappers() {
1338
  $wrappers = file_get_stream_wrappers();
1339
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
1340
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
1341
  return $wrappers;
1342
}