Projet

Général

Profil

Paste
Télécharger (49,7 ko) Statistiques
| Branche: | Révision:

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

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

    
259
  list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
260

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

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

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

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

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

    
299
  $output = theme('status_messages') . drupal_render($form);
300
  $js = drupal_add_js();
301
  $settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
302

    
303
  $commands[] = ajax_command_replace(NULL, $output, $settings);
304
  return array('#type' => 'ajax', '#commands' => $commands);
305
}
306

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
530
  foreach ($libraries as &$library) {
531
    $library += $common;
532
  }
533
  return $libraries;
534
}
535

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

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

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

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

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

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

    
664
  return $file;
665
}
666

    
667
/**
668
 * Utility function to recursively run check_plain on an array.
669
 *
670
 * @todo There is probably something in core I am not aware of that does this.
671
 */
672
function media_recursive_check_plain(&$value, $key) {
673
  $value = check_plain($value);
674
}
675

    
676
/**
677
 * Implements hook_element_info().
678
 */
679
function media_element_info() {
680
  $types['media'] = array(
681
    '#input' => TRUE,
682
    '#process' => array('media_element_process'),
683
    '#value_callback' => 'media_file_value',
684
    '#element_validate' => array('media_element_validate'),
685
    '#pre_render' => array('media_element_pre_render'),
686
    '#theme' => 'media_widget',
687
    '#theme_wrappers' => array('form_element'),
688
    '#size' => 22,
689
    '#extended' => FALSE,
690
    '#media_options' => array(
691
      'global' => array(
692
        // Example: array('image', 'audio');
693
        'types' => array(),
694
        // Example: array('http', 'ftp', 'flickr');
695
        'schemes' => array(),
696
      ),
697
    ),
698
    '#attached' => array(
699
      'library' => array(
700
        array('media', 'media_browser'),
701
      ),
702
    ),
703
  );
704

    
705
  $setting = array();
706
  $setting['media']['global'] = $types['media']['#media_options'];
707

    
708
  $types['media']['#attached']['js'][] = array(
709
    'type' => 'setting',
710
    'data' => $setting,
711
  );
712

    
713
  return $types;
714
}
715

    
716
/**
717
 * Process callback for the media form element.
718
 */
