Projet

Général

Profil

Paste
Télécharger (50,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / media.module @ 8fa03d70

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
  if (module_exists('entity_translation')) {
71
    $entity_info['file']['translation']['entity_translation']['class'] = 'MediaEntityTranslationHandler';
72
    $entity_info['file']['translation']['entity_translation']['path schemes']['media'] = array('edit path' => 'media/%file/edit/%ctools_js');
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
  if (module_exists('admin_language')) {
172
    $paths['media/ajax/*'] = TRUE; // For admin_language module compatibility.
173
  }
174

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

    
183
  return $paths;
184
}
185

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

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

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

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

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

    
251
  // Sanitize form parents before using them.
252
  $form_parents = array_filter($form_parents, 'element_child');
253

    
254
  if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
255
    // Invalid request.
256
    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');
257
    $commands = array();
258
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
259
    return array('#type' => 'ajax', '#commands' => $commands);
260
  }
261

    
262
  list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
263

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

    
272
  // Get the current element and count the number of files.
273
  $current_element = $form;
274
  foreach ($form_parents as $parent) {
275
    if (isset($current_element[$parent])) {
276
      $current_element = $current_element[$parent];
277
    }
278
    else {
279
      $current_element = NULL;
280
      break;
281
    }
282
  }
283
  $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
284

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

    
288
  // Retrieve the element to be rendered.
289
  foreach ($form_parents as $parent) {
290
    $form = $form[$parent];
291
  }
292

    
293
  // Add the special Ajax class if a new file was added.
294
  if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
295
    $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
296
  }
297
  // Otherwise just add the new content class on a placeholder.
298
  else {
299
    $form['#suffix'] .= '<span class="ajax-new-content"></span>';
300
  }
301

    
302
  $output = theme('status_messages') . drupal_render($form);
303
  $js = drupal_add_js();
304
  $settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
305

    
306
  $commands[] = ajax_command_replace(NULL, $output, $settings);
307
  return array('#type' => 'ajax', '#commands' => $commands);
308
}
309

    
310
/**
311
 * Implements hook_image_default_styles().
312
 */
313
function media_image_default_styles() {
314
  $styles = array();
315
  $styles['media_thumbnail'] = array(
316
    'label' => 'Media thumbnail (100x100)',
317
    'effects' => array(
318
      array(
319
        'name' => 'image_scale_and_crop',
320
        'data' => array('width' => 100, 'height' => 100),
321
        'weight' => 0,
322
      ),
323
    ),
324
  );
325
  return $styles;
326
}
327

    
328
/**
329
 * Implements hook_page_alter().
330
 *
331
 * This is used to use our alternate template when ?render=media-popup is passed
332
 * in the URL.
333
 */
334
function media_page_alter(&$page) {
335
  if (isset($_GET['render']) && $_GET['render'] == 'media-popup') {
336
    $page['#theme'] = 'media_dialog_page';
337

    
338
    // Disable administration modules from adding output to the popup.
339
    // @see http://drupal.org/node/914786
340
    module_invoke_all('suppress', TRUE);
341

    
342
    foreach (element_children($page) as $key) {
343
      if ($key != 'content') {
344
        unset($page[$key]);
345
      }
346
    }
347
  }
348
}
349

    
350
/**
351
 * Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
352
 *
353
 * @todo: Respect field settings in 7.x-2.x and handle them in the media widget
354
 * UI.
355
 */
356
function media_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
357
  // On file fields that use the media widget we need remove specific fields.
358
  if ($form['#field']['type'] == 'file' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
359
    $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
360
    $form['instance']['settings']['file_extensions']['#maxlength'] = 255;
361
    $form['instance']['settings']['file_extensions']['#description'] .= '<br />' . t('If empty, the file extensions list will be composed automatically using the allowed file types.');
362
    $form['instance']['settings']['file_extensions']['#required'] = FALSE;
363
  }
364

    
365
  // On image fields using the media widget we remove the alt/title fields.
366
  if ($form['#field']['type'] == 'image' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
367
    $form['instance']['settings']['alt_field']['#access'] = FALSE;
368
    $form['instance']['settings']['title_field']['#access'] = FALSE;
369
    $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
370
    // Do not increase maxlength of file extensions for image fields, since
371
    // presumably they will not need a long list of extensions.
372
  }
373

    
374
  // Add a validation function to any field instance which uses the media widget
375
  // to ensure that the upload destination scheme is one of the allowed schemes
376
  // if any defined by settings.
377
  if (isset($form['instance']['widget']) && $form['instance']['widget']['type']['#value'] == 'media_generic' && isset($form['#field']['settings']['uri_scheme'])) {
378
    $form['#validate'][] = 'media_field_instance_validate';
379
  }
380
}
381

    
382
/**
383
 * Validation handler; ensure that the upload destination scheme is one of the
384
 * allowed schemes.
385
 */
386
function media_field_instance_validate($form, &$form_state) {
387
  $allowed_schemes = array_filter($form_state['values']['instance']['widget']['settings']['allowed_schemes']);
388
  $upload_destination = $form_state['values']['field']['settings']['uri_scheme'];
389

    
390
  if (!empty($allowed_schemes) && !in_array($upload_destination, $allowed_schemes)) {
391
    form_set_error('allowed_schemes', t('The upload destination must be one of the allowed schemes.'));
392
  }
393
}
394

    
395
/**
396
 * Implements hook_form_alter().
397
 */
