Project

General

Profile

Paste
Download (49.8 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / media / media.module @ 01f36513

1
<?php
2

    
3
/**
4
 * @file
5
 * Media API
6
 *
7
 * The core Media API.
8
 * See http://drupal.org/project/media for more details.
9
 */
10

    
11
// Code relating to using media as a field.
12
require_once dirname(__FILE__) . '/includes/media.fields.inc';
13

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

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

    
30
/**
31
 * Implements hook_help().
32
 */
33
function media_help($path, $arg) {
34
  switch ($path) {
35
    case 'admin/help#media':
36
      $output = '';
37
      $output .= '<h3>' . t('About') . '</h3>';
38
      $output .= '<p>' . t('The Media module is a File Browser to the Internet, media provides a framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site. It replaces the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Media module also provides rich integration with WYSIWYG module to let content creators access media assets in rich text editor. Javascript is required to use the Media module.  For more information check <a href="@media_faq">Media Module page</a>', array('@media_faq' => 'http://drupal.org/project/media')) . '.</p>';
39
      $output .= '<h3>' . t('Uses') . '</h3>';
40
      $output .= '<dl>';
41
      $output .= '<dt>' . t('Media Repository') . '</dt>';
42
      $output .= '<dd>' . t('Media module allows you to maintain a <a href="@mediarepo">media asset repository</a> where in you can add, remove, reuse your media assets. You can add the media file using upload form or from a url and also do bulk operations on the media assets.', array('@mediarepo' => url('admin/content/media'))) . '</dd>';
43
      $output .= '<dt>' . t('Attaching media assets to content types') . '</dt>';
44
      $output .= '<dd>' . t('Media assets can be attached to content types as fields. To add a media field to a <a href="@content-type">content type</a>, go to the content type\'s <em>manage fields</em> page, and add a new field of type <em>Multimedia Asset</em>.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
45
      $output .= '<dt>' . t('Using media assets in WYSIWYG') . '</dt>';
46
      $output .= '<dd>' . t('Media module provides rich integration with WYSIWYG editors, using Media Browser plugin you can select media asset from library to add to the rich text editor moreover you can add media asset from the media browser itself using either upload method or add from url method. To configure media with WYSIWYG you need two steps of configuration:');
47
      $output .= '<ul><li>' . t('Enable WYSIWYG plugin on your desired <a href="@wysiwyg-profile">WYSIWYG profile</a>. Please note that you will need to have <a href="@wysiwyg">WYSIWYG</a> module enabled.', array('@wysiwyg-profile' => url('admin/config/content/wysiwyg'), '@wysiwyg' => 'http://drupal.org/project/wysiwyg')) . '</li>';
48
      $output .= '<li>' . t('Enable the <em>Convert Media tags to markup</em> filter on the <a href="@input-format">Input format</a> you are using with the WYSIWYG profile.', array('@input-format' => url('admin/config/content/formats'))) . '</li></ul></dd>';
49
      return $output;
50
  }
51
}
52

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

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

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

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

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

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

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

    
145
  return $items;
146
}
147

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

    
165
/**
166
 * Implements hook_admin_paths().
167
 */
168
function media_admin_paths() {
169
  $paths['media/*/edit/*'] = TRUE;
170
  $paths['media/*/format-form'] = TRUE;
171
  if (module_exists('admin_language')) {
172
    $paths['media/ajax/*'] = TRUE; // For admin_language module compatibility.
173
  }
174

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

    
183
  return $paths;
184
}
185

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
667
  return $file;
668
}
669

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

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

    
708
  $setting = array();
709
  $setting['media']['global'] = $types['media']['#media_options'];
710

    
711
  $types['media']['#attached']['js'][] = array(
712
    'type' => 'setting',
713
    'data' => $setting,
714
  );
715

    
716
  return $types;
717
}
718

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

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

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

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

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

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

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

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

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

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

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

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

    
834
  $element['fid'] = array(
835
    '#type' => 'hidden',
836
    '#value' => $fid,
837
    '#attributes' => array('class' => array('fid')),
838
  );
839

    
840
  // Media browser attach code.
841
  $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
842

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

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

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

    
859
  $element['#attached']['library'][] = array('media', 'media_browser');
860
  $element['#attached']['library'][] = array('media', 'media_browser_settings');
861

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

    
866
  return $element;
867
}
868

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

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

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

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

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

    
905
  // Process any input and attach files.
906
  if ($input !== FALSE) {
907
    $return = $input;
908

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

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

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

    
947
  $return['fid'] = $fid;
948

    
949
  return $return;
950
}
951

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

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

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

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

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

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

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

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

    
1038
  return $file;
1039
}
1040

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

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

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

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

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

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

    
1134
  return $preview;
1135
}
1136

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

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

    
1161
  return $errors;
1162
}
1163

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

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

    
1184
  $replace_options = array(
1185
    'clear' => TRUE,
1186
    'sanitize' => FALSE,
1187
  );
1188

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

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

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

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

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

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

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

    
1263
    array_walk_recursive($params, 'media_recursive_check_plain');
1264

    
1265
    // Provide some default parameters.
1266
    $params += array(
1267
      'types' => array(),
1268
      'multiselect' => FALSE,
1269
    );
1270

    
1271
    // Allow modules to alter the parameters.
1272
    drupal_alter('media_browser_params', $params);
1273
  }
1274

    
1275
  return $params;
1276
}
1277

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

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

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

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

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

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

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

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

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

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

    
1393
  return $return;
1394
}
1395

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

    
1408
  if (!isset($info)) {
1409
    $info = module_invoke_all('media_browser_plugin_info');
1410
    drupal_alter('media_browser_plugin_info', $info);
1411
  }
1412

    
1413
  return $info;
1414
}
1415

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

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

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

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