719
function media_element_process($element, &$form_state, $form) {
720
  ctools_include('modal');
721
  ctools_include('ajax');
722
  ctools_modal_add_js();
723

    
724
  // Append the '-upload' to the #id so the field label's 'for' attribute
725
  // corresponds with the textfield element.
726
  $original_id = $element['#id'];
727
  $element['#id'] .= '-upload';
728
  $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
729

    
730
  // Set some default element properties.
731
  $element['#file'] = $fid ? file_load($fid) : FALSE;
732
  $element['#tree'] = TRUE;
733

    
734
  $ajax_settings = array(
735
    'path' => 'media/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
736
    'wrapper' => $original_id . '-ajax-wrapper',
737
    'effect' => 'fade',
738
  );
739

    
740
  // Set up the buttons first since we need to check if they were clicked.
741
  $element['attach_button'] = array(
742
    '#name' => implode('_', $element['#parents']) . '_attach_button',
743
    '#type' => 'submit',
744
    '#value' => t('Attach'),
745
    '#validate' => array(),
746
    '#submit' => array('media_file_submit'),
747
    '#limit_validation_errors' => array($element['#parents']),
748
    '#ajax' => $ajax_settings,
749
    '#attributes' => array('class' => array('attach')),
750
    '#weight' => -1,
751
  );
752

    
753
  $element['preview'] = array(
754
    'content' => array(),
755
    '#prefix' => '<div class="preview">',
756
    '#suffix' => '</div>',
757
    '#ajax' => $ajax_settings,
758
    '#weight' => -10,
759
  );
760

    
761
  // Substitute the JS preview for a true file thumbnail once the file is
762
  // attached.
763
  if ($fid && $element['#file']) {
764
    $element['preview']['content'] = media_get_thumbnail_preview($element['#file']);
765
  }
766

    
767
  // The file ID field itself.
768
  $element['upload'] = array(
769
    '#name' => 'media[' . implode('_', $element['#parents']) . ']',
770
    '#type' => 'textfield',
771
    '#title' => t('Enter the ID of an existing file'),
772
    '#title_display' => 'invisible',
773
    '#field_prefix' => t('File ID'),
774
    '#size' => $element['#size'],
775
    '#theme_wrappers' => array(),
776
    '#attributes' => array('class' => array('upload')),
777
    '#weight' => -9,
778
  );
779

    
780
  $element['browse_button'] = array(
781
    '#type' => 'link',
782
    '#href' => '',
783
    '#title' => t('Browse'),
784
    '#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
785
    '#options' => array('fragment' => FALSE, 'external' => TRUE),
786
    '#weight' => -8,
787
  );
788

    
789
  // Force the progress indicator for the remove button to be either 'none' or
790
  // 'throbber', even if the upload button is using something else.
791
  $ajax_settings['progress']['type'] = 'throbber';
792
  $ajax_settings['progress']['message'] = NULL;
793
  $ajax_settings['effect'] = 'none';
794
  $element['edit'] = array(
795
    '#type' => 'link',
796
    '#href' => 'media/' . $fid . '/edit/nojs',
797
    '#title' => t('Edit'),
798
    '#attributes' => array(
799
      'class' => array(
800
        // Required for CTools modal to work.
801
        'ctools-use-modal',
802
        'ctools-modal-media-file-edit', 'button', 'edit',
803
      ),
804
    ),
805
    '#weight' => 20,
806
    '#access' => $element['#file'] ? file_entity_access('update', $element['#file']) : FALSE,
807
  );
808

    
809
  // If we have parent entity form/source langcodes, pass them in query. They
810
  // will be used in
811
  /* @see media_file_edit_modal() */
812
  if (!empty($element['#media_parent_entity_form_langcode'])) {
813
    $element['edit']['#options']['query']['media_parent_entity_form_langcode'] = $element['#media_parent_entity_form_langcode'];
814
    if (!empty($element['#media_parent_entity_source_langcode'])) {
815
      $element['edit']['#options']['query']['media_parent_entity_source_langcode'] = $element['#media_parent_entity_source_langcode'];
816
    }
817
  }
818

    
819
  $element['remove_button'] = array(
820
    '#name' => implode('_', $element['#parents']) . '_remove_button',
821
    '#type' => 'submit',
822
    '#value' => t('Remove'),
823
    '#validate' => array(),
824
    '#submit' => array('media_file_submit'),
825
    '#limit_validation_errors' => array($element['#parents']),
826
    '#ajax' => $ajax_settings,
827
    '#attributes' => array('class' => array('remove')),
828
    '#weight' => 0,
829
  );
830

    
831
  $element['fid'] = array(
832
    '#type' => 'hidden',
833
    '#value' => $fid,
834
    '#attributes' => array('class' => array('fid')),
835
  );
836

    
837
  // Media browser attach code.
838
  $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
839

    
840
  // IDs of form elements are 'unstable' in Drupal because of drupal_html_id
841
  // add a class for our Javascript instead.
842
  $element_js_class = drupal_html_class('js-media-element-' . $element['#id']);
843
  $element['upload']['#attributes']['class'][] = $element_js_class;
844

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

    
849
  $element['browse_button']['#attached']['js'] = array(
850
    array(
851
      'type' => 'setting',
852
      'data' => array('media' => array('elements' => array('.' . $element_js_class => array('global' => array('options' => $cid))))),
853
    )
854
  );
855

    
856
  $element['#attached']['library'][] = array('media', 'media_browser');
857
  $element['#attached']['library'][] = array('media', 'media_browser_settings');
858

    
859
  // Prefix and suffix used for Ajax replacement.
860
  $element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
861
  $element['#suffix'] = '</div>';
862

    
863
  return $element;
864
}
865

    
866
/**
867
 * Implements hook_form_FORM_ID_alter().
868
 */
869
function media_form_file_entity_edit_alter(&$form, &$form_state) {
870
  // Make adjustments to the file edit form when used in a CTools modal.
871
  if (!empty($form_state['ajax'])) {
872
    // Remove the preview and the delete button.
873
    $form['preview']['#access'] = FALSE;
874
    $form['actions']['delete']['#access'] = FALSE;
875

    
876
    // Convert the cancel link to a button which triggers a modal close.
877
    $form['actions']['cancel']['#attributes']['class'][] = 'button';
878
    $form['actions']['cancel']['#attributes']['class'][] = 'button-no';
879
    $form['actions']['cancel']['#attributes']['class'][] = 'ctools-close-modal';
880
  }
881
}
882

    
883
/**
884
 * The #value_callback for a media type element.
885
 */
