file.field.inc 35 KB

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