Projet

Général

Profil

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

root / drupal7 / sites / all / modules / media / media.module @ 7547bb19

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

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

    
180
  return $paths;
181
}
182

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

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

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

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

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

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

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

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

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

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

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

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

    
296
  $output = theme('status_messages') . drupal_render($form);
297
  $js = drupal_add_js();
298
  $settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
299

    
300
  $commands[] = ajax_command_replace(NULL, $output, $settings);
301
  return array('#type' => 'ajax', '#commands' => $commands);
302
}
303

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
527
  foreach ($libraries as &$library) {
528
    $library += $common;
529
  }
530
  return $libraries;
531
}
532

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

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

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

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

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

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

    
655
  return $file;
656
}
657

    
658
/**
659
 * Utility function to recursively run check_plain on an array.
660
 *
661
 * @todo There is probably something in core I am not aware of that does this.
662
 */
663
function media_recursive_check_plain(&$value, $key) {
664
  $value = check_plain($value);
665
}
666

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

    
696
  $setting = array();
697
  $setting['media']['global'] = $types['media']['#media_options'];
698

    
699
  $types['media']['#attached']['js'][] = array(
700
    'type' => 'setting',
701
    'data' => $setting,
702
  );
703

    
704
  return $types;
705
}
706

    
707
/**
708
 * Process callback for the media form element.
709
 */
710
function media_element_process($element, &$form_state, $form) {
711
  ctools_include('modal');
712
  ctools_include('ajax');
713
  ctools_modal_add_js();
714

    
715
  // Append the '-upload' to the #id so the field label's 'for' attribute
716
  // corresponds with the textfield element.
717
  $original_id = $element['#id'];
718
  $element['#id'] .= '-upload';
719
  $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
720

    
721
  // Set some default element properties.
722
  $element['#file'] = $fid ? file_load($fid) : FALSE;
723
  $element['#tree'] = TRUE;
724

    
725
  $ajax_settings = array(
726
    'path' => 'media/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
727
    'wrapper' => $original_id . '-ajax-wrapper',
728
    'effect' => 'fade',
729
  );
730

    
731
  // Set up the buttons first since we need to check if they were clicked.
732
  $element['attach_button'] = array(
733
    '#name' => implode('_', $element['#parents']) . '_attach_button',
734
    '#type' => 'submit',
735
    '#value' => t('Attach'),
736
    '#validate' => array(),
737
    '#submit' => array('media_file_submit'),
738
    '#limit_validation_errors' => array($element['#parents']),
739
    '#ajax' => $ajax_settings,
740
    '#attributes' => array('class' => array('attach')),
741
    '#weight' => -1,
742
  );
743

    
744
  $element['preview'] = array(
745
    'content' => array(),
746
    '#prefix' => '<div class="preview">',
747
    '#suffix' => '</div>',
748
    '#ajax' => $ajax_settings,
749
    '#weight' => -10,
750
  );
751

    
752
  // Substitute the JS preview for a true file thumbnail once the file is
753
  // attached.
754
  if ($fid && $element['#file']) {
755
    $element['preview']['content'] = media_get_thumbnail_preview($element['#file']);
756
  }
757

    
758
  // The file ID field itself.
759
  $element['upload'] = array(
760
    '#name' => 'media[' . implode('_', $element['#parents']) . ']',
761
    '#type' => 'textfield',
762
    '#title' => t('Enter the ID of an existing file'),
763
    '#title_display' => 'invisible',
764
    '#field_prefix' => t('File ID'),
765
    '#size' => $element['#size'],
766
    '#theme_wrappers' => array(),
767
    '#attributes' => array('class' => array('upload')),
768
    '#weight' => -9,
769
  );
770

    
771
  $element['browse_button'] = array(
772
    '#type' => 'link',
773
    '#href' => '',
774
    '#title' => t('Browse'),
775
    '#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
776
    '#options' => array('fragment' => FALSE, 'external' => TRUE),
777
    '#weight' => -8,
778
  );
779

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

    
800
  // If we have parent entity form/source langcodes, pass them in query. They
801
  // will be used in
802
  /* @see media_file_edit_modal() */
803
  if (!empty($element['#media_parent_entity_form_langcode'])) {
804
    $element['edit']['#options']['query']['media_parent_entity_form_langcode'] = $element['#media_parent_entity_form_langcode'];
805
    if (!empty($element['#media_parent_entity_source_langcode'])) {
806
      $element['edit']['#options']['query']['media_parent_entity_source_langcode'] = $element['#media_parent_entity_source_langcode'];
807
    }
808
  }
809

    
810
  $element['remove_button'] = array(
811
    '#name' => implode('_', $element['#parents']) . '_remove_button',
812
    '#type' => 'submit',
813
    '#value' => t('Remove'),
814
    '#validate' => array(),
815
    '#submit' => array('media_file_submit'),
816
    '#limit_validation_errors' => array($element['#parents']),
817
    '#ajax' => $ajax_settings,
818
    '#attributes' => array('class' => array('remove')),
819
    '#weight' => 0,
820
  );
821

    
822
  $element['fid'] = array(
823
    '#type' => 'hidden',
824
    '#value' => $fid,
825
    '#attributes' => array('class' => array('fid')),
826
  );
827

    
828
  // Media browser attach code.
829
  $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
830

    
831
  // Add the media options to the page as JavaScript settings.
832
  $element['browse_button']['#attached']['js'] = array(
833
    array(
834
      'type' => 'setting',
835
      'data' => array('media' => array('elements' => array('#' . $element['#id'] => $element['#media_options'])))
836
    )
837
  );
838

    
839
  $element['#attached']['library'][] = array('media', 'media_browser');
840
  $element['#attached']['library'][] = array('media', 'media_browser_settings');
841

    
842
  // Prefix and suffix used for Ajax replacement.
843
  $element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
844
  $element['#suffix'] = '</div>';
845

    
846
  return $element;
847
}
848

    
849
/**
850
 * Implements hook_form_FORM_ID_alter().
851
 */