398
function media_form_alter(&$form, &$form_state, $form_id) {
399
  // If we're in the media browser, set the #media_browser key to true
400
  // so that if an ajax request gets sent to a different path, the form
401
  // still uses the media_browser_form_submit callback.
402
  if (current_path() == 'media/browser') {
403
    if ($form_id == 'views_exposed_form') {
404
      $form['render'] = array('#type' => 'hidden', '#value' => 'media-popup');
405
      $form['#action'] = '/media/browser';
406
    } else {
407
      $form_state['#media_browser'] = TRUE;
408
    }
409
  }
410

    
411
  // If the #media_browser key isset and is true we are using the browser
412
  // popup, so add the media_browser submit handler.
413
  if (!empty($form_state['#media_browser'])) {
414
    $form['#submit'][] = 'media_browser_form_submit';
415
  }
416
}
417

    
418
/**
419
 * Submit handler; direction form submissions in the media browser.
420
 */
421
function media_browser_form_submit($form, &$form_state) {
422
  $url = NULL;
423
  $parameters = array();
424

    
425
  // Single upload.
426
  if (!empty($form_state['file'])) {
427
    $file = $form_state['file'];
428
    $url = 'media/browser';
429
    $parameters = array('query' => array('render' => 'media-popup', 'fid' => $file->fid));
430
  }
431

    
432
  // If $url is set, we had some sort of upload, so redirect the form.
433
  if (!empty($url)) {
434
    $form_state['redirect'] = array($url, $parameters);
435
  }
436
}
437

    
438
/**
439
 * Implements hook_library().
440
 */
441
function media_library() {
442
  $path = drupal_get_path('module', 'media');
443
  $info = system_get_info('module', 'media');
444

    
445
  $common = array(
446
    'website' => 'http://drupal.org/project/media',
447
    'version' => !empty($info['version']) ? $info['version'] : '7.x-2.x',
448
  );
449

    
450
  // Contains libraries common to other media modules.
451
  $libraries['media_base'] = array(
452
    'title' => 'Media base',
453
    'js' => array(
454
      $path . '/js/media.core.js' => array('group' => JS_LIBRARY, 'weight' => -5),
455
      $path . '/js/util/json2.js' => array('group' => JS_LIBRARY),
456
      $path . '/js/util/ba-debug.min.js' => array('group' => JS_LIBRARY),
457
    ),
458
    'css' => array(
459
      $path . '/css/media.css',
460
    ),
461
  );
462

    
463
  // Includes resources needed to launch the media browser.  Should be included
464
  // on pages where the media browser needs to be launched from.
465
  $libraries['media_browser'] = array(
466
    'title' => 'Media Browser popup libraries',
467
    'js' => array(
468
      $path . '/js/media.popups.js' => array('group' => JS_DEFAULT),
469
    ),
470
    'dependencies' => array(
471
      array('system', 'ui.resizable'),
472
      array('system', 'ui.draggable'),
473
      array('system', 'ui.dialog'),
474
      array('media', 'media_base'),
475
    ),
476
  );
477

    
478
  // Resources needed in the media browser itself.
479
  $libraries['media_browser_page'] = array(
480
    'title' => 'Media browser',
481
    'js' => array(
482
      $path . '/js/media.browser.js'  => array('group' => JS_DEFAULT),
483
    ),
484
    'dependencies' => array(
485
      array('system', 'ui.tabs'),
486
      array('system', 'ui.draggable'),
487
      array('system', 'ui.dialog'),
488
      array('media', 'media_base'),
489
    ),
490
  );
491

    
492
  // Settings for the dialog etc.
493
  $settings = array(
494
    'browserUrl' => url('media/browser', array(
495
      'query' => array(
496
        'render' => 'media-popup'
497
      ))
498
    ),
499
    'styleSelectorUrl' => url('media/-media_id-/format-form', array(
500
      'query' => array(
501
        'render' => 'media-popup'
502
      ))
503
    ),
504
    'dialogOptions' => array(
505
      'dialogclass' => variable_get('media_dialogclass', 'media-wrapper'),
506
      'modal' => (boolean)variable_get('media_modal', TRUE),
507
      'draggable' => (boolean)variable_get('media_draggable', FALSE),
508
      'resizable' => (boolean)variable_get('media_resizable', FALSE),
509
      'minwidth' => (int)variable_get('media_minwidth', 500),
510
      'width' => (int)variable_get('media_width', 670),
511
      'height' => (int)variable_get('media_height', 280),
512
      'position' => variable_get('media_position', 'center'),
513
      'overlay' => array(
514
        'backgroundcolor' => variable_get('media_backgroundcolor', '#000000'),
515
        'opacity' => (float)variable_get('media_opacity', 0.4),
516
      ),
517
      'zindex' => (int)variable_get('media_zindex', 10000),
518
    ),
519
  );
520

    
521
  $libraries['media_browser_settings'] = array(
522
    'title' => 'Media browser settings',
523
    'js' => array(
524
      0 => array(
525
        'data' => array(
526
          'media' => $settings,
527
        ),
528
        'type' => 'setting',
529
      ),
530
    ),
531
  );
532

    
533
  foreach ($libraries as &$library) {
534
    $library += $common;
535
  }
536
  return $libraries;
537
}
538

    
539
/**
540
 * Theme callback used to identify when we are in a popup dialog.
541
 *
542
 * Generally the default theme will look terrible in the media browser. This
543
 * will default to the administration theme, unless set otherwise.
544
 */
