file.module 42 KB

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