summaryrefslogtreecommitdiff
path: root/sites/all/modules/media/media.module
blob: 1f97bcb7a9db2f04dbe94b750def3c933b81d806 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
<?php

/**
 * @file
 * Media API
 *
 * The core Media API.
 * See http://drupal.org/project/media for more details.
 */

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

/**
 * Implements hook_hook_info().
 */
function media_hook_info() {
  $hooks = array(
    'media_parse',
    'media_browser_plugin_info',
    'media_browser_plugin_info_alter',
    'media_browser_plugins_alter',
    'media_browser_params_alter',
    'query_media_browser_alter',
  );

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

/**
 * Implements hook_help().
 */
function media_help($path, $arg) {
  switch ($path) {
    case 'admin/help#media':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $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>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Media Repository') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Attaching media assets to content types') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Using media assets in WYSIWYG') . '</dt>';
      $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:');
      $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>';
      $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>';
      return $output;
  }
}

/**
 * Implements hook_entity_info_alter().
 */
function media_entity_info_alter(&$entity_info) {
  // For sites that updated from Media 1.x, continue to provide these deprecated
  // view modes.
  // @see http://drupal.org/node/1051090
  if (variable_get('media_show_deprecated_view_modes', FALSE)) {
    $entity_info['file']['view modes']['media_link'] = array(
      'label' => t('Link'),
      'custom settings' => TRUE,
    );
    $entity_info['file']['view modes']['media_original'] = array(
      'label' => t('Original'),
      'custom settings' => TRUE,
    );
  }

  if (module_exists('entity_translation')) {
    $entity_info['file']['translation']['entity_translation']['class'] = 'MediaEntityTranslationHandler';
  }
}

/**
 * Implements hook_menu().
 */