852
function media_form_file_entity_edit_alter(&$form, &$form_state) {
853
  // Make adjustments to the file edit form when used in a CTools modal.
854
  if (!empty($form_state['ajax'])) {
855
    // Remove the preview and the delete button.
856
    $form['preview']['#access'] = FALSE;
857
    $form['actions']['delete']['#access'] = FALSE;
858

    
859
    // Convert the cancel link to a button which triggers a modal close.
860
    $form['actions']['cancel']['#attributes']['class'][] = 'button';
861
    $form['actions']['cancel']['#attributes']['class'][] = 'button-no';
862
    $form['actions']['cancel']['#attributes']['class'][] = 'ctools-close-modal';
863
  }
864
}
865

    
866
/**
867
 * The #value_callback for a media type element.
868
 */
869
function media_file_value(&$element, $input = FALSE, $form_state = NULL) {
870
  $fid = 0;
871

    
872
  // Find the current value of this field from the form state.
873
  $form_state_fid = $form_state['values'];
874
  foreach ($element['#parents'] as $parent) {
875
    $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
876
  }
877

    
878
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
879
    $fid = $form_state_fid['fid'];
880
  }
881
  elseif (is_numeric($form_state_fid)) {
882
    $fid = $form_state_fid;
883
  }
884

    
885
  // Process any input and attach files.
886
  if ($input !== FALSE) {
887
    $return = $input;
888

    
889
    // Attachments take priority over all other values.
890
    if ($file = media_attach_file($element)) {
891
      $fid = $file->fid;
892
    }
893
    else {
894
      // Check for #filefield_value_callback values.
895
      // Because FAPI does not allow multiple #value_callback values like it
896
      // does for #element_validate and #process, this fills the missing
897
      // functionality to allow File fields to be extended through FAPI.
898
      if (isset($element['#file_value_callbacks'])) {
899
        foreach ($element['#file_value_callbacks'] as $callback) {
900
          $callback($element, $input, $form_state);
901
        }
902
      }
903
      // Load file if the FID has changed to confirm it exists.
904
      if (isset($input['fid']) && $file = file_load($input['fid'])) {
905
        $fid = $file->fid;
906
      }
907
    }
908
  }