545
function media_dialog_get_theme_name() {
546
  return variable_get('media_dialog_theme', variable_get('admin_theme'));
547
}
548

    
549
/**
550
 * This will parse a url or embedded code into a unique URI.
551
 *
552
 * The function will call all modules implementing hook_media_parse($url),
553
 * which should return either a string containing a parsed URI or NULL.
554
 *
555
 * @NOTE The implementing modules may throw an error, which will not be caught
556
 * here; it's up to the calling function to catch any thrown errors.
557
 *
558
 * @NOTE In emfield, we originally also accepted an array of regex patterns
559
 * to match against. However, that module used a registration for providers,
560
 * and simply stored the match in the database keyed to the provider object.
561
 * However, other than the stream wrappers, there is currently no formal
562
 * registration for media handling. Additionally, few, if any, stream wrappers
563
 * will choose to store a straight match from the parsed URL directly into
564
 * the URI. Thus, we leave both the matching and the final URI result to the
565
 * implementing module in this implementation.
566
 *
567
 * An alternative might be to do the regex pattern matching here, and pass a
568
 * successful match back to the implementing module. However, that would
569
 * require either an overloaded function or a new hook, which seems like more
570
 * overhead than it's worth at this point.
571
 *
572
 * @TODO Once hook_module_implements_alter() is in core (see the issue at
573
 * http://drupal.org/node/692950) we may want to implement media_media_parse()
574
 * to ensure we were passed a valid URL, rather than an unsupported or
575
 * malformed embed code that wasn't caught earlier. It will needed to be
576
 * weighted so it's called after all other streams have a go, as the fallback,
577
 * and will need to throw an error.
578
 *
579
 * @param string $url
580
 *   The original URL or embed code to parse.
581
 *
582
 * @return string
583
 *   The unique URI for the file, based on its stream wrapper, or NULL.
584
 *
585
 * @see media_parse_to_file()
586
 * @see media_add_from_url_validate()
587
 */
588
function media_parse_to_uri($url) {
589
  // Trim any whitespace before parsing.
590
  $url = trim($url);
591
  foreach (module_implements('media_parse') as $module) {
592
    $success = module_invoke($module, 'media_parse', $url);
593
    $context = array(
594
      'url' => $url,
595
      'module' => $module,
596
    );
597
    drupal_alter('media_parse', $success, $context);
598
    if (isset($success)) {
599
      return $success;
600
    }
601
  }
602
}
603

    
604
/**
605
 * Parse a URL or embed code and return a file object.
606
 *
607
 * If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
608
 * then we'll copy the file locally.
609
 *
610
 * @NOTE The implementing modules may throw an error, which will not be caught
611
 * here; it's up to the calling function to catch any thrown errors.
612
 *
613
 * @see media_parse_to_uri()
614
 * @see media_add_from_url_submit()
615
 */
616
function media_parse_to_file($url, $params = array()) {
617
  try {
618
    $uri = media_parse_to_uri($url);
619
  }
620
  catch (Exception $e) {
621
    // Pass the error along.
622
    throw $e;
623
    return;
624
  }
625

    
626
  if (isset($uri)) {
627
    // Attempt to load an existing file from the unique URI.
628
    $select = db_select('file_managed', 'f')
629
    ->extend('PagerDefault')
630
    ->fields('f', array('fid'))
631
    ->condition('uri', $uri);
632

    
633
    $fid = $select->execute()->fetchCol();
634
    if (!empty($fid)) {
635
      $file = file_load(array_pop($fid));
636
      return $file;
637
    }
638
  }
639

    
640
  if (isset($uri)) {
641
    // The URL was successfully parsed to a URI, but does not yet have an
642
    // associated file: save it!
643
    $file = file_uri_to_object($uri);
644
    file_save($file);
645
  }
646
  else {
647
    // The URL wasn't parsed. We'll try to save a remote file.
648
    // Copy to temporary first.
649
    $source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
650
    if (!@copy(@$url, $source_uri)) {
651
      throw new Exception('Unable to add file ' . $url);
652
      return;
653
    }
654
    $source_file = file_uri_to_object($source_uri);
655
    if(isset($params['to_directory'])){
656
      $scheme = variable_get('file_default_scheme', 'public') . '://' . $params['to_directory'] . '/';
657
    }
658
    else{
659
      $scheme = variable_get('file_default_scheme', 'public') . '://';
660
    }
661
    $uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);
662
    // Now to its new home.
663
    file_prepare_directory($scheme, FILE_CREATE_DIRECTORY || FILE_MODIFY_PERMISSIONS);
664
    $file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
665
  }
666

    
667
  return $file;
668
}
669

    
670
/**
671
 * Custom implementation of array_walk_recursive() that works around a crash
672
 * some users have been experiencing with that function in PHP 7.
673
 *
674
 * @see https://www.drupal.org/project/media/issues/2998097
675
 */
676
function media_array_walk_recursive(&$array) {
677
  foreach ($array as $key => $value) {
678
    if (is_array($array[$key])) {
679
      media_array_walk_recursive($array[$key]);
680
    }
681
    else {
682
      $array[$key] = check_plain($array[$key]);
683
    }
684
  }
685
}
686

    
687
/**
688
 * Implements hook_element_info().
689
 */
690
function media_element_info() {
691
  $types['media'] = array(
692
    '#input' => TRUE,
693
    '#process' => array('media_element_process'),
694
    '#value_callback' => 'media_file_value',
695
    '#element_validate' => array('media_element_validate'),
696
    '#pre_render' => array('media_element_pre_render'),
697
    '#theme' => 'media_widget',
698
    '#theme_wrappers' => array('form_element'),
699
    '#size' => 22,
700
    '#extended' => FALSE,
701
    '#media_options' => array(
702
      'global' => array(
703
        // Example: array('image', 'audio');
704
        'types' => array(),
705
        // Example: array('http', 'ftp', 'flickr');
706
        'schemes' => array(),
707
      ),
708
    ),
709
    '#attached' => array(
710
      'library' => array(
711
        array('media', 'media_browser'),
712
      ),
713
    ),
714
  );
715

    
716
  $setting = array();
717
  $setting['media']['global'] = $types['media']['#media_options'];
718

    
719
  $types['media']['#attached']['js'][] = array(
720
    'type' => 'setting',
721
    'data' => $setting,
722
  );
723

    
724
  return $types;
725
}
726

    
727
/**
728
 * Process callback for the media form element.
729
 */