886
function media_file_value(&$element, $input = FALSE, $form_state = NULL) {
887
  $fid = 0;
888

    
889
  // Find the current value of this field from the form state.
890
  $form_state_fid = $form_state['values'];
891
  foreach ($element['#parents'] as $parent) {
892
    $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
893
  }
894

    
895
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
896
    $fid = $form_state_fid['fid'];
897
  }
898
  elseif (is_numeric($form_state_fid)) {
899
    $fid = $form_state_fid;
900
  }
901

    
902
  // Process any input and attach files.
903
  if ($input !== FALSE) {
904
    $return = $input;
905

    
906
    // Attachments take priority over all other values.
907
    if ($file = media_attach_file($element)) {
908
      $fid = $file->fid;
909
    }
910
    else {
911
      // Check for #filefield_value_callback values.
912
      // Because FAPI does not allow multiple #value_callback values like it
913
      // does for #element_validate and #process, this fills the missing
914
      // functionality to allow File fields to be extended through FAPI.
915
      if (isset($element['#file_value_callbacks'])) {
916
        foreach ($element['#file_value_callbacks'] as $callback) {
917
          $callback($element, $input, $form_state);
918
        }
919
      }
920
      // Load file if the FID has changed to confirm it exists.
921
      if (isset($input['fid']) && $file = file_load($input['fid'])) {
922
        $fid = $file->fid;
923
      }
924
    }
925
  }
926

    
927
  // If there is no input, set the default value.
928
  else {
929
    if ($element['#extended']) {
930
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
931
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
932
    }
933
    else {
934
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
935
      $return = array('fid' => 0);
936
    }
937

    
938
    // Confirm that the file exists when used as a default value.
939
    if ($default_fid && $file = file_load($default_fid)) {
940
      $fid = $file->fid;
941
    }
942
  }
943

    
944
  $return['fid'] = $fid;
945

    
946
  return $return;
947
}
948

    
949
/**
950
 * Validate media form elements.
951
 *
952
 * The file type is validated during the upload process, but this is necessary
953
 * necessary in order to respect the #required property.
954
 */
955
function media_element_validate(&$element, &$form_state) {
956
  $clicked_button = end($form_state['triggering_element']['#parents']);
957

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

    
963
  // Consolidate the array value of this field to a single FID.
964
  if (!$element['#extended']) {
965
    form_set_value($element, $element['fid']['#value'], $form_state);
966
  }
967
}
968

    
969
/**
970
 * Form submission handler for attach / remove buttons of media elements.
971
 *
972
 * @see media_element_process()
973
 */
974
function media_file_submit($form, &$form_state) {
975
  // Determine whether it was the attach or remove button that was clicked, and
976
  // set $element to the managed_file element that contains that button.
977
  $parents = $form_state['triggering_element']['#array_parents'];
978
  $button_key = array_pop($parents);
979
  $element = drupal_array_get_nested_value($form, $parents);
980

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

    
1004
  // Set the form to rebuild so that $form is correctly updated in response to
1005
  // processing the file removal. Since this function did not change $form_state
1006
  // if the upload button was clicked, a rebuild isn't necessary in that
1007
  // situation and setting $form_state['redirect'] to FALSE would suffice.
1008
  // However, we choose to always rebuild, to keep the form processing workflow
1009
  // consistent between the two buttons.
1010
  $form_state['rebuild'] = TRUE;
1011
}
1012

    
1013
/**
1014
 * Attaches any files that have been referenced by a media element.
1015
 *
1016
 * @param $element
1017
 *   The FAPI element whose files are being attached.
1018
 *
1019
 * @return
1020
 *   The file object representing the file that was attached, or FALSE if no
1021
 *   file was attached.
1022
 */
1023
function media_attach_file($element) {
1024
  $upload_name = implode('_', $element['#parents']);
1025
  if (empty($_POST['media'][$upload_name])) {
1026
    return FALSE;
1027
  }
1028

    
1029
  if (!$file = file_load($_POST['media'][$upload_name])) {
1030
    watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
1031
    form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
1032
    return FALSE;
1033
  }
1034

    
1035
  return $file;
1036
}
1037

    
1038
/**
1039
 * Returns HTML for a managed file element.
1040
 *
1041
 * @param $variables
1042
 *   An associative array containing:
1043
 *   - element: A render element representing the file.
1044
 *
1045
 * @ingroup themeable
1046
 */
