file.field.inc 34 KB

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