730
function media_element_process($element, &$form_state, $form) {
731
  ctools_include('modal');
732
  ctools_include('ajax');
733
  ctools_modal_add_js();
734

    
735
  // Append the '-upload' to the #id so the field label's 'for' attribute
736
  // corresponds with the textfield element.
737
  $original_id = $element['#id'];
738
  $element['#id'] .= '-upload';
739
  $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
740

    
741
  // Set some default element properties.
742
  $element['#file'] = $fid ? file_load($fid) : FALSE;
743
  $element['#tree'] = TRUE;
744

    
745
  $ajax_settings = array(
746
    'path' => 'media/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
747
    'wrapper' => $original_id . '-ajax-wrapper',
748
    'effect' => 'fade',
749
  );
750

    
751
  // Set up the buttons first since we need to check if they were clicked.
752
  $element['attach_button'] = array(
753
    '#name' => implode('_', $element['#parents']) . '_attach_button',
754
    '#type' => 'submit',
755
    '#value' => t('Attach'),
756
    '#validate' => array(),
757
    '#submit' => array('media_file_submit'),
758
    '#limit_validation_errors' => array($element['#parents']),
759
    '#ajax' => $ajax_settings,
760
    '#attributes' => array('class' => array('attach')),
761
    '#weight' => -1,
762
  );
763

    
764
  $element['preview'] = array(
765
    'content' => array(),
766
    '#prefix' => '<div class="preview">',
767
    '#suffix' => '</div>',
768
    '#ajax' => $ajax_settings,
769
    '#weight' => -10,
770
  );
771

    
772
  // Substitute the JS preview for a true file thumbnail once the file is
773
  // attached.
774
  if ($fid && $element['#file']) {
775
    $element['preview']['content'] = media_get_thumbnail_preview($element['#file']);
776
  }
777

    
778
  // The file ID field itself.
779
  $element['upload'] = array(
780
    '#name' => 'media[' . implode('_', $element['#parents']) . ']',
781
    '#type' => 'textfield',
782
    '#title' => t('Enter the ID of an existing file'),
783
    '#title_display' => 'invisible',
784
    '#field_prefix' => t('File ID'),
785
    '#size' => $element['#size'],
786
    '#theme_wrappers' => array(),
787
    '#attributes' => array('class' => array('upload')),
788
    '#weight' => -9,
789
  );
790

    
791
  $element['browse_button'] = array(
792
    '#type' => 'link',
793
    '#href' => '',
794
    '#title' => t('Browse'),
795
    '#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
796
    '#options' => array('fragment' => FALSE, 'external' => TRUE),
797
    '#weight' => -8,
798
  );
799

    
800
  // Force the progress indicator for the remove button to be either 'none' or
801
  // 'throbber', even if the upload button is using something else.
802
  $ajax_settings['progress']['type'] = 'throbber';
803
  $ajax_settings['progress']['message'] = NULL;
804
  $ajax_settings['effect'] = 'none';
805
  $element['edit'] = array(
806
    '#type' => 'link',
807
    '#href' => 'media/' . $fid . '/edit/nojs',
808
    '#title' => t('Edit'),
809
    '#attributes' => array(
810
      'class' => array(
811
        // Required for CTools modal to work.
812
        'ctools-use-modal',
813
        'ctools-modal-media-file-edit', 'button', 'edit',
814
      ),
815
    ),
816
    '#weight' => 20,
817
    '#access' => $element['#file'] ? file_entity_access('update', $element['#file']) : FALSE,
818
  );
819

    
820
  // If we have parent entity form/source langcodes, pass them in query. They
821
  // will be used in
822
  /* @see media_file_edit_modal() */
823
  if (!empty($element['#media_parent_entity_form_langcode'])) {
824
    $element['edit']['#options']['query']['media_parent_entity_form_langcode'] = $element['#media_parent_entity_form_langcode'];
825
    if (!empty($element['#media_parent_entity_source_langcode'])) {
826
      $element['edit']['#options']['query']['media_parent_entity_source_langcode'] = $element['#media_parent_entity_source_langcode'];
827
    }
828
  }
829

    
830
  $element['remove_button'] = array(
831
    '#name' => implode('_', $element['#parents']) . '_remove_button',
832
    '#type' => 'submit',
833
    '#value' => t('Remove'),
834
    '#validate' => array(),
835
    '#submit' => array('media_file_submit'),
836
    '#limit_validation_errors' => array($element['#parents']),
837
    '#ajax' => $ajax_settings,
838
    '#attributes' => array('class' => array('remove')),
839
    '#weight' => 0,
840
  );
841

    
842
  $element['fid'] = array(
843
    '#type' => 'hidden',
844
    '#value' => $fid,
845
    '#attributes' => array('class' => array('fid')),
846
  );
847

    
848
  // Media browser attach code.
849
  $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
850

    
851
  // IDs of form elements are 'unstable' in Drupal because of drupal_html_id
852
  // add a class for our Javascript instead.
853
  $element_js_class = drupal_html_class('js-media-element-' . $element['#id']);
854
  $element['upload']['#attributes']['class'][] = $element_js_class;
855

    
856
  // Cache the media options and pass the cache ID as a JavaScript setting.
857
  $cid = drupal_get_token(drupal_random_bytes(32));
858
  cache_set('media_options:' . $cid, $element['#media_options']['global'], 'cache_form', REQUEST_TIME + 21600);
859

    
860
  $element['browse_button']['#attached']['js'] = array(
861
    array(
862
      'type' => 'setting',
863
      'data' => array('media' => array('elements' => array('.' . $element_js_class => array('global' => array('options' => $cid))))),
864
    )
865
  );
866

    
867
  $element['#attached']['library'][] = array('media', 'media_browser');
868
  $element['#attached']['library'][] = array('media', 'media_browser_settings');
869

    
870
  // Prefix and suffix used for Ajax replacement.
871
  $element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
872
  $element['#suffix'] = '</div>';
873

    
874
  return $element;
875
}
876

    
877
/**
878
 * Implements hook_form_FORM_ID_alter().
879
 */