1047
function theme_media_element($variables) {
1048
  $element = $variables['element'];
1049

    
1050
  $attributes = array();
1051
  if (isset($element['#id'])) {
1052
    $attributes['id'] = $element['#id'];
1053
  }
1054
  if (!empty($element['#attributes']['class'])) {
1055
    $attributes['class'] = (array) $element['#attributes']['class'];
1056
  }
1057
  $attributes['class'][] = 'form-media';
1058

    
1059
  // This wrapper is required to apply JS behaviors and CSS styling.
1060
  $output = '';
1061
  $output .= '<div' . drupal_attributes($attributes) . '>';
1062
  $output .= drupal_render_children($element);
1063
  $output .= '</div>';
1064
  return $output;
1065
}
1066

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

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

    
1125
  $preview = file_view_file($file, $view_mode);
1126
  $preview['#show_names'] = TRUE;
1127
  $preview['#add_link'] = $link;
1128
  $preview['#theme_wrappers'][] = 'media_thumbnail';
1129
  $preview['#attached']['css'][] = drupal_get_path('module', 'media') . '/css/media.css';
1130

    
1131
  return $preview;
1132
}
1133

    
1134
/**
1135
 * Check that the media is one of the selected types.
1136
 *
1137
 * @param object $file
1138
 *   A Drupal file object.
1139
 * @param array $types
1140
 *   An array of media type names
1141
 *
1142
 * @return array
1143
 *   If the file type is not allowed, it will contain an error message.
1144
 *
1145
 * @see hook_file_validate()
1146
 */
1147
function media_file_validate_types($file, $types) {
1148
  $errors = array();
1149

    
1150
  if (!function_exists('file_entity_get_filetype_candidates')) {
1151
    module_load_include('inc', 'file_entity', 'file_entity.pages');
1152
  }
1153
  $file_candidates = array_keys(file_entity_get_filetype_candidates($file));
1154
  if (!array_intersect($file_candidates, $types)) {
1155
    $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
1156
  }
1157

    
1158
  return $errors;
1159
}
1160

    
1161
/**
1162
 * Implements hook_file_displays_alter().
1163
 */
1164
function media_file_displays_alter(&$displays, $file, $view_mode) {
1165
  if ($view_mode == 'preview' && empty($displays)) {
1166
    // We re in the media browser and this file has no formatters enabled.
1167
    // Instead of letting it go through theme_file_link(), pass it through
1168
    // theme_media_formatter_large_icon() to get our cool file icon instead.
1169
    $displays['file_field_media_large_icon'] = array(
1170
      'weight' => 0,
1171
      'status' => 1,
1172
      'settings' => NULL,
1173
    );
1174
  }
1175

    
1176
  // Alt and title are special.
1177
  // @see file_entity_file_load
1178
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
1179
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
1180

    
1181
  $replace_options = array(
1182
    'clear' => TRUE,
1183
    'sanitize' => FALSE,
1184
  );
1185

    
1186
  // Load alt and title text from fields.
1187
  if (!empty($alt)) {
1188
    $file->alt = decode_entities(token_replace($alt, array('file' => $file), $replace_options));
1189
  }
1190
  if (!empty($title)) {
1191
    $file->title = decode_entities(token_replace($title, array('file' => $file), $replace_options));
1192
  }
1193
}
1194

    
1195
/**
1196
 * For sanity in grammar.
1197
 *
1198
 * @see media_set_browser_params()
1199
 */
1200
function media_get_browser_params() {
1201
  return media_set_browser_params();
1202
}
1203

    
1204
/**
1205
 * Provides a singleton of the params passed to the media browser.
1206
 *
1207
 * This is useful in situations like form alters because callers can pass
1208
 * id="wysiywg_form" or whatever they want, and a form alter could pick this up.
1209
 * We may want to change the hook_media_browser_plugin_view() implementations to
1210
 * use this function instead of being passed params for consistency.
1211
 *
1212
 * It also offers a chance for some meddler to meddle with them.
1213
 *
1214
 * @see media_browser()
1215
 */