909

    
910
  // If there is no input, set the default value.
911
  else {
912
    if ($element['#extended']) {
913
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
914
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
915
    }
916
    else {
917
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
918
      $return = array('fid' => 0);
919
    }
920

    
921
    // Confirm that the file exists when used as a default value.
922
    if ($default_fid && $file = file_load($default_fid)) {
923
      $fid = $file->fid;
924
    }
925
  }
926

    
927
  $return['fid'] = $fid;
928

    
929
  return $return;
930
}
931

    
932
/**
933
 * Validate media form elements.
934
 *
935
 * The file type is validated during the upload process, but this is necessary
936
 * necessary in order to respect the #required property.
937
 */
938
function media_element_validate(&$element, &$form_state) {
939
  $clicked_button = end($form_state['triggering_element']['#parents']);
940

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

    
946
  // Consolidate the array value of this field to a single FID.
947
  if (!$element['#extended']) {
948
    form_set_value($element, $element['fid']['#value'], $form_state);
949
  }
950
}
951

    
952
/**
953
 * Form submission handler for attach / remove buttons of media elements.
954
 *
955
 * @see media_element_process()
956
 */
957
function media_file_submit($form, &$form_state) {
958
  // Determine whether it was the attach or remove button that was clicked, and
959
  // set $element to the managed_file element that contains that button.
960
  $parents = $form_state['triggering_element']['#array_parents'];
961
  $button_key = array_pop($parents);
962
  $element = drupal_array_get_nested_value($form, $parents);
963

    
964
  // No action is needed here for the attach button, because all media
965
  // attachments on the form are processed by media_file_value() regardless of
966
  // which button was clicked. Action is needed here for the remove button,
967
  // because we only remove a file in response to its remove button being
968
  // clicked.
969
  if ($button_key == 'remove_button') {
970
    // If it's a temporary file we can safely remove it immediately, otherwise
971
    // it's up to the implementing module to clean up files that are in use.
972
    if ($element['#file'] && $element['#file']->status == 0) {
973
      file_delete($element['#file']);
974
    }
975
    // Update both $form_state['values'] and $form_state['input'] to reflect
976
    // that the file has been removed, so that the form is rebuilt correctly.
977
    // $form_state['values'] must be updated in case additional submit handlers
978
    // run, and for form building functions that run during the rebuild, such as
979
    // when the media element is part of a field widget.
980
    // $form_state['input'] must be updated so that media_file_value() has
981
    // correct information during the rebuild.
982
    $values_element = $element['#extended'] ? $element['fid'] : $element;
983
    form_set_value($values_element, NULL, $form_state);
984
    drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
985
  }
986

    
987
  // Set the form to rebuild so that $form is correctly updated in response to
988
  // processing the file removal. Since this function did not change $form_state
989
  // if the upload button was clicked, a rebuild isn't necessary in that
990
  // situation and setting $form_state['redirect'] to FALSE would suffice.
991
  // However, we choose to always rebuild, to keep the form processing workflow
992
  // consistent between the two buttons.
993
  $form_state['rebuild'] = TRUE;
994
}
995

    
996
/**
997
 * Attaches any files that have been referenced by a media element.
998
 *
999
 * @param $element
1000
 *   The FAPI element whose files are being attached.
1001
 *
1002
 * @return
1003
 *   The file object representing the file that was attached, or FALSE if no
1004
 *   file was attached.
1005
 */
1006
function media_attach_file($element) {
1007
  $upload_name = implode('_', $element['#parents']);
1008
  if (empty($_POST['media'][$upload_name])) {
1009
    return FALSE;
1010
  }
1011

    
1012
  if (!$file = file_load($_POST['media'][$upload_name])) {
1013
    watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
1014
    form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
1015
    return FALSE;
1016
  }
1017

    
1018
  return $file;
1019
}
1020

    
1021
/**
1022
 * Returns HTML for a managed file element.
1023
 *
1024
 * @param $variables
1025
 *   An associative array containing:
1026
 *   - element: A render element representing the file.
1027
 *
1028
 * @ingroup themeable
1029
 */