880
function media_form_file_entity_edit_alter(&$form, &$form_state) {
881
  // Make adjustments to the file edit form when used in a CTools modal.
882
  if (!empty($form_state['ajax'])) {
883
    // Remove the preview and the delete button.
884
    $form['preview']['#access'] = FALSE;
885
    $form['actions']['delete']['#access'] = FALSE;
886

    
887
    // Convert the cancel link to a button which triggers a modal close.
888
    $form['actions']['cancel']['#attributes']['class'][] = 'button';
889
    $form['actions']['cancel']['#attributes']['class'][] = 'button-no';
890
    $form['actions']['cancel']['#attributes']['class'][] = 'ctools-close-modal';
891
  }
892
}
893

    
894
/**
895
 * The #value_callback for a media type element.
896
 */
897
function media_file_value(&$element, $input = FALSE, $form_state = NULL) {
898
  $fid = 0;
899

    
900
  // Find the current value of this field from the form state.
901
  $form_state_fid = $form_state['values'];
902
  foreach ($element['#parents'] as $parent) {
903
    $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
904
  }
905

    
906
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
907
    $fid = $form_state_fid['fid'];
908
  }
909
  elseif (is_numeric($form_state_fid)) {
910
    $fid = $form_state_fid;
911
  }
912

    
913
  // Process any input and attach files.
914
  if ($input !== FALSE) {
915
    $return = $input;
916

    
917
    // Attachments take priority over all other values.
918
    if ($file = media_attach_file($element)) {
919
      $fid = $file->fid;
920
    }
921
    else {
922
      // Check for #filefield_value_callback values.
923
      // Because FAPI does not allow multiple #value_callback values like it
924
      // does for #element_validate and #process, this fills the missing
925
      // functionality to allow File fields to be extended through FAPI.
926
      if (isset($element['#file_value_callbacks'])) {
927
        foreach ($element['#file_value_callbacks'] as $callback) {
928
          $callback($element, $input, $form_state);
929
        }
930
      }
931
      // Load file if the FID has changed to confirm it exists.
932
      if (isset($input['fid']) && $file = file_load($input['fid'])) {
933
        $fid = $file->fid;
934
      }
935
    }
936
  }
937

    
938
  // If there is no input, set the default value.
939
  else {
940
    if ($element['#extended']) {
941
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
942
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
943
    }
944
    else {
945
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
946
      $return = array('fid' => 0);
947
    }
948

    
949
    // Confirm that the file exists when used as a default value.
950
    if ($default_fid && $file = file_load($default_fid)) {
951
      $fid = $file->fid;
952
    }
953
  }
954

    
955
  $return['fid'] = $fid;
956

    
957
  return $return;
958
}
959

    
960
/**
961
 * Validate media form elements.
962
 *
963
 * The file type is validated during the upload process, but this is necessary
964
 * necessary in order to respect the #required property.
965
 */
966
function media_element_validate(&$element, &$form_state) {
967
  $clicked_button = end($form_state['triggering_element']['#parents']);
968

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

    
974
  // Consolidate the array value of this field to a single FID.
975
  if (!$element['#extended']) {
976
    form_set_value($element, $element['fid']['#value'], $form_state);
977
  }
978
}
979

    
980
/**
981
 * Form submission handler for attach / remove buttons of media elements.
982
 *
983
 * @see media_element_process()
984
 */
985
function media_file_submit($form, &$form_state) {
986
  // Determine whether it was the attach or remove button that was clicked, and
987
  // set $element to the managed_file element that contains that button.
988
  $parents = $form_state['triggering_element']['#array_parents'];
989
  $button_key = array_pop($parents);
990
  $element = drupal_array_get_nested_value($form, $parents);
991

    
992
  // No action is needed here for the attach button, because all media
993
  // attachments on the form are processed by media_file_value() regardless of
994
  // which button was clicked. Action is needed here for the remove button,
995
  // because we only remove a file in response to its remove button being
996
  // clicked.
997
  if ($button_key == 'remove_button') {
998
    // If it's a temporary file we can safely remove it immediately, otherwise
999
    // it's up to the implementing module to clean up files that are in use.
1000
    if ($element['#file'] && $element['#file']->status == 0) {
1001
      file_delete($element['#file']);
1002
    }
1003
    // Update both $form_state['values'] and $form_state['input'] to reflect
1004
    // that the file has been removed, so that the form is rebuilt correctly.
1005
    // $form_state['values'] must be updated in case additional submit handlers
1006
    // run, and for form building functions that run during the rebuild, such as
1007
    // when the media element is part of a field widget.
1008
    // $form_state['input'] must be updated so that media_file_value() has
1009
    // correct information during the rebuild.
1010
    $values_element = $element['#extended'] ? $element['fid'] : $element;
1011
    form_set_value($values_element, NULL, $form_state);
1012
    drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
1013
  }
1014

    
1015
  // Set the form to rebuild so that $form is correctly updated in response to
1016
  // processing the file removal. Since this function did not change $form_state
1017
  // if the upload button was clicked, a rebuild isn't necessary in that
1018
  // situation and setting $form_state['redirect'] to FALSE would suffice.
1019
  // However, we choose to always rebuild, to keep the form processing workflow
1020
  // consistent between the two buttons.
1021
  $form_state['rebuild'] = TRUE;
1022
}
1023

    
1024
/**
1025
 * Attaches any files that have been referenced by a media element.
1026
 *
1027
 * @param $element
1028
 *   The FAPI element whose files are being attached.
1029
 *
1030
 * @return
1031
 *   The file object representing the file that was attached, or FALSE if no
1032
 *   file was attached.
1033
 */
