Skip navigation
Help

file.module

  1. drupal
    1. 7 drupal/modules/file/file.module

Defines a "managed_file" Form API field and a "file" field for Field module.

Functions & methods

NameDescription
file_ajax_progressMenu callback for upload progress.
file_ajax_uploadMenu callback; Shared Ajax callback for file uploads and deletions.
file_element_infoImplements hook_element_info().
file_file_deleteImplements hook_file_delete().
file_file_downloadImplements hook_file_download().
file_get_file_referencesGets a list of references to a file.
file_helpImplements hook_help().
file_icon_mapDetermine the generic icon MIME package based on a file's MIME type.
file_icon_pathGiven a file object, create a path to a matching icon.
file_icon_urlGiven a file object, create a URL to a matching icon.
file_managed_file_pre_render#pre_render callback to hide display of the upload or remove controls.
file_managed_file_processProcess function to expand the managed_file element type.
file_managed_file_save_uploadGiven a managed_file element, save any files that have been uploaded into it.
file_managed_file_submitSubmit handler for upload and remove buttons of managed_file elements.
file_managed_file_validateAn #element_validate callback for the managed_file element.
file_managed_file_valueThe #value_callback for a managed_file type element.
file_menuImplements hook_menu().
file_progress_implementationDetermine the preferred upload progress implementation.
file_themeImplements hook_theme().
theme_file_iconReturns HTML for an image with an appropriate icon for the given file.
theme_file_linkReturns HTML for a link to a file.
theme_file_managed_fileReturns HTML for a managed file element.

File

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