1030
function theme_media_element($variables) {
1031
  $element = $variables['element'];
1032

    
1033
  $attributes = array();
1034
  if (isset($element['#id'])) {
1035
    $attributes['id'] = $element['#id'];
1036
  }
1037
  if (!empty($element['#attributes']['class'])) {
1038
    $attributes['class'] = (array) $element['#attributes']['class'];
1039
  }
1040
  $attributes['class'][] = 'form-media';
1041

    
1042
  // This wrapper is required to apply JS behaviors and CSS styling.
1043
  $output = '';
1044
  $output .= '<div' . drupal_attributes($attributes) . '>';
1045
  $output .= drupal_render_children($element);
1046
  $output .= '</div>';
1047
  return $output;
1048
}
1049

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

    
1084
/**
1085
 * Generates a thumbnail preview of a file.
1086
 *
1087
 * Provides default fallback images if an image of the file cannot be generated.
1088
 *
1089
 * @param object $file
1090
 *   A Drupal file object.
1091
 * @param boolean $link
1092
 *   (optional) Boolean indicating whether the thumbnail should be linked to the
1093
 *   file. Defaults to FALSE.
1094
 * @param string $view_mode
1095
 *   (optional) The view mode to use when rendering the thumbnail. Defaults to
1096
 *   'preview'.
1097
 *
1098
 * @return array
1099
 *   Renderable array suitable for drupal_render() with the necessary classes
1100
 *   and CSS to support a media thumbnail.
1101
 */
1102
function media_get_thumbnail_preview($file, $link = FALSE, $view_mode = 'preview') {
1103
  // If a file has an invalid type, allow file_view_file() to work.
1104
  if (!file_type_is_enabled($file->type)) {
1105
    $file->type = file_get_type($file);
1106
  }
1107

    
1108
  $preview = file_view_file($file, $view_mode);
1109
  $preview['#show_names'] = TRUE;
1110
  $preview['#add_link'] = $link;
1111
  $preview['#theme_wrappers'][] = 'media_thumbnail';
1112
  $preview['#attached']['css'][] = drupal_get_path('module', 'media') . '/css/media.css';
1113

    
1114
  return $preview;
1115
}
1116

    
1117
/**
1118
 * Check that the media is one of the selected types.
1119
 *
1120
 * @param object $file
1121
 *   A Drupal file object.
1122
 * @param array $types
1123
 *   An array of media type names
1124
 *
1125
 * @return array
1126
 *   If the file type is not allowed, it will contain an error message.
1127
 *
1128
 * @see hook_file_validate()
1129
 */
1130
function media_file_validate_types($file, $types) {
1131
  $errors = array();
1132
  if (!in_array(file_get_type($file), $types)) {
1133
    $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
1134
  }
1135

    
1136
  return $errors;
1137
}
1138

    
1139
/**
1140
 * Implements hook_file_displays_alter().
1141
 */
1142
function media_file_displays_alter(&$displays, $file, $view_mode) {
1143
  if ($view_mode == 'preview' && empty($displays)) {
1144
    // We re in the media browser and this file has no formatters enabled.
1145
    // Instead of letting it go through theme_file_link(), pass it through
1146
    // theme_media_formatter_large_icon() to get our cool file icon instead.
1147
    $displays['file_field_media_large_icon'] = array(
1148
      'weight' => 0,
1149
      'status' => 1,
1150
      'settings' => NULL,
1151
    );
1152
  }
1153

    
1154
  // Alt and title are special.
1155
  // @see file_entity_file_load
1156
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
1157
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
1158

    
1159
  $replace_options = array(
1160
    'clear' => TRUE,
1161
    'sanitize' => FALSE,
1162
  );
1163

    
1164
  // Load alt and title text from fields.
1165
  if (!empty($alt)) {
1166
    $file->alt = decode_entities(token_replace($alt, array('file' => $file), $replace_options));
1167
  }
1168
  if (!empty($title)) {
1169
    $file->title = decode_entities(token_replace($title, array('file' => $file), $replace_options));
1170
  }
1171
}
1172

    
1173
/**
1174
 * For sanity in grammar.
1175
 *
1176
 * @see media_set_browser_params()
1177
 */