1034
function media_attach_file($element) {
1035
  $upload_name = implode('_', $element['#parents']);
1036
  if (empty($_POST['media'][$upload_name])) {
1037
    return FALSE;
1038
  }
1039

    
1040
  if (!$file = file_load($_POST['media'][$upload_name])) {
1041
    watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
1042
    form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
1043
    return FALSE;
1044
  }
1045

    
1046
  return $file;
1047
}
1048

    
1049
/**
1050
 * Returns HTML for a managed file element.
1051
 *
1052
 * @param $variables
1053
 *   An associative array containing:
1054
 *   - element: A render element representing the file.
1055
 *
1056
 * @ingroup themeable
1057
 */
1058
function theme_media_element($variables) {
1059
  $element = $variables['element'];
1060

    
1061
  $attributes = array();
1062
  if (isset($element['#id'])) {
1063
    $attributes['id'] = $element['#id'];
1064
  }
1065
  if (!empty($element['#attributes']['class'])) {
1066
    $attributes['class'] = (array) $element['#attributes']['class'];
1067
  }
1068
  $attributes['class'][] = 'form-media';
1069

    
1070
  // This wrapper is required to apply JS behaviors and CSS styling.
1071
  $output = '';
1072
  $output .= '<div' . drupal_attributes($attributes) . '>';
1073
  $output .= drupal_render_children($element);
1074
  $output .= '</div>';
1075
  return $output;
1076
}
1077

    
1078
/**
1079
 * #pre_render callback to hide display of the browse/attach or remove controls.
1080
 *
1081
 * Browse/attach controls are hidden when a file is already attached.
1082
 * Remove controls are hidden when there is no file attached. Controls are
1083
 * hidden here instead of in media_element_process(), because #access for these
1084
 * buttons depends on the media element's #value. See the documentation of
1085
 * form_builder() for more detailed information about the relationship between
1086
 * #process, #value, and #access.
1087
 *
1088
 * Because #access is set here, it affects display only and does not prevent
1089
 * JavaScript or other untrusted code from submitting the form as though access
1090
 * were enabled. The form processing functions for these elements should not
1091
 * assume that the buttons can't be "clicked" just because they are not
1092
 * displayed.
1093
 *
1094
 * @see media_element_process()
1095
 * @see form_builder()
1096
 */
1097
function media_element_pre_render($element) {
1098
  // If we already have a file, we don't want to show the browse and attach
1099
  // controls.
1100
  if (!empty($element['#value']['fid'])) {
1101
    $element['upload']['#access'] = FALSE;
1102
    $element['browse_button']['#access'] = FALSE;
1103
    $element['attach_button']['#access'] = FALSE;
1104
  }
1105
  // If we don't already have a file, there is nothing to remove.
1106
  else {
1107
    $element['remove_button']['#access'] = FALSE;
1108
  }
1109
  return $element;
1110
}
1111

    
1112
/**
1113
 * Generates a thumbnail preview of a file.
1114
 *
1115
 * Provides default fallback images if an image of the file cannot be generated.
1116
 *
1117
 * @param object $file
1118
 *   A Drupal file object.
1119
 * @param boolean $link
1120
 *   (optional) Boolean indicating whether the thumbnail should be linked to the
1121
 *   file. Defaults to FALSE.
1122
 * @param string $view_mode
1123
 *   (optional) The view mode to use when rendering the thumbnail. Defaults to
1124
 *   'preview'.
1125
 *
1126
 * @return array
1127
 *   Renderable array suitable for drupal_render() with the necessary classes
1128
 *   and CSS to support a media thumbnail.
1129
 */
1130
function media_get_thumbnail_preview($file, $link = FALSE, $view_mode = 'preview') {
1131
  // If a file has an invalid type, allow file_view_file() to work.
1132
  if (!file_type_is_enabled($file->type)) {
1133
    $file->type = file_get_type($file);
1134
  }
1135

    
1136
  $preview = file_view_file($file, $view_mode);
1137
  $preview['#show_names'] = TRUE;
1138
  $preview['#add_link'] = $link;
1139
  $preview['#theme_wrappers'][] = 'media_thumbnail';
1140
  $preview['#attached']['css'][] = drupal_get_path('module', 'media') . '/css/media.css';
1141

    
1142
  return $preview;
1143
}
1144

    
1145
/**
1146
 * Check that the media is one of the selected types.
1147
 *
1148
 * @param object $file
1149
 *   A Drupal file object.
1150
 * @param array $types
1151
 *   An array of media type names
1152
 *
1153
 * @return array
1154
 *   If the file type is not allowed, it will contain an error message.
1155
 *
1156
 * @see hook_file_validate()
1157
 */
