1. 8.3.x core/modules/file/file.field.inc
  2. 8.0.x core/modules/file/file.field.inc
  3. 8.1.x core/modules/file/file.field.inc
  4. 8.2.x core/modules/file/file.field.inc
  5. 8.4.x core/modules/file/file.field.inc
  6. 7.x modules/file/file.field.inc

Field module functionality for the File module.

File

modules/file/file.field.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Field module functionality for the File module.
  5. */
  6. /**
  7. * Implements hook_field_info().
  8. */
  9. function file_field_info() {
  10. return array(
  11. 'file' => array(
  12. 'label' => t('File'),
  13. 'description' => t('This field stores the ID of a file as an integer value.'),
  14. 'settings' => array(
  15. 'display_field' => 0,
  16. 'display_default' => 0,
  17. 'uri_scheme' => variable_get('file_default_scheme', 'public'),
  18. ),
  19. 'instance_settings' => array(
  20. 'file_extensions' => 'txt',
  21. 'file_directory' => '',
  22. 'max_filesize' => '',
  23. 'description_field' => 0,
  24. ),
  25. 'default_widget' => 'file_generic',
  26. 'default_formatter' => 'file_default',
  27. ),
  28. );
  29. }
  30. /**
  31. * Implements hook_field_settings_form().
  32. */
  33. function file_field_settings_form($field, $instance, $has_data) {
  34. $defaults = field_info_field_settings($field['type']);
  35. $settings = array_merge($defaults, $field['settings']);
  36. $form['#attached']['js'][] = drupal_get_path('module', 'file') . '/file.js';
  37. $form['display_field'] = array(
  38. '#type' => 'checkbox',
  39. '#title' => t('Enable <em>Display</em> field'),
  40. '#default_value' => $settings['display_field'],
  41. '#description' => t('The display option allows users to choose if a file should be shown when viewing the content.'),
  42. );
  43. $form['display_default'] = array(
  44. '#type' => 'checkbox',
  45. '#title' => t('Files displayed by default'),
  46. '#default_value' => $settings['display_default'],
  47. '#description' => t('This setting only has an effect if the display option is enabled.'),
  48. );
  49. $scheme_options = array();
  50. foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
  51. $scheme_options[$scheme] = $stream_wrapper['name'];
  52. }
  53. $form['uri_scheme'] = array(
  54. '#type' => 'radios',
  55. '#title' => t('Upload destination'),
  56. '#options' => $scheme_options,
  57. '#default_value' => $settings['uri_scheme'],
  58. '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
  59. '#disabled' => $has_data,
  60. );
  61. return $form;
  62. }
  63. /**
  64. * Implements hook_field_instance_settings_form().
  65. */
  66. function file_field_instance_settings_form($field, $instance) {
  67. $settings = $instance['settings'];
  68. $form['file_directory'] = array(
  69. '#type' => 'textfield',
  70. '#title' => t('File directory'),
  71. '#default_value' => $settings['file_directory'],
  72. '#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'),
  73. '#element_validate' => array('_file_generic_settings_file_directory_validate'),
  74. '#weight' => 3,
  75. );
  76. // Make the extension list a little more human-friendly by comma-separation.
  77. $extensions = str_replace(' ', ', ', $settings['file_extensions']);
  78. $form['file_extensions'] = array(
  79. '#type' => 'textfield',
  80. '#title' => t('Allowed file extensions'),
  81. '#default_value' => $extensions,
  82. '#description' => t('Separate extensions with a space or comma and do not include the leading dot.'),
  83. '#element_validate' => array('_file_generic_settings_extensions'),
  84. '#weight' => 1,
  85. '#maxlength' => 256,
  86. // By making this field required, we prevent a potential security issue
  87. // that would allow files of any type to be uploaded.
  88. '#required' => TRUE,
  89. );
  90. $form['max_filesize'] = array(
  91. '#type' => 'textfield',
  92. '#title' => t('Maximum upload size'),
  93. '#default_value' => $settings['max_filesize'],
  94. '#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))),
  95. '#size' => 10,
  96. '#element_validate' => array('_file_generic_settings_max_filesize'),
  97. '#weight' => 5,
  98. );
  99. $form['description_field'] = array(
  100. '#type' => 'checkbox',
  101. '#title' => t('Enable <em>Description</em> field'),
  102. '#default_value' => isset($settings['description_field']) ? $settings['description_field'] : '',
  103. '#description' => t('The description field allows users to enter a description about the uploaded file.'),
  104. '#parents' => array('instance', 'settings', 'description_field'),
  105. '#weight' => 11,
  106. );
  107. return $form;
  108. }
  109. /**
  110. * Element validate callback for the maximum upload size field.
  111. *
  112. * Ensure a size that can be parsed by parse_size() has been entered.
  113. */
  114. function _file_generic_settings_max_filesize($element, &$form_state) {
  115. if (!empty($element['#value']) && !is_numeric(parse_size($element['#value']))) {
  116. form_error($element, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title']))));
  117. }
  118. }
  119. /**
  120. * Element validate callback for the allowed file extensions field.
  121. *
  122. * This doubles as a convenience clean-up function and a validation routine.
  123. * Commas are allowed by the end-user, but ultimately the value will be stored
  124. * as a space-separated list for compatibility with file_validate_extensions().
  125. */
  126. function _file_generic_settings_extensions($element, &$form_state) {
  127. if (!empty($element['#value'])) {
  128. $extensions = preg_replace('/([, ]+\.?)/', ' ', trim(strtolower($element['#value'])));
  129. $extensions = array_filter(explode(' ', $extensions));
  130. $extensions = implode(' ', array_unique($extensions));
  131. if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) {
  132. form_error($element, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.'));
  133. }
  134. else {
  135. form_set_value($element, $extensions, $form_state);
  136. }
  137. }
  138. }
  139. /**
  140. * Element validate callback for the file destination field.
  141. *
  142. * Remove slashes from the beginning and end of the destination value and ensure
  143. * that the file directory path is not included at the beginning of the value.
  144. */
  145. function _file_generic_settings_file_directory_validate($element, &$form_state) {
  146. // Strip slashes from the beginning and end of $widget['file_directory'].
  147. $value = trim($element['#value'], '\\/');
  148. form_set_value($element, $value, $form_state);
  149. }
  150. /**
  151. * Implements hook_field_load().
  152. */
  153. function file_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  154. $fids = array();
  155. foreach ($entities as $id => $entity) {
  156. // Load the files from the files table.
  157. foreach ($items[$id] as $delta => $item) {
  158. if (!empty($item['fid'])) {
  159. $fids[] = $item['fid'];
  160. }
  161. }
  162. }
  163. $files = file_load_multiple($fids);
  164. foreach ($entities as $id => $entity) {
  165. foreach ($items[$id] as $delta => $item) {
  166. // If the file does not exist, mark the entire item as empty.
  167. if (empty($item['fid']) || !isset($files[$item['fid']])) {
  168. $items[$id][$delta] = NULL;
  169. }
  170. else {
  171. $items[$id][$delta] = array_merge((array) $files[$item['fid']], $item);
  172. }
  173. }
  174. }
  175. }
  176. /**
  177. * Implements hook_field_prepare_view().
  178. */
  179. function file_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  180. // Remove files specified to not be displayed.
  181. foreach ($entities as $id => $entity) {
  182. foreach ($items[$id] as $delta => $item) {
  183. if (!file_field_displayed($item, $field)) {
  184. unset($items[$id][$delta]);
  185. }
  186. }
  187. // Ensure consecutive deltas.
  188. $items[$id] = array_values($items[$id]);
  189. }
  190. }
  191. /**
  192. * Implements hook_field_presave().
  193. */
  194. function file_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  195. // Make sure that each file which will be saved with this object has a
  196. // permanent status, so that it will not be removed when temporary files are
  197. // cleaned up.
  198. foreach ($items as $delta => $item) {
  199. if (empty($item['fid'])) {
  200. unset($items[$delta]);
  201. continue;
  202. }
  203. $file = file_load($item['fid']);
  204. if (empty($file)) {
  205. unset($items[$delta]);
  206. continue;
  207. }
  208. if (!$file->status) {
  209. $file->status = FILE_STATUS_PERMANENT;
  210. file_save($file);
  211. }
  212. }
  213. }
  214. /**
  215. * Implements hook_field_insert().
  216. */
  217. function file_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  218. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  219. // Add a new usage of each uploaded file.
  220. foreach ($items as $item) {
  221. $file = (object) $item;
  222. file_usage_add($file, 'file', $entity_type, $id);
  223. }
  224. }
  225. /**
  226. * Implements hook_field_update().
  227. *
  228. * Checks for files that have been removed from the object.
  229. */
  230. function file_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  231. // Check whether the field is defined on the object.
  232. if (!isset($entity->{$field['field_name']})) {
  233. // We cannot check for removed files if the field is not defined.
  234. return;
  235. }
  236. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  237. // On new revisions, all files are considered to be a new usage and no
  238. // deletion of previous file usages are necessary.
  239. if (!empty($entity->revision)) {
  240. foreach ($items as $item) {
  241. $file = (object) $item;
  242. file_usage_add($file, 'file', $entity_type, $id);
  243. }
  244. return;
  245. }
  246. // Build a display of the current FIDs.
  247. $current_fids = array();
  248. foreach ($items as $item) {
  249. $current_fids[] = $item['fid'];
  250. }
  251. // Compare the original field values with the ones that are being saved. Use
  252. // $entity->original to check this when possible, but if it isn't available,
  253. // create a bare-bones entity and load its previous values instead.
  254. if (isset($entity->original)) {
  255. $original = $entity->original;
  256. }
  257. else {
  258. $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
  259. field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
  260. }
  261. $original_fids = array();
  262. if (!empty($original->{$field['field_name']}[$langcode])) {
  263. foreach ($original->{$field['field_name']}[$langcode] as $original_item) {
  264. $original_fids[] = $original_item['fid'];
  265. if (isset($original_item['fid']) && !in_array($original_item['fid'], $current_fids)) {
  266. // Decrement the file usage count by 1 and delete the file if possible.
  267. file_field_delete_file($original_item, $field, $entity_type, $id);
  268. }
  269. }
  270. }
  271. // Add new usage entries for newly added files.
  272. foreach ($items as $item) {
  273. if (!in_array($item['fid'], $original_fids)) {
  274. $file = (object) $item;
  275. file_usage_add($file, 'file', $entity_type, $id);
  276. }
  277. }
  278. }
  279. /**
  280. * Implements hook_field_delete().
  281. */
  282. function file_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
  283. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  284. // Delete all file usages within this entity.
  285. foreach ($items as $delta => $item) {
  286. file_field_delete_file($item, $field, $entity_type, $id, 0);
  287. }
  288. }
  289. /**
  290. * Implements hook_field_delete_revision().
  291. */
  292. function file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
  293. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  294. foreach ($items as $delta => $item) {
  295. // Decrement the file usage count by 1 and delete the file if possible.
  296. if (file_field_delete_file($item, $field, $entity_type, $id)) {
  297. $items[$delta] = NULL;
  298. }
  299. }
  300. }
  301. /**
  302. * Decrements the usage count for a file and attempts to delete it.
  303. *
  304. * This function only has an effect if the file being deleted is used only by
  305. * File module.
  306. *
  307. * @param $item
  308. * The field item that contains a file array.
  309. * @param $field
  310. * The field structure for the operation.
  311. * @param $entity_type
  312. * The type of $entity.
  313. * @param $id
  314. * The entity ID which contains the file being deleted.
  315. * @param $count
  316. * (optional) The number of references to decrement from the object
  317. * containing the file. Defaults to 1.
  318. *
  319. * @return
  320. * Boolean TRUE if the file was deleted, or an array of remaining references
  321. * if the file is still in use by other modules. Boolean FALSE if an error
  322. * was encountered.
  323. */
  324. function file_field_delete_file($item, $field, $entity_type, $id, $count = 1) {
  325. // To prevent the file field from deleting files it doesn't know about, check
  326. // the file reference count. Temporary files can be deleted because they
  327. // are not yet associated with any content at all.
  328. $file = (object) $item;
  329. $file_usage = file_usage_list($file);
  330. if ($file->status == 0 || !empty($file_usage['file'])) {
  331. file_usage_delete($file, 'file', $entity_type, $id, $count);
  332. return file_delete($file);
  333. }
  334. // Even if the file is not deleted, return TRUE to indicate the file field
  335. // record can be removed from the field database tables.
  336. return TRUE;
  337. }
  338. /**
  339. * Implements hook_field_is_empty().
  340. */
  341. function file_field_is_empty($item, $field) {
  342. return empty($item['fid']);
  343. }
  344. /**
  345. * Determines whether a file should be displayed when outputting field content.
  346. *
  347. * @param $item
  348. * A field item array.
  349. * @param $field
  350. * A field array.
  351. *
  352. * @return
  353. * Boolean TRUE if the file will be displayed, FALSE if the file is hidden.
  354. */
  355. function file_field_displayed($item, $field) {
  356. if (!empty($field['settings']['display_field'])) {
  357. return (bool) $item['display'];
  358. }
  359. return TRUE;
  360. }
  361. /**
  362. * Implements hook_field_formatter_info().
  363. */
  364. function file_field_formatter_info() {
  365. return array(
  366. 'file_default' => array(
  367. 'label' => t('Generic file'),
  368. 'field types' => array('file'),
  369. ),
  370. 'file_table' => array(
  371. 'label' => t('Table of files'),
  372. 'field types' => array('file'),
  373. ),
  374. 'file_url_plain' => array(
  375. 'label' => t('URL to file'),
  376. 'field types' => array('file'),
  377. ),
  378. );
  379. }
  380. /**
  381. * Implements hook_field_widget_info().
  382. */
  383. function file_field_widget_info() {
  384. return array(
  385. 'file_generic' => array(
  386. 'label' => t('File'),
  387. 'field types' => array('file'),
  388. 'settings' => array(
  389. 'progress_indicator' => 'throbber',
  390. ),
  391. 'behaviors' => array(
  392. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  393. 'default value' => FIELD_BEHAVIOR_NONE,
  394. ),
  395. ),
  396. );
  397. }
  398. /**
  399. * Implements hook_field_widget_settings_form().
  400. */
  401. function file_field_widget_settings_form($field, $instance) {
  402. $widget = $instance['widget'];
  403. $settings = $widget['settings'];
  404. $form['progress_indicator'] = array(
  405. '#type' => 'radios',
  406. '#title' => t('Progress indicator'),
  407. '#options' => array(
  408. 'throbber' => t('Throbber'),
  409. 'bar' => t('Bar with progress meter'),
  410. ),
  411. '#default_value' => $settings['progress_indicator'],
  412. '#description' => t('The throbber display does not show the status of uploads but takes up less space. The progress bar is helpful for monitoring progress on large uploads.'),
  413. '#weight' => 16,
  414. '#access' => file_progress_implementation(),
  415. );
  416. return $form;
  417. }
  418. /**
  419. * Implements hook_field_widget_form().
  420. */
  421. function file_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  422. $defaults = array(
  423. 'fid' => 0,
  424. 'display' => !empty($field['settings']['display_default']),
  425. 'description' => '',
  426. );
  427. // Load the items for form rebuilds from the field state as they might not be
  428. // in $form_state['values'] because of validation limitations. Also, they are
  429. // only passed in as $items when editing existing entities.
  430. $field_state = field_form_get_state($element['#field_parents'], $field['field_name'], $langcode, $form_state);
  431. if (isset($field_state['items'])) {
  432. $items = $field_state['items'];
  433. }
  434. // Essentially we use the managed_file type, extended with some enhancements.
  435. $element_info = element_info('managed_file');
  436. $element += array(
  437. '#type' => 'managed_file',
  438. '#upload_location' => file_field_widget_uri($field, $instance),
  439. '#upload_validators' => file_field_widget_upload_validators($field, $instance),
  440. '#value_callback' => 'file_field_widget_value',
  441. '#process' => array_merge($element_info['#process'], array('file_field_widget_process')),
  442. '#progress_indicator' => $instance['widget']['settings']['progress_indicator'],
  443. // Allows this field to return an array instead of a single value.
  444. '#extended' => TRUE,
  445. );
  446. if ($field['cardinality'] == 1) {
  447. // Set the default value.
  448. $element['#default_value'] = !empty($items) ? $items[0] : $defaults;
  449. // If there's only one field, return it as delta 0.
  450. if (empty($element['#default_value']['fid'])) {
  451. $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
  452. }
  453. $elements = array($element);
  454. }
  455. else {
  456. // If there are multiple values, add an element for each existing one.
  457. foreach ($items as $item) {
  458. $elements[$delta] = $element;
  459. $elements[$delta]['#default_value'] = $item;
  460. $elements[$delta]['#weight'] = $delta;
  461. $delta++;
  462. }
  463. // And then add one more empty row for new uploads except when this is a
  464. // programmed form as it is not necessary.
  465. if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
  466. $elements[$delta] = $element;
  467. $elements[$delta]['#default_value'] = $defaults;
  468. $elements[$delta]['#weight'] = $delta;
  469. $elements[$delta]['#required'] = ($element['#required'] && $delta == 0);
  470. }
  471. // The group of elements all-together need some extra functionality
  472. // after building up the full list (like draggable table rows).
  473. $elements['#file_upload_delta'] = $delta;
  474. $elements['#theme'] = 'file_widget_multiple';
  475. $elements['#theme_wrappers'] = array('fieldset');
  476. $elements['#process'] = array('file_field_widget_process_multiple');
  477. $elements['#title'] = $element['#title'];
  478. $elements['#description'] = $element['#description'];
  479. $elements['#field_name'] = $element['#field_name'];
  480. $elements['#language'] = $element['#language'];
  481. $elements['#display_field'] = $field['settings']['display_field'];
  482. // Add some properties that will eventually be added to the file upload
  483. // field. These are added here so that they may be referenced easily through
  484. // a hook_form_alter().
  485. $elements['#file_upload_title'] = t('Add a new file');
  486. $elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));
  487. }
  488. return $elements;
  489. }
  490. /**
  491. * Retrieves the upload validators for a file field.
  492. *
  493. * @param $field
  494. * A field array.
  495. *
  496. * @return
  497. * An array suitable for passing to file_save_upload() or the file field
  498. * element's '#upload_validators' property.
  499. */
  500. function file_field_widget_upload_validators($field, $instance) {
  501. // Cap the upload size according to the PHP limit.
  502. $max_filesize = parse_size(file_upload_max_size());
  503. if (!empty($instance['settings']['max_filesize']) && parse_size($instance['settings']['max_filesize']) < $max_filesize) {
  504. $max_filesize = parse_size($instance['settings']['max_filesize']);
  505. }
  506. $validators = array();
  507. // There is always a file size limit due to the PHP server limit.
  508. $validators['file_validate_size'] = array($max_filesize);
  509. // Add the extension check if necessary.
  510. if (!empty($instance['settings']['file_extensions'])) {
  511. $validators['file_validate_extensions'] = array($instance['settings']['file_extensions']);
  512. }
  513. return $validators;
  514. }
  515. /**
  516. * Determines the URI for a file field instance.
  517. *
  518. * @param $field
  519. * A field array.
  520. * @param $instance
  521. * A field instance array.
  522. * @param $data
  523. * An array of token objects to pass to token_replace().
  524. *
  525. * @return
  526. * A file directory URI with tokens replaced.
  527. *
  528. * @see token_replace()
  529. */
  530. function file_field_widget_uri($field, $instance, $data = array()) {
  531. $destination = trim($instance['settings']['file_directory'], '/');
  532. // Replace tokens.
  533. $destination = token_replace($destination, $data);
  534. return $field['settings']['uri_scheme'] . '://' . $destination;
  535. }
  536. /**
  537. * The #value_callback for the file_generic field element.
  538. */
  539. function file_field_widget_value($element, $input = FALSE, $form_state) {
  540. if ($input) {
  541. // Checkboxes lose their value when empty.
  542. // If the display field is present make sure its unchecked value is saved.
  543. $field = field_widget_field($element, $form_state);
  544. if (empty($input['display'])) {
  545. $input['display'] = $field['settings']['display_field'] ? 0 : 1;
  546. }
  547. }
  548. // We depend on the managed file element to handle uploads.
  549. $return = file_managed_file_value($element, $input, $form_state);
  550. // Ensure that all the required properties are returned even if empty.
  551. $return += array(
  552. 'fid' => 0,
  553. 'display' => 1,
  554. 'description' => '',
  555. );
  556. return $return;
  557. }
  558. /**
  559. * An element #process callback for the file_generic field type.
  560. *
  561. * Expands the file_generic type to include the description and display fields.
  562. */
  563. function file_field_widget_process($element, &$form_state, $form) {
  564. $item = $element['#value'];
  565. $item['fid'] = $element['fid']['#value'];
  566. $field = field_widget_field($element, $form_state);
  567. $instance = field_widget_instance($element, $form_state);
  568. $settings = $instance['widget']['settings'];
  569. $element['#theme'] = 'file_widget';
  570. // Add the display field if enabled.
  571. if (!empty($field['settings']['display_field'])) {
  572. $element['display'] = array(
  573. '#type' => empty($item['fid']) ? 'hidden' : 'checkbox',
  574. '#title' => t('Include file in display'),
  575. '#value' => isset($item['display']) ? $item['display'] : $field['settings']['display_default'],
  576. '#attributes' => array('class' => array('file-display')),
  577. );
  578. }
  579. else {
  580. $element['display'] = array(
  581. '#type' => 'hidden',
  582. '#value' => '1',
  583. );
  584. }
  585. // Add the description field if enabled.
  586. if (!empty($instance['settings']['description_field']) && $item['fid']) {
  587. $element['description'] = array(
  588. '#type' => variable_get('file_description_type', 'textfield'),
  589. '#title' => t('Description'),
  590. '#value' => isset($item['description']) ? $item['description'] : '',
  591. '#maxlength' => variable_get('file_description_length', 128),
  592. '#description' => t('The description may be used as the label of the link to the file.'),
  593. );
  594. }
  595. // Adjust the Ajax settings so that on upload and remove of any individual
  596. // file, the entire group of file fields is updated together.
  597. if ($field['cardinality'] != 1) {
  598. $parents = array_slice($element['#array_parents'], 0, -1);
  599. $new_path = 'file/ajax/' . implode('/', $parents) . '/' . $form['form_build_id']['#value'];
  600. $field_element = drupal_array_get_nested_value($form, $parents);
  601. $new_wrapper = $field_element['#id'] . '-ajax-wrapper';
  602. foreach (element_children($element) as $key) {
  603. if (isset($element[$key]['#ajax'])) {
  604. $element[$key]['#ajax']['path'] = $new_path;
  605. $element[$key]['#ajax']['wrapper'] = $new_wrapper;
  606. }
  607. }
  608. unset($element['#prefix'], $element['#suffix']);
  609. }
  610. // Add another submit handler to the upload and remove buttons, to implement
  611. // functionality needed by the field widget. This submit handler, along with
  612. // the rebuild logic in file_field_widget_form() requires the entire field,
  613. // not just the individual item, to be valid.
  614. foreach (array('upload_button', 'remove_button') as $key) {
  615. $element[$key]['#submit'][] = 'file_field_widget_submit';
  616. $element[$key]['#limit_validation_errors'] = array(array_slice($element['#parents'], 0, -1));
  617. }
  618. return $element;
  619. }
  620. /**
  621. * An element #process callback for a group of file_generic fields.
  622. *
  623. * Adds the weight field to each row so it can be ordered and adds a new Ajax
  624. * wrapper around the entire group so it can be replaced all at once.
  625. */
  626. function file_field_widget_process_multiple($element, &$form_state, $form) {
  627. $element_children = element_children($element, TRUE);
  628. $count = count($element_children);
  629. foreach ($element_children as $delta => $key) {
  630. if ($key != $element['#file_upload_delta']) {
  631. $description = _file_field_get_description_from_element($element[$key]);
  632. $element[$key]['_weight'] = array(
  633. '#type' => 'weight',
  634. '#title' => $description ? t('Weight for @title', array('@title' => $description)) : t('Weight for new file'),
  635. '#title_display' => 'invisible',
  636. '#delta' => $count,
  637. '#default_value' => $delta,
  638. );
  639. }
  640. else {
  641. // The title needs to be assigned to the upload field so that validation
  642. // errors include the correct widget label.
  643. $element[$key]['#title'] = $element['#title'];
  644. $element[$key]['_weight'] = array(
  645. '#type' => 'hidden',
  646. '#default_value' => $delta,
  647. );
  648. }
  649. }
  650. // Add a new wrapper around all the elements for Ajax replacement.
  651. $element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
  652. $element['#suffix'] = '</div>';
  653. return $element;
  654. }
  655. /**
  656. * Retrieves the file description from a field field element.
  657. *
  658. * This helper function is used by file_field_widget_process_multiple().
  659. *
  660. * @param $element
  661. * The element being processed.
  662. *
  663. * @return
  664. * A description of the file suitable for use in the administrative interface.
  665. */
  666. function _file_field_get_description_from_element($element) {
  667. // Use the actual file description, if it's available.
  668. if (!empty($element['#default_value']['description'])) {
  669. return $element['#default_value']['description'];
  670. }
  671. // Otherwise, fall back to the filename.
  672. if (!empty($element['#default_value']['filename'])) {
  673. return $element['#default_value']['filename'];
  674. }
  675. // This is probably a newly uploaded file; no description is available.
  676. return FALSE;
  677. }
  678. /**
  679. * Form submission handler for upload/remove button of file_field_widget_form().
  680. *
  681. * This runs in addition to and after file_managed_file_submit().
  682. *
  683. * @see file_managed_file_submit()
  684. * @see file_field_widget_form()
  685. * @see file_field_widget_process()
  686. */
  687. function file_field_widget_submit($form, &$form_state) {
  688. // During the form rebuild, file_field_widget_form() will create field item
  689. // widget elements using re-indexed deltas, so clear out $form_state['input']
  690. // to avoid a mismatch between old and new deltas. The rebuilt elements will
  691. // have #default_value set appropriately for the current state of the field,
  692. // so nothing is lost in doing this.
  693. $parents = array_slice($form_state['triggering_element']['#parents'], 0, -2);
  694. drupal_array_set_nested_value($form_state['input'], $parents, NULL);
  695. $button = $form_state['triggering_element'];
  696. // Go one level up in the form, to the widgets container.
  697. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  698. $field_name = $element['#field_name'];
  699. $langcode = $element['#language'];
  700. $parents = $element['#field_parents'];
  701. $submitted_values = drupal_array_get_nested_value($form_state['values'], array_slice($button['#parents'], 0, -2));
  702. foreach ($submitted_values as $delta => $submitted_value) {
  703. if (!$submitted_value['fid']) {
  704. unset($submitted_values[$delta]);
  705. }
  706. }
  707. // Re-index deltas after removing empty items.
  708. $submitted_values = array_values($submitted_values);
  709. // Update form_state values.
  710. drupal_array_set_nested_value($form_state['values'], array_slice($button['#parents'], 0, -2), $submitted_values);
  711. // Update items.
  712. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  713. $field_state['items'] = $submitted_values;
  714. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  715. }
  716. /**
  717. * Returns HTML for an individual file upload widget.
  718. *
  719. * @param $variables
  720. * An associative array containing:
  721. * - element: A render element representing the widget.
  722. *
  723. * @ingroup themeable
  724. */
  725. function theme_file_widget($variables) {
  726. $element = $variables['element'];
  727. $output = '';
  728. // The "form-managed-file" class is required for proper Ajax functionality.
  729. $output .= '<div class="file-widget form-managed-file clearfix">';
  730. if ($element['fid']['#value'] != 0) {
  731. // Add the file size after the file name.
  732. $element['filename']['#markup'] .= ' <span class="file-size">(' . format_size($element['#file']->filesize) . ')</span> ';
  733. }
  734. $output .= drupal_render_children($element);
  735. $output .= '</div>';
  736. return $output;
  737. }
  738. /**
  739. * Returns HTML for a group of file upload widgets.
  740. *
  741. * @param $variables
  742. * An associative array containing:
  743. * - element: A render element representing the widgets.
  744. *
  745. * @ingroup themeable
  746. */
  747. function theme_file_widget_multiple($variables) {
  748. $element = $variables['element'];
  749. // Special ID and classes for draggable tables.
  750. $weight_class = $element['#id'] . '-weight';
  751. $table_id = $element['#id'] . '-table';
  752. // Build up a table of applicable fields.
  753. $headers = array();
  754. $headers[] = t('File information');
  755. if ($element['#display_field']) {
  756. $headers[] = array(
  757. 'data' => t('Display'),
  758. 'class' => array('checkbox'),
  759. );
  760. }
  761. $headers[] = t('Weight');
  762. $headers[] = t('Operations');
  763. // Get our list of widgets in order (needed when the form comes back after
  764. // preview or failed validation).
  765. $widgets = array();
  766. foreach (element_children($element) as $key) {
  767. $widgets[] = &$element[$key];
  768. }
  769. usort($widgets, '_field_sort_items_value_helper');
  770. $rows = array();
  771. foreach ($widgets as $key => &$widget) {
  772. // Save the uploading row for last.
  773. if ($widget['#file'] == FALSE) {
  774. $widget['#title'] = $element['#file_upload_title'];
  775. $widget['#description'] = $element['#file_upload_description'];
  776. continue;
  777. }
  778. // Delay rendering of the buttons, so that they can be rendered later in the
  779. // "operations" column.
  780. $operations_elements = array();
  781. foreach (element_children($widget) as $sub_key) {
  782. if (isset($widget[$sub_key]['#type']) && $widget[$sub_key]['#type'] == 'submit') {
  783. hide($widget[$sub_key]);
  784. $operations_elements[] = &$widget[$sub_key];
  785. }
  786. }
  787. // Delay rendering of the "Display" option and the weight selector, so that
  788. // each can be rendered later in its own column.
  789. if ($element['#display_field']) {
  790. hide($widget['display']);
  791. }
  792. hide($widget['_weight']);
  793. // Render everything else together in a column, without the normal wrappers.
  794. $widget['#theme_wrappers'] = array();
  795. $information = drupal_render($widget);
  796. // Render the previously hidden elements, using render() instead of
  797. // drupal_render(), to undo the earlier hide().
  798. $operations = '';
  799. foreach ($operations_elements as $operation_element) {
  800. $operations .= render($operation_element);
  801. }
  802. $display = '';
  803. if ($element['#display_field']) {
  804. unset($widget['display']['#title']);
  805. $display = array(
  806. 'data' => render($widget['display']),
  807. 'class' => array('checkbox'),
  808. );
  809. }
  810. $widget['_weight']['#attributes']['class'] = array($weight_class);
  811. $weight = render($widget['_weight']);
  812. // Arrange the row with all of the rendered columns.
  813. $row = array();
  814. $row[] = $information;
  815. if ($element['#display_field']) {
  816. $row[] = $display;
  817. }
  818. $row[] = $weight;
  819. $row[] = $operations;
  820. $rows[] = array(
  821. 'data' => $row,
  822. 'class' => isset($widget['#attributes']['class']) ? array_merge($widget['#attributes']['class'], array('draggable')) : array('draggable'),
  823. );
  824. }
  825. drupal_add_tabledrag($table_id, 'order', 'sibling', $weight_class);
  826. $output = '';
  827. $output = empty($rows) ? '' : theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => $table_id)));
  828. $output .= drupal_render_children($element);
  829. return $output;
  830. }
  831. /**
  832. * Returns HTML for help text based on file upload validators.
  833. *
  834. * @param $variables
  835. * An associative array containing:
  836. * - description: The normal description for this field, specified by the
  837. * user.
  838. * - upload_validators: An array of upload validators as used in
  839. * $element['#upload_validators'].
  840. *
  841. * @ingroup themeable
  842. */
  843. function theme_file_upload_help($variables) {
  844. $description = $variables['description'];
  845. $upload_validators = $variables['upload_validators'];
  846. $descriptions = array();
  847. if (strlen($description)) {
  848. $descriptions[] = $description;
  849. }
  850. if (isset($upload_validators['file_validate_size'])) {
  851. $descriptions[] = t('Files must be less than !size.', array('!size' => '<strong>' . format_size($upload_validators['file_validate_size'][0]) . '</strong>'));
  852. }
  853. if (isset($upload_validators['file_validate_extensions'])) {
  854. $descriptions[] = t('Allowed file types: !extensions.', array('!extensions' => '<strong>' . check_plain($upload_validators['file_validate_extensions'][0]) . '</strong>'));
  855. }
  856. if (isset($upload_validators['file_validate_image_resolution'])) {
  857. $max = $upload_validators['file_validate_image_resolution'][0];
  858. $min = $upload_validators['file_validate_image_resolution'][1];
  859. if ($min && $max && $min == $max) {
  860. $descriptions[] = t('Images must be exactly !size pixels.', array('!size' => '<strong>' . $max . '</strong>'));
  861. }
  862. elseif ($min && $max) {
  863. $descriptions[] = t('Images must be between !min and !max pixels.', array('!min' => '<strong>' . $min . '</strong>', '!max' => '<strong>' . $max . '</strong>'));
  864. }
  865. elseif ($min) {
  866. $descriptions[] = t('Images must be larger than !min pixels.', array('!min' => '<strong>' . $min . '</strong>'));
  867. }
  868. elseif ($max) {
  869. $descriptions[] = t('Images must be smaller than !max pixels.', array('!max' => '<strong>' . $max . '</strong>'));
  870. }
  871. }
  872. return implode('<br />', $descriptions);
  873. }
  874. /**
  875. * Implements hook_field_formatter_view().
  876. */
  877. function file_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  878. $element = array();
  879. switch ($display['type']) {
  880. case 'file_default':
  881. foreach ($items as $delta => $item) {
  882. $element[$delta] = array(
  883. '#theme' => 'file_link',
  884. '#file' => (object) $item,
  885. );
  886. }
  887. break;
  888. case 'file_url_plain':
  889. foreach ($items as $delta => $item) {
  890. $element[$delta] = array('#markup' => empty($item['uri']) ? '' : file_create_url($item['uri']));
  891. }
  892. break;
  893. case 'file_table':
  894. if (!empty($items)) {
  895. // Display all values in a single element..
  896. $element[0] = array(
  897. '#theme' => 'file_formatter_table',
  898. '#items' => $items,
  899. );
  900. }
  901. break;
  902. }
  903. return $element;
  904. }
  905. /**
  906. * Returns HTML for a file attachments table.
  907. *
  908. * @param $variables
  909. * An associative array containing:
  910. * - items: An array of file attachments.
  911. *
  912. * @ingroup themeable
  913. */
  914. function theme_file_formatter_table($variables) {
  915. $header = array(t('Attachment'), t('Size'));
  916. $rows = array();
  917. foreach ($variables['items'] as $delta => $item) {
  918. $rows[] = array(
  919. theme('file_link', array('file' => (object) $item)),
  920. format_size($item['filesize']),
  921. );
  922. }
  923. return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
  924. }