function media_menu() {
  // For managing different types of media and the fields associated with them.
  $items['admin/config/media/browser'] = array(
    'title' => 'Media browser settings',
    'description' => 'Configure the behavior and display of the media browser.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('media_admin_config_browser'),
    'access arguments' => array('administer media browser'),
    'file' => 'includes/media.admin.inc',
  );

  // Administrative screens for managing media.
  $items['admin/content/file/thumbnails'] = array(
    'title' => 'Thumbnails',
    'description' => 'Manage files used on your site.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('file_entity_admin_file'),
    'access arguments' => array('administer files'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'file_entity.admin.inc',
    'file path' => drupal_get_path('module', 'file_entity'),
    'weight' => 10,
  );

  $items['media/ajax'] = array(
    'page callback' => 'media_ajax_upload',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

  $items['media/browser'] = array(
    'title' => 'Media browser',
    'description' => 'Media Browser for picking media and uploading new media',
    'page callback' => 'media_browser',
    'access arguments' => array('access media browser'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/media.browser.inc',
    'theme callback' => 'media_dialog_get_theme_name',
  );

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

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

  return $items;
}

/**
 * Implements hook_menu_local_tasks_alter().
 */
function media_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'file/add' on 'admin/content/file/thumbnails' page.
  if ($root_path == 'admin/content/file/thumbnails') {
    $item = menu_get_item('file/add');
    if (!empty($item['access'])) {
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
        '#weight' => $item['weight'],
      );
    }
  }
}

/**
 * Implements hook_admin_paths().
 */
function media_admin_paths() {
  $paths['media/*/edit/*'] = TRUE;
  $paths['media/*/format-form'] = TRUE;

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

  return $paths;
}

/**
 * Implements hook_permission().
 */
function media_permission() {
  return array(
    'administer media browser' => array(
      'title' => t('Administer media browser'),
      'description' => t('Access media browser settings.'),
    ),
    'access media browser' => array(
      'title' => t('Use the media browser'),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function media_theme() {
  return array(
    // media.module.
    'media_element' => array(
      'render element' => 'element',
    ),

    // media.field.inc.
    'media_widget' => array(
      'render element' => 'element',
    ),
    'media_widget_multiple' => array(
      'render element' => 'element',
    ),
    'media_upload_help' => array(
      'variables' => array('description' => NULL),
    ),

    // media.theme.inc.
    'media_thumbnail' => array(
      'render element' => 'element',
      'file' => 'includes/media.theme.inc',
    ),
    'media_formatter_large_icon' => array(
      'variables' => array('file' => NULL, 'attributes' => array(), 'style_name' => 'media_thumbnail'),
      'file' => 'includes/media.theme.inc',
    ),
    'media_dialog_page' => array(
      'render element' => 'page',
      'template' => 'templates/media-dialog-page',
      'file' => 'includes/media.theme.inc',
    ),
  );
}

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

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

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

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

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

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

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

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

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

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

/**
 * Implements hook_image_default_styles().
 */
function media_image_default_styles() {
  $styles = array();
  $styles['media_thumbnail'] = array(
    'label' => 'Media thumbnail (100x100)',
    'effects' => array(
      array(
        'name' => 'image_scale_and_crop',
        'data' => array('width' => 100, 'height' => 100),
        'weight' => 0,
      ),
    ),
  );
  return $styles;
}

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

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

    foreach (element_children($page) as $key) {
      if ($key != 'content') {
        unset($page[$key]);
      }
    }
  }
}

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

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

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

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

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

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

/**
 * Implements hook_form_alter().
 */
function media_form_alter(&$form, &$form_state, $form_id) {
  // If we're in the media browser, set the #media_browser key to true
  // so that if an ajax request gets sent to a different path, the form
  // still uses the media_browser_form_submit callback.
  if (current_path() == 'media/browser') {
    if ($form_id == 'views_exposed_form') {
      $form['render'] = array('#type' => 'hidden', '#value' => 'media-popup');
      $form['#action'] = '/media/browser';
    } else {
      $form_state['#media_browser'] = TRUE;
    }
  }

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

/**
 * Submit handler; direction form submissions in the media browser.
 */
function media_browser_form_submit($form, &$form_state) {
  $url = NULL;
  $parameters = array();

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

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

/**
 * Implements hook_library().
 */
function media_library() {
  $path = drupal_get_path('module', 'media');
  $info = system_get_info('module', 'media');

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

  // Contains libraries common to other media modules.
  $libraries['media_base'] = array(
    'title' => 'Media base',
    'js' => array(
      $path . '/js/media.core.js' => array('group' => JS_LIBRARY, 'weight' => -5),
      $path . '/js/util/json2.js' => array('group' => JS_LIBRARY),
      $path . '/js/util/ba-debug.min.js' => array('group' => JS_LIBRARY),
    ),
    'css' => array(
      $path . '/css/media.css',
    ),
  );

  // Includes resources needed to launch the media browser.  Should be included
  // on pages where the media browser needs to be launched from.
  $libraries['media_browser'] = array(
    'title' => 'Media Browser popup libraries',
    'js' => array(
      $path . '/js/media.popups.js' => array('group' => JS_DEFAULT),
    ),
    'dependencies' => array(
      array('system', 'ui.resizable'),
      array('system', 'ui.draggable'),
      array('system', 'ui.dialog'),
      array('media', 'media_base'),
    ),
  );

  // Resources needed in the media browser itself.
  $libraries['media_browser_page'] = array(
    'title' => 'Media browser',
    'js' => array(
      $path . '/js/media.browser.js'  => array('group' => JS_DEFAULT),
    ),
    'dependencies' => array(
      array('system', 'ui.tabs'),
      array('system', 'ui.draggable'),
      array('system', 'ui.dialog'),
      array('media', 'media_base'),
    ),
  );

  // Settings for the dialog etc.
  $settings = array(
    'browserUrl' => url('media/browser', array(
      'query' => array(
        'render' => 'media-popup'
      ))
    ),
    'styleSelectorUrl' => url('media/-media_id-/format-form', array(
      'query' => array(
        'render' => 'media-popup'
      ))
    ),
    'dialogOptions' => array(
      'dialogclass' => variable_get('media_dialogclass', 'media-wrapper'),
      'modal' => (boolean)variable_get('media_modal', TRUE),
      'draggable' => (boolean)variable_get('media_draggable', FALSE),
      'resizable' => (boolean)variable_get('media_resizable', FALSE),
      'minwidth' => (int)variable_get('media_minwidth', 500),
      'width' => (int)variable_get('media_width', 670),
      'height' => (int)variable_get('media_height', 280),
      'position' => variable_get('media_position', 'center'),
      'overlay' => array(
        'backgroundcolor' => variable_get('media_backgroundcolor', '#000000'),
        'opacity' => (float)variable_get('media_opacity', 0.4),
      ),
      'zindex' => (int)variable_get('media_zindex', 10000),
    ),
  );

  $libraries['media_browser_settings'] = array(
    'title' => 'Media browser settings',
    'js' => array(
      0 => array(
        'data' => array(
          'media' => $settings,
        ),
        'type' => 'setting',
      ),
    ),
  );

  foreach ($libraries as &$library) {
    $library += $common;
  }
  return $libraries;
}

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

/**
 * This will parse a url or embedded code into a unique URI.
 *
 * The function will call all modules implementing hook_media_parse($url),
 * which should return either a string containing a parsed URI or NULL.
 *
 * @NOTE The implementing modules may throw an error, which will not be caught
 * here; it's up to the calling function to catch any thrown errors.
 *
 * @NOTE In emfield, we originally also accepted an array of regex patterns
 * to match against. However, that module used a registration for providers,
 * and simply stored the match in the database keyed to the provider object.
 * However, other than the stream wrappers, there is currently no formal
 * registration for media handling. Additionally, few, if any, stream wrappers
 * will choose to store a straight match from the parsed URL directly into
 * the URI. Thus, we leave both the matching and the final URI result to the
 * implementing module in this implementation.
 *
 * An alternative might be to do the regex pattern matching here, and pass a
 * successful match back to the implementing module. However, that would
 * require either an overloaded function or a new hook, which seems like more
 * overhead than it's worth at this point.
 *
 * @TODO Once hook_module_implements_alter() is in core (see the issue at
 * http://drupal.org/node/692950) we may want to implement media_media_parse()
 * to ensure we were passed a valid URL, rather than an unsupported or
 * malformed embed code that wasn't caught earlier. It will needed to be
 * weighted so it's called after all other streams have a go, as the fallback,
 * and will need to throw an error.
 *
 * @param string $url
 *   The original URL or embed code to parse.
 *
 * @return string
 *   The unique URI for the file, based on its stream wrapper, or NULL.
 *
 * @see media_parse_to_file()
 * @see media_add_from_url_validate()
 */
function media_parse_to_uri($url) {
  // Trim any whitespace before parsing.
  $url = trim($url);
  foreach (module_implements('media_parse') as $module) {
    $success = module_invoke($module, 'media_parse', $url);
    $context = array(
      'url' => $url,
      'module' => $module,
    );
    drupal_alter('media_parse', $success, $context);
    if (isset($success)) {
      return $success;
    }
  }
}

/**
 * Parse a URL or embed code and return a file object.
 *
 * If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
 * then we'll copy the file locally.
 *
 * @NOTE The implementing modules may throw an error, which will not be caught
 * here; it's up to the calling function to catch any thrown errors.
 *
 * @see media_parse_to_uri()
 * @see media_add_from_url_submit()
 */
function media_parse_to_file($url) {
  try {
    $uri = media_parse_to_uri($url);
  }
  catch (Exception $e) {
    // Pass the error along.
    throw $e;
    return;
  }

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

    $fid = $select->execute()->fetchCol();
    if (!empty($fid)) {
      $file = file_load(array_pop($fid));
      return $file;
    }
  }

  if (isset($uri)) {
    // The URL was successfully parsed to a URI, but does not yet have an
    // associated file: save it!
    $file = file_uri_to_object($uri);
    file_save($file);
  }
  else {
    // The URL wasn't parsed. We'll try to save a remote file.
    // Copy to temporary first.
    $source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
    if (!@copy(@$url, $source_uri)) {
      throw new Exception('Unable to add file ' . $url);
      return;
    }
    $source_file = file_uri_to_object($source_uri);
    $scheme = variable_get('file_default_scheme', 'public') . '://';
    $uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);
    // Now to its new home.
    $file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
  }

  return $file;
}

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

/**
 * Implements hook_element_info().
 */
function media_element_info() {
  $types['media'] = array(
    '#input' => TRUE,
    '#process' => array('media_element_process'),
    '#value_callback' => 'media_file_value',
    '#element_validate' => array('media_element_validate'),
    '#pre_render' => array('media_element_pre_render'),
    '#theme' => 'media_element',
    '#theme_wrappers' => array('form_element'),
    '#size' => 22,
    '#extended' => FALSE,
    '#media_options' => array(
      'global' => array(
        // Example: array('image', 'audio');
        'types' => array(),
        // Example: array('http', 'ftp', 'flickr');
        'schemes' => array(),
      ),
    ),
    '#attached' => array(
      'library' => array(
        array('media', 'media_browser'),
      ),
    ),
  );

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

  $types['media']['#attached']['js'][] = array(
    'type' => 'setting',
    'data' => $setting,
  );

  return $types;
}

/**
 * Process callback for the media form element.
 */
function media_element_process($element, &$form_state, $form) {
  ctools_include('modal');
  ctools_include('ajax');
  ctools_modal_add_js();

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

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

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

  // Set up the buttons first since we need to check if they were clicked.
  $element['attach_button'] = array(
    '#name' => implode('_', $element['#parents']) . '_attach_button',
    '#type' => 'submit',
    '#value' => t('Attach'),
    '#validate' => array(),
    '#submit' => array('media_file_submit'),
    '#limit_validation_errors' => array($element['#parents']),
    '#ajax' => $ajax_settings,
    '#attributes' => array('class' => array('attach')),
    '#weight' => -1,
  );

  $element['preview'] = array(
    'content' => array(),
    '#prefix' => '<div class="preview">',
    '#suffix' => '</div>',
    '#ajax' => $ajax_settings,
    '#weight' => -10,
  );

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

  // The file ID field itself.
  $element['upload'] = array(
    '#name' => 'media[' . implode('_', $element['#parents']) . ']',
    '#type' => 'textfield',
    '#title' => t('Enter the ID of an existing file'),
    '#title_display' => 'invisible',
    '#field_prefix' => t('File ID'),
    '#size' => $element['#size'],
    '#theme_wrappers' => array(),
    '#attributes' => array('class' => array('upload')),
    '#weight' => -9,
  );

  $element['browse_button'] = array(
    '#type' => 'link',
    '#href' => '',
    '#title' => t('Browse'),
    '#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
    '#options' => array('fragment' => FALSE, 'external' => TRUE),
    '#weight' => -8,
  );

  // Force the progress indicator for the remove button to be either 'none' or
  // 'throbber', even if the upload button is using something else.
  $ajax_settings['progress']['type'] = 'throbber';
  $ajax_settings['progress']['message'] = NULL;
  $ajax_settings['effect'] = 'none';
  $element['edit'] = array(
    '#type' => 'link',
    '#href' => 'media/' . $fid . '/edit/nojs',
    '#title' => t('Edit'),
    '#attributes' => array(
      'class' => array(
        // Required for CTools modal to work.
        'ctools-use-modal', 'use-ajax',
        'ctools-modal-media-file-edit', 'button', 'edit',
      ),
    ),
    '#weight' => 20,
    '#access' => $element['#file'] ? file_entity_access('update', $element['#file']) : FALSE,
  );
  $element['remove_button'] = array(
    '#name' => implode('_', $element['#parents']) . '_remove_button',
    '#type' => 'submit',
    '#value' => t('Remove'),
    '#validate' => array(),
    '#submit' => array('media_file_submit'),
    '#limit_validation_errors' => array($element['#parents']),
    '#ajax' => $ajax_settings,
    '#attributes' => array('class' => array('remove')),
    '#weight' => 0,
  );

  $element['fid'] = array(
    '#type' => 'hidden',
    '#value' => $fid,
    '#attributes' => array('class' => array('fid')),
  );

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

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

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

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

  return $element;
}

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

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

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

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

  if ($element['#extended'] && isset($form_state_fid['fid'])) {
    $fid = $form_state_fid['fid'];
  }
  elseif (is_numeric($form_state_fid)) {
    $fid = $form_state_fid;
  }

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

    // Attachments take priority over all other values.
    if ($file = media_attach_file($element)) {
      $fid = $file->fid;
    }
    else {
      // Check for #filefield_value_callback values.
      // Because FAPI does not allow multiple #value_callback values like it
      // does for #element_validate and #process, this fills the missing
      // functionality to allow File fields to be extended through FAPI.
      if (isset($element['#file_value_callbacks'])) {
        foreach ($element['#file_value_callbacks'] as $callback) {
          $callback($element, $input, $form_state);
        }
      }
      // Load file if the FID has changed to confirm it exists.
      if (isset($input['fid']) && $file = file_load($input['fid'])) {
        $fid = $file->fid;
      }
    }
  }

  // If there is no input, set the default value.
  else {
    if ($element['#extended']) {
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
    }
    else {
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
      $return = array('fid' => 0);
    }

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

  $return['fid'] = $fid;

  return $return;
}

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

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

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

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

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

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

/**
 * Attaches any files that have been referenced by a media element.
 *
 * @param $element
 *   The FAPI element whose files are being attached.
 *
 * @return
 *   The file object representing the file that was attached, or FALSE if no
 *   file was attached.
 */
function media_attach_file($element) {
  $upload_name = implode('_', $element['#parents']);
  if (empty($_POST['media'][$upload_name])) {
    return FALSE;
  }

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

  return $file;
}

/**
 * Returns HTML for a managed file element.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: A render element representing the file.
 *
 * @ingroup themeable
 */
function theme_media_element($variables) {
  $element = $variables['element'];

  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = (array) $element['#attributes']['class'];
  }
  $attributes['class'][] = 'form-media';

  // This wrapper is required to apply JS behaviors and CSS styling.
  $output = '';
  $output .= '<div' . drupal_attributes($attributes) . '>';
  $output .= drupal_render_children($element);
  $output .= '</div>';
  return $output;
}

