file.module 41 KB

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