media.browser.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. /**
  3. * @file
  4. * Media Browser page callback
  5. */
  6. function media_browser($selected = NULL) {
  7. $output = array();
  8. $output['#attached']['library'][] = array('media', 'media_browser_page');
  9. $params = drupal_get_query_parameters();
  10. array_walk_recursive($params, '_media_recursive_check_plain');
  11. $params = media_set_browser_params($params);
  12. // If one or more files have been selected, the browser interaction is now
  13. // complete. Return empty page content to the dialog which now needs to close,
  14. // but populate Drupal.settings with information about the selected files.
  15. if (isset($params['fid'])) {
  16. $fids = is_array($params['fid']) ? $params['fid'] : array($params['fid']);
  17. if (!is_numeric($fids[0])) {
  18. throw new Exception('Error selecting media, fid param is not an fid or an array of fids');
  19. }
  20. $files = file_load_multiple($fids);
  21. foreach ($files as $file) {
  22. media_browser_build_media_item($file);
  23. }
  24. $setting = array('media' => array('selectedMedia' => array_values($files)));
  25. drupal_add_js($setting, 'setting');
  26. return $output;
  27. }
  28. // Normal browser operation.
  29. foreach (module_implements('media_browser_plugin_info') as $module) {
  30. foreach (module_invoke($module, 'media_browser_plugin_info') as $key => $plugin_data) {
  31. $plugins[$key] = $plugin_data + array(
  32. '#module' => $module,
  33. '#weight' => 0,
  34. );
  35. $plugins[$key]['#weight'] += count($plugins)/1000;
  36. }
  37. }
  38. // Only the plugins in this array are loaded.
  39. if (!empty($params['enabledPlugins'])) {
  40. $plugins = array_intersect_key($plugins, array_fill_keys($params['enabledPlugins'], 1));
  41. }
  42. elseif (!empty($params['disabledPlugins'])) {
  43. $plugins = array_diff_key($plugins, array_fill_keys($params['disabledPlugins'], 1));
  44. }
  45. foreach ($plugins as $key => &$plugin) {
  46. $plugin += module_invoke($plugin['#module'], 'media_browser_plugin_view', $key, $params);
  47. }
  48. // Allow modules to change the tab names or whatever else they want to change
  49. // before we render. Perhaps this should be an alter on the theming function
  50. // that we should write to be making the tabs.
  51. drupal_alter('media_browser_plugins', $plugins);
  52. $tabs = array(); // List of tabs to render.
  53. $settings = array('media' => array('browser' => array()));
  54. $browser_settings =& $settings['media']['browser'];
  55. //@todo: replace with Tabs module if it gets upgraded.
  56. foreach (element_children($plugins, TRUE) as $key) {
  57. $plugin =& $plugins[$key];
  58. //Add any JS settings
  59. $browser_settings[$key] = isset($plugin['#settings']) ? $plugin['#settings'] : array();
  60. // If this is a "ajax" style tab, add the href, otherwise an id.
  61. $href = isset($plugin['#callback']) ? $plugin['#callback'] : "#media-tab-$key";
  62. $tabs[] = "<a href='$href'><span>{$plugin['#title']}</span></a>";
  63. // Create a div for each tab's content.
  64. $plugin['#prefix'] = <<<EOS
  65. <div class="media-browser-tab" id="media-tab-$key">
  66. EOS;
  67. $plugin['#suffix'] = <<<EOS
  68. </div>
  69. <!-- End #media-tab-$key -->
  70. EOS;
  71. }
  72. drupal_add_js($settings, 'setting');
  73. $output['tabset'] = array(
  74. '#prefix' => '<div id="media-browser-tabset">',
  75. '#suffix' => '</div>',
  76. );
  77. $output['tabset']['list'] = array(
  78. '#markup' => '<ul><li>' . implode('</li><li>', $tabs) . '</li></ul>'
  79. );
  80. $output['tabset']['plugins'] = $plugins;
  81. return $output;
  82. }
  83. /**
  84. * Provides a singleton of the params passed to the media browser.
  85. *
  86. * This is useful in situations like form alters because callers can pass
  87. * id="wysiywg_form" or whatever they want, and a form alter could pick this up.
  88. * We may want to change the hook_media_browser_plugin_view() implementations to
  89. * use this function instead of being passed params for consistency.
  90. *
  91. * It also offers a chance for some meddler to meddle with them.
  92. *
  93. * @param array $params
  94. * An array of parameters provided when a media_browser is launched.
  95. *
  96. * @see media_browser()
  97. */
  98. function media_set_browser_params(array $params = NULL) {
  99. $stored_params = &drupal_static(__FUNCTION__, array());
  100. if (isset($params)) {
  101. $stored_params = $params;
  102. // Allow modules to alter the parameters.
  103. drupal_alter('media_browser_params', $stored_params);
  104. }
  105. return $stored_params;
  106. }
  107. /**
  108. * For sanity in grammar.
  109. *
  110. * @see media_set_browser_params()
  111. */
  112. function media_get_browser_params() {
  113. return media_set_browser_params();
  114. }
  115. /**
  116. * AJAX Callback function to return a list of media files
  117. */
  118. function media_browser_list() {
  119. $params = drupal_get_query_parameters();
  120. // How do we validate these? I don't know.
  121. // I think PDO should protect them, but I'm not 100% certain.
  122. array_walk_recursive($params, '_media_recursive_check_plain');
  123. $remote_types = !empty($params['types']) ? $params['types'] : NULL;
  124. $url_include_patterns = !empty($params['url_include_patterns']) ? $params['url_include_patterns'] : NULL;
  125. $url_exclude_patterns = !empty($params['url_exclude_patterns']) ? $params['url_exclude_patterns'] : NULL;
  126. $allowed_schemes = !empty($params['schemes']) ? array_filter($params['schemes']) : array();
  127. $start = isset($params['start']) ? $params['start'] : 0;
  128. $limit = isset($params['limit']) ? $params['limit'] : media_variable_get('browser_pager_limit');
  129. $query = db_select('file_managed', 'f');
  130. $query->fields('f', array('fid'));
  131. $query->range($start, $limit);
  132. $query->orderBy('f.timestamp', 'DESC');
  133. // Add conditions based on remote file type *or* local allowed extensions.
  134. $or_condition = db_or();
  135. // Include local files with the allowed extensions.
  136. if (!empty($params['file_extensions'])) {
  137. $extensions = array_filter(explode(' ', $params['file_extensions']));
  138. $local_wrappers = array_intersect_key(media_get_local_stream_wrappers(), $allowed_schemes);
  139. if (!empty($local_wrappers) && !empty($extensions)) {
  140. $local_condition = db_or();
  141. foreach (array_keys($local_wrappers) as $scheme) {
  142. foreach ($extensions as $extension) {
  143. $local_condition->condition('f.uri', db_like($scheme . '://') . '%' . db_like('.' . $extension), 'LIKE');
  144. }
  145. }
  146. $or_condition->condition($local_condition);
  147. }
  148. }
  149. // Include remote files with the allowed file types.
  150. if (!empty($remote_types)) {
  151. $remote_wrappers = array_intersect_key(media_get_remote_stream_wrappers(), $allowed_schemes);
  152. if (!empty($remote_wrappers)) {
  153. $remote_condition = db_and();
  154. $wrapper_condition = db_or();
  155. foreach (array_keys($remote_wrappers) as $scheme) {
  156. $wrapper_condition->condition('f.uri', db_like($scheme . '://') . '%', 'LIKE');
  157. }
  158. $remote_condition->condition($wrapper_condition);
  159. $remote_condition->condition('f.type', $remote_types, 'IN');
  160. $or_condition->condition($remote_condition);
  161. }
  162. }
  163. if ($or_condition->count()) {
  164. $query->condition($or_condition);
  165. }
  166. if ($url_include_patterns) {
  167. $query->condition('f.uri', '%' . db_like($url_include_patterns) . '%', 'LIKE');
  168. // Insert stream related restrictions here.
  169. }
  170. if ($url_exclude_patterns) {
  171. $query->condition('f.uri', '%' . db_like($url_exclude_patterns) . '%', 'NOT LIKE');
  172. }
  173. // @todo Implement granular editorial access: http://drupal.org/node/696970.
  174. // In the meantime, protect information about private files from being
  175. // discovered by unprivileged users. See also media_view_page().
  176. if (!user_access('administer media')) {
  177. $query->condition('f.uri', db_like('private://') . '%', 'NOT LIKE');
  178. }
  179. $query->condition('f.status', FILE_STATUS_PERMANENT);
  180. foreach (array_keys(media_get_hidden_stream_wrappers()) as $name) {
  181. $query->condition('f.uri', db_like($name . '://') . '%', 'NOT LIKE');
  182. }
  183. $fids = $query->execute()->fetchCol();
  184. $files = file_load_multiple($fids);
  185. foreach ($files as $file) {
  186. media_browser_build_media_item($file);
  187. }
  188. drupal_json_output(array('media' => array_values($files)));
  189. exit();
  190. }
  191. /**
  192. * Silly function to recursively run check_plain on an array.
  193. *
  194. * There is probably something in core I am not aware of that does this.
  195. *
  196. * @param $value
  197. * @param $key
  198. */
  199. function _media_recursive_check_plain(&$value, $key) {
  200. $value = check_plain($value);
  201. }
  202. /**
  203. * Attaches media browser javascript to an element.
  204. *
  205. * @param $element
  206. * The element array to attach to.
  207. */
  208. function media_attach_browser_js(&$element) {
  209. $javascript = media_browser_js();
  210. foreach ($javascript as $key => $definitions) {
  211. foreach ($definitions as $definition) {
  212. $element['#attached'][$key][] = $definition;
  213. }
  214. }
  215. }
  216. /**
  217. * Helper function to define browser javascript.
  218. */
  219. function media_browser_js() {
  220. $settings = array(
  221. 'browserUrl' => url('media/browser',
  222. array('query' => array('render' => 'media-popup'))),
  223. 'styleSelectorUrl' => url('media/-media_id-/format-form',
  224. array('query' => array('render' => 'media-popup'))),
  225. );
  226. $js = array(
  227. 'library' => array(
  228. array('media', 'media_browser'),
  229. ),
  230. 'js' => array(
  231. array(
  232. 'data' => array('media' => $settings),
  233. 'type' => 'setting',
  234. ),
  235. ),
  236. );
  237. return $js;
  238. }
  239. /**
  240. * Menu callback for testing the media browser
  241. */
  242. function media_browser_testbed($form) {
  243. media_attach_browser_js($form);
  244. $form['test_element'] = array(
  245. '#type' => 'media',
  246. '#media_options' => array(
  247. 'global' => array(
  248. 'types' => array('video', 'audio'),
  249. ),
  250. )
  251. );
  252. $launcher = '<a href="#" id="launcher"> Launch Media Browser</a>';
  253. $form['options'] = array(
  254. '#type' => 'textarea',
  255. '#title' => 'Options (JSON)',
  256. '#rows' => 10,
  257. );
  258. $form['launcher'] = array(
  259. '#markup' => $launcher,
  260. );
  261. $form['result'] = array(
  262. '#type' => 'textarea',
  263. '#title' => 'Result',
  264. );
  265. $js = <<<EOF
  266. Drupal.behaviors.mediaTest = {
  267. attach: function(context, settings) {
  268. var delim = "---";
  269. var recentOptions = [];
  270. var recentOptionsCookie = jQuery.cookie("recentOptions");
  271. if (recentOptionsCookie) {
  272. recentOptions = recentOptionsCookie.split("---");
  273. }
  274. var recentSelectBox = jQuery('<select id="recent_options" style="width:100%"></select>').change(function() { jQuery('#edit-options').val(jQuery(this).val())});
  275. jQuery('.form-item-options').append('<label for="recent_options">Recent</a>');
  276. jQuery('.form-item-options').append(recentSelectBox);
  277. jQuery('.form-item-options').append(jQuery('<a href="#">Reset</a>').click(function() {alert('reset'); jQuery.cookie("recentOptions", null); window.location.reload(); }));
  278. jQuery.each(recentOptions, function (idx, val) {
  279. recentSelectBox.append(jQuery('<option></option>').val(val).html(val));
  280. });
  281. jQuery('#launcher').click(function () {
  282. jQuery('#edit-result').val('');
  283. var options = {};
  284. var optionsTxt = jQuery('#edit-options').val();
  285. if (optionsTxt) {
  286. // Store it in the recent box
  287. recentOptionsCookie += "---" + optionsTxt
  288. jQuery.cookie("recentOptions", recentOptionsCookie, { expires: 7 });
  289. recentSelectBox.append(jQuery('<option></option>').val(optionsTxt).html(optionsTxt));
  290. options = eval('(' + optionsTxt + ')');
  291. }
  292. Drupal.media.popups.mediaBrowser(Drupal.behaviors.mediaTest.mediaSelected, options);
  293. return false;
  294. });
  295. },
  296. mediaSelected: function(selectedMedia) {
  297. var result = JSON.stringify(selectedMedia);
  298. jQuery('#edit-result').val(result);
  299. }
  300. }
  301. EOF;
  302. drupal_add_js($js, array('type' => 'inline'));
  303. return $form;
  304. }
  305. /**
  306. * Adds properties to the passed in file that are needed by the media browser JS code.
  307. */
  308. function media_browser_build_media_item($file) {
  309. $preview = media_get_thumbnail_preview($file);
  310. $file->preview = drupal_render($preview);
  311. $file->url = file_create_url($file->uri);
  312. }