media.module 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. <?php
  2. /**
  3. * @file
  4. * Media API
  5. *
  6. * The core Media API.
  7. * See http://drupal.org/project/media for more details.
  8. */
  9. // Code relating to using media as a field.
  10. require_once dirname(__FILE__) . '/includes/media.fields.inc';
  11. /**
  12. * Implements hook_hook_info().
  13. */
  14. function media_hook_info() {
  15. $hooks = array(
  16. 'media_parse',
  17. 'media_browser_plugin_info',
  18. 'media_browser_plugin_info_alter',
  19. 'media_browser_plugins_alter',
  20. 'media_browser_params_alter',
  21. 'query_media_browser_alter',
  22. );
  23. return array_fill_keys($hooks, array('group' => 'media'));
  24. }
  25. /**
  26. * Implements hook_help().
  27. */
  28. function media_help($path, $arg) {
  29. switch ($path) {
  30. case 'admin/help#media':
  31. $output = '';
  32. $output .= '<h3>' . t('About') . '</h3>';
  33. $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>';
  34. $output .= '<h3>' . t('Uses') . '</h3>';
  35. $output .= '<dl>';
  36. $output .= '<dt>' . t('Media Repository') . '</dt>';
  37. $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>';
  38. $output .= '<dt>' . t('Attaching media assets to content types') . '</dt>';
  39. $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>';
  40. $output .= '<dt>' . t('Using media assets in WYSIWYG') . '</dt>';
  41. $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:');
  42. $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>';
  43. $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>';
  44. return $output;
  45. }
  46. }
  47. /**
  48. * Implements hook_entity_info_alter().
  49. */
  50. function media_entity_info_alter(&$entity_info) {
  51. // For sites that updated from Media 1.x, continue to provide these deprecated
  52. // view modes.
  53. // @see http://drupal.org/node/1051090
  54. if (variable_get('media_show_deprecated_view_modes', FALSE)) {
  55. $entity_info['file']['view modes']['media_link'] = array(
  56. 'label' => t('Link'),
  57. 'custom settings' => TRUE,
  58. );
  59. $entity_info['file']['view modes']['media_original'] = array(
  60. 'label' => t('Original'),
  61. 'custom settings' => TRUE,
  62. );
  63. }
  64. if (module_exists('entity_translation')) {
  65. $entity_info['file']['translation']['entity_translation']['class'] = 'MediaEntityTranslationHandler';
  66. $entity_info['file']['translation']['entity_translation']['path schemes']['media'] = array('edit path' => 'media/%file/edit/%ctools_js');
  67. }
  68. }
  69. /**
  70. * Implements hook_menu().
  71. */
  72. function media_menu() {
  73. // For managing different types of media and the fields associated with them.
  74. $items['admin/config/media/browser'] = array(
  75. 'title' => 'Media browser settings',
  76. 'description' => 'Configure the behavior and display of the media browser.',
  77. 'page callback' => 'drupal_get_form',
  78. 'page arguments' => array('media_admin_config_browser'),
  79. 'access arguments' => array('administer media browser'),
  80. 'file' => 'includes/media.admin.inc',
  81. );
  82. // Administrative screens for managing media.
  83. $items['admin/content/file/thumbnails'] = array(
  84. 'title' => 'Thumbnails',
  85. 'description' => 'Manage files used on your site.',
  86. 'page callback' => 'drupal_get_form',
  87. 'page arguments' => array('file_entity_admin_file'),
  88. 'access arguments' => array('administer files'),
  89. 'type' => MENU_LOCAL_TASK,
  90. 'file' => 'file_entity.admin.inc',
  91. 'file path' => drupal_get_path('module', 'file_entity'),
  92. 'weight' => 10,
  93. );
  94. $items['media/ajax'] = array(
  95. 'page callback' => 'media_ajax_upload',
  96. 'delivery callback' => 'ajax_deliver',
  97. 'access arguments' => array('access content'),
  98. 'theme callback' => 'ajax_base_page_theme',
  99. 'type' => MENU_CALLBACK,
  100. );
  101. $items['media/browser'] = array(
  102. 'title' => 'Media browser',
  103. 'description' => 'Media Browser for picking media and uploading new media',
  104. 'page callback' => 'media_browser',
  105. 'access arguments' => array('access media browser'),
  106. 'type' => MENU_CALLBACK,
  107. 'file' => 'includes/media.browser.inc',
  108. 'theme callback' => 'media_dialog_get_theme_name',
  109. );
  110. // A testbed to try out the media browser with different launch commands.
  111. $items['media/browser/testbed'] = array(
  112. 'title' => 'Media Browser test',
  113. 'description' => 'Make it easier to test media browser',
  114. 'page callback' => 'drupal_get_form',
  115. 'page arguments' => array('media_browser_testbed'),
  116. 'access arguments' => array('administer files'),
  117. 'type' => MENU_CALLBACK,
  118. 'file' => 'includes/media.browser.inc',
  119. );
  120. // We could re-use the file/%file/edit path for the modal callback, but
  121. // it is just easier to use our own namespace here.
  122. $items['media/%file/edit/%ctools_js'] = array(
  123. 'title' => 'Edit',
  124. 'page callback' => 'drupal_get_form',
  125. 'page arguments' => array('media_file_edit_modal', 1, 3),
  126. 'access callback' => 'file_entity_access',
  127. 'access arguments' => array('update', 1),
  128. 'theme callback' => 'ajax_base_page_theme',
  129. 'file' => 'includes/media.pages.inc',
  130. 'type' => MENU_CALLBACK,
  131. );
  132. return $items;
  133. }
  134. /**
  135. * Implements hook_menu_local_tasks_alter().
  136. */
  137. function media_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  138. // Add action link to 'file/add' on 'admin/content/file/thumbnails' page.
  139. if ($root_path == 'admin/content/file/thumbnails') {
  140. $item = menu_get_item('file/add');
  141. if (!empty($item['access'])) {
  142. $data['actions']['output'][] = array(
  143. '#theme' => 'menu_local_action',
  144. '#link' => $item,
  145. '#weight' => $item['weight'],
  146. );
  147. }
  148. }
  149. }
  150. /**
  151. * Implements hook_admin_paths().
  152. */
  153. function media_admin_paths() {
  154. $paths['media/*/edit/*'] = TRUE;
  155. $paths['media/*/format-form'] = TRUE;
  156. if (module_exists('admin_language')) {
  157. $paths['media/ajax/*'] = TRUE; // For admin_language module compatibility.
  158. }
  159. // If the media browser theme is set to the admin theme, ensure it gets set
  160. // as an admin path as well.
  161. $dialog_theme = variable_get('media_dialog_theme', '');
  162. if (empty($dialog_theme) || $dialog_theme == variable_get('admin_theme')) {
  163. $paths['media/browser'] = TRUE;
  164. $paths['media/browser/*'] = TRUE;
  165. }
  166. return $paths;
  167. }
  168. /**
  169. * Implements hook_permission().
  170. */
  171. function media_permission() {
  172. return array(
  173. 'administer media browser' => array(
  174. 'title' => t('Administer media browser'),
  175. 'description' => t('Access media browser settings.'),
  176. ),
  177. 'access media browser' => array(
  178. 'title' => t('Use the media browser'),
  179. ),
  180. );
  181. }
  182. /**
  183. * Implements hook_theme().
  184. */
  185. function media_theme() {
  186. return array(
  187. // media.module.
  188. 'media_element' => array(
  189. 'render element' => 'element',
  190. ),
  191. // media.field.inc.
  192. 'media_widget' => array(
  193. 'render element' => 'element',
  194. ),
  195. 'media_widget_multiple' => array(
  196. 'render element' => 'element',
  197. ),
  198. 'media_upload_help' => array(
  199. 'variables' => array('description' => NULL),
  200. ),
  201. // media.theme.inc.
  202. 'media_thumbnail' => array(
  203. 'render element' => 'element',
  204. 'file' => 'includes/media.theme.inc',
  205. ),
  206. 'media_formatter_large_icon' => array(
  207. 'variables' => array('file' => NULL, 'attributes' => array(), 'style_name' => 'media_thumbnail'),
  208. 'file' => 'includes/media.theme.inc',
  209. ),
  210. 'media_dialog_page' => array(
  211. 'render element' => 'page',
  212. 'template' => 'templates/media-dialog-page',
  213. 'file' => 'includes/media.theme.inc',
  214. ),
  215. );
  216. }
  217. /**
  218. * Menu callback; Shared Ajax callback for media attachment and deletions.
  219. *
  220. * This rebuilds the form element for a particular field item. As long as the
  221. * form processing is properly encapsulated in the widget element the form
  222. * should rebuild correctly using FAPI without the need for additional callbacks
  223. * or processing.
  224. */
  225. function media_ajax_upload() {
  226. $form_parents = func_get_args();
  227. $form_build_id = (string) array_pop($form_parents);
  228. // Sanitize form parents before using them.
  229. $form_parents = array_filter($form_parents, 'element_child');
  230. if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
  231. // Invalid request.
  232. 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');
  233. $commands = array();
  234. $commands[] = ajax_command_replace(NULL, theme('status_messages'));
  235. return array('#type' => 'ajax', '#commands' => $commands);
  236. }
  237. list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
  238. if (!$form) {
  239. // Invalid form_build_id.
  240. drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
  241. $commands = array();
  242. $commands[] = ajax_command_replace(NULL, theme('status_messages'));
  243. return array('#type' => 'ajax', '#commands' => $commands);
  244. }
  245. // Get the current element and count the number of files.
  246. $current_element = $form;
  247. foreach ($form_parents as $parent) {
  248. if (isset($current_element[$parent])) {
  249. $current_element = $current_element[$parent];
  250. }
  251. else {
  252. $current_element = NULL;
  253. break;
  254. }
  255. }
  256. $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
  257. // Process user input. $form and $form_state are modified in the process.
  258. drupal_process_form($form['#form_id'], $form, $form_state);
  259. // Retrieve the element to be rendered.
  260. foreach ($form_parents as $parent) {
  261. $form = $form[$parent];
  262. }
  263. // Add the special Ajax class if a new file was added.
  264. if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
  265. $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
  266. }
  267. // Otherwise just add the new content class on a placeholder.
  268. else {
  269. $form['#suffix'] .= '<span class="ajax-new-content"></span>';
  270. }
  271. $output = theme('status_messages') . drupal_render($form);
  272. $js = drupal_add_js();
  273. $settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
  274. $commands[] = ajax_command_replace(NULL, $output, $settings);
  275. return array('#type' => 'ajax', '#commands' => $commands);
  276. }
  277. /**
  278. * Implements hook_image_default_styles().
  279. */
  280. function media_image_default_styles() {
  281. $styles = array();
  282. $styles['media_thumbnail'] = array(
  283. 'label' => 'Media thumbnail (100x100)',
  284. 'effects' => array(
  285. array(
  286. 'name' => 'image_scale_and_crop',
  287. 'data' => array('width' => 100, 'height' => 100),
  288. 'weight' => 0,
  289. ),
  290. ),
  291. );
  292. return $styles;
  293. }
  294. /**
  295. * Implements hook_page_alter().
  296. *
  297. * This is used to use our alternate template when ?render=media-popup is passed
  298. * in the URL.
  299. */
  300. function media_page_alter(&$page) {
  301. if (isset($_GET['render']) && $_GET['render'] == 'media-popup') {
  302. $page['#theme'] = 'media_dialog_page';
  303. // Disable administration modules from adding output to the popup.
  304. // @see http://drupal.org/node/914786
  305. module_invoke_all('suppress', TRUE);
  306. foreach (element_children($page) as $key) {
  307. if ($key != 'content') {
  308. unset($page[$key]);
  309. }
  310. }
  311. }
  312. }
  313. /**
  314. * Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
  315. *
  316. * @todo: Respect field settings in 7.x-2.x and handle them in the media widget
  317. * UI.
  318. */
  319. function media_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  320. // On file fields that use the media widget we need remove specific fields.
  321. if ($form['#field']['type'] == 'file' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
  322. $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
  323. $form['instance']['settings']['file_extensions']['#maxlength'] = 255;
  324. $form['instance']['settings']['file_extensions']['#description'] .= '<br />' . t('If empty, the file extensions list will be composed automatically using the allowed file types.');
  325. $form['instance']['settings']['file_extensions']['#required'] = FALSE;
  326. }
  327. if ($form['#field']['type'] == 'image' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
  328. $form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
  329. // Do not increase maxlength of file extensions for image fields, since
  330. // presumably they will not need a long list of extensions.
  331. }
  332. // Add a validation function to any field instance which uses the media widget
  333. // to ensure that the upload destination scheme is one of the allowed schemes
  334. // if any defined by settings.
  335. if (isset($form['instance']['widget']) && isset($form['instance']['widget']['type']) && $form['instance']['widget']['type']['#value'] == 'media_generic' && isset($form['#field']['settings']['uri_scheme'])) {
  336. $form['#validate'][] = 'media_field_instance_validate';
  337. }
  338. }
  339. /**
  340. * Validation handler; ensure that the upload destination scheme is one of the
  341. * allowed schemes.
  342. */
  343. function media_field_instance_validate($form, &$form_state) {
  344. $widget_settings = $form_state['values']['instance']['widget']['settings'];
  345. $browser_plugins = array();
  346. if (isset($widget_settings['browser_plugins'])) {
  347. $browser_plugins = array_filter($widget_settings['browser_plugins']);
  348. }
  349. $allowed_schemes = array();
  350. if (isset($widget_settings['allowed_schemes'])) {
  351. $allowed_schemes = array_filter($widget_settings['allowed_schemes']);
  352. }
  353. $upload_destination = $form_state['values']['field']['settings']['uri_scheme'];
  354. $is_upload_enabled = (empty($browser_plugins) || in_array('upload', $browser_plugins));
  355. if ($is_upload_enabled && !empty($allowed_schemes) && !in_array($upload_destination, $allowed_schemes)) {
  356. form_set_error('allowed_schemes', t('When upload is enabled, the upload destination must be one of the allowed schemes.'));
  357. }
  358. }
  359. /**
  360. * Implements hook_form_alter().
  361. */
  362. function media_form_alter(&$form, &$form_state, $form_id) {
  363. // If we're in the media browser, set the #media_browser key to true
  364. // so that if an ajax request gets sent to a different path, the form
  365. // still uses the media_browser_form_submit callback.
  366. if (current_path() == 'media/browser') {
  367. if ($form_id == 'views_exposed_form') {
  368. $form['render'] = array('#type' => 'hidden', '#value' => 'media-popup');
  369. $form['#action'] = '/media/browser';
  370. } else {
  371. $form_state['#media_browser'] = TRUE;
  372. }
  373. }
  374. // If the #media_browser key isset and is true we are using the browser
  375. // popup, so add the media_browser submit handler.
  376. if (!empty($form_state['#media_browser'])) {
  377. $form['#submit'][] = 'media_browser_form_submit';
  378. }
  379. }
  380. /**
  381. * Submit handler; direction form submissions in the media browser.
  382. */
  383. function media_browser_form_submit($form, &$form_state) {
  384. $url = NULL;
  385. $parameters = array();
  386. // Single upload.
  387. if (!empty($form_state['file'])) {
  388. $file = $form_state['file'];
  389. $url = 'media/browser';
  390. $parameters = array('query' => array('render' => 'media-popup', 'fid' => $file->fid));
  391. }
  392. // If $url is set, we had some sort of upload, so redirect the form.
  393. if (!empty($url)) {
  394. $form_state['redirect'] = array($url, $parameters);
  395. }
  396. }
  397. /**
  398. * Implements hook_library().
  399. */
  400. function media_library() {
  401. $path = drupal_get_path('module', 'media');
  402. $info = system_get_info('module', 'media');
  403. $common = array(
  404. 'website' => 'http://drupal.org/project/media',
  405. 'version' => !empty($info['version']) ? $info['version'] : '7.x-2.x',
  406. );
  407. // Contains libraries common to other media modules.
  408. $libraries['media_base'] = array(
  409. 'title' => 'Media base',
  410. 'js' => array(
  411. $path . '/js/media.core.js' => array('group' => JS_LIBRARY, 'weight' => -5),
  412. $path . '/js/util/json2.js' => array('group' => JS_LIBRARY),
  413. $path . '/js/util/ba-debug.min.js' => array('group' => JS_LIBRARY),
  414. ),
  415. 'css' => array(
  416. $path . '/css/media.css',
  417. ),
  418. );
  419. // Includes resources needed to launch the media browser. Should be included
  420. // on pages where the media browser needs to be launched from.
  421. $libraries['media_browser'] = array(
  422. 'title' => 'Media Browser popup libraries',
  423. 'js' => array(
  424. $path . '/js/media.popups.js' => array('group' => JS_DEFAULT),
  425. ),
  426. 'dependencies' => array(
  427. array('system', 'ui.resizable'),
  428. array('system', 'ui.draggable'),
  429. array('system', 'ui.dialog'),
  430. array('media', 'media_base'),
  431. ),
  432. );
  433. // Resources needed in the media browser itself.
  434. $libraries['media_browser_page'] = array(
  435. 'title' => 'Media browser',
  436. 'js' => array(
  437. $path . '/js/media.browser.js' => array('group' => JS_DEFAULT),
  438. ),
  439. 'dependencies' => array(
  440. array('system', 'ui.tabs'),
  441. array('system', 'ui.draggable'),
  442. array('system', 'ui.dialog'),
  443. array('media', 'media_base'),
  444. ),
  445. );
  446. // Settings for the dialog etc.
  447. $settings = array(
  448. 'browserUrl' => url('media/browser', array(
  449. 'query' => array(
  450. 'render' => 'media-popup'
  451. ))
  452. ),
  453. 'styleSelectorUrl' => url('media/-media_id-/format-form', array(
  454. 'query' => array('render' => 'media-popup')
  455. )
  456. ),
  457. 'dialogOptions' => array(
  458. 'dialogclass' => variable_get('media_dialogclass', 'media-wrapper'),
  459. 'modal' => (boolean) variable_get('media_modal', TRUE),
  460. 'draggable' => (boolean) variable_get('media_draggable', FALSE),
  461. 'resizable' => (boolean) variable_get('media_resizable', FALSE),
  462. 'minwidth' => (int) variable_get('media_minwidth', 500),
  463. 'width' => (int) variable_get('media_width', 670),
  464. 'height' => (int) variable_get('media_height', 280),
  465. 'position' => variable_get('media_position', 'center'),
  466. 'overlay' => array(
  467. 'backgroundcolor' => variable_get('media_backgroundcolor', '#000000'),
  468. 'opacity' => (float) variable_get('media_opacity', 0.4),
  469. ),
  470. 'zindex' => (int) variable_get('media_zindex', 10000),
  471. ),
  472. );
  473. $libraries['media_browser_settings'] = array(
  474. 'title' => 'Media browser settings',
  475. 'js' => array(
  476. 0 => array(
  477. 'data' => array(
  478. 'media' => $settings,
  479. ),
  480. 'type' => 'setting',
  481. ),
  482. ),
  483. );
  484. foreach ($libraries as &$library) {
  485. $library += $common;
  486. }
  487. return $libraries;
  488. }
  489. /**
  490. * Theme callback used to identify when we are in a popup dialog.
  491. *
  492. * Generally the default theme will look terrible in the media browser. This
  493. * will default to the administration theme, unless set otherwise.
  494. */
  495. function media_dialog_get_theme_name() {
  496. return variable_get('media_dialog_theme', variable_get('admin_theme'));
  497. }
  498. /**
  499. * This will parse a url or embedded code into a unique URI.
  500. *
  501. * The function will call all modules implementing hook_media_parse($url),
  502. * which should return either a string containing a parsed URI or NULL.
  503. *
  504. * @NOTE The implementing modules may throw an error, which will not be caught
  505. * here; it's up to the calling function to catch any thrown errors.
  506. *
  507. * @NOTE In emfield, we originally also accepted an array of regex patterns
  508. * to match against. However, that module used a registration for providers,
  509. * and simply stored the match in the database keyed to the provider object.
  510. * However, other than the stream wrappers, there is currently no formal
  511. * registration for media handling. Additionally, few, if any, stream wrappers
  512. * will choose to store a straight match from the parsed URL directly into
  513. * the URI. Thus, we leave both the matching and the final URI result to the
  514. * implementing module in this implementation.
  515. *
  516. * An alternative might be to do the regex pattern matching here, and pass a
  517. * successful match back to the implementing module. However, that would
  518. * require either an overloaded function or a new hook, which seems like more
  519. * overhead than it's worth at this point.
  520. *
  521. * @TODO Once hook_module_implements_alter() is in core (see the issue at
  522. * http://drupal.org/node/692950) we may want to implement media_media_parse()
  523. * to ensure we were passed a valid URL, rather than an unsupported or
  524. * malformed embed code that wasn't caught earlier. It will needed to be
  525. * weighted so it's called after all other streams have a go, as the fallback,
  526. * and will need to throw an error.
  527. *
  528. * @param string $url
  529. * The original URL or embed code to parse.
  530. *
  531. * @return string
  532. * The unique URI for the file, based on its stream wrapper, or NULL.
  533. *
  534. * @see media_parse_to_file()
  535. * @see media_add_from_url_validate()
  536. */
  537. function media_parse_to_uri($url) {
  538. // Trim any whitespace before parsing.
  539. $url = trim($url);
  540. foreach (module_implements('media_parse') as $module) {
  541. $success = module_invoke($module, 'media_parse', $url);
  542. $context = array(
  543. 'url' => $url,
  544. 'module' => $module,
  545. );
  546. drupal_alter('media_parse', $success, $context);
  547. if (isset($success)) {
  548. return $success;
  549. }
  550. }
  551. }
  552. /**
  553. * Parse a URL or embed code and return a file object.
  554. *
  555. * If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
  556. * then we'll copy the file locally.
  557. *
  558. * @NOTE The implementing modules may throw an error, which will not be caught
  559. * here; it's up to the calling function to catch any thrown errors.
  560. *
  561. * @see media_parse_to_uri()
  562. * @see media_add_from_url_submit()
  563. */
  564. function media_parse_to_file($url, $params = array()) {
  565. try {
  566. $uri = media_parse_to_uri($url);
  567. }
  568. catch (Exception $e) {
  569. // Pass the error along.
  570. throw $e;
  571. return;
  572. }
  573. if (isset($uri)) {
  574. // Attempt to load an existing file from the unique URI.
  575. $select = db_select('file_managed', 'f')
  576. ->extend('PagerDefault')
  577. ->fields('f', array('fid'))
  578. ->condition('uri', $uri);
  579. $fid = $select->execute()->fetchCol();
  580. if (!empty($fid)) {
  581. $file = file_load(array_pop($fid));
  582. return $file;
  583. }
  584. }
  585. if (isset($uri)) {
  586. // The URL was successfully parsed to a URI, but does not yet have an
  587. // associated file: save it!
  588. $file = file_uri_to_object($uri);
  589. file_save($file);
  590. }
  591. else {
  592. // The URL wasn't parsed. We'll try to save a remote file.
  593. // Copy to temporary first.
  594. $source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
  595. if (!@copy(@$url, $source_uri)) {
  596. throw new Exception('Unable to add file ' . $url);
  597. }
  598. $source_file = file_uri_to_object($source_uri);
  599. if (isset($params['to_directory'])) {
  600. $scheme = variable_get('file_default_scheme', 'public') . '://' . $params['to_directory'] . '/';
  601. }
  602. else{
  603. $scheme = variable_get('file_default_scheme', 'public') . '://';
  604. }
  605. $uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);
  606. // Now to its new home.
  607. file_prepare_directory($scheme, FILE_CREATE_DIRECTORY || FILE_MODIFY_PERMISSIONS);
  608. $file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
  609. }
  610. return $file;
  611. }
  612. /**
  613. * Custom implementation of array_walk_recursive() that works around a crash
  614. * some users have been experiencing with that function in PHP 7.
  615. *
  616. * @see https://www.drupal.org/project/media/issues/2998097
  617. */
  618. function media_array_walk_recursive(&$array) {
  619. foreach ($array as $key => $value) {
  620. if (is_array($array[$key])) {
  621. media_array_walk_recursive($array[$key]);
  622. }
  623. else {
  624. $array[$key] = check_plain($array[$key]);
  625. }
  626. }
  627. }
  628. /**
  629. * Implements hook_element_info().
  630. */
  631. function media_element_info() {
  632. $types['media'] = array(
  633. '#input' => TRUE,
  634. '#process' => array('media_element_process'),
  635. '#value_callback' => 'media_file_value',
  636. '#element_validate' => array('media_element_validate'),
  637. '#pre_render' => array('media_element_pre_render'),
  638. '#theme' => 'media_widget',
  639. '#theme_wrappers' => array('form_element'),
  640. '#size' => 22,
  641. '#extended' => FALSE,
  642. '#media_options' => array(
  643. 'global' => array(
  644. // Example: array('image', 'audio');
  645. 'types' => array(),
  646. // Example: array('http', 'ftp', 'flickr');
  647. 'schemes' => array(),
  648. ),
  649. ),
  650. '#attached' => array(
  651. 'library' => array(
  652. array('media', 'media_browser'),
  653. ),
  654. ),
  655. );
  656. $setting = array();
  657. $setting['media']['global'] = $types['media']['#media_options'];
  658. $types['media']['#attached']['js'][] = array(
  659. 'type' => 'setting',
  660. 'data' => $setting,
  661. );
  662. return $types;
  663. }
  664. /**
  665. * Process callback for the media form element.
  666. */
  667. function media_element_process($element, &$form_state, $form) {
  668. ctools_include('modal');
  669. ctools_include('ajax');
  670. ctools_modal_add_js();
  671. // Append the '-upload' to the #id so the field label's 'for' attribute
  672. // corresponds with the textfield element.
  673. $original_id = $element['#id'];
  674. $element['#id'] .= '-upload';
  675. $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
  676. // Set some default element properties.
  677. $element['#file'] = $fid ? file_load($fid) : FALSE;
  678. $element['#tree'] = TRUE;
  679. $ajax_settings = array(
  680. 'path' => 'media/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
  681. 'wrapper' => $original_id . '-ajax-wrapper',
  682. 'effect' => 'fade',
  683. );
  684. // Set up the buttons first since we need to check if they were clicked.
  685. $element['attach_button'] = array(
  686. '#name' => implode('_', $element['#parents']) . '_attach_button',
  687. '#type' => 'submit',
  688. '#value' => t('Attach'),
  689. '#validate' => array(),
  690. '#submit' => array('media_file_submit'),
  691. '#limit_validation_errors' => array($element['#parents']),
  692. '#ajax' => $ajax_settings,
  693. '#attributes' => array('class' => array('attach')),
  694. '#weight' => -1,
  695. );
  696. $element['preview'] = array(
  697. 'content' => array(),
  698. '#prefix' => '<div class="preview">',
  699. '#suffix' => '</div>',
  700. '#ajax' => $ajax_settings,
  701. '#weight' => -10,
  702. );
  703. // Substitute the JS preview for a true file thumbnail once the file is
  704. // attached.
  705. if ($fid && $element['#file']) {
  706. $element['preview']['content'] = media_get_thumbnail_preview($element['#file']);
  707. }
  708. // The file ID field itself.
  709. $element['upload'] = array(
  710. '#name' => 'media[' . implode('_', $element['#parents']) . ']',
  711. '#type' => 'textfield',
  712. '#title' => t('Enter the ID of an existing file'),
  713. '#title_display' => 'invisible',
  714. '#field_prefix' => t('File ID'),
  715. '#size' => $element['#size'],
  716. '#theme_wrappers' => array(),
  717. '#attributes' => array('class' => array('upload')),
  718. '#weight' => -9,
  719. );
  720. $element['browse_button'] = array(
  721. '#type' => 'link',
  722. '#href' => '',
  723. '#title' => t('Browse'),
  724. '#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
  725. '#options' => array('fragment' => FALSE, 'external' => TRUE),
  726. '#weight' => -8,
  727. );
  728. // Force the progress indicator for the remove button to be either 'none' or
  729. // 'throbber', even if the upload button is using something else.
  730. $ajax_settings['progress']['type'] = 'throbber';
  731. $ajax_settings['progress']['message'] = NULL;
  732. $ajax_settings['effect'] = 'none';
  733. $element['edit'] = array(
  734. '#type' => 'link',
  735. '#href' => 'media/' . $fid . '/edit/nojs',
  736. '#title' => t('Edit'),
  737. '#attributes' => array(
  738. 'class' => array(
  739. // Required for CTools modal to work.
  740. 'ctools-use-modal',
  741. 'ctools-modal-media-file-edit', 'button', 'edit',
  742. ),
  743. ),
  744. '#weight' => 20,
  745. '#access' => $element['#file'] ? file_entity_access('update', $element['#file']) : FALSE,
  746. );
  747. // If we have parent entity form/source langcodes, pass them in query. They
  748. // will be used in
  749. /* @see media_file_edit_modal() */
  750. if (!empty($element['#media_parent_entity_form_langcode'])) {
  751. $element['edit']['#options']['query']['media_parent_entity_form_langcode'] = $element['#media_parent_entity_form_langcode'];
  752. if (!empty($element['#media_parent_entity_source_langcode'])) {
  753. $element['edit']['#options']['query']['media_parent_entity_source_langcode'] = $element['#media_parent_entity_source_langcode'];
  754. }
  755. }
  756. $element['remove_button'] = array(
  757. '#name' => implode('_', $element['#parents']) . '_remove_button',
  758. '#type' => 'submit',
  759. '#value' => t('Remove'),
  760. '#validate' => array(),
  761. '#submit' => array('media_file_submit'),
  762. '#limit_validation_errors' => array($element['#parents']),
  763. '#ajax' => $ajax_settings,
  764. '#attributes' => array('class' => array('remove')),
  765. '#weight' => 0,
  766. );
  767. $element['fid'] = array(
  768. '#type' => 'hidden',
  769. '#value' => $fid,
  770. '#attributes' => array('class' => array('fid')),
  771. );
  772. // Media browser attach code.
  773. $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
  774. // IDs of form elements are 'unstable' in Drupal because of drupal_html_id
  775. // add a class for our Javascript instead.
  776. $element_js_class = drupal_html_class('js-media-element-' . $element['#id']);
  777. $element['upload']['#attributes']['class'][] = $element_js_class;
  778. // Cache the media options and pass the cache ID as a JavaScript setting.
  779. $cid = drupal_get_token(drupal_random_bytes(32));
  780. cache_set('media_options:' . $cid, $element['#media_options']['global'], 'cache_form', REQUEST_TIME + 21600);
  781. $element['browse_button']['#attached']['js'] = array(
  782. array(
  783. 'type' => 'setting',
  784. 'data' => array('media' => array('elements' => array('.' . $element_js_class => array('global' => array('options' => $cid))))),
  785. )
  786. );
  787. $element['#attached']['library'][] = array('media', 'media_browser');
  788. $element['#attached']['library'][] = array('media', 'media_browser_settings');
  789. // Prefix and suffix used for Ajax replacement.
  790. $element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
  791. $element['#suffix'] = '</div>';
  792. return $element;
  793. }
  794. /**
  795. * Implements hook_form_FORM_ID_alter().
  796. */
  797. function media_form_file_entity_edit_alter(&$form, &$form_state) {
  798. // Make adjustments to the file edit form when used in a CTools modal.
  799. if (!empty($form_state['ajax'])) {
  800. // Remove the preview and the delete button.
  801. $form['preview']['#access'] = FALSE;
  802. $form['actions']['delete']['#access'] = FALSE;
  803. // Convert the cancel link to a button which triggers a modal close.
  804. $form['actions']['cancel']['#attributes']['class'][] = 'button';
  805. $form['actions']['cancel']['#attributes']['class'][] = 'button-no';
  806. $form['actions']['cancel']['#attributes']['class'][] = 'ctools-close-modal';
  807. }
  808. }
  809. /**
  810. * The #value_callback for a media type element.
  811. */
  812. function media_file_value(&$element, $input = FALSE, $form_state = NULL) {
  813. $fid = 0;
  814. // Find the current value of this field from the form state.
  815. $form_state_fid = $form_state['values'];
  816. foreach ($element['#parents'] as $parent) {
  817. $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
  818. }
  819. if ($element['#extended'] && isset($form_state_fid['fid'])) {
  820. $fid = $form_state_fid['fid'];
  821. }
  822. elseif (is_numeric($form_state_fid)) {
  823. $fid = $form_state_fid;
  824. }
  825. // Process any input and attach files.
  826. if ($input !== FALSE) {
  827. $return = $input;
  828. // Attachments take priority over all other values.
  829. if ($file = media_attach_file($element)) {
  830. $fid = $file->fid;
  831. }
  832. else {
  833. // Check for #filefield_value_callback values.
  834. // Because FAPI does not allow multiple #value_callback values like it
  835. // does for #element_validate and #process, this fills the missing
  836. // functionality to allow File fields to be extended through FAPI.
  837. if (isset($element['#file_value_callbacks'])) {
  838. foreach ($element['#file_value_callbacks'] as $callback) {
  839. $callback($element, $input, $form_state);
  840. }
  841. }
  842. // Load file if the FID has changed to confirm it exists.
  843. if (isset($input['fid']) && $file = file_load($input['fid'])) {
  844. $fid = $file->fid;
  845. }
  846. }
  847. }
  848. // If there is no input, set the default value.
  849. else {
  850. if ($element['#extended']) {
  851. $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
  852. $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
  853. }
  854. else {
  855. $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
  856. $return = array('fid' => 0);
  857. }
  858. // Confirm that the file exists when used as a default value.
  859. if ($default_fid && $file = file_load($default_fid)) {
  860. $fid = $file->fid;
  861. }
  862. }
  863. $return['fid'] = $fid;
  864. return $return;
  865. }
  866. /**
  867. * Validate media form elements.
  868. *
  869. * The file type is validated during the upload process, but this is necessary
  870. * necessary in order to respect the #required property.
  871. */
  872. function media_element_validate(&$element, &$form_state) {
  873. $clicked_button = end($form_state['triggering_element']['#parents']);
  874. // Check required property based on the FID.
  875. if ($element['#required'] && empty($element['fid']['#value']) && !in_array($clicked_button, array('attach_button', 'remove_button'))) {
  876. form_error($element['browse_button'], t('!name field is required.', array('!name' => $element['#title'])));
  877. }
  878. // Consolidate the array value of this field to a single FID.
  879. if (!$element['#extended']) {
  880. form_set_value($element, $element['fid']['#value'], $form_state);
  881. }
  882. }
  883. /**
  884. * Form submission handler for attach / remove buttons of media elements.
  885. *
  886. * @see media_element_process()
  887. */
  888. function media_file_submit($form, &$form_state) {
  889. // Determine whether it was the attach or remove button that was clicked, and
  890. // set $element to the managed_file element that contains that button.
  891. $parents = $form_state['triggering_element']['#array_parents'];
  892. $button_key = array_pop($parents);
  893. $element = drupal_array_get_nested_value($form, $parents);
  894. // No action is needed here for the attach button, because all media
  895. // attachments on the form are processed by media_file_value() regardless of
  896. // which button was clicked. Action is needed here for the remove button,
  897. // because we only remove a file in response to its remove button being
  898. // clicked.
  899. if ($button_key == 'remove_button') {
  900. // If it's a temporary file we can safely remove it immediately, otherwise
  901. // it's up to the implementing module to clean up files that are in use.
  902. if ($element['#file'] && $element['#file']->status == 0) {
  903. file_delete($element['#file']);
  904. }
  905. // Update both $form_state['values'] and $form_state['input'] to reflect
  906. // that the file has been removed, so that the form is rebuilt correctly.
  907. // $form_state['values'] must be updated in case additional submit handlers
  908. // run, and for form building functions that run during the rebuild, such as
  909. // when the media element is part of a field widget.
  910. // $form_state['input'] must be updated so that media_file_value() has
  911. // correct information during the rebuild.
  912. $values_element = $element['#extended'] ? $element['fid'] : $element;
  913. form_set_value($values_element, NULL, $form_state);
  914. drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
  915. }
  916. // Set the form to rebuild so that $form is correctly updated in response to
  917. // processing the file removal. Since this function did not change $form_state
  918. // if the upload button was clicked, a rebuild isn't necessary in that
  919. // situation and setting $form_state['redirect'] to FALSE would suffice.
  920. // However, we choose to always rebuild, to keep the form processing workflow
  921. // consistent between the two buttons.
  922. $form_state['rebuild'] = TRUE;
  923. }
  924. /**
  925. * Attaches any files that have been referenced by a media element.
  926. *
  927. * @param $element
  928. * The FAPI element whose files are being attached.
  929. *
  930. * @return
  931. * The file object representing the file that was attached, or FALSE if no
  932. * file was attached.
  933. */
  934. function media_attach_file($element) {
  935. $upload_name = implode('_', $element['#parents']);
  936. if (empty($_POST['media'][$upload_name])) {
  937. return FALSE;
  938. }
  939. if (!$file = file_load($_POST['media'][$upload_name])) {
  940. watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
  941. form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
  942. return FALSE;
  943. }
  944. return $file;
  945. }
  946. /**
  947. * Returns HTML for a managed file element.
  948. *
  949. * @param $variables
  950. * An associative array containing:
  951. * - element: A render element representing the file.
  952. *
  953. * @ingroup themeable
  954. */
  955. function theme_media_element($variables) {
  956. $element = $variables['element'];
  957. $attributes = array();
  958. if (isset($element['#id'])) {
  959. $attributes['id'] = $element['#id'];
  960. }
  961. if (!empty($element['#attributes']['class'])) {
  962. $attributes['class'] = (array) $element['#attributes']['class'];
  963. }
  964. $attributes['class'][] = 'form-media';
  965. // This wrapper is required to apply JS behaviors and CSS styling.
  966. $output = '';
  967. $output .= '<div' . drupal_attributes($attributes) . '>';
  968. $output .= drupal_render_children($element);
  969. $output .= '</div>';
  970. return $output;
  971. }
  972. /**
  973. * #pre_render callback to hide display of the browse/attach or remove controls.
  974. *
  975. * Browse/attach controls are hidden when a file is already attached.
  976. * Remove controls are hidden when there is no file attached. Controls are
  977. * hidden here instead of in media_element_process(), because #access for these
  978. * buttons depends on the media element's #value. See the documentation of
  979. * form_builder() for more detailed information about the relationship between
  980. * #process, #value, and #access.
  981. *
  982. * Because #access is set here, it affects display only and does not prevent
  983. * JavaScript or other untrusted code from submitting the form as though access
  984. * were enabled. The form processing functions for these elements should not
  985. * assume that the buttons can't be "clicked" just because they are not
  986. * displayed.
  987. *
  988. * @see media_element_process()
  989. * @see form_builder()
  990. */
  991. function media_element_pre_render($element) {
  992. // If we already have a file, we don't want to show the browse and attach
  993. // controls.
  994. if (!empty($element['#value']['fid'])) {
  995. $element['upload']['#access'] = FALSE;
  996. $element['browse_button']['#access'] = FALSE;
  997. $element['attach_button']['#access'] = FALSE;
  998. }
  999. // If we don't already have a file, there is nothing to remove.
  1000. else {
  1001. $element['remove_button']['#access'] = FALSE;
  1002. }
  1003. return $element;
  1004. }
  1005. /**
  1006. * Generates a thumbnail preview of a file.
  1007. *
  1008. * Provides default fallback images if an image of the file cannot be generated.
  1009. *
  1010. * @param object $file
  1011. * A Drupal file object.
  1012. * @param boolean $link
  1013. * (optional) Boolean indicating whether the thumbnail should be linked to the
  1014. * file. Defaults to FALSE.
  1015. * @param string $view_mode
  1016. * (optional) The view mode to use when rendering the thumbnail. Defaults to
  1017. * 'preview'.
  1018. *
  1019. * @return array
  1020. * Renderable array suitable for drupal_render() with the necessary classes
  1021. * and CSS to support a media thumbnail.
  1022. */
  1023. function media_get_thumbnail_preview($file, $link = FALSE, $view_mode = 'preview') {
  1024. // If a file has an invalid type, allow file_view_file() to work.
  1025. if (!file_type_is_enabled($file->type)) {
  1026. $file->type = file_get_type($file);
  1027. }
  1028. $preview = file_view_file($file, $view_mode);
  1029. $preview['#show_names'] = TRUE;
  1030. $preview['#add_link'] = $link;
  1031. $preview['#theme_wrappers'][] = 'media_thumbnail';
  1032. $preview['#attached']['css'][] = drupal_get_path('module', 'media') . '/css/media.css';
  1033. return $preview;
  1034. }
  1035. /**
  1036. * Check that the media is one of the selected types.
  1037. *
  1038. * @param object $file
  1039. * A Drupal file object.
  1040. * @param array $types
  1041. * An array of media type names
  1042. *
  1043. * @return array
  1044. * If the file type is not allowed, it will contain an error message.
  1045. *
  1046. * @see hook_file_validate()
  1047. */
  1048. function media_file_validate_types($file, $types) {
  1049. $errors = array();
  1050. if (!function_exists('file_entity_get_filetype_candidates')) {
  1051. module_load_include('inc', 'file_entity', 'file_entity.pages');
  1052. }
  1053. $file_candidates = array_keys(file_entity_get_filetype_candidates($file));
  1054. if (!array_intersect($file_candidates, $types)) {
  1055. $errors[] = t('Only the following types of files are allowed to be uploaded: %types-allowed', array('%types-allowed' => implode(', ', $types)));
  1056. }
  1057. return $errors;
  1058. }
  1059. /**
  1060. * Implements hook_file_displays_alter().
  1061. */
  1062. function media_file_displays_alter(&$displays, $file, $view_mode) {
  1063. if ($view_mode == 'preview' && empty($displays)) {
  1064. // We re in the media browser and this file has no formatters enabled.
  1065. // Instead of letting it go through theme_file_link(), pass it through
  1066. // theme_media_formatter_large_icon() to get our cool file icon instead.
  1067. $displays['file_field_media_large_icon'] = array(
  1068. 'weight' => 0,
  1069. 'status' => 1,
  1070. 'settings' => NULL,
  1071. );
  1072. }
  1073. // Alt and title are special.
  1074. // @see file_entity_file_load
  1075. $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
  1076. $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
  1077. $replace_options = array(
  1078. 'clear' => TRUE,
  1079. 'sanitize' => FALSE,
  1080. );
  1081. // Load alt and title text from fields.
  1082. if (!empty($alt)) {
  1083. $file->alt = decode_entities(token_replace($alt, array('file' => $file), $replace_options));
  1084. }
  1085. if (!empty($title)) {
  1086. $file->title = decode_entities(token_replace($title, array('file' => $file), $replace_options));
  1087. }
  1088. // Reduce memory footprint and response size in media browser.
  1089. $file->file_contents = '';
  1090. }
  1091. /**
  1092. * For sanity in grammar.
  1093. *
  1094. * @see media_set_browser_params()
  1095. */
  1096. function media_get_browser_params() {
  1097. return media_set_browser_params();
  1098. }
  1099. /**
  1100. * Provides a singleton of the params passed to the media browser.
  1101. *
  1102. * This is useful in situations like form alters because callers can pass
  1103. * id="wysiywg_form" or whatever they want, and a form alter could pick this up.
  1104. * We may want to change the hook_media_browser_plugin_view() implementations to
  1105. * use this function instead of being passed params for consistency.
  1106. *
  1107. * It also offers a chance for some meddler to meddle with them.
  1108. *
  1109. * @see media_browser()
  1110. */
  1111. function media_set_browser_params() {
  1112. $params = &drupal_static(__FUNCTION__, array());
  1113. if (empty($params)) {
  1114. // Build out browser settings. Permissions- and security-related behaviors
  1115. // should not rely on these parameters, since they come from the HTTP query.
  1116. // There are two ways of passing secure data:
  1117. // - Store the options in the 'cache_form' cache bin, using a random key
  1118. // prefixed with 'media_options:'. Pass the random key in the 'options'
  1119. // query argument.
  1120. // - Inject the options by altering the browser parameters.
  1121. // @see hook_media_browser_params_alter()
  1122. $params = drupal_get_query_parameters();
  1123. // Filter out everything except a whitelist of known safe options.
  1124. $safe_options = array(
  1125. 'enabledPlugins',
  1126. 'fid',
  1127. 'id',
  1128. 'multiselect',
  1129. 'field',
  1130. 'options',
  1131. 'plugins',
  1132. 'render',
  1133. 'types',
  1134. 'render_multi_edit_form',
  1135. );
  1136. $params = array_intersect_key($params, array_flip($safe_options));
  1137. // If the cache is present, use its values instead of the GET parameters.
  1138. if (!empty($params['options']) && is_string($params['options']) && $options = cache_get('media_options:' . $params['options'], 'cache_form')) {
  1139. $params = $options->data;
  1140. }
  1141. // Transform text 'true' and 'false' to actual booleans.
  1142. foreach ($params as $k => $v) {
  1143. if ($v === 'true') {
  1144. $params[$k] = TRUE;
  1145. }
  1146. elseif ($v === 'false') {
  1147. $params[$k] = FALSE;
  1148. }
  1149. }
  1150. media_array_walk_recursive($params);
  1151. // Provide some default parameters.
  1152. $params += array(
  1153. 'types' => array(),
  1154. 'multiselect' => FALSE,
  1155. );
  1156. // Allow modules to alter the parameters.
  1157. drupal_alter('media_browser_params', $params);
  1158. }
  1159. return $params;
  1160. }
  1161. /**
  1162. * Implements hook_ctools_plugin_api().
  1163. *
  1164. * Lets CTools know which plugin APIs are implemented by Media module.
  1165. */
  1166. function media_ctools_plugin_api($module, $api) {
  1167. if ($module == 'file_entity' && $api == 'file_default_displays') {
  1168. return array(
  1169. 'version' => 1,
  1170. );
  1171. }
  1172. }
  1173. /**
  1174. * Implements hook_form_FORM_ID_alter().
  1175. *
  1176. * This alter enhances the default admin/content/file page, addding JS and CSS.
  1177. * It also makes modifications to the thumbnail view by replacing the existing
  1178. * checkboxes and table with thumbnails.
  1179. */
  1180. function media_form_file_entity_admin_file_alter(&$form, $form_state) {
  1181. if (!empty($form_state['values']['operation'])) {
  1182. // The form is being rebuilt because an operation requiring confirmation
  1183. // We don't want to be messing with it in this case.
  1184. return;
  1185. }
  1186. // Add the "Add file" local action, and notify users if they have files
  1187. // selected and they try to switch between the "Thumbnail" and "List" local
  1188. // tasks.
  1189. $path = drupal_get_path('module', 'media');
  1190. $form['#attributes']['class'][] = 'file-entity-admin-file-form';
  1191. $form['#attached']['js'][] = $path . '/js/media.admin.js';
  1192. $form['#attached']['css'][] = $path . '/css/media.css';
  1193. // By default, this form contains a table select element called "files". For
  1194. // the 'thumbnails' tab, Media generates a thumbnail for each file and
  1195. // replaces the tableselect with a grid of thumbnails.
  1196. if (arg(3) == 'thumbnails') {
  1197. if (empty($form['admin']['files']['#options'])) {
  1198. // Display empty text if there are no files.
  1199. $form['admin']['files'] = array(
  1200. '#markup' => '<p>' . $form['admin']['files']['#empty'] . '</p>',
  1201. );
  1202. }
  1203. else {
  1204. $files = file_load_multiple(array_keys($form['admin']['files']['#options']));
  1205. $form['admin']['files'] = array(
  1206. '#tree' => TRUE,
  1207. '#prefix' => '<div class="media-display-thumbnails media-clear clearfix"><ul id="media-browser-library-list" class="media-list-thumbnails">',
  1208. '#suffix' => '</ul></div>',
  1209. );
  1210. foreach ($files as $file) {
  1211. $preview = media_get_thumbnail_preview($file, TRUE);
  1212. $form['admin']['files'][$file->fid] = array(
  1213. '#type' => 'checkbox',
  1214. '#title' => '',
  1215. '#prefix' => '<li>' . drupal_render($preview),
  1216. '#suffix' => '</li>',
  1217. );
  1218. }
  1219. }
  1220. }
  1221. }
  1222. /**
  1223. * Implements hook_views_api().
  1224. */
  1225. function media_views_api() {
  1226. return array(
  1227. 'api' => 3,
  1228. 'path' => drupal_get_path('module', 'media'),
  1229. );
  1230. }
  1231. /**
  1232. * Implements hook_views_default_views().
  1233. */
  1234. function media_views_default_views() {
  1235. return media_load_all_exports('media', 'views', 'view.inc', 'view');
  1236. }
  1237. /**
  1238. * Fetches an array of exportables from files.
  1239. *
  1240. * @param string $module
  1241. * The module invoking this request. (Can be called by other modules.)
  1242. * @param string $directory
  1243. * The subdirectory in the custom module.
  1244. * @param string $extension
  1245. * The file extension.
  1246. * @param string $name
  1247. * The name of the variable found in each file. Defaults to the same as
  1248. * $extension.
  1249. *
  1250. * @return array
  1251. * Array of $name objects.
  1252. */
  1253. function media_load_all_exports($module, $directory, $extension, $name = NULL) {
  1254. if (!$name) {
  1255. $name = $extension;
  1256. }
  1257. $return = array();
  1258. // Find all the files in the directory with the correct extension.
  1259. $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
  1260. foreach ($files as $path => $file) {
  1261. require $path;
  1262. if (isset($$name)) {
  1263. $return[$$name->name] = $$name;
  1264. }
  1265. }
  1266. return $return;
  1267. }
  1268. /**
  1269. * Returns metadata describing Media browser plugins.
  1270. *
  1271. * @return
  1272. * An associative array of plugin information, keyed by plugin.
  1273. *
  1274. * @see hook_media_browser_plugin_info()
  1275. * @see hook_media_browser_plugin_info_alter()
  1276. */
  1277. function media_get_browser_plugin_info() {
  1278. $info = &drupal_static(__FUNCTION__);
  1279. if (!isset($info)) {
  1280. $info = module_invoke_all('media_browser_plugin_info');
  1281. drupal_alter('media_browser_plugin_info', $info);
  1282. }
  1283. return $info;
  1284. }
  1285. /**
  1286. * Gets the MIME type mapped to a given extension.
  1287. *
  1288. * @param string $extension
  1289. * A file extension.
  1290. *
  1291. * @return string
  1292. * The MIME type associated with the extension or FALSE if the extension does
  1293. * not have an associated MIME type.
  1294. *
  1295. * @see file_mimetype_mapping()
  1296. */
  1297. function media_get_extension_mimetype($extension) {
  1298. include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
  1299. $mimetype_mappings = file_mimetype_mapping();
  1300. if (isset($mimetype_mappings['extensions'][$extension])) {
  1301. $id = $mimetype_mappings['extensions'][$extension];
  1302. return $mimetype_mappings['mimetypes'][$id];
  1303. }
  1304. else {
  1305. return FALSE;
  1306. }
  1307. }
  1308. /**
  1309. * Helper function to get a list of local stream wrappers.
  1310. */
  1311. function media_get_local_stream_wrappers() {
  1312. return file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL);
  1313. }
  1314. /**
  1315. * Helper function to get a list of remote stream wrappers.
  1316. */
  1317. function media_get_remote_stream_wrappers() {
  1318. $wrappers = file_get_stream_wrappers();
  1319. $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_NORMAL));
  1320. $wrappers = array_diff_key($wrappers, file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL_HIDDEN));
  1321. return $wrappers;
  1322. }