1178
function media_get_browser_params() {
1179
  return media_set_browser_params();
1180
}
1181

    
1182
/**
1183
 * Provides a singleton of the params passed to the media browser.
1184
 *
1185
 * This is useful in situations like form alters because callers can pass
1186
 * id="wysiywg_form" or whatever they want, and a form alter could pick this up.
1187
 * We may want to change the hook_media_browser_plugin_view() implementations to
1188
 * use this function instead of being passed params for consistency.
1189
 *
1190
 * It also offers a chance for some meddler to meddle with them.
1191
 *
1192
 * @see media_browser()
1193
 */
1194
function media_set_browser_params() {
1195
  $params = &drupal_static(__FUNCTION__, array());
1196

    
1197
  if (empty($params)) {
1198
    // Build out browser settings. Permissions- and security-related behaviors
1199
    // should not rely on these parameters, since they come from the HTTP query.
1200
    // @TODO make sure we treat parameters as user input.
1201
    $params = drupal_get_query_parameters() + array(
1202
        'types' => array(),
1203
        'multiselect' => FALSE,
1204
      );
1205

    
1206
    // Transform text 'true' and 'false' to actual booleans.
1207
    foreach ($params as $k => $v) {
1208
      if ($v === 'true') {
1209
        $params[$k] = TRUE;
1210
      }
1211
      elseif ($v === 'false') {
1212
        $params[$k] = FALSE;
1213
      }
1214
    }
1215

    
1216
    array_walk_recursive($params, 'media_recursive_check_plain');
1217

    
1218
    // Allow modules to alter the parameters.
1219
    drupal_alter('media_browser_params', $params);
1220
  }
1221

    
1222
  return $params;
1223
}
1224

    
1225
/**
1226
 * Implements hook_ctools_plugin_api().
1227
 *
1228
 * Lets CTools know which plugin APIs are implemented by Media module.
1229
 */
1230
function media_ctools_plugin_api($module, $api) {
1231
  if ($module == 'file_entity' && $api == 'file_default_displays') {
1232
    return array(
1233
      'version' => 1,
1234
    );
1235
  }
1236
}
1237

    
1238
/**
1239
 * Implements hook_form_FORM_ID_alter().
1240
 *
1241
 * This alter enhances the default admin/content/file page, addding JS and CSS.
1242
 * It also makes modifications to the thumbnail view by replacing the existing
1243
 * checkboxes and table with thumbnails.
1244
 */
1245
function media_form_file_entity_admin_file_alter(&$form, $form_state) {
1246
  if (!empty($form_state['values']['operation'])) {
1247
    // The form is being rebuilt because an operation requiring confirmation
1248
    // We don't want to be messing with it in this case.
1249
    return;
1250
  }
1251

    
1252
  // Add the "Add file" local action, and notify users if they have files
1253
  // selected and they try to switch between the "Thumbnail" and "List" local
1254
  // tasks.
1255
  $path = drupal_get_path('module', 'media');
1256
  $form['#attributes']['class'][] = 'file-entity-admin-file-form';
1257
  $form['#attached']['js'][] = $path . '/js/media.admin.js';
1258
  $form['#attached']['css'][] = $path . '/css/media.css';
1259

    
1260
  // By default, this form contains a table select element called "files". For
1261
  // the 'thumbnails' tab, Media generates a thumbnail for each file and
1262
  // replaces the tableselect with a grid of thumbnails.
1263
  if (arg(3) == 'thumbnails') {
1264
    if (empty($form['admin']['files']['#options'])) {
1265
      // Display empty text if there are no files.
1266
      $form['admin']['files'] = array(
1267
        '#markup' => '<p>' . $form['admin']['files']['#empty'] . '</p>',
1268
      );
1269
    }
1270
    else {
1271
      $files = file_load_multiple(array_keys($form['admin']['files']['#options']));
1272

    
1273
      $form['admin']['files'] = array(
1274
        '#tree' => TRUE,
1275
        '#prefix' => '<div class="media-display-thumbnails media-clear clearfix"><ul id="media-browser-library-list" class="media-list-thumbnails">',
1276
        '#suffix' => '</ul></div>',
1277
      );
1278

    
1279
      foreach ($files as $file) {
1280
        $preview = media_get_thumbnail_preview($file, TRUE);
1281
        $form['admin']['files'][$file->fid] = array(
1282
          '#type' => 'checkbox',
1283
          '#title' => '',
1284
          '#prefix' => '<li>' . drupal_render($preview),
1285
          '#suffix' => '</li>',
1286
        );
1287
      }
1288
    }
1289
  }
1290
}
1291

    
1292
/**
1293
 * Implements hook_views_api().
1294
 */
