file.module 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. <?php
  2. /**
  3. * @file
  4. * Defines a "managed_file" Form API field and a "file" field for Field module.
  5. */
  6. // Load all Field module hooks for File.
  7. require_once DRUPAL_ROOT . '/modules/file/file.field.inc';
  8. /**
  9. * Implements hook_help().
  10. */
  11. function file_help($path, $arg) {
  12. switch ($path) {
  13. case 'admin/help#file':
  14. $output = '';
  15. $output .= '<h3>' . t('About') . '</h3>';
  16. $output .= '<p>' . t('The File module defines a <em>File</em> field type for the Field module, which lets you manage and validate uploaded files attached to content on your site (see the <a href="@field-help">Field module help page</a> for more information about fields). For more information, see the online handbook entry for <a href="@file">File module</a>.', array('@field-help' => url('admin/help/field'), '@file' => 'http://drupal.org/documentation/modules/file')) . '</p>';
  17. $output .= '<h3>' . t('Uses') . '</h3>';
  18. $output .= '<dl>';
  19. $output .= '<dt>' . t('Attaching files to content') . '</dt>';
  20. $output .= '<dd>' . t('The File module allows users to attach files to content (e.g., PDF files, spreadsheets, etc.), when a <em>File</em> field is added to a given content type using the <a href="@fieldui-help">Field UI module</a>. You can add validation options to your File field, such as specifying a maximum file size and allowed file extensions.', array('@fieldui-help' => url('admin/help/field_ui'))) . '</dd>';
  21. $output .= '<dt>' . t('Managing attachment display') . '</dt>';
  22. $output .= '<dd>' . t('When you attach a file to content, you can specify whether it is <em>listed</em> or not. Listed files are displayed automatically in a section at the bottom of your content; non-listed files are available for embedding in your content, but are not included in the list at the bottom.') . '</dd>';
  23. $output .= '<dt>' . t('Managing file locations') . '</dt>';
  24. $output .= '<dd>' . t("When you create a File field, you can specify a directory where the files will be stored, which can be within either the <em>public</em> or <em>private</em> files directory. Files in the public directory can be accessed directly through the web server; when public files are listed, direct links to the files are used, and anyone who knows a file's URL can download the file. Files in the private directory are not accessible directly through the web server; when private files are listed, the links are Drupal path requests. This adds to server load and download time, since Drupal must start up and resolve the path for each file download request, but allows for access restrictions.") . '</dd>';
  25. $output .= '</dl>';
  26. return $output;
  27. }
  28. }
  29. /**
  30. * Implements hook_menu().
  31. */
  32. function file_menu() {
  33. $items = array();
  34. $items['file/ajax'] = array(
  35. 'page callback' => 'file_ajax_upload',
  36. 'delivery callback' => 'ajax_deliver',
  37. 'access arguments' => array('access content'),
  38. 'theme callback' => 'ajax_base_page_theme',
  39. 'type' => MENU_CALLBACK,
  40. );
  41. $items['file/progress'] = array(
  42. 'page callback' => 'file_ajax_progress',
  43. 'access arguments' => array('access content'),
  44. 'theme callback' => 'ajax_base_page_theme',
  45. 'type' => MENU_CALLBACK,
  46. );
  47. return $items;
  48. }
  49. /**
  50. * Implements hook_element_info().
  51. *
  52. * The managed file element may be used anywhere in Drupal.
  53. */
  54. function file_element_info() {
  55. $file_path = drupal_get_path('module', 'file');
  56. $types['managed_file'] = array(
  57. '#input' => TRUE,
  58. '#process' => array('file_managed_file_process'),
  59. '#value_callback' => 'file_managed_file_value',
  60. '#element_validate' => array('file_managed_file_validate'),
  61. '#pre_render' => array('file_managed_file_pre_render'),
  62. '#theme' => 'file_managed_file',
  63. '#theme_wrappers' => array('form_element'),
  64. '#progress_indicator' => 'throbber',
  65. '#progress_message' => NULL,
  66. '#upload_validators' => array(),
  67. '#upload_location' => NULL,
  68. '#size' => 22,
  69. '#extended' => FALSE,
  70. '#attached' => array(
  71. 'css' => array($file_path . '/file.css'),
  72. 'js' => array($file_path . '/file.js'),
  73. ),
  74. );
  75. return $types;
  76. }
  77. /**
  78. * Implements hook_theme().
  79. */
  80. function file_theme() {
  81. return array(
  82. // file.module.
  83. 'file_link' => array(
  84. 'variables' => array('file' => NULL, 'icon_directory' => NULL),
  85. ),
  86. 'file_icon' => array(
  87. 'variables' => array('file' => NULL, 'icon_directory' => NULL, 'alt' => ''),
  88. ),
  89. 'file_managed_file' => array(
  90. 'render element' => 'element',
  91. ),
  92. // file.field.inc.
  93. 'file_widget' => array(
  94. 'render element' => 'element',
  95. ),
  96. 'file_widget_multiple' => array(
  97. 'render element' => 'element',
  98. ),
  99. 'file_formatter_table' => array(
  100. 'variables' => array('items' => NULL),
  101. ),
  102. 'file_upload_help' => array(
  103. 'variables' => array('description' => NULL, 'upload_validators' => NULL),
  104. ),
  105. );
  106. }
  107. /**
  108. * Implements hook_file_download().
  109. *
  110. * This function takes an extra parameter $field_type so that it may
  111. * be re-used by other File-like modules, such as Image.
  112. */
  113. function file_file_download($uri, $field_type = 'file') {
  114. global $user;
  115. // Get the file record based on the URI. If not in the database just return.
  116. $files = file_load_multiple(array(), array('uri' => $uri));
  117. if (count($files)) {
  118. foreach ($files as $item) {
  119. // Since some database servers sometimes use a case-insensitive comparison
  120. // by default, double check that the filename is an exact match.
  121. if ($item->uri === $uri) {
  122. $file = $item;
  123. break;
  124. }
  125. }
  126. }
  127. if (!isset($file)) {
  128. return;
  129. }
  130. // Find out which (if any) fields of this type contain the file.
  131. $references = file_get_file_references($file, NULL, FIELD_LOAD_CURRENT, $field_type, FALSE);
  132. // Stop processing if there are no references in order to avoid returning
  133. // headers for files controlled by other modules. Make an exception for
  134. // temporary files where the host entity has not yet been saved (for example,
  135. // an image preview on a node/add form) in which case, allow download by the
  136. // file's owner. For anonymous file owners, only the browser session that
  137. // uploaded the file should be granted access.
  138. if (empty($references) && ($file->status == FILE_STATUS_PERMANENT || $file->uid != $user->uid || (!$user->uid && empty($_SESSION['anonymous_allowed_file_ids'][$file->fid])))) {
  139. return;
  140. }
  141. // Default to allow access.
  142. $denied = FALSE;
  143. // Loop through all references of this file. If a reference explicitly allows
  144. // access to the field to which this file belongs, no further checks are done
  145. // and download access is granted. If a reference denies access, eventually
  146. // existing additional references are checked. If all references were checked
  147. // and no reference denied access, access is granted as well. If at least one
  148. // reference denied access, access is denied.
  149. foreach ($references as $field_name => $field_references) {
  150. foreach ($field_references as $entity_type => $type_references) {
  151. foreach ($type_references as $id => $reference) {
  152. // Try to load $entity and $field.
  153. $entity = entity_load($entity_type, array($id));
  154. $entity = reset($entity);
  155. $field = field_info_field($field_name);
  156. // Load the field item that references the file.
  157. $field_item = NULL;
  158. if ($entity) {
  159. // Load all field items for that entity.
  160. $field_items = field_get_items($entity_type, $entity, $field_name);
  161. // Find the field item with the matching URI.
  162. foreach ($field_items as $item) {
  163. if ($item['uri'] == $uri) {
  164. $field_item = $item;
  165. break;
  166. }
  167. }
  168. }
  169. // Check that $entity, $field and $field_item were loaded successfully
  170. // and check if access to that field is not disallowed. If any of these
  171. // checks fail, stop checking access for this reference.
  172. if (empty($entity) || empty($field) || empty($field_item) || !field_access('view', $field, $entity_type, $entity)) {
  173. $denied = TRUE;
  174. break;
  175. }
  176. // Invoke hook and collect grants/denies for download access.
  177. // Default to FALSE and let entities overrule this ruling.
  178. $grants = array('system' => FALSE);
  179. foreach (module_implements('file_download_access') as $module) {
  180. $grants = array_merge($grants, array($module => module_invoke($module, 'file_download_access', $field_item, $entity_type, $entity)));
  181. }
  182. // Allow other modules to alter the returned grants/denies.
  183. drupal_alter('file_download_access', $grants, $field_item, $entity_type, $entity);
  184. if (in_array(TRUE, $grants)) {
  185. // If TRUE is returned, access is granted and no further checks are
  186. // necessary.
  187. $denied = FALSE;
  188. break 3;
  189. }
  190. if (in_array(FALSE, $grants)) {
  191. // If an implementation returns FALSE, access to this entity is denied
  192. // but the file could belong to another entity to which the user might
  193. // have access. Continue with these.
  194. $denied = TRUE;
  195. }
  196. }
  197. }
  198. }
  199. // Access specifically denied.
  200. if ($denied) {
  201. return -1;
  202. }
  203. // Access is granted.
  204. $headers = file_get_content_headers($file);
  205. return $headers;
  206. }
  207. /**
  208. * Menu callback; Shared Ajax callback for file uploads and deletions.
  209. *
  210. * This rebuilds the form element for a particular field item. As long as the
  211. * form processing is properly encapsulated in the widget element the form
  212. * should rebuild correctly using FAPI without the need for additional callbacks
  213. * or processing.
  214. */
  215. function file_ajax_upload() {
  216. $form_parents = func_get_args();
  217. $form_build_id = (string) array_pop($form_parents);
  218. // Sanitize form parents before using them.
  219. $form_parents = array_filter($form_parents, 'element_child');
  220. if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
  221. // Invalid request.
  222. 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');
  223. $commands = array();
  224. $commands[] = ajax_command_replace(NULL, theme('status_messages'));
  225. return array('#type' => 'ajax', '#commands' => $commands);
  226. }
  227. list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
  228. if (!$form) {
  229. // Invalid form_build_id.
  230. drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
  231. $commands = array();
  232. $commands[] = ajax_command_replace(NULL, theme('status_messages'));
  233. return array('#type' => 'ajax', '#commands' => $commands);
  234. }
  235. // Get the current element and count the number of files.
  236. $current_element = $form;
  237. foreach ($form_parents as $parent) {
  238. $current_element = $current_element[$parent];
  239. }
  240. $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
  241. // Process user input. $form and $form_state are modified in the process.
  242. drupal_process_form($form['#form_id'], $form, $form_state);
  243. // Retrieve the element to be rendered.
  244. foreach ($form_parents as $parent) {
  245. $form = $form[$parent];
  246. }
  247. // Add the special Ajax class if a new file was added.
  248. if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
  249. $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
  250. }
  251. // Otherwise just add the new content class on a placeholder.
  252. else {
  253. $form['#suffix'] = (isset($form['#suffix']) ? $form['#suffix'] : '') . '<span class="ajax-new-content"></span>';
  254. }
  255. $form['#prefix'] = (isset($form['#prefix']) ? $form['#prefix'] : '') . theme('status_messages');
  256. $output = drupal_render($form);
  257. $js = drupal_add_js();
  258. $settings = drupal_array_merge_deep_array($js['settings']['data']);
  259. $commands[] = ajax_command_replace(NULL, $output, $settings);
  260. return array('#type' => 'ajax', '#commands' => $commands);
  261. }
  262. /**
  263. * Menu callback for upload progress.
  264. *
  265. * @param $key
  266. * The unique key for this upload process.
  267. */
  268. function file_ajax_progress($key) {
  269. $progress = array(
  270. 'message' => t('Starting upload...'),
  271. 'percentage' => -1,
  272. );
  273. $implementation = file_progress_implementation();
  274. if ($implementation == 'uploadprogress') {
  275. $status = uploadprogress_get_info($key);
  276. if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
  277. $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
  278. $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
  279. }
  280. }
  281. elseif ($implementation == 'apc') {
  282. $status = apc_fetch('upload_' . $key);
  283. if (isset($status['current']) && !empty($status['total'])) {
  284. $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
  285. $progress['percentage'] = round(100 * $status['current'] / $status['total']);
  286. }
  287. }
  288. drupal_json_output($progress);
  289. }
  290. /**
  291. * Determines the preferred upload progress implementation.
  292. *
  293. * @return
  294. * A string indicating which upload progress system is available. Either "apc"
  295. * or "uploadprogress". If neither are available, returns FALSE.
  296. */
  297. function file_progress_implementation() {
  298. static $implementation;
  299. if (!isset($implementation)) {
  300. $implementation = FALSE;
  301. // We prefer the PECL extension uploadprogress because it supports multiple
  302. // simultaneous uploads. APC only supports one at a time.
  303. if (extension_loaded('uploadprogress')) {
  304. $implementation = 'uploadprogress';
  305. }
  306. elseif (extension_loaded('apc') && ini_get('apc.rfc1867')) {
  307. $implementation = 'apc';
  308. }
  309. }
  310. return $implementation;
  311. }
  312. /**
  313. * Implements hook_file_delete().
  314. */
  315. function file_file_delete($file) {
  316. // TODO: Remove references to a file that is in-use.
  317. }
  318. /**
  319. * Process function to expand the managed_file element type.
  320. *
  321. * Expands the file type to include Upload and Remove buttons, as well as
  322. * support for a default value.
  323. */
  324. function file_managed_file_process($element, &$form_state, $form) {
  325. // Append the '-upload' to the #id so the field label's 'for' attribute
  326. // corresponds with the file element.
  327. $original_id = $element['#id'];
  328. $element['#id'] .= '-upload';
  329. $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
  330. // Set some default element properties.
  331. $element['#progress_indicator'] = empty($element['#progress_indicator']) ? 'none' : $element['#progress_indicator'];
  332. $element['#file'] = $fid ? file_load($fid) : FALSE;
  333. $element['#tree'] = TRUE;
  334. $ajax_settings = array(
  335. 'path' => 'file/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
  336. 'wrapper' => $original_id . '-ajax-wrapper',
  337. 'effect' => 'fade',
  338. 'progress' => array(
  339. 'type' => $element['#progress_indicator'],
  340. 'message' => $element['#progress_message'],
  341. ),
  342. );
  343. // Set up the buttons first since we need to check if they were clicked.
  344. $element['upload_button'] = array(
  345. '#name' => implode('_', $element['#parents']) . '_upload_button',
  346. '#type' => 'submit',
  347. '#value' => t('Upload'),
  348. '#validate' => array(),
  349. '#submit' => array('file_managed_file_submit'),
  350. '#limit_validation_errors' => array($element['#parents']),
  351. '#ajax' => $ajax_settings,
  352. '#weight' => -5,
  353. );
  354. // Force the progress indicator for the remove button to be either 'none' or
  355. // 'throbber', even if the upload button is using something else.
  356. $ajax_settings['progress']['type'] = ($element['#progress_indicator'] == 'none') ? 'none' : 'throbber';
  357. $ajax_settings['progress']['message'] = NULL;
  358. $ajax_settings['effect'] = 'none';
  359. $element['remove_button'] = array(
  360. '#name' => implode('_', $element['#parents']) . '_remove_button',
  361. '#type' => 'submit',
  362. '#value' => t('Remove'),
  363. '#validate' => array(),
  364. '#submit' => array('file_managed_file_submit'),
  365. '#limit_validation_errors' => array($element['#parents']),
  366. '#ajax' => $ajax_settings,
  367. '#weight' => -5,
  368. );
  369. $element['fid'] = array(
  370. '#type' => 'hidden',
  371. '#value' => $fid,
  372. );
  373. // Add progress bar support to the upload if possible.
  374. if ($element['#progress_indicator'] == 'bar' && $implementation = file_progress_implementation()) {
  375. $upload_progress_key = mt_rand();
  376. if ($implementation == 'uploadprogress') {
  377. $element['UPLOAD_IDENTIFIER'] = array(
  378. '#type' => 'hidden',
  379. '#value' => $upload_progress_key,
  380. '#attributes' => array('class' => array('file-progress')),
  381. // Uploadprogress extension requires this field to be at the top of the
  382. // form.
  383. '#weight' => -20,
  384. );
  385. }
  386. elseif ($implementation == 'apc') {
  387. $element['APC_UPLOAD_PROGRESS'] = array(
  388. '#type' => 'hidden',
  389. '#value' => $upload_progress_key,
  390. '#attributes' => array('class' => array('file-progress')),
  391. // Uploadprogress extension requires this field to be at the top of the
  392. // form.
  393. '#weight' => -20,
  394. );
  395. }
  396. // Add the upload progress callback.
  397. $element['upload_button']['#ajax']['progress']['path'] = 'file/progress/' . $upload_progress_key;
  398. }
  399. // The file upload field itself.
  400. $element['upload'] = array(
  401. '#name' => 'files[' . implode('_', $element['#parents']) . ']',
  402. '#type' => 'file',
  403. '#title' => t('Choose a file'),
  404. '#title_display' => 'invisible',
  405. '#size' => $element['#size'],
  406. '#theme_wrappers' => array(),
  407. '#weight' => -10,
  408. );
  409. if ($fid && $element['#file']) {
  410. $element['filename'] = array(
  411. '#type' => 'markup',
  412. '#markup' => theme('file_link', array('file' => $element['#file'])) . ' ',
  413. '#weight' => -10,
  414. );
  415. // Anonymous users who have uploaded a temporary file need a
  416. // non-session-based token added so file_managed_file_value() can check
  417. // that they have permission to use this file on subsequent submissions of
  418. // the same form (for example, after an Ajax upload or form validation
  419. // error).
  420. if (!$GLOBALS['user']->uid && $element['#file']->status != FILE_STATUS_PERMANENT) {
  421. $element['fid_token'] = array(
  422. '#type' => 'hidden',
  423. '#value' => drupal_hmac_base64('file-' . $fid, drupal_get_private_key() . drupal_get_hash_salt()),
  424. );
  425. }
  426. }
  427. // Add the extension list to the page as JavaScript settings.
  428. if (isset($element['#upload_validators']['file_validate_extensions'][0])) {
  429. $extension_list = implode(',', array_filter(explode(' ', $element['#upload_validators']['file_validate_extensions'][0])));
  430. $element['upload']['#attached']['js'] = array(
  431. array(
  432. 'type' => 'setting',
  433. 'data' => array('file' => array('elements' => array('#' . $element['#id'] => $extension_list)))
  434. )
  435. );
  436. }
  437. // Prefix and suffix used for Ajax replacement.
  438. $element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
  439. $element['#suffix'] = '</div>';
  440. return $element;
  441. }
  442. /**
  443. * The #value_callback for a managed_file type element.
  444. */
  445. function file_managed_file_value(&$element, $input = FALSE, $form_state = NULL) {
  446. $fid = 0;
  447. $force_default = FALSE;
  448. // Find the current value of this field from the form state.
  449. $form_state_fid = $form_state['values'];
  450. foreach ($element['#parents'] as $parent) {
  451. $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
  452. }
  453. if ($element['#extended'] && isset($form_state_fid['fid'])) {
  454. $fid = $form_state_fid['fid'];
  455. }
  456. elseif (is_numeric($form_state_fid)) {
  457. $fid = $form_state_fid;
  458. }
  459. // Process any input and save new uploads.
  460. if ($input !== FALSE) {
  461. $return = $input;
  462. // Uploads take priority over all other values.
  463. if ($file = file_managed_file_save_upload($element)) {
  464. $fid = $file->fid;
  465. }
  466. else {
  467. // Check for #filefield_value_callback values.
  468. // Because FAPI does not allow multiple #value_callback values like it
  469. // does for #element_validate and #process, this fills the missing
  470. // functionality to allow File fields to be extended through FAPI.
  471. if (isset($element['#file_value_callbacks'])) {
  472. foreach ($element['#file_value_callbacks'] as $callback) {
  473. $callback($element, $input, $form_state);
  474. }
  475. }
  476. // If a FID was submitted, load the file (and check access if it's not a
  477. // public file) to confirm it exists and that the current user has access
  478. // to it.
  479. if (isset($input['fid']) && ($file = file_load($input['fid']))) {
  480. // By default the public:// file scheme provided by Drupal core is the
  481. // only one that allows files to be publicly accessible to everyone, so
  482. // it is the only one for which the file access checks are bypassed.
  483. // Other modules which provide publicly accessible streams of their own
  484. // in hook_stream_wrappers() can add the corresponding scheme to the
  485. // 'file_public_schema' variable to bypass file access checks for those
  486. // as well. This should only be done for schemes that are completely
  487. // publicly accessible, with no download restrictions; for security
  488. // reasons all other schemes must go through the file_download_access()
  489. // check.
  490. if (!in_array(file_uri_scheme($file->uri), variable_get('file_public_schema', array('public'))) && !file_download_access($file->uri)) {
  491. $force_default = TRUE;
  492. }
  493. // Temporary files that belong to other users should never be allowed.
  494. elseif ($file->status != FILE_STATUS_PERMANENT) {
  495. if ($GLOBALS['user']->uid && $file->uid != $GLOBALS['user']->uid) {
  496. $force_default = TRUE;
  497. }
  498. // Since file ownership can't be determined for anonymous users, they
  499. // are not allowed to reuse temporary files at all. But they do need
  500. // to be able to reuse their own files from earlier submissions of
  501. // the same form, so to allow that, check for the token added by
  502. // file_managed_file_process().
  503. elseif (!$GLOBALS['user']->uid) {
  504. $token = drupal_array_get_nested_value($form_state['input'], array_merge($element['#parents'], array('fid_token')));
  505. if ($token !== drupal_hmac_base64('file-' . $file->fid, drupal_get_private_key() . drupal_get_hash_salt())) {
  506. $force_default = TRUE;
  507. }
  508. }
  509. }
  510. // If all checks pass, allow the file to be changed.
  511. if (!$force_default) {
  512. $fid = $file->fid;
  513. }
  514. }
  515. }
  516. }
  517. // If there is no input or if the default value was requested above, use the
  518. // default value.
  519. if ($input === FALSE || $force_default) {
  520. if ($element['#extended']) {
  521. $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
  522. $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
  523. }
  524. else {
  525. $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
  526. $return = array('fid' => 0);
  527. }
  528. // Confirm that the file exists when used as a default value.
  529. if ($default_fid && $file = file_load($default_fid)) {
  530. $fid = $file->fid;
  531. }
  532. }
  533. $return['fid'] = $fid;
  534. return $return;
  535. }
  536. /**
  537. * An #element_validate callback for the managed_file element.
  538. */
  539. function file_managed_file_validate(&$element, &$form_state) {
  540. // If referencing an existing file, only allow if there are existing
  541. // references. This prevents unmanaged files from being deleted if this
  542. // item were to be deleted.
  543. $clicked_button = end($form_state['triggering_element']['#parents']);
  544. if ($clicked_button != 'remove_button' && !empty($element['fid']['#value'])) {
  545. if ($file = file_load($element['fid']['#value'])) {
  546. if ($file->status == FILE_STATUS_PERMANENT) {
  547. $references = file_usage_list($file);
  548. if (empty($references)) {
  549. form_error($element, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title'])));
  550. }
  551. }
  552. }
  553. else {
  554. form_error($element, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title'])));
  555. }
  556. }
  557. // Check required property based on the FID.
  558. if ($element['#required'] && empty($element['fid']['#value']) && !in_array($clicked_button, array('upload_button', 'remove_button'))) {
  559. form_error($element['upload'], t('!name field is required.', array('!name' => $element['#title'])));
  560. }
  561. // Consolidate the array value of this field to a single FID.
  562. if (!$element['#extended']) {
  563. form_set_value($element, $element['fid']['#value'], $form_state);
  564. }
  565. }
  566. /**
  567. * Form submission handler for upload / remove buttons of managed_file elements.
  568. *
  569. * @see file_managed_file_process()
  570. */
  571. function file_managed_file_submit($form, &$form_state) {
  572. // Determine whether it was the upload or the remove button that was clicked,
  573. // and set $element to the managed_file element that contains that button.
  574. $parents = $form_state['triggering_element']['#array_parents'];
  575. $button_key = array_pop($parents);
  576. $element = drupal_array_get_nested_value($form, $parents);
  577. // No action is needed here for the upload button, because all file uploads on
  578. // the form are processed by file_managed_file_value() regardless of which
  579. // button was clicked. Action is needed here for the remove button, because we
  580. // only remove a file in response to its remove button being clicked.
  581. if ($button_key == 'remove_button') {
  582. // If it's a temporary file we can safely remove it immediately, otherwise
  583. // it's up to the implementing module to clean up files that are in use.
  584. if ($element['#file'] && $element['#file']->status == 0) {
  585. file_delete($element['#file']);
  586. }
  587. // Update both $form_state['values'] and $form_state['input'] to reflect
  588. // that the file has been removed, so that the form is rebuilt correctly.
  589. // $form_state['values'] must be updated in case additional submit handlers
  590. // run, and for form building functions that run during the rebuild, such as
  591. // when the managed_file element is part of a field widget.
  592. // $form_state['input'] must be updated so that file_managed_file_value()
  593. // has correct information during the rebuild.
  594. $values_element = $element['#extended'] ? $element['fid'] : $element;
  595. form_set_value($values_element, NULL, $form_state);
  596. drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
  597. }
  598. // Set the form to rebuild so that $form is correctly updated in response to
  599. // processing the file removal. Since this function did not change $form_state
  600. // if the upload button was clicked, a rebuild isn't necessary in that
  601. // situation and setting $form_state['redirect'] to FALSE would suffice.
  602. // However, we choose to always rebuild, to keep the form processing workflow
  603. // consistent between the two buttons.
  604. $form_state['rebuild'] = TRUE;
  605. }
  606. /**
  607. * Saves any files that have been uploaded into a managed_file element.
  608. *
  609. * @param $element
  610. * The FAPI element whose values are being saved.
  611. *
  612. * @return
  613. * The file object representing the file that was saved, or FALSE if no file
  614. * was saved.
  615. */
  616. function file_managed_file_save_upload($element) {
  617. $upload_name = implode('_', $element['#parents']);
  618. if (empty($_FILES['files']['name'][$upload_name])) {
  619. return FALSE;
  620. }
  621. $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
  622. if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
  623. watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $destination, '!name' => $element['#field_name']));
  624. form_set_error($upload_name, t('The file could not be uploaded.'));
  625. return FALSE;
  626. }
  627. if (!$file = file_save_upload($upload_name, $element['#upload_validators'], $destination)) {
  628. watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
  629. form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
  630. return FALSE;
  631. }
  632. return $file;
  633. }
  634. /**
  635. * Returns HTML for a managed file element.
  636. *
  637. * @param $variables
  638. * An associative array containing:
  639. * - element: A render element representing the file.
  640. *
  641. * @ingroup themeable
  642. */
  643. function theme_file_managed_file($variables) {
  644. $element = $variables['element'];
  645. $attributes = array();
  646. if (isset($element['#id'])) {
  647. $attributes['id'] = $element['#id'];
  648. }
  649. if (!empty($element['#attributes']['class'])) {
  650. $attributes['class'] = (array) $element['#attributes']['class'];
  651. }
  652. $attributes['class'][] = 'form-managed-file';
  653. // This wrapper is required to apply JS behaviors and CSS styling.
  654. $output = '';
  655. $output .= '<div' . drupal_attributes($attributes) . '>';
  656. $output .= drupal_render_children($element);
  657. $output .= '</div>';
  658. return $output;
  659. }
  660. /**
  661. * #pre_render callback to hide display of the upload or remove controls.
  662. *
  663. * Upload controls are hidden when a file is already uploaded. Remove controls
  664. * are hidden when there is no file attached. Controls are hidden here instead
  665. * of in file_managed_file_process(), because #access for these buttons depends
  666. * on the managed_file element's #value. See the documentation of form_builder()
  667. * for more detailed information about the relationship between #process,
  668. * #value, and #access.
  669. *
  670. * Because #access is set here, it affects display only and does not prevent
  671. * JavaScript or other untrusted code from submitting the form as though access
  672. * were enabled. The form processing functions for these elements should not
  673. * assume that the buttons can't be "clicked" just because they are not
  674. * displayed.
  675. *
  676. * @see file_managed_file_process()
  677. * @see form_builder()
  678. */
  679. function file_managed_file_pre_render($element) {
  680. // If we already have a file, we don't want to show the upload controls.
  681. if (!empty($element['#value']['fid'])) {
  682. $element['upload']['#access'] = FALSE;
  683. $element['upload_button']['#access'] = FALSE;
  684. }
  685. // If we don't already have a file, there is nothing to remove.
  686. else {
  687. $element['remove_button']['#access'] = FALSE;
  688. }
  689. return $element;
  690. }
  691. /**
  692. * Returns HTML for a link to a file.
  693. *
  694. * @param $variables
  695. * An associative array containing:
  696. * - file: A file object to which the link will be created.
  697. * - icon_directory: (optional) A path to a directory of icons to be used for
  698. * files. Defaults to the value of the "file_icon_directory" variable.
  699. *
  700. * @ingroup themeable
  701. */
  702. function theme_file_link($variables) {
  703. $file = $variables['file'];
  704. $icon_directory = $variables['icon_directory'];
  705. $url = file_create_url($file->uri);
  706. // Human-readable names, for use as text-alternatives to icons.
  707. $mime_name = array(
  708. 'application/msword' => t('Microsoft Office document icon'),
  709. 'application/vnd.ms-excel' => t('Office spreadsheet icon'),
  710. 'application/vnd.ms-powerpoint' => t('Office presentation icon'),
  711. 'application/pdf' => t('PDF icon'),
  712. 'video/quicktime' => t('Movie icon'),
  713. 'audio/mpeg' => t('Audio icon'),
  714. 'audio/wav' => t('Audio icon'),
  715. 'image/jpeg' => t('Image icon'),
  716. 'image/png' => t('Image icon'),
  717. 'image/gif' => t('Image icon'),
  718. 'application/zip' => t('Package icon'),
  719. 'text/html' => t('HTML icon'),
  720. 'text/plain' => t('Plain text icon'),
  721. 'application/octet-stream' => t('Binary Data'),
  722. );
  723. $mimetype = file_get_mimetype($file->uri);
  724. $icon = theme('file_icon', array(
  725. 'file' => $file,
  726. 'icon_directory' => $icon_directory,
  727. 'alt' => !empty($mime_name[$mimetype]) ? $mime_name[$mimetype] : t('File'),
  728. ));
  729. // Set options as per anchor format described at
  730. // http://microformats.org/wiki/file-format-examples
  731. $options = array(
  732. 'attributes' => array(
  733. 'type' => $file->filemime . '; length=' . $file->filesize,
  734. ),
  735. );
  736. // Use the description as the link text if available.
  737. if (empty($file->description)) {
  738. $link_text = $file->filename;
  739. }
  740. else {
  741. $link_text = $file->description;
  742. $options['attributes']['title'] = check_plain($file->filename);
  743. }
  744. return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
  745. }
  746. /**
  747. * Returns HTML for an image with an appropriate icon for the given file.
  748. *
  749. * @param $variables
  750. * An associative array containing:
  751. * - file: A file object for which to make an icon.
  752. * - icon_directory: (optional) A path to a directory of icons to be used for
  753. * files. Defaults to the value of the "file_icon_directory" variable.
  754. * - alt: (optional) The alternative text to represent the icon in text-based
  755. * browsers. Defaults to an empty string.
  756. *
  757. * @ingroup themeable
  758. */
  759. function theme_file_icon($variables) {
  760. $file = $variables['file'];
  761. $alt = $variables['alt'];
  762. $icon_directory = $variables['icon_directory'];
  763. $mime = check_plain($file->filemime);
  764. $icon_url = file_icon_url($file, $icon_directory);
  765. return '<img class="file-icon" alt="' . check_plain($alt) . '" title="' . $mime . '" src="' . $icon_url . '" />';
  766. }
  767. /**
  768. * Creates a URL to the icon for a file object.
  769. *
  770. * @param $file
  771. * A file object.
  772. * @param $icon_directory
  773. * (optional) A path to a directory of icons to be used for files. Defaults to
  774. * the value of the "file_icon_directory" variable.
  775. *
  776. * @return
  777. * A URL string to the icon, or FALSE if an appropriate icon cannot be found.
  778. */
  779. function file_icon_url($file, $icon_directory = NULL) {
  780. if ($icon_path = file_icon_path($file, $icon_directory)) {
  781. return base_path() . $icon_path;
  782. }
  783. return FALSE;
  784. }
  785. /**
  786. * Creates a path to the icon for a file object.
  787. *
  788. * @param $file
  789. * A file object.
  790. * @param $icon_directory
  791. * (optional) A path to a directory of icons to be used for files. Defaults to
  792. * the value of the "file_icon_directory" variable.
  793. *
  794. * @return
  795. * A string to the icon as a local path, or FALSE if an appropriate icon could
  796. * not be found.
  797. */
  798. function file_icon_path($file, $icon_directory = NULL) {
  799. // Use the default set of icons if none specified.
  800. if (!isset($icon_directory)) {
  801. $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');
  802. }
  803. // If there's an icon matching the exact mimetype, go for it.
  804. $dashed_mime = strtr($file->filemime, array('/' => '-'));
  805. $icon_path = $icon_directory . '/' . $dashed_mime . '.png';
  806. if (file_exists($icon_path)) {
  807. return $icon_path;
  808. }
  809. // For a few mimetypes, we can "manually" map to a generic icon.
  810. $generic_mime = (string) file_icon_map($file);
  811. $icon_path = $icon_directory . '/' . $generic_mime . '.png';
  812. if ($generic_mime && file_exists($icon_path)) {
  813. return $icon_path;
  814. }
  815. // Use generic icons for each category that provides such icons.
  816. foreach (array('audio', 'image', 'text', 'video') as $category) {
  817. if (strpos($file->filemime, $category . '/') === 0) {
  818. $icon_path = $icon_directory . '/' . $category . '-x-generic.png';
  819. if (file_exists($icon_path)) {
  820. return $icon_path;
  821. }
  822. }
  823. }
  824. // Try application-octet-stream as last fallback.
  825. $icon_path = $icon_directory . '/application-octet-stream.png';
  826. if (file_exists($icon_path)) {
  827. return $icon_path;
  828. }
  829. // No icon can be found.
  830. return FALSE;
  831. }
  832. /**
  833. * Determines the generic icon MIME package based on a file's MIME type.
  834. *
  835. * @param $file
  836. * A file object.
  837. *
  838. * @return
  839. * The generic icon MIME package expected for this file.
  840. */
  841. function file_icon_map($file) {
  842. switch ($file->filemime) {
  843. // Word document types.
  844. case 'application/msword':
  845. case 'application/vnd.ms-word.document.macroEnabled.12':
  846. case 'application/vnd.oasis.opendocument.text':
  847. case 'application/vnd.oasis.opendocument.text-template':
  848. case 'application/vnd.oasis.opendocument.text-master':
  849. case 'application/vnd.oasis.opendocument.text-web':
  850. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  851. case 'application/vnd.stardivision.writer':
  852. case 'application/vnd.sun.xml.writer':
  853. case 'application/vnd.sun.xml.writer.template':
  854. case 'application/vnd.sun.xml.writer.global':
  855. case 'application/vnd.wordperfect':
  856. case 'application/x-abiword':
  857. case 'application/x-applix-word':
  858. case 'application/x-kword':
  859. case 'application/x-kword-crypt':
  860. return 'x-office-document';
  861. // Spreadsheet document types.
  862. case 'application/vnd.ms-excel':
  863. case 'application/vnd.ms-excel.sheet.macroEnabled.12':
  864. case 'application/vnd.oasis.opendocument.spreadsheet':
  865. case 'application/vnd.oasis.opendocument.spreadsheet-template':
  866. case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
  867. case 'application/vnd.stardivision.calc':
  868. case 'application/vnd.sun.xml.calc':
  869. case 'application/vnd.sun.xml.calc.template':
  870. case 'application/vnd.lotus-1-2-3':
  871. case 'application/x-applix-spreadsheet':
  872. case 'application/x-gnumeric':
  873. case 'application/x-kspread':
  874. case 'application/x-kspread-crypt':
  875. return 'x-office-spreadsheet';
  876. // Presentation document types.
  877. case 'application/vnd.ms-powerpoint':
  878. case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
  879. case 'application/vnd.oasis.opendocument.presentation':
  880. case 'application/vnd.oasis.opendocument.presentation-template':
  881. case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
  882. case 'application/vnd.stardivision.impress':
  883. case 'application/vnd.sun.xml.impress':
  884. case 'application/vnd.sun.xml.impress.template':
  885. case 'application/x-kpresenter':
  886. return 'x-office-presentation';
  887. // Compressed archive types.
  888. case 'application/zip':
  889. case 'application/x-zip':
  890. case 'application/stuffit':
  891. case 'application/x-stuffit':
  892. case 'application/x-7z-compressed':
  893. case 'application/x-ace':
  894. case 'application/x-arj':
  895. case 'application/x-bzip':
  896. case 'application/x-bzip-compressed-tar':
  897. case 'application/x-compress':
  898. case 'application/x-compressed-tar':
  899. case 'application/x-cpio-compressed':
  900. case 'application/x-deb':
  901. case 'application/x-gzip':
  902. case 'application/x-java-archive':
  903. case 'application/x-lha':
  904. case 'application/x-lhz':
  905. case 'application/x-lzop':
  906. case 'application/x-rar':
  907. case 'application/x-rpm':
  908. case 'application/x-tzo':
  909. case 'application/x-tar':
  910. case 'application/x-tarz':
  911. case 'application/x-tgz':
  912. return 'package-x-generic';
  913. // Script file types.
  914. case 'application/ecmascript':
  915. case 'application/javascript':
  916. case 'application/mathematica':
  917. case 'application/vnd.mozilla.xul+xml':
  918. case 'application/x-asp':
  919. case 'application/x-awk':
  920. case 'application/x-cgi':
  921. case 'application/x-csh':
  922. case 'application/x-m4':
  923. case 'application/x-perl':
  924. case 'application/x-php':
  925. case 'application/x-ruby':
  926. case 'application/x-shellscript':
  927. case 'text/vnd.wap.wmlscript':
  928. case 'text/x-emacs-lisp':
  929. case 'text/x-haskell':
  930. case 'text/x-literate-haskell':
  931. case 'text/x-lua':
  932. case 'text/x-makefile':
  933. case 'text/x-matlab':
  934. case 'text/x-python':
  935. case 'text/x-sql':
  936. case 'text/x-tcl':
  937. return 'text-x-script';
  938. // HTML aliases.
  939. case 'application/xhtml+xml':
  940. return 'text-html';
  941. // Executable types.
  942. case 'application/x-macbinary':
  943. case 'application/x-ms-dos-executable':
  944. case 'application/x-pef-executable':
  945. return 'application-x-executable';
  946. default:
  947. return FALSE;
  948. }
  949. }
  950. /**
  951. * @defgroup file-module-api File module public API functions
  952. * @{
  953. * These functions may be used to determine if and where a file is in use.
  954. */
  955. /**
  956. * Retrieves a list of references to a file.
  957. *
  958. * @param $file
  959. * A file object.
  960. * @param $field
  961. * (optional) A field array to be used for this check. If given, limits the
  962. * reference check to the given field.
  963. * @param $age
  964. * (optional) A constant that specifies which references to count. Use
  965. * FIELD_LOAD_REVISION to retrieve all references within all revisions or
  966. * FIELD_LOAD_CURRENT to retrieve references only in the current revisions.
  967. * @param $field_type
  968. * (optional) The name of a field type. If given, limits the reference check
  969. * to fields of the given type.
  970. * @param $check_access
  971. * (optional) A boolean that specifies whether the permissions of the current
  972. * user should be checked when retrieving references. If FALSE, all
  973. * references to the file are returned. If TRUE, only references from
  974. * entities that the current user has access to are returned. Defaults to
  975. * TRUE for backwards compatibility reasons, but FALSE is recommended for
  976. * most situations.
  977. *
  978. * @return
  979. * An integer value.
  980. */
  981. function file_get_file_references($file, $field = NULL, $age = FIELD_LOAD_REVISION, $field_type = 'file', $check_access = TRUE) {
  982. $references = drupal_static(__FUNCTION__, array());
  983. $fields = isset($field) ? array($field['field_name'] => $field) : field_info_fields();
  984. foreach ($fields as $field_name => $file_field) {
  985. if ((empty($field_type) || $file_field['type'] == $field_type) && !isset($references[$field_name])) {
  986. // Get each time this file is used within a field.
  987. $query = new EntityFieldQuery();
  988. $query
  989. ->fieldCondition($file_field, 'fid', $file->fid)
  990. ->age($age);
  991. if (!$check_access) {
  992. // Neutralize the 'entity_field_access' query tag added by
  993. // field_sql_storage_field_storage_query().
  994. $query->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
  995. }
  996. $references[$field_name] = $query->execute();
  997. }
  998. }
  999. return isset($field) ? $references[$field['field_name']] : array_filter($references);
  1000. }
  1001. /**
  1002. * @} End of "defgroup file-module-api".
  1003. */