1158
function media_file_validate_types($file, $types) {
1159
  $errors = array();
1160

    
1161
  if (!function_exists('file_entity_get_filetype_candidates')) {
1162
    module_load_include('inc', 'file_entity', 'file_entity.pages');
1163
  }
1164
  $file_candidates = array_keys(file_entity_get_filetype_candidates($file));
1165
  if (!array_intersect($file_candidates, $types)) {
1166
    $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
1167
  }
1168

    
1169
  return $errors;
1170
}
1171

    
1172
/**
1173
 * Implements hook_file_displays_alter().
1174
 */
1175
function media_file_displays_alter(&$displays, $file, $view_mode) {
1176
  if ($view_mode == 'preview' && empty($displays)) {
1177
    // We re in the media browser and this file has no formatters enabled.
1178
    // Instead of letting it go through theme_file_link(), pass it through
1179
    // theme_media_formatter_large_icon() to get our cool file icon instead.
1180
    $displays['file_field_media_large_icon'] = array(
1181
      'weight' => 0,
1182
      'status' => 1,
1183
      'settings' => NULL,
1184
    );
1185
  }
1186

    
1187
  // Alt and title are special.
1188
  // @see file_entity_file_load
1189
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
1190
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
1191

    
1192
  $replace_options = array(
1193
    'clear' => TRUE,
1194
    'sanitize' => FALSE,
1195
  );
1196

    
1197
  // Load alt and title text from fields.
1198
  if (!empty($alt)) {
1199
    $file->alt = decode_entities(token_replace($alt, array('file' => $file), $replace_options));
1200
  }
1201
  if (!empty($title)) {
1202
    $file->title = decode_entities(token_replace($title, array('file' => $file), $replace_options));
1203
  }
1204

    
1205
  // Reduce memory footprint and response size in media browser.
1206
  $file->file_contents = '';
1207
}
1208

    
1209
/**
1210
 * For sanity in grammar.
1211
 *
1212
 * @see media_set_browser_params()
1213
 */
1214
function media_get_browser_params() {
1215
  return media_set_browser_params();
1216
}
1217

    
1218
/**
1219
 * Provides a singleton of the params passed to the media browser.
1220
 *
1221
 * This is useful in situations like form alters because callers can pass
1222
 * id="wysiywg_form" or whatever they want, and a form alter could pick this up.
1223
 * We may want to change the hook_media_browser_plugin_view() implementations to
1224
 * use this function instead of being passed params for consistency.
1225
 *
1226
 * It also offers a chance for some meddler to meddle with them.
1227
 *
1228
 * @see media_browser()
1229
 */
1230
function media_set_browser_params() {
1231
  $params = &drupal_static(__FUNCTION__, array());
1232

    
1233
  if (empty($params)) {
1234
    // Build out browser settings. Permissions- and security-related behaviors
1235
    // should not rely on these parameters, since they come from the HTTP query.
1236
    // There are two ways of passing secure data:
1237
    // - Store the options in the 'cache_form' cache bin, using a random key
1238
    //   prefixed with 'media_options:'. Pass the random key in the 'options'
1239
    //   query argument.
1240
    // - Inject the options by altering the browser parameters.
1241
    //   @see hook_media_browser_params_alter()
1242
    $params = drupal_get_query_parameters();
1243

    
1244
    // Filter out everything except a whitelist of known safe options.
1245
    $safe_options = array(
1246
      'enabledPlugins',
1247
      'fid',
1248
      'id',
1249
      'multiselect',
1250
      'field',
1251
      'options',
1252
      'plugins',
1253
      'render',
1254
      'types',
1255
      'render_multi_edit_form',
1256
    );
1257
    $params = array_intersect_key($params, array_flip($safe_options));
1258

    
1259
    // If the cache is present, use its values instead of the GET parameters.
1260
    if (!empty($params['options']) && is_string($params['options']) && $options = cache_get('media_options:' . $params['options'], 'cache_form')) {
1261
      $params = $options->data;
1262
    }
1263

    
1264
    // Transform text 'true' and 'false' to actual booleans.
1265
    foreach ($params as $k => $v) {
1266
      if ($v === 'true') {
1267
        $params[$k] = TRUE;
1268
      }
1269
      elseif ($v === 'false') {
1270
        $params[$k] = FALSE;
1271
      }
1272
    }
1273

    
1274
    media_array_walk_recursive($params);
1275

    
1276
    // Provide some default parameters.
1277
    $params += array(
1278
      'types' => array(),
1279
      'multiselect' => FALSE,
1280
    );
1281

    
1282
    // Allow modules to alter the parameters.
1283
    drupal_alter('media_browser_params', $params);
1284
  }
1285

    
1286
  return $params;
1287
}
1288

    
1289
/**
1290
 * Implements hook_ctools_plugin_api().
1291
 *
1292
 * Lets CTools know which plugin APIs are implemented by Media module.
1293
 */
1294
function media_ctools_plugin_api($module, $api) {
1295
  if ($module == 'file_entity' && $api == 'file_default_displays') {
1296
    return array(
1297
      'version' => 1,
1298
    );
1299
  }
1300
}
1301

    
1302
/**
1303
 * Implements hook_form_FORM_ID_alter().
1304
 *
1305
 * This alter enhances the default admin/content/file page, addding JS and CSS.
1306
 * It also makes modifications to the thumbnail view by replacing the existing
1307
 * checkboxes and table with thumbnails.
1308
 */