1216
function media_set_browser_params() {
1217
  $params = &drupal_static(__FUNCTION__, array());
1218

    
1219
  if (empty($params)) {
1220
    // Build out browser settings. Permissions- and security-related behaviors
1221
    // should not rely on these parameters, since they come from the HTTP query.
1222
    // There are two ways of passing secure data:
1223
    // - Store the options in the 'cache_form' cache bin, using a random key
1224
    //   prefixed with 'media_options:'. Pass the random key in the 'options'
1225
    //   query argument.
1226
    // - Inject the options by altering the browser parameters.
1227
    //   @see hook_media_browser_params_alter()
1228
    $params = drupal_get_query_parameters();
1229

    
1230
    // Filter out everything except a whitelist of known safe options.
1231
    $safe_options = array(
1232
      'enabledPlugins',
1233
      'fid',
1234
      'id',
1235
      'multiselect',
1236
      'field',
1237
      'options',
1238
      'plugins',
1239
      'render',
1240
      'types',
1241
      'render_multi_edit_form',
1242
    );
1243
    $params = array_intersect_key($params, array_flip($safe_options));
1244

    
1245
    // If the cache is present, use its values instead of the GET parameters.
1246
    if (!empty($params['options']) && is_string($params['options']) && $options = cache_get('media_options:' . $params['options'], 'cache_form')) {
1247
      $params = $options->data;
1248
    }
1249

    
1250
    // Transform text 'true' and 'false' to actual booleans.
1251
    foreach ($params as $k => $v) {
1252
      if ($v === 'true') {
1253
        $params[$k] = TRUE;
1254
      }
1255
      elseif ($v === 'false') {
1256
        $params[$k] = FALSE;
1257
      }
1258
    }
1259

    
1260
    array_walk_recursive($params, 'media_recursive_check_plain');
1261

    
1262
    // Provide some default parameters.
1263
    $params += array(
1264
      'types' => array(),
1265
      'multiselect' => FALSE,
1266
    );
1267

    
1268
    // Allow modules to alter the parameters.
1269
    drupal_alter('media_browser_params', $params);
1270
  }
1271

    
1272
  return $params;
1273
}
1274

    
1275
/**
1276
 * Implements hook_ctools_plugin_api().
1277
 *
1278
 * Lets CTools know which plugin APIs are implemented by Media module.
1279
 */
1280
function media_ctools_plugin_api($module, $api) {
1281
  if ($module == 'file_entity' && $api == 'file_default_displays') {
1282
    return array(
1283
      'version' => 1,
1284
    );
1285
  }
1286
}
1287

    
1288
/**
1289
 * Implements hook_form_FORM_ID_alter().
1290
 *
1291
 * This alter enhances the default admin/content/file page, addding JS and CSS.
1292
 * It also makes modifications to the thumbnail view by replacing the existing
1293
 * checkboxes and table with thumbnails.
1294
 */
1295
function media_form_file_entity_admin_file_alter(&$form, $form_state) {
1296
  if (!empty($form_state['values']['operation'])) {
1297
    // The form is being rebuilt because an operation requiring confirmation
1298
    // We don't want to be messing with it in this case.
1299
    return;
1300
  }
1301

    
1302
  // Add the "Add file" local action, and notify users if they have files
1303
  // selected and they try to switch between the "Thumbnail" and "List" local
1304
  // tasks.
1305
  $path = drupal_get_path('module', 'media');
1306
  $form['#attributes']['class'][] = 'file-entity-admin-file-form';
1307
  $form['#attached']['js'][] = $path . '/js/media.admin.js';
1308
  $form['#attached']['css'][] = $path . '/css/media.css';
1309

    
1310
  // By default, this form contains a table select element called "files". For
1311
  // the 'thumbnails' tab, Media generates a thumbnail for each file and
1312
  // replaces the tableselect with a grid of thumbnails.
1313
  if (arg(3) == 'thumbnails') {
1314
    if (empty($form['admin']['files']['#options'])) {
1315
      // Display empty text if there are no files.
1316
      $form['admin']['files'] = array(
1317
        '#markup' => '<p>' . $form['admin']['files']['#empty'] . '</p>',
1318
      );
1319
    }
1320
    else {
1321
      $files = file_load_multiple(array_keys($form['admin']['files']['#options']));
1322

    
1323
      $form['admin']['files'] = array(
1324
        '#tree' => TRUE,
1325
        '#prefix' => '<div class="media-display-thumbnails media-clear clearfix"><ul id="media-browser-library-list" class="media-list-thumbnails">',
1326
        '#suffix' => '</ul></div>',
1327
      );
1328

    
1329
      foreach ($files as $file) {
1330
        $preview = media_get_thumbnail_preview($file, TRUE);
1331
        $form['admin']['files'][$file->fid] = array(
1332
          '#type' => 'checkbox',
1333
          '#title' => '',
1334
          '#prefix' => '<li>' . drupal_render($preview),
1335
          '#suffix' => '</li>',
1336
        );
1337
      }
1338
    }
1339
  }
1340
}
1341

    
1342
/**
1343
 * Implements hook_views_api().
1344
 */
