file.module 37 KB

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