/**
 * #pre_render callback to hide display of the browse/attach or remove controls.
 *
 * Browse/attach controls are hidden when a file is already attached.
 * Remove controls are hidden when there is no file attached. Controls are
 * hidden here instead of in media_element_process(), because #access for these
 * buttons depends on the media element's #value. See the documentation of
 * form_builder() for more detailed information about the relationship between
 * #process, #value, and #access.
 *
 * Because #access is set here, it affects display only and does not prevent
 * JavaScript or other untrusted code from submitting the form as though access
 * were enabled. The form processing functions for these elements should not
 * assume that the buttons can't be "clicked" just because they are not
 * displayed.
 *
 * @see media_element_process()
 * @see form_builder()
 */
function media_element_pre_render($element) {
  // If we already have a file, we don't want to show the browse and attach
  // controls.
  if (!empty($element['#value']['fid'])) {
    $element['upload']['#access'] = FALSE;
    $element['browse_button']['#access'] = FALSE;
    $element['attach_button']['#access'] = FALSE;
  }
  // If we don't already have a file, there is nothing to remove.
  else {
    $element['remove_button']['#access'] = FALSE;
  }
  return $element;
}

/**
 * Generates a thumbnail preview of a file.
 *
 * Provides default fallback images if an image of the file cannot be generated.
 *
 * @param object $file
 *   A Drupal file object.
 * @param boolean $link
 *   (optional) Boolean indicating whether the thumbnail should be linked to the
 *   file. Defaults to FALSE.
 * @param string $view_mode
 *   (optional) The view mode to use when rendering the thumbnail. Defaults to
 *   'preview'.
 *
 * @return array
 *   Renderable array suitable for drupal_render() with the necessary classes
 *   and CSS to support a media thumbnail.
 */