Functions

Namesort descending Description
file_field_delete Implements hook_field_delete().
file_field_delete_file Decrements the usage count for a file and attempts to delete it.
file_field_delete_revision Implements hook_field_delete_revision().
file_field_displayed Determines whether a file should be displayed when outputting field content.
file_field_formatter_info Implements hook_field_formatter_info().
file_field_formatter_view Implements hook_field_formatter_view().
file_field_info Implements hook_field_info().
file_field_insert Implements hook_field_insert().
file_field_instance_settings_form Implements hook_field_instance_settings_form().
file_field_is_empty Implements hook_field_is_empty().
file_field_load Implements hook_field_load().
file_field_prepare_view Implements hook_field_prepare_view().
file_field_presave Implements hook_field_presave().
file_field_settings_form Implements hook_field_settings_form().
file_field_update Implements hook_field_update().
file_field_widget_form Implements hook_field_widget_form().
file_field_widget_info Implements hook_field_widget_info().
file_field_widget_process An element #process callback for the file_generic field type.
file_field_widget_process_multiple An element #process callback for a group of file_generic fields.
file_field_widget_settings_form Implements hook_field_widget_settings_form().
file_field_widget_submit Form submission handler for upload/remove button of file_field_widget_form().
file_field_widget_upload_validators Retrieves the upload validators for a file field.
file_field_widget_uri Determines the URI for a file field instance.
file_field_widget_value The #value_callback for the file_generic field element.
theme_file_formatter_table Returns HTML for a file attachments table.
theme_file_upload_help Returns HTML for help text based on file upload validators.
theme_file_widget Returns HTML for an individual file upload widget.
theme_file_widget_multiple Returns HTML for a group of file upload widgets.
_file_field_get_description_from_element Retrieves the file description from a field field element.
_file_generic_settings_extensions Element validate callback for the allowed file extensions field.
_file_generic_settings_file_directory_validate Element validate callback for the file destination field.
_file_generic_settings_max_filesize Element validate callback for the maximum upload size field.