1309
function media_form_file_entity_admin_file_alter(&$form, $form_state) {
1310
  if (!empty($form_state['values']['operation'])) {
1311
    // The form is being rebuilt because an operation requiring confirmation
1312
    // We don't want to be messing with it in this case.
1313
    return;
1314
  }
1315

    
1316
  // Add the "Add file" local action, and notify users if they have files
1317
  // selected and they try to switch between the "Thumbnail" and "List" local
1318
  // tasks.
1319
  $path = drupal_get_path('module', 'media');
1320
  $form['#attributes']['class'][] = 'file-entity-admin-file-form';
1321
  $form['#attached']['js'][] = $path . '/js/media.admin.js';
1322
  $form['#attached']['css'][] = $path . '/css/media.css';
1323

    
1324
  // By default, this form contains a table select element called "files". For
1325
  // the 'thumbnails' tab, Media generates a thumbnail for each file and
1326
  // replaces the tableselect with a grid of thumbnails.
1327
  if (arg(3) == 'thumbnails') {
1328
    if (empty($form['admin']['files']['#options'])) {
1329
      // Display empty text if there are no files.
1330
      $form['admin']['files'] = array(
1331
        '#markup' => '<p>' . $form['admin']['files']['#empty'] . '</p>',
1332
      );
1333
    }
1334
    else {
1335
      $files = file_load_multiple(array_keys($form['admin']['files']['#options']));
1336

    
1337
      $form['admin']['files'] = array(
1338
        '#tree' => TRUE,
1339
        '#prefix' => '<div class="media-display-thumbnails media-clear clearfix"><ul id="media-browser-library-list" class="media-list-thumbnails">',
1340
        '#suffix' => '</ul></div>',
1341
      );
1342

    
1343
      foreach ($files as $file) {
1344
        $preview = media_get_thumbnail_preview($file, TRUE);
1345
        $form['admin']['files'][$file->fid] = array(
1346
          '#type' => 'checkbox',
1347
          '#title' => '',
1348
          '#prefix' => '<li>' . drupal_render($preview),
1349
          '#suffix' => '</li>',
1350
        );
1351
      }
1352
    }
1353
  }
1354
}
1355

    
1356
/**
1357
 * Implements hook_views_api().
1358
 */
1359
function media_views_api() {
1360
  return array(
1361
    'api' => 3,
1362
    'path' => drupal_get_path('module', 'media'),
1363
  );
1364
}
1365

    
1366
/**
1367
 * Implements hook_views_default_views().
1368
 */
1369
function media_views_default_views() {
1370
  return media_load_all_exports('media', 'views', 'view.inc', 'view');
1371
}
1372

    
1373
/**
1374
 * Fetches an array of exportables from files.
1375
 *
1376
 * @param string $module
1377
 *   The module invoking this request. (Can be called by other modules.)
1378
 * @param string $directory
1379
 *   The subdirectory in the custom module.
1380
 * @param string $extension
1381
 *   The file extension.
1382
 * @param string $name
1383
 *   The name of the variable found in each file. Defaults to the same as
1384
 *   $extension.
1385
 *
1386
 * @return array
1387
 *   Array of $name objects.
1388
 */
1389
function media_load_all_exports($module, $directory, $extension, $name = NULL) {
1390
  if (!$name) {
1391
    $name = $extension;
1392
  }
1393

    
1394
  $return = array();
1395
  // Find all the files in the directory with the correct extension.
1396
  $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
1397
  foreach ($files as $path => $file) {
1398
    require $path;
1399
    if (isset($$name)) {
1400
      $return[$$name->name] = $$name;
1401
    }
1402
  }
1403

    
1404
  return $return;
1405
}
1406

    
1407
/**
1408
 * Returns metadata describing Media browser plugins.
1409
 *
1410
 * @return
1411
 *   An associative array of plugin information, keyed by plugin.
1412
 *
1413
 * @see hook_media_browser_plugin_info()
1414
 * @see hook_media_browser_plugin_info_alter()
1415
 */
1416
function media_get_browser_plugin_info() {
1417
  $info = &drupal_static(__FUNCTION__);
1418

    
1419
  if (!isset($info)) {
1420
    $info = module_invoke_all('media_browser_plugin_info');
1421
    drupal_alter('media_browser_plugin_info', $info);
1422
  }
1423

    
1424
  return $info;
1425
}
1426

    
1427
/**
1428
 * Gets the MIME type mapped to a given extension.
1429
 *
1430
 * @param string $extension
1431
 *   A file extension.
1432
 *
1433
 * @return string
1434
 *   The MIME type associated with the extension or FALSE if the extension does
1435
 *   not have an associated MIME type.
1436
 *
1437
 * @see file_mimetype_mapping()
1438
 */
1439
function media_get_extension_mimetype($extension) {
1440
  include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
1441
  $mimetype_mappings = file_mimetype_mapping();
1442

    
1443
  if (isset($mimetype_mappings['extensions'][$extension])) {
1444
    $id = $mimetype_mappings['extensions'][$extension];
1445
    return $mimetype_mappings['mimetypes'][$id];
1446
  }
1447
  else {
1448
    return FALSE;
1449
  }
1450
}
1451

    
1452
/**
1453
 * Helper function to get a list of local stream wrappers.
1454
 */
1455
function media_get_local_stream_wrappers() {
1456
  return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
1457
}
1458

    
1459
/**
1460
 * Helper function to get a list of remote stream wrappers.
1461
 */
1462
function media_get_remote_stream_wrappers() {
1463
  $wrappers = file_get_stream_wrappers();
1464
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
1465
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
1466
  return $wrappers;
1467
}