function media_get_thumbnail_preview($file, $link = FALSE, $view_mode = 'preview') {
  // If a file has an invalid type, allow file_view_file() to work.
  if (!file_type_is_enabled($file->type)) {
    $file->type = file_get_type($file);
  }

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

  return $preview;
}

/**
 * Check that the media is one of the selected types.
 *
 * @param object $file
 *   A Drupal file object.
 * @param array $types
 *   An array of media type names
 *
 * @return array
 *   If the file type is not allowed, it will contain an error message.
 *
 * @see hook_file_validate()
 */
function media_file_validate_types($file, $types) {
  $errors = array();
  if (!in_array(file_get_type($file), $types)) {
    $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
  }

  return $errors;
}

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

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

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

  $replace_options = array(
    'clear' => TRUE,
    'sanitize' => FALSE,
  );

  // Load alt and title text from fields.
  if (!empty($alt)) {
    $file->alt = token_replace($alt, array('file' => $file), $replace_options);
  }
  if (!empty($title)) {
    $file->title = token_replace($title, array('file' => $file), $replace_options);
  }
}

/**
 * For sanity in grammar.
 *
 * @see media_set_browser_params()
 */
function media_get_browser_params() {
  return media_set_browser_params();
}

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

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

    // Transform text 'true' and 'false' to actual booleans.
    foreach ($params as $k => $v) {
      if ($v === 'true') {
        $params[$k] = TRUE;
      }
      elseif ($v === 'false') {
        $params[$k] = FALSE;
      }
    }

    array_walk_recursive($params, 'media_recursive_check_plain');

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

  return $params;
}