1345
function media_views_api() {
1346
  return array(
1347
    'api' => 3,
1348
    'path' => drupal_get_path('module', 'media'),
1349
  );
1350
}
1351

    
1352
/**
1353
 * Implements hook_views_default_views().
1354
 */
1355
function media_views_default_views() {
1356
  return media_load_all_exports('media', 'views', 'view.inc', 'view');
1357
}
1358

    
1359
/**
1360
 * Fetches an array of exportables from files.
1361
 *
1362
 * @param string $module
1363
 *   The module invoking this request. (Can be called by other modules.)
1364
 * @param string $directory
1365
 *   The subdirectory in the custom module.
1366
 * @param string $extension
1367
 *   The file extension.
1368
 * @param string $name
1369
 *   The name of the variable found in each file. Defaults to the same as
1370
 *   $extension.
1371
 *
1372
 * @return array
1373
 *   Array of $name objects.
1374
 */
1375
function media_load_all_exports($module, $directory, $extension, $name = NULL) {
1376
  if (!$name) {
1377
    $name = $extension;
1378
  }
1379

    
1380
  $return = array();
1381
  // Find all the files in the directory with the correct extension.
1382
  $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
1383
  foreach ($files as $path => $file) {
1384
    require $path;
1385
    if (isset($$name)) {
1386
      $return[$$name->name] = $$name;
1387
    }
1388
  }
1389

    
1390
  return $return;
1391
}
1392

    
1393
/**
1394
 * Returns metadata describing Media browser plugins.
1395
 *
1396
 * @return
1397
 *   An associative array of plugin information, keyed by plugin.
1398
 *
1399
 * @see hook_media_browser_plugin_info()
1400
 * @see hook_media_browser_plugin_info_alter()
1401
 */
1402
function media_get_browser_plugin_info() {
1403
  $info = &drupal_static(__FUNCTION__);
1404

    
1405
  if (!isset($info)) {
1406
    $info = module_invoke_all('media_browser_plugin_info');
1407
    drupal_alter('media_browser_plugin_info', $info);
1408
  }
1409

    
1410
  return $info;
1411
}
1412

    
1413
/**
1414
 * Gets the MIME type mapped to a given extension.
1415
 *
1416
 * @param string $extension
1417
 *   A file extension.
1418
 *
1419
 * @return string
1420
 *   The MIME type associated with the extension or FALSE if the extension does
1421
 *   not have an associated MIME type.
1422
 *
1423
 * @see file_mimetype_mapping()
1424
 */
1425
function media_get_extension_mimetype($extension) {
1426
  include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
1427
  $mimetype_mappings = file_mimetype_mapping();
1428

    
1429
  if (isset($mimetype_mappings['extensions'][$extension])) {
1430
    $id = $mimetype_mappings['extensions'][$extension];
1431
    return $mimetype_mappings['mimetypes'][$id];
1432
  }
1433
  else {
1434
    return FALSE;
1435
  }
1436
}
1437

    
1438
/**
1439
 * Helper function to get a list of local stream wrappers.
1440
 */
1441
function media_get_local_stream_wrappers() {
1442
  return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
1443
}
1444

    
1445
/**
1446
 * Helper function to get a list of remote stream wrappers.
1447
 */
1448
function media_get_remote_stream_wrappers() {
1449
  $wrappers = file_get_stream_wrappers();
1450
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
1451
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
1452
  return $wrappers;
1453
}