file.module 41 KB

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