/**
 * Implements hook_ctools_plugin_api().
 *
 * Lets CTools know which plugin APIs are implemented by Media module.
 */
function media_ctools_plugin_api($module, $api) {
  if ($module == 'file_entity' && $api == 'file_default_displays') {
    return array(
      'version' => 1,
    );
  }
}

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

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

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

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

      foreach ($files as $file) {
        $preview = media_get_thumbnail_preview($file, TRUE);
        $form['admin']['files'][$file->fid] = array(
          '#type' => 'checkbox',
          '#title' => '',
          '#prefix' => '<li>' . drupal_render($preview),
          '#suffix' => '</li>',
        );
      }
    }
  }
}

/**
 * Implements hook_views_api().
 */
function media_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'media'),
  );
}

/**
 * Implements hook_views_default_views().
 */
function media_views_default_views() {
  return media_load_all_exports('media', 'views', 'view.inc', 'view');
}

/**
 * Fetches an array of exportables from files.
 *
 * @param string $module
 *   The module invoking this request. (Can be called by other modules.)
 * @param string $directory
 *   The subdirectory in the custom module.
 * @param string $extension
 *   The file extension.
 * @param string $name
 *   The name of the variable found in each file. Defaults to the same as
 *   $extension.
 *
 * @return array
 *   Array of $name objects.
 */