1295
function media_views_api() {
1296
  return array(
1297
    'api' => 3,
1298
    'path' => drupal_get_path('module', 'media'),
1299
  );
1300
}
1301

    
1302
/**
1303
 * Implements hook_views_default_views().
1304
 */
1305
function media_views_default_views() {
1306
  return media_load_all_exports('media', 'views', 'view.inc', 'view');
1307
}
1308

    
1309
/**
1310
 * Fetches an array of exportables from files.
1311
 *
1312
 * @param string $module
1313
 *   The module invoking this request. (Can be called by other modules.)
1314
 * @param string $directory
1315
 *   The subdirectory in the custom module.
1316
 * @param string $extension
1317
 *   The file extension.
1318
 * @param string $name
1319
 *   The name of the variable found in each file. Defaults to the same as
1320
 *   $extension.
1321
 *
1322
 * @return array
1323
 *   Array of $name objects.
1324
 */
1325
function media_load_all_exports($module, $directory, $extension, $name = NULL) {
1326
  if (!$name) {
1327
    $name = $extension;
1328
  }
1329

    
1330
  $return = array();
1331
  // Find all the files in the directory with the correct extension.
1332
  $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
1333
  foreach ($files as $path => $file) {
1334
    require $path;
1335
    if (isset($$name)) {
1336
      $return[$$name->name] = $$name;
1337
    }
1338
  }
1339

    
1340
  return $return;
1341
}
1342

    
1343
/**
1344
 * Returns metadata describing Media browser plugins.
1345
 *
1346
 * @return
1347
 *   An associative array of plugin information, keyed by plugin.
1348
 *
1349
 * @see hook_media_browser_plugin_info()
1350
 * @see hook_media_browser_plugin_info_alter()
1351
 */
1352
function media_get_browser_plugin_info() {
1353
  $info = &drupal_static(__FUNCTION__);
1354

    
1355
  if (!isset($info)) {
1356
    $info = module_invoke_all('media_browser_plugin_info');
1357
    drupal_alter('media_browser_plugin_info', $info);
1358
  }
1359

    
1360
  return $info;
1361
}
1362

    
1363
/**
1364
 * Gets the MIME type mapped to a given extension.
1365
 *
1366
 * @param string $extension
1367
 *   A file extension.
1368
 *
1369
 * @return string
1370
 *   The MIME type associated with the extension or FALSE if the extension does
1371
 *   not have an associated MIME type.
1372
 *
1373
 * @see file_mimetype_mapping()
1374
 */
1375
function media_get_extension_mimetype($extension) {
1376
  include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
1377
  $mimetype_mappings = file_mimetype_mapping();
1378

    
1379
  if (isset($mimetype_mappings['extensions'][$extension])) {
1380
    $id = $mimetype_mappings['extensions'][$extension];
1381
    return $mimetype_mappings['mimetypes'][$id];
1382
  }
1383
  else {
1384
    return FALSE;
1385
  }
1386
}
1387

    
1388
/**
1389
 * Helper function to get a list of local stream wrappers.
1390
 */
1391
function media_get_local_stream_wrappers() {
1392
  return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
1393
}
1394

    
1395
/**
1396
 * Helper function to get a list of remote stream wrappers.
1397
 */
1398
function media_get_remote_stream_wrappers() {
1399
  $wrappers = file_get_stream_wrappers();
1400
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
1401
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
1402
  return $wrappers;
1403
}