function media_load_all_exports($module, $directory, $extension, $name = NULL) {
  if (!$name) {
    $name = $extension;
  }

  $return = array();
  // Find all the files in the directory with the correct extension.
  $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
  foreach ($files as $path => $file) {
    require $path;
    if (isset($$name)) {
      $return[$$name->name] = $$name;
    }
  }

  return $return;
}

/**
 * Returns metadata describing Media browser plugins.
 *
 * @return
 *   An associative array of plugin information, keyed by plugin.
 *
 * @see hook_media_browser_plugin_info()
 * @see hook_media_browser_plugin_info_alter()
 */
function media_get_browser_plugin_info() {
  $info = &drupal_static(__FUNCTION__);

  if (!isset($info)) {
    $info = module_invoke_all('media_browser_plugin_info');
    drupal_alter('media_browser_plugin_info', $info);
  }

  return $info;
}

/**
 * Gets the MIME type mapped to a given extension.
 *
 * @param string $extension
 *   A file extension.
 *
 * @return string
 *   The MIME type associated with the extension or FALSE if the extension does
 *   not have an associated MIME type.
 *
 * @see file_mimetype_mapping()
 */
function media_get_extension_mimetype($extension) {
  include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
  $mimetype_mappings = file_mimetype_mapping();

  if (isset($mimetype_mappings['extensions'][$extension])) {
    $id = $mimetype_mappings['extensions'][$extension];
    return $mimetype_mappings['mimetypes'][$id];
  }
  else {
    return FALSE;
  }
}

/**
 * Helper function to get a list of local stream wrappers.
 */
function media_get_local_stream_wrappers() {
  return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
}

/**
 * Helper function to get a list of remote stream wrappers.
 */
function media_get_remote_stream_wrappers() {
  $wrappers = file_get_stream_wrappers();
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
  $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
  return $wrappers;
}