file.module 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  1. <?php
  2. /**
  3. * @file
  4. * Defines a "managed_file" Form API field and a "file" field for Field module.
  5. */
  6. use Drupal\Core\Datetime\Entity\DateFormat;
  7. use Drupal\Core\Field\FieldDefinitionInterface;
  8. use Drupal\Core\Form\FormStateInterface;
  9. use Drupal\Core\Render\BubbleableMetadata;
  10. use Drupal\Core\Render\Element;
  11. use Drupal\Core\Routing\RouteMatchInterface;
  12. use Drupal\Core\Url;
  13. use Drupal\file\Entity\File;
  14. use Drupal\file\FileInterface;
  15. use Drupal\Component\Utility\NestedArray;
  16. use Drupal\Component\Utility\Unicode;
  17. use Drupal\Core\Entity\EntityStorageInterface;
  18. use Drupal\Core\Template\Attribute;
  19. // Load all Field module hooks for File.
  20. require_once __DIR__ . '/file.field.inc';
  21. /**
  22. * Implements hook_help().
  23. */
  24. function file_help($route_name, RouteMatchInterface $route_match) {
  25. switch ($route_name) {
  26. case 'help.page.file':
  27. $output = '';
  28. $output .= '<h3>' . t('About') . '</h3>';
  29. $output .= '<p>' . t('The File module allows you to create fields that contain files. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":file_documentation">online documentation for the File module</a>.', [':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#', ':file_documentation' => 'https://www.drupal.org/documentation/modules/file']) . '</p>';
  30. $output .= '<h3>' . t('Uses') . '</h3>';
  31. $output .= '<dl>';
  32. $output .= '<dt>' . t('Managing and displaying file fields') . '</dt>';
  33. $output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the file field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '</dd>';
  34. $output .= '<dt>' . t('Allowing file extensions') . '</dt>';
  35. $output .= '<dd>' . t('In the field settings, you can define the allowed file extensions (for example <em>pdf docx psd</em>) for the files that will be uploaded with the file field.') . '</dd>';
  36. $output .= '<dt>' . t('Storing files') . '</dt>';
  37. $output .= '<dd>' . t('Uploaded files can either be stored as <em>public</em> or <em>private</em>, depending on the <a href=":file-system">File system settings</a>. For more information, see the <a href=":system-help">System module help page</a>.', [':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', ['name' => 'system'])]) . '</dd>';
  38. $output .= '<dt>' . t('Restricting the maximum file size') . '</dt>';
  39. $output .= '<dd>' . t('The maximum file size that users can upload is limited by PHP settings of the server, but you can restrict by entering the desired value as the <em>Maximum upload size</em> setting. The maximum file size is automatically displayed to users in the help text of the file field.') . '</dd>';
  40. $output .= '<dt>' . t('Displaying files and descriptions') . '<dt>';
  41. $output .= '<dd>' . t('In the field settings, you can allow users to toggle whether individual files are displayed. In the display settings, you can then choose one of the following formats: <ul><li><em>Generic file</em> displays links to the files and adds icons that symbolize the file extensions. If <em>descriptions</em> are enabled and have been submitted, then the description is displayed instead of the file name.</li><li><em>URL to file</em> displays the full path to the file as plain text.</li><li><em>Table of files</em> lists links to the files and the file sizes in a table.</li><li><em>RSS enclosure</em> only displays the first file, and only in a RSS feed, formatted according to the RSS 2.0 syntax for enclosures.</li></ul> A file can still be linked to directly by its URI even if it is not displayed.') . '</dd>';
  42. $output .= '</dl>';
  43. return $output;
  44. }
  45. }
  46. /**
  47. * Implements hook_field_widget_info_alter().
  48. */
  49. function file_field_widget_info_alter(array &$info) {
  50. // Allows using the 'uri' widget for the 'file_uri' field type, which uses it
  51. // as the default widget.
  52. // @see \Drupal\file\Plugin\Field\FieldType\FileUriItem
  53. $info['uri']['field_types'][] = 'file_uri';
  54. }
  55. /**
  56. * Loads file entities from the database.
  57. *
  58. * @param array|null $fids
  59. * (optional) An array of entity IDs. If omitted or NULL, all entities are
  60. * loaded.
  61. * @param bool $reset
  62. * (optional) Whether to reset the internal file_load_multiple() cache.
  63. * Defaults to FALSE.
  64. *
  65. * @return array
  66. * An array of file entities, indexed by fid.
  67. *
  68. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  69. * Use \Drupal\file\Entity\File::loadMultiple().
  70. *
  71. * @see hook_ENTITY_TYPE_load()
  72. * @see file_load()
  73. * @see entity_load()
  74. * @see \Drupal\Core\Entity\Query\EntityQueryInterface
  75. */
  76. function file_load_multiple(array $fids = NULL, $reset = FALSE) {
  77. if ($reset) {
  78. \Drupal::entityManager()->getStorage('file')->resetCache($fids);
  79. }
  80. return File::loadMultiple($fids);
  81. }
  82. /**
  83. * Loads a single file entity from the database.
  84. *
  85. * @param int $fid
  86. * A file ID.
  87. * @param bool $reset
  88. * (optional) Whether to reset the internal file_load_multiple() cache.
  89. * Defaults to FALSE.
  90. *
  91. * @return \Drupal\file\FileInterface|null
  92. * A file entity or NULL if the file was not found.
  93. *
  94. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  95. * Use \Drupal\file\Entity\File::load().
  96. *
  97. * @see hook_ENTITY_TYPE_load()
  98. * @see file_load_multiple()
  99. */
  100. function file_load($fid, $reset = FALSE) {
  101. if ($reset) {
  102. \Drupal::entityManager()->getStorage('file')->resetCache([$fid]);
  103. }
  104. return File::load($fid);
  105. }
  106. /**
  107. * Copies a file to a new location and adds a file record to the database.
  108. *
  109. * This function should be used when manipulating files that have records
  110. * stored in the database. This is a powerful function that in many ways
  111. * performs like an advanced version of copy().
  112. * - Checks if $source and $destination are valid and readable/writable.
  113. * - If file already exists in $destination either the call will error out,
  114. * replace the file or rename the file based on the $replace parameter.
  115. * - If the $source and $destination are equal, the behavior depends on the
  116. * $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
  117. * will rename the file until the $destination is unique.
  118. * - Adds the new file to the files database. If the source file is a
  119. * temporary file, the resulting file will also be a temporary file. See
  120. * file_save_upload() for details on temporary files.
  121. *
  122. * @param \Drupal\file\FileInterface $source
  123. * A file entity.
  124. * @param string $destination
  125. * A string containing the destination that $source should be
  126. * copied to. This must be a stream wrapper URI.
  127. * @param int $replace
  128. * (optional) Replace behavior when the destination file already exists.
  129. * Possible values include:
  130. * - FILE_EXISTS_REPLACE: Replace the existing file. If a managed file with
  131. * the destination name exists, then its database entry will be updated. If
  132. * no database entry is found, then a new one will be created.
  133. * - FILE_EXISTS_RENAME: (default) Append _{incrementing number} until the
  134. * filename is unique.
  135. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  136. *
  137. * @return \Drupal\file\FileInterface|false
  138. * File entity if the copy is successful, or FALSE in the event of an error.
  139. *
  140. * @see file_unmanaged_copy()
  141. * @see hook_file_copy()
  142. */
  143. function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  144. if (!file_valid_uri($destination)) {
  145. if (($realpath = \Drupal::service('file_system')->realpath($source->getFileUri())) !== FALSE) {
  146. \Drupal::logger('file')->notice('File %file (%realpath) could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]);
  147. }
  148. else {
  149. \Drupal::logger('file')->notice('File %file could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%destination' => $destination]);
  150. }
  151. drupal_set_message(t('The specified file %file could not be copied because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]), 'error');
  152. return FALSE;
  153. }
  154. if ($uri = file_unmanaged_copy($source->getFileUri(), $destination, $replace)) {
  155. $file = $source->createDuplicate();
  156. $file->setFileUri($uri);
  157. $file->setFilename(drupal_basename($uri));
  158. // If we are replacing an existing file re-use its database record.
  159. // @todo Do not create a new entity in order to update it. See
  160. // https://www.drupal.org/node/2241865.
  161. if ($replace == FILE_EXISTS_REPLACE) {
  162. $existing_files = entity_load_multiple_by_properties('file', ['uri' => $uri]);
  163. if (count($existing_files)) {
  164. $existing = reset($existing_files);
  165. $file->fid = $existing->id();
  166. $file->setOriginalId($existing->id());
  167. $file->setFilename($existing->getFilename());
  168. }
  169. }
  170. // If we are renaming around an existing file (rather than a directory),
  171. // use its basename for the filename.
  172. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  173. $file->setFilename(drupal_basename($destination));
  174. }
  175. $file->save();
  176. // Inform modules that the file has been copied.
  177. \Drupal::moduleHandler()->invokeAll('file_copy', [$file, $source]);
  178. return $file;
  179. }
  180. return FALSE;
  181. }
  182. /**
  183. * Moves a file to a new location and update the file's database entry.
  184. *
  185. * - Checks if $source and $destination are valid and readable/writable.
  186. * - Performs a file move if $source is not equal to $destination.
  187. * - If file already exists in $destination either the call will error out,
  188. * replace the file or rename the file based on the $replace parameter.
  189. * - Adds the new file to the files database.
  190. *
  191. * @param \Drupal\file\FileInterface $source
  192. * A file entity.
  193. * @param string $destination
  194. * A string containing the destination that $source should be moved
  195. * to. This must be a stream wrapper URI.
  196. * @param int $replace
  197. * (optional) The replace behavior when the destination file already exists.
  198. * Possible values include:
  199. * - FILE_EXISTS_REPLACE: Replace the existing file. If a managed file with
  200. * the destination name exists then its database entry will be updated and
  201. * $source->delete() called after invoking hook_file_move(). If no database
  202. * entry is found, then the source files record will be updated.
  203. * - FILE_EXISTS_RENAME: (default) Append _{incrementing number} until the
  204. * filename is unique.
  205. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  206. *
  207. * @return \Drupal\file\FileInterface|false
  208. * Resulting file entity for success, or FALSE in the event of an error.
  209. *
  210. * @see file_unmanaged_move()
  211. * @see hook_file_move()
  212. */
  213. function file_move(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  214. if (!file_valid_uri($destination)) {
  215. if (($realpath = \Drupal::service('file_system')->realpath($source->getFileUri())) !== FALSE) {
  216. \Drupal::logger('file')->notice('File %file (%realpath) could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]);
  217. }
  218. else {
  219. \Drupal::logger('file')->notice('File %file could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%destination' => $destination]);
  220. }
  221. drupal_set_message(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]), 'error');
  222. return FALSE;
  223. }
  224. if ($uri = file_unmanaged_move($source->getFileUri(), $destination, $replace)) {
  225. $delete_source = FALSE;
  226. $file = clone $source;
  227. $file->setFileUri($uri);
  228. // If we are replacing an existing file re-use its database record.
  229. if ($replace == FILE_EXISTS_REPLACE) {
  230. $existing_files = entity_load_multiple_by_properties('file', ['uri' => $uri]);
  231. if (count($existing_files)) {
  232. $existing = reset($existing_files);
  233. $delete_source = TRUE;
  234. $file->fid = $existing->id();
  235. $file->uuid = $existing->uuid();
  236. }
  237. }
  238. // If we are renaming around an existing file (rather than a directory),
  239. // use its basename for the filename.
  240. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  241. $file->setFilename(drupal_basename($destination));
  242. }
  243. $file->save();
  244. // Inform modules that the file has been moved.
  245. \Drupal::moduleHandler()->invokeAll('file_move', [$file, $source]);
  246. // Delete the original if it's not in use elsewhere.
  247. if ($delete_source && !\Drupal::service('file.usage')->listUsage($source)) {
  248. $source->delete();
  249. }
  250. return $file;
  251. }
  252. return FALSE;
  253. }
  254. /**
  255. * Checks that a file meets the criteria specified by the validators.
  256. *
  257. * After executing the validator callbacks specified hook_file_validate() will
  258. * also be called to allow other modules to report errors about the file.
  259. *
  260. * @param \Drupal\file\FileInterface $file
  261. * A file entity.
  262. * @param array $validators
  263. * (optional) An associative array of callback functions used to validate
  264. * the file. The keys are function names and the values arrays of callback
  265. * parameters which will be passed in after the file entity. The functions
  266. * should return an array of error messages; an empty array indicates that
  267. * the file passed validation. The callback functions will be called in the
  268. * order specified in the array, then the hook hook_file_validate()
  269. * will be invoked so other modules can validate the new file.
  270. *
  271. * @return array
  272. * An array containing validation error messages.
  273. *
  274. * @see hook_file_validate()
  275. */
  276. function file_validate(FileInterface $file, $validators = []) {
  277. // Call the validation functions specified by this function's caller.
  278. $errors = [];
  279. foreach ($validators as $function => $args) {
  280. if (function_exists($function)) {
  281. array_unshift($args, $file);
  282. $errors = array_merge($errors, call_user_func_array($function, $args));
  283. }
  284. }
  285. // Let other modules perform validation on the new file.
  286. return array_merge($errors, \Drupal::moduleHandler()->invokeAll('file_validate', [$file]));
  287. }
  288. /**
  289. * Checks for files with names longer than can be stored in the database.
  290. *
  291. * @param \Drupal\file\FileInterface $file
  292. * A file entity.
  293. *
  294. * @return array
  295. * An empty array if the file name length is smaller than the limit or an
  296. * array containing an error message if it's not or is empty.
  297. */
  298. function file_validate_name_length(FileInterface $file) {
  299. $errors = [];
  300. if (!$file->getFilename()) {
  301. $errors[] = t("The file's name is empty. Please give a name to the file.");
  302. }
  303. if (strlen($file->getFilename()) > 240) {
  304. $errors[] = t("The file's name exceeds the 240 characters limit. Please rename the file and try again.");
  305. }
  306. return $errors;
  307. }
  308. /**
  309. * Checks that the filename ends with an allowed extension.
  310. *
  311. * @param \Drupal\file\FileInterface $file
  312. * A file entity.
  313. * @param string $extensions
  314. * A string with a space separated list of allowed extensions.
  315. *
  316. * @return array
  317. * An empty array if the file extension is allowed or an array containing an
  318. * error message if it's not.
  319. *
  320. * @see hook_file_validate()
  321. */
  322. function file_validate_extensions(FileInterface $file, $extensions) {
  323. $errors = [];
  324. $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  325. if (!preg_match($regex, $file->getFilename())) {
  326. $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => $extensions]);
  327. }
  328. return $errors;
  329. }
  330. /**
  331. * Checks that the file's size is below certain limits.
  332. *
  333. * @param \Drupal\file\FileInterface $file
  334. * A file entity.
  335. * @param int $file_limit
  336. * (optional) The maximum file size in bytes. Zero (the default) indicates
  337. * that no limit should be enforced.
  338. * @param int $user_limit
  339. * (optional) The maximum number of bytes the user is allowed. Zero (the
  340. * default) indicates that no limit should be enforced.
  341. *
  342. * @return array
  343. * An empty array if the file size is below limits or an array containing an
  344. * error message if it's not.
  345. *
  346. * @see hook_file_validate()
  347. */
  348. function file_validate_size(FileInterface $file, $file_limit = 0, $user_limit = 0) {
  349. $user = \Drupal::currentUser();
  350. $errors = [];
  351. if ($file_limit && $file->getSize() > $file_limit) {
  352. $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', ['%filesize' => format_size($file->getSize()), '%maxsize' => format_size($file_limit)]);
  353. }
  354. // Save a query by only calling spaceUsed() when a limit is provided.
  355. if ($user_limit && (\Drupal::entityManager()->getStorage('file')->spaceUsed($user->id()) + $file->getSize()) > $user_limit) {
  356. $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', ['%filesize' => format_size($file->getSize()), '%quota' => format_size($user_limit)]);
  357. }
  358. return $errors;
  359. }
  360. /**
  361. * Checks that the file is recognized as a valid image.
  362. *
  363. * @param \Drupal\file\FileInterface $file
  364. * A file entity.
  365. *
  366. * @return array
  367. * An empty array if the file is a valid image or an array containing an error
  368. * message if it's not.
  369. *
  370. * @see hook_file_validate()
  371. */
  372. function file_validate_is_image(FileInterface $file) {
  373. $errors = [];
  374. $image_factory = \Drupal::service('image.factory');
  375. $image = $image_factory->get($file->getFileUri());
  376. if (!$image->isValid()) {
  377. $supported_extensions = $image_factory->getSupportedExtensions();
  378. $errors[] = t('The image file is invalid or the image type is not allowed. Allowed types: %types', ['%types' => implode(', ', $supported_extensions)]);
  379. }
  380. return $errors;
  381. }
  382. /**
  383. * Verifies that image dimensions are within the specified maximum and minimum.
  384. *
  385. * Non-image files will be ignored. If an image toolkit is available the image
  386. * will be scaled to fit within the desired maximum dimensions.
  387. *
  388. * @param \Drupal\file\FileInterface $file
  389. * A file entity. This function may resize the file affecting its size.
  390. * @param string|int $maximum_dimensions
  391. * (optional) A string in the form WIDTHxHEIGHT; for example, '640x480' or
  392. * '85x85'. If an image toolkit is installed, the image will be resized down
  393. * to these dimensions. A value of zero (the default) indicates no restriction
  394. * on size, so no resizing will be attempted.
  395. * @param string|int $minimum_dimensions
  396. * (optional) A string in the form WIDTHxHEIGHT. This will check that the
  397. * image meets a minimum size. A value of zero (the default) indicates that
  398. * there is no restriction on size.
  399. *
  400. * @return array
  401. * An empty array if the file meets the specified dimensions, was resized
  402. * successfully to meet those requirements or is not an image. If the image
  403. * does not meet the requirements or an attempt to resize it fails, an array
  404. * containing the error message will be returned.
  405. *
  406. * @see hook_file_validate()
  407. */
  408. function file_validate_image_resolution(FileInterface $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  409. $errors = [];
  410. // Check first that the file is an image.
  411. $image_factory = \Drupal::service('image.factory');
  412. $image = $image_factory->get($file->getFileUri());
  413. if ($image->isValid()) {
  414. $scaling = FALSE;
  415. if ($maximum_dimensions) {
  416. // Check that it is smaller than the given dimensions.
  417. list($width, $height) = explode('x', $maximum_dimensions);
  418. if ($image->getWidth() > $width || $image->getHeight() > $height) {
  419. // Try to resize the image to fit the dimensions.
  420. if ($image->scale($width, $height)) {
  421. $scaling = TRUE;
  422. $image->save();
  423. if (!empty($width) && !empty($height)) {
  424. $message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
  425. [
  426. '%dimensions' => $maximum_dimensions,
  427. '%new_width' => $image->getWidth(),
  428. '%new_height' => $image->getHeight(),
  429. ]);
  430. }
  431. elseif (empty($width)) {
  432. $message = t('The image was resized to fit within the maximum allowed height of %height pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
  433. [
  434. '%height' => $height,
  435. '%new_width' => $image->getWidth(),
  436. '%new_height' => $image->getHeight(),
  437. ]);
  438. }
  439. elseif (empty($height)) {
  440. $message = t('The image was resized to fit within the maximum allowed width of %width pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
  441. [
  442. '%width' => $width,
  443. '%new_width' => $image->getWidth(),
  444. '%new_height' => $image->getHeight(),
  445. ]);
  446. }
  447. drupal_set_message($message);
  448. }
  449. else {
  450. $errors[] = t('The image exceeds the maximum allowed dimensions and an attempt to resize it failed.');
  451. }
  452. }
  453. }
  454. if ($minimum_dimensions) {
  455. // Check that it is larger than the given dimensions.
  456. list($width, $height) = explode('x', $minimum_dimensions);
  457. if ($image->getWidth() < $width || $image->getHeight() < $height) {
  458. if ($scaling) {
  459. $errors[] = t('The resized image is too small. The minimum dimensions are %dimensions pixels and after resizing, the image size will be %widthx%height pixels.',
  460. [
  461. '%dimensions' => $minimum_dimensions,
  462. '%width' => $image->getWidth(),
  463. '%height' => $image->getHeight(),
  464. ]);
  465. }
  466. else {
  467. $errors[] = t('The image is too small. The minimum dimensions are %dimensions pixels and the image size is %widthx%height pixels.',
  468. [
  469. '%dimensions' => $minimum_dimensions,
  470. '%width' => $image->getWidth(),
  471. '%height' => $image->getHeight(),
  472. ]);
  473. }
  474. }
  475. }
  476. }
  477. return $errors;
  478. }
  479. /**
  480. * Saves a file to the specified destination and creates a database entry.
  481. *
  482. * @param string $data
  483. * A string containing the contents of the file.
  484. * @param string|null $destination
  485. * (optional) A string containing the destination URI. This must be a stream
  486. * wrapper URI. If no value or NULL is provided, a randomized name will be
  487. * generated and the file will be saved using Drupal's default files scheme,
  488. * usually "public://".
  489. * @param int $replace
  490. * (optional) The replace behavior when the destination file already exists.
  491. * Possible values include:
  492. * - FILE_EXISTS_REPLACE: Replace the existing file. If a managed file with
  493. * the destination name exists, then its database entry will be updated. If
  494. * no database entry is found, then a new one will be created.
  495. * - FILE_EXISTS_RENAME: (default) Append _{incrementing number} until the
  496. * filename is unique.
  497. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  498. *
  499. * @return \Drupal\file\FileInterface|false
  500. * A file entity, or FALSE on error.
  501. *
  502. * @see file_unmanaged_save_data()
  503. */
  504. function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  505. $user = \Drupal::currentUser();
  506. if (empty($destination)) {
  507. $destination = file_default_scheme() . '://';
  508. }
  509. if (!file_valid_uri($destination)) {
  510. \Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', ['%destination' => $destination]);
  511. drupal_set_message(t('The data could not be saved because the destination is invalid. More information is available in the system log.'), 'error');
  512. return FALSE;
  513. }
  514. if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
  515. // Create a file entity.
  516. $file = File::create([
  517. 'uri' => $uri,
  518. 'uid' => $user->id(),
  519. 'status' => FILE_STATUS_PERMANENT,
  520. ]);
  521. // If we are replacing an existing file re-use its database record.
  522. // @todo Do not create a new entity in order to update it. See
  523. // https://www.drupal.org/node/2241865.
  524. if ($replace == FILE_EXISTS_REPLACE) {
  525. $existing_files = entity_load_multiple_by_properties('file', ['uri' => $uri]);
  526. if (count($existing_files)) {
  527. $existing = reset($existing_files);
  528. $file->fid = $existing->id();
  529. $file->setOriginalId($existing->id());
  530. $file->setFilename($existing->getFilename());
  531. }
  532. }
  533. // If we are renaming around an existing file (rather than a directory),
  534. // use its basename for the filename.
  535. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  536. $file->setFilename(drupal_basename($destination));
  537. }
  538. $file->save();
  539. return $file;
  540. }
  541. return FALSE;
  542. }
  543. /**
  544. * Examines a file entity and returns appropriate content headers for download.
  545. *
  546. * @param \Drupal\file\FileInterface $file
  547. * A file entity.
  548. *
  549. * @return array
  550. * An associative array of headers, as expected by
  551. * \Symfony\Component\HttpFoundation\StreamedResponse.
  552. */
  553. function file_get_content_headers(FileInterface $file) {
  554. $type = Unicode::mimeHeaderEncode($file->getMimeType());
  555. return [
  556. 'Content-Type' => $type,
  557. 'Content-Length' => $file->getSize(),
  558. 'Cache-Control' => 'private',
  559. ];
  560. }
  561. /**
  562. * Implements hook_theme().
  563. */
  564. function file_theme() {
  565. return [
  566. // From file.module.
  567. 'file_link' => [
  568. 'variables' => ['file' => NULL, 'description' => NULL, 'attributes' => []],
  569. ],
  570. 'file_managed_file' => [
  571. 'render element' => 'element',
  572. ],
  573. 'file_audio' => [
  574. 'variables' => ['files' => [], 'attributes' => NULL],
  575. ],
  576. 'file_video' => [
  577. 'variables' => ['files' => [], 'attributes' => NULL],
  578. ],
  579. // From file.field.inc.
  580. 'file_widget_multiple' => [
  581. 'render element' => 'element',
  582. 'file' => 'file.field.inc',
  583. ],
  584. 'file_upload_help' => [
  585. 'variables' => ['description' => NULL, 'upload_validators' => NULL, 'cardinality' => NULL],
  586. 'file' => 'file.field.inc',
  587. ],
  588. ];
  589. }
  590. /**
  591. * Implements hook_file_download().
  592. */
  593. function file_file_download($uri) {
  594. // Get the file record based on the URI. If not in the database just return.
  595. /** @var \Drupal\file\FileInterface[] $files */
  596. $files = entity_load_multiple_by_properties('file', ['uri' => $uri]);
  597. if (count($files)) {
  598. foreach ($files as $item) {
  599. // Since some database servers sometimes use a case-insensitive comparison
  600. // by default, double check that the filename is an exact match.
  601. if ($item->getFileUri() === $uri) {
  602. $file = $item;
  603. break;
  604. }
  605. }
  606. }
  607. if (!isset($file)) {
  608. return;
  609. }
  610. // Find out if a temporary file is still used in the system.
  611. if ($file->isTemporary()) {
  612. $usage = \Drupal::service('file.usage')->listUsage($file);
  613. if (empty($usage) && $file->getOwnerId() != \Drupal::currentUser()->id()) {
  614. // Deny access to temporary files without usage that are not owned by the
  615. // same user. This prevents the security issue that a private file that
  616. // was protected by field permissions becomes available after its usage
  617. // was removed and before it is actually deleted from the file system.
  618. // Modules that depend on this behavior should make the file permanent
  619. // instead.
  620. return -1;
  621. }
  622. }
  623. // Find out which (if any) fields of this type contain the file.
  624. $references = file_get_file_references($file, NULL, EntityStorageInterface::FIELD_LOAD_CURRENT, NULL);
  625. // Stop processing if there are no references in order to avoid returning
  626. // headers for files controlled by other modules. Make an exception for
  627. // temporary files where the host entity has not yet been saved (for example,
  628. // an image preview on a node/add form) in which case, allow download by the
  629. // file's owner.
  630. if (empty($references) && ($file->isPermanent() || $file->getOwnerId() != \Drupal::currentUser()->id())) {
  631. return;
  632. }
  633. if (!$file->access('download')) {
  634. return -1;
  635. }
  636. // Access is granted.
  637. $headers = file_get_content_headers($file);
  638. return $headers;
  639. }
  640. /**
  641. * Implements hook_cron().
  642. */
  643. function file_cron() {
  644. $age = \Drupal::config('system.file')->get('temporary_maximum_age');
  645. $file_storage = \Drupal::entityManager()->getStorage('file');
  646. // Only delete temporary files if older than $age. Note that automatic cleanup
  647. // is disabled if $age set to 0.
  648. if ($age) {
  649. $fids = Drupal::entityQuery('file')
  650. ->condition('status', FILE_STATUS_PERMANENT, '<>')
  651. ->condition('changed', REQUEST_TIME - $age, '<')
  652. ->range(0, 100)
  653. ->execute();
  654. $files = $file_storage->loadMultiple($fids);
  655. foreach ($files as $file) {
  656. $references = \Drupal::service('file.usage')->listUsage($file);
  657. if (empty($references)) {
  658. if (file_exists($file->getFileUri())) {
  659. $file->delete();
  660. }
  661. else {
  662. \Drupal::logger('file system')->error('Could not delete temporary file "%path" during garbage collection', ['%path' => $file->getFileUri()]);
  663. }
  664. }
  665. else {
  666. \Drupal::logger('file system')->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', ['%path' => $file->getFileUri(), '%modules' => implode(', ', array_keys($references))]);
  667. }
  668. }
  669. }
  670. }
  671. /**
  672. * Saves form file uploads.
  673. *
  674. * The files will be added to the {file_managed} table as temporary files.
  675. * Temporary files are periodically cleaned. Use the 'file.usage' service to
  676. * register the usage of the file which will automatically mark it as permanent.
  677. *
  678. * @param array $element
  679. * The FAPI element whose values are being saved.
  680. * @param \Drupal\Core\Form\FormStateInterface $form_state
  681. * The current state of the form.
  682. * @param null|int $delta
  683. * (optional) The delta of the file to return the file entity.
  684. * Defaults to NULL.
  685. * @param int $replace
  686. * (optional) The replace behavior when the destination file already exists.
  687. * Possible values include:
  688. * - FILE_EXISTS_REPLACE: Replace the existing file.
  689. * - FILE_EXISTS_RENAME: (default) Append _{incrementing number} until the
  690. * filename is unique.
  691. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  692. *
  693. * @return array|\Drupal\file\FileInterface|null|false
  694. * An array of file entities or a single file entity if $delta != NULL. Each
  695. * array element contains the file entity if the upload succeeded or FALSE if
  696. * there was an error. Function returns NULL if no file was uploaded.
  697. *
  698. * @deprecated in Drupal 8.4.x, will be removed before Drupal 9.0.0.
  699. * For backwards compatibility use core file upload widgets in forms.
  700. *
  701. * @internal
  702. * This function wraps file_save_upload() to allow correct error handling in
  703. * forms.
  704. *
  705. * @todo Revisit after https://www.drupal.org/node/2244513.
  706. */
  707. function _file_save_upload_from_form(array $element, FormStateInterface $form_state, $delta = NULL, $replace = FILE_EXISTS_RENAME) {
  708. // Get all errors set before calling this method. This will also clear them
  709. // from $_SESSION.
  710. $errors_before = drupal_get_messages('error');
  711. $upload_location = isset($element['#upload_location']) ? $element['#upload_location'] : FALSE;
  712. $upload_name = implode('_', $element['#parents']);
  713. $upload_validators = isset($element['#upload_validators']) ? $element['#upload_validators'] : [];
  714. $result = file_save_upload($upload_name, $upload_validators, $upload_location, $delta, $replace);
  715. // Get new errors that are generated while trying to save the upload. This
  716. // will also clear them from $_SESSION.
  717. $errors_new = drupal_get_messages('error');
  718. if (!empty($errors_new['error'])) {
  719. $errors_new = $errors_new['error'];
  720. if (count($errors_new) > 1) {
  721. // Render multiple errors into a single message.
  722. // This is needed because only one error per element is supported.
  723. $render_array = [
  724. 'error' => [
  725. '#markup' => t('One or more files could not be uploaded.'),
  726. ],
  727. 'item_list' => [
  728. '#theme' => 'item_list',
  729. '#items' => $errors_new,
  730. ],
  731. ];
  732. $error_message = \Drupal::service('renderer')->renderPlain($render_array);
  733. }
  734. else {
  735. $error_message = reset($errors_new);
  736. }
  737. $form_state->setError($element, $error_message);
  738. }
  739. // Ensure that errors set prior to calling this method are still shown to the
  740. // user.
  741. if (!empty($errors_before['error'])) {
  742. foreach ($errors_before['error'] as $error) {
  743. drupal_set_message($error, 'error');
  744. }
  745. }
  746. return $result;
  747. }
  748. /**
  749. * Saves file uploads to a new location.
  750. *
  751. * The files will be added to the {file_managed} table as temporary files.
  752. * Temporary files are periodically cleaned. Use the 'file.usage' service to
  753. * register the usage of the file which will automatically mark it as permanent.
  754. *
  755. * Note that this function does not support correct form error handling. The
  756. * file upload widgets in core do support this. It is advised to use these in
  757. * any custom form, instead of calling this function.
  758. *
  759. * @param string $form_field_name
  760. * A string that is the associative array key of the upload form element in
  761. * the form array.
  762. * @param array $validators
  763. * (optional) An associative array of callback functions used to validate the
  764. * file. See file_validate() for a full discussion of the array format.
  765. * If the array is empty, it will be set up to call file_validate_extensions()
  766. * with a safe list of extensions, as follows: "jpg jpeg gif png txt doc
  767. * xls pdf ppt pps odt ods odp". To allow all extensions, you must explicitly
  768. * set this array to ['file_validate_extensions' => '']. (Beware: this is not
  769. * safe and should only be allowed for trusted users, if at all.)
  770. * @param string|false $destination
  771. * (optional) A string containing the URI that the file should be copied to.
  772. * This must be a stream wrapper URI. If this value is omitted or set to
  773. * FALSE, Drupal's temporary files scheme will be used ("temporary://").
  774. * @param null|int $delta
  775. * (optional) The delta of the file to return the file entity.
  776. * Defaults to NULL.
  777. * @param int $replace
  778. * (optional) The replace behavior when the destination file already exists.
  779. * Possible values include:
  780. * - FILE_EXISTS_REPLACE: Replace the existing file.
  781. * - FILE_EXISTS_RENAME: (default) Append _{incrementing number} until the
  782. * filename is unique.
  783. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  784. *
  785. * @return array|\Drupal\file\FileInterface|null|false
  786. * An array of file entities or a single file entity if $delta != NULL. Each
  787. * array element contains the file entity if the upload succeeded or FALSE if
  788. * there was an error. Function returns NULL if no file was uploaded.
  789. *
  790. * @see _file_save_upload_from_form()
  791. *
  792. * @todo: move this logic to a service in https://www.drupal.org/node/2244513.
  793. */
  794. function file_save_upload($form_field_name, $validators = [], $destination = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) {
  795. $user = \Drupal::currentUser();
  796. static $upload_cache;
  797. $all_files = \Drupal::request()->files->get('files', []);
  798. // Make sure there's an upload to process.
  799. if (empty($all_files[$form_field_name])) {
  800. return NULL;
  801. }
  802. $file_upload = $all_files[$form_field_name];
  803. // Return cached objects without processing since the file will have
  804. // already been processed and the paths in $_FILES will be invalid.
  805. if (isset($upload_cache[$form_field_name])) {
  806. if (isset($delta)) {
  807. return $upload_cache[$form_field_name][$delta];
  808. }
  809. return $upload_cache[$form_field_name];
  810. }
  811. // Prepare uploaded files info. Representation is slightly different
  812. // for multiple uploads and we fix that here.
  813. $uploaded_files = $file_upload;
  814. if (!is_array($file_upload)) {
  815. $uploaded_files = [$file_upload];
  816. }
  817. $files = [];
  818. foreach ($uploaded_files as $i => $file_info) {
  819. // Check for file upload errors and return FALSE for this file if a lower
  820. // level system error occurred. For a complete list of errors:
  821. // See http://php.net/manual/features.file-upload.errors.php.
  822. switch ($file_info->getError()) {
  823. case UPLOAD_ERR_INI_SIZE:
  824. case UPLOAD_ERR_FORM_SIZE:
  825. drupal_set_message(t('The file %file could not be saved because it exceeds %maxsize, the maximum allowed size for uploads.', ['%file' => $file_info->getFilename(), '%maxsize' => format_size(file_upload_max_size())]), 'error');
  826. $files[$i] = FALSE;
  827. continue;
  828. case UPLOAD_ERR_PARTIAL:
  829. case UPLOAD_ERR_NO_FILE:
  830. drupal_set_message(t('The file %file could not be saved because the upload did not complete.', ['%file' => $file_info->getFilename()]), 'error');
  831. $files[$i] = FALSE;
  832. continue;
  833. case UPLOAD_ERR_OK:
  834. // Final check that this is a valid upload, if it isn't, use the
  835. // default error handler.
  836. if (is_uploaded_file($file_info->getRealPath())) {
  837. break;
  838. }
  839. // Unknown error
  840. default:
  841. drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', ['%file' => $file_info->getFilename()]), 'error');
  842. $files[$i] = FALSE;
  843. continue;
  844. }
  845. // Begin building file entity.
  846. $values = [
  847. 'uid' => $user->id(),
  848. 'status' => 0,
  849. 'filename' => $file_info->getClientOriginalName(),
  850. 'uri' => $file_info->getRealPath(),
  851. 'filesize' => $file_info->getSize(),
  852. ];
  853. $values['filemime'] = \Drupal::service('file.mime_type.guesser')->guess($values['filename']);
  854. $file = File::create($values);
  855. $extensions = '';
  856. if (isset($validators['file_validate_extensions'])) {
  857. if (isset($validators['file_validate_extensions'][0])) {
  858. // Build the list of non-munged extensions if the caller provided them.
  859. $extensions = $validators['file_validate_extensions'][0];
  860. }
  861. else {
  862. // If 'file_validate_extensions' is set and the list is empty then the
  863. // caller wants to allow any extension. In this case we have to remove the
  864. // validator or else it will reject all extensions.
  865. unset($validators['file_validate_extensions']);
  866. }
  867. }
  868. else {
  869. // No validator was provided, so add one using the default list.
  870. // Build a default non-munged safe list for file_munge_filename().
  871. $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
  872. $validators['file_validate_extensions'] = [];
  873. $validators['file_validate_extensions'][0] = $extensions;
  874. }
  875. if (!empty($extensions)) {
  876. // Munge the filename to protect against possible malicious extension
  877. // hiding within an unknown file type (ie: filename.html.foo).
  878. $file->setFilename(file_munge_filename($file->getFilename(), $extensions));
  879. }
  880. // Rename potentially executable files, to help prevent exploits (i.e. will
  881. // rename filename.php.foo and filename.php to filename.php.foo.txt and
  882. // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
  883. // evaluates to TRUE.
  884. if (!\Drupal::config('system.file')->get('allow_insecure_uploads') && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->getFilename()) && (substr($file->getFilename(), -4) != '.txt')) {
  885. $file->setMimeType('text/plain');
  886. // The destination filename will also later be used to create the URI.
  887. $file->setFilename($file->getFilename() . '.txt');
  888. // The .txt extension may not be in the allowed list of extensions. We have
  889. // to add it here or else the file upload will fail.
  890. if (!empty($extensions)) {
  891. $validators['file_validate_extensions'][0] .= ' txt';
  892. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()]));
  893. }
  894. }
  895. // If the destination is not provided, use the temporary directory.
  896. if (empty($destination)) {
  897. $destination = 'temporary://';
  898. }
  899. // Assert that the destination contains a valid stream.
  900. $destination_scheme = file_uri_scheme($destination);
  901. if (!file_stream_wrapper_valid_scheme($destination_scheme)) {
  902. drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]), 'error');
  903. $files[$i] = FALSE;
  904. continue;
  905. }
  906. $file->source = $form_field_name;
  907. // A file URI may already have a trailing slash or look like "public://".
  908. if (substr($destination, -1) != '/') {
  909. $destination .= '/';
  910. }
  911. $file->destination = file_destination($destination . $file->getFilename(), $replace);
  912. // If file_destination() returns FALSE then $replace === FILE_EXISTS_ERROR and
  913. // there's an existing file so we need to bail.
  914. if ($file->destination === FALSE) {
  915. drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', ['%source' => $form_field_name, '%directory' => $destination]), 'error');
  916. $files[$i] = FALSE;
  917. continue;
  918. }
  919. // Add in our check of the file name length.
  920. $validators['file_validate_name_length'] = [];
  921. // Call the validation functions specified by this function's caller.
  922. $errors = file_validate($file, $validators);
  923. // Check for errors.
  924. if (!empty($errors)) {
  925. $message = [
  926. 'error' => [
  927. '#markup' => t('The specified file %name could not be uploaded.', ['%name' => $file->getFilename()]),
  928. ],
  929. 'item_list' => [
  930. '#theme' => 'item_list',
  931. '#items' => $errors,
  932. ],
  933. ];
  934. // @todo Add support for render arrays in drupal_set_message()? See
  935. // https://www.drupal.org/node/2505497.
  936. drupal_set_message(\Drupal::service('renderer')->renderPlain($message), 'error');
  937. $files[$i] = FALSE;
  938. continue;
  939. }
  940. // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
  941. // directory. This overcomes open_basedir restrictions for future file
  942. // operations.
  943. $file->setFileUri($file->destination);
  944. if (!drupal_move_uploaded_file($file_info->getRealPath(), $file->getFileUri())) {
  945. drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error');
  946. \Drupal::logger('file')->notice('Upload error. Could not move uploaded file %file to destination %destination.', ['%file' => $file->getFilename(), '%destination' => $file->getFileUri()]);
  947. $files[$i] = FALSE;
  948. continue;
  949. }
  950. // Set the permissions on the new file.
  951. drupal_chmod($file->getFileUri());
  952. // If we are replacing an existing file re-use its database record.
  953. // @todo Do not create a new entity in order to update it. See
  954. // https://www.drupal.org/node/2241865.
  955. if ($replace == FILE_EXISTS_REPLACE) {
  956. $existing_files = entity_load_multiple_by_properties('file', ['uri' => $file->getFileUri()]);
  957. if (count($existing_files)) {
  958. $existing = reset($existing_files);
  959. $file->fid = $existing->id();
  960. $file->setOriginalId($existing->id());
  961. }
  962. }
  963. // If we made it this far it's safe to record this file in the database.
  964. $file->save();
  965. $files[$i] = $file;
  966. // Allow an anonymous user who creates a non-public file to see it. See
  967. // \Drupal\file\FileAccessControlHandler::checkAccess().
  968. if ($user->isAnonymous() && $destination_scheme !== 'public') {
  969. $session = \Drupal::request()->getSession();
  970. $allowed_temp_files = $session->get('anonymous_allowed_file_ids', []);
  971. $allowed_temp_files[$file->id()] = $file->id();
  972. $session->set('anonymous_allowed_file_ids', $allowed_temp_files);
  973. }
  974. }
  975. // Add files to the cache.
  976. $upload_cache[$form_field_name] = $files;
  977. return isset($delta) ? $files[$delta] : $files;
  978. }
  979. /**
  980. * Determines the preferred upload progress implementation.
  981. *
  982. * @return string|false
  983. * A string indicating which upload progress system is available. Either "apc"
  984. * or "uploadprogress". If neither are available, returns FALSE.
  985. */
  986. function file_progress_implementation() {
  987. static $implementation;
  988. if (!isset($implementation)) {
  989. $implementation = FALSE;
  990. // We prefer the PECL extension uploadprogress because it supports multiple
  991. // simultaneous uploads. APCu only supports one at a time.
  992. if (extension_loaded('uploadprogress')) {
  993. $implementation = 'uploadprogress';
  994. }
  995. elseif (version_compare(PHP_VERSION, '7', '<') && extension_loaded('apc') && ini_get('apc.rfc1867')) {
  996. $implementation = 'apc';
  997. }
  998. }
  999. return $implementation;
  1000. }
  1001. /**
  1002. * Implements hook_ENTITY_TYPE_predelete() for file entities.
  1003. */
  1004. function file_file_predelete(File $file) {
  1005. // @todo Remove references to a file that is in-use.
  1006. }
  1007. /**
  1008. * Implements hook_tokens().
  1009. */
  1010. function file_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  1011. $token_service = \Drupal::token();
  1012. $url_options = ['absolute' => TRUE];
  1013. if (isset($options['langcode'])) {
  1014. $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
  1015. $langcode = $options['langcode'];
  1016. }
  1017. else {
  1018. $langcode = NULL;
  1019. }
  1020. $replacements = [];
  1021. if ($type == 'file' && !empty($data['file'])) {
  1022. /** @var \Drupal\file\FileInterface $file */
  1023. $file = $data['file'];
  1024. foreach ($tokens as $name => $original) {
  1025. switch ($name) {
  1026. // Basic keys and values.
  1027. case 'fid':
  1028. $replacements[$original] = $file->id();
  1029. break;
  1030. // Essential file data
  1031. case 'name':
  1032. $replacements[$original] = $file->getFilename();
  1033. break;
  1034. case 'path':
  1035. $replacements[$original] = $file->getFileUri();
  1036. break;
  1037. case 'mime':
  1038. $replacements[$original] = $file->getMimeType();
  1039. break;
  1040. case 'size':
  1041. $replacements[$original] = format_size($file->getSize());
  1042. break;
  1043. case 'url':
  1044. // Ideally, this would use file_url_transform_relative(), but because
  1045. // tokens are also often used in e-mails, it's better to keep absolute
  1046. // file URLs. The 'url.site' cache context is associated to ensure the
  1047. // correct absolute URL is used in case of a multisite setup.
  1048. $replacements[$original] = file_create_url($file->getFileUri());
  1049. $bubbleable_metadata->addCacheContexts(['url.site']);
  1050. break;
  1051. // These tokens are default variations on the chained tokens handled below.
  1052. case 'created':
  1053. $date_format = DateFormat::load('medium');
  1054. $bubbleable_metadata->addCacheableDependency($date_format);
  1055. $replacements[$original] = format_date($file->getCreatedTime(), 'medium', '', NULL, $langcode);
  1056. break;
  1057. case 'changed':
  1058. $date_format = DateFormat::load('medium');
  1059. $bubbleable_metadata = $bubbleable_metadata->addCacheableDependency($date_format);
  1060. $replacements[$original] = format_date($file->getChangedTime(), 'medium', '', NULL, $langcode);
  1061. break;
  1062. case 'owner':
  1063. $owner = $file->getOwner();
  1064. $bubbleable_metadata->addCacheableDependency($owner);
  1065. $name = $owner->label();
  1066. $replacements[$original] = $name;
  1067. break;
  1068. }
  1069. }
  1070. if ($date_tokens = $token_service->findWithPrefix($tokens, 'created')) {
  1071. $replacements += $token_service->generate('date', $date_tokens, ['date' => $file->getCreatedTime()], $options, $bubbleable_metadata);
  1072. }
  1073. if ($date_tokens = $token_service->findWithPrefix($tokens, 'changed')) {
  1074. $replacements += $token_service->generate('date', $date_tokens, ['date' => $file->getChangedTime()], $options, $bubbleable_metadata);
  1075. }
  1076. if (($owner_tokens = $token_service->findWithPrefix($tokens, 'owner')) && $file->getOwner()) {
  1077. $replacements += $token_service->generate('user', $owner_tokens, ['user' => $file->getOwner()], $options, $bubbleable_metadata);
  1078. }
  1079. }
  1080. return $replacements;
  1081. }
  1082. /**
  1083. * Implements hook_token_info().
  1084. */
  1085. function file_token_info() {
  1086. $types['file'] = [
  1087. 'name' => t("Files"),
  1088. 'description' => t("Tokens related to uploaded files."),
  1089. 'needs-data' => 'file',
  1090. ];
  1091. // File related tokens.
  1092. $file['fid'] = [
  1093. 'name' => t("File ID"),
  1094. 'description' => t("The unique ID of the uploaded file."),
  1095. ];
  1096. $file['name'] = [
  1097. 'name' => t("File name"),
  1098. 'description' => t("The name of the file on disk."),
  1099. ];
  1100. $file['path'] = [
  1101. 'name' => t("Path"),
  1102. 'description' => t("The location of the file relative to Drupal root."),
  1103. ];
  1104. $file['mime'] = [
  1105. 'name' => t("MIME type"),
  1106. 'description' => t("The MIME type of the file."),
  1107. ];
  1108. $file['size'] = [
  1109. 'name' => t("File size"),
  1110. 'description' => t("The size of the file."),
  1111. ];
  1112. $file['url'] = [
  1113. 'name' => t("URL"),
  1114. 'description' => t("The web-accessible URL for the file."),
  1115. ];
  1116. $file['created'] = [
  1117. 'name' => t("Created"),
  1118. 'description' => t("The date the file created."),
  1119. 'type' => 'date',
  1120. ];
  1121. $file['changed'] = [
  1122. 'name' => t("Changed"),
  1123. 'description' => t("The date the file was most recently changed."),
  1124. 'type' => 'date',
  1125. ];
  1126. $file['owner'] = [
  1127. 'name' => t("Owner"),
  1128. 'description' => t("The user who originally uploaded the file."),
  1129. 'type' => 'user',
  1130. ];
  1131. return [
  1132. 'types' => $types,
  1133. 'tokens' => [
  1134. 'file' => $file,
  1135. ],
  1136. ];
  1137. }
  1138. /**
  1139. * Form submission handler for upload / remove buttons of managed_file elements.
  1140. *
  1141. * @see \Drupal\file\Element\ManagedFile::processManagedFile()
  1142. */
  1143. function file_managed_file_submit($form, FormStateInterface $form_state) {
  1144. // Determine whether it was the upload or the remove button that was clicked,
  1145. // and set $element to the managed_file element that contains that button.
  1146. $parents = $form_state->getTriggeringElement()['#array_parents'];
  1147. $button_key = array_pop($parents);
  1148. $element = NestedArray::getValue($form, $parents);
  1149. // No action is needed here for the upload button, because all file uploads on
  1150. // the form are processed by \Drupal\file\Element\ManagedFile::valueCallback()
  1151. // regardless of which button was clicked. Action is needed here for the
  1152. // remove button, because we only remove a file in response to its remove
  1153. // button being clicked.
  1154. if ($button_key == 'remove_button') {
  1155. $fids = array_keys($element['#files']);
  1156. // Get files that will be removed.
  1157. if ($element['#multiple']) {
  1158. $remove_fids = [];
  1159. foreach (Element::children($element) as $name) {
  1160. if (strpos($name, 'file_') === 0 && $element[$name]['selected']['#value']) {
  1161. $remove_fids[] = (int) substr($name, 5);
  1162. }
  1163. }
  1164. $fids = array_diff($fids, $remove_fids);
  1165. }
  1166. else {
  1167. // If we deal with single upload element remove the file and set
  1168. // element's value to empty array (file could not be removed from
  1169. // element if we don't do that).
  1170. $remove_fids = $fids;
  1171. $fids = [];
  1172. }
  1173. foreach ($remove_fids as $fid) {
  1174. // If it's a temporary file we can safely remove it immediately, otherwise
  1175. // it's up to the implementing module to remove usages of files to have them
  1176. // removed.
  1177. if ($element['#files'][$fid] && $element['#files'][$fid]->isTemporary()) {
  1178. $element['#files'][$fid]->delete();
  1179. }
  1180. }
  1181. // Update both $form_state->getValues() and FormState::$input to reflect
  1182. // that the file has been removed, so that the form is rebuilt correctly.
  1183. // $form_state->getValues() must be updated in case additional submit
  1184. // handlers run, and for form building functions that run during the
  1185. // rebuild, such as when the managed_file element is part of a field widget.
  1186. // FormState::$input must be updated so that
  1187. // \Drupal\file\Element\ManagedFile::valueCallback() has correct information
  1188. // during the rebuild.
  1189. $form_state->setValueForElement($element['fids'], implode(' ', $fids));
  1190. NestedArray::setValue($form_state->getUserInput(), $element['fids']['#parents'], implode(' ', $fids));
  1191. }
  1192. // Set the form to rebuild so that $form is correctly updated in response to
  1193. // processing the file removal. Since this function did not change $form_state
  1194. // if the upload button was clicked, a rebuild isn't necessary in that
  1195. // situation and calling $form_state->disableRedirect() would suffice.
  1196. // However, we choose to always rebuild, to keep the form processing workflow
  1197. // consistent between the two buttons.
  1198. $form_state->setRebuild();
  1199. }
  1200. /**
  1201. * Saves any files that have been uploaded into a managed_file element.
  1202. *
  1203. * @param array $element
  1204. * The FAPI element whose values are being saved.
  1205. * @param \Drupal\Core\Form\FormStateInterface $form_state
  1206. * The current state of the form.
  1207. *
  1208. * @return array|false
  1209. * An array of file entities for each file that was saved, keyed by its file
  1210. * ID. Each array element contains a file entity. Function returns FALSE if
  1211. * upload directory could not be created or no files were uploaded.
  1212. */
  1213. function file_managed_file_save_upload($element, FormStateInterface $form_state) {
  1214. $upload_name = implode('_', $element['#parents']);
  1215. $all_files = \Drupal::request()->files->get('files', []);
  1216. if (empty($all_files[$upload_name])) {
  1217. return FALSE;
  1218. }
  1219. $file_upload = $all_files[$upload_name];
  1220. $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
  1221. if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
  1222. \Drupal::logger('file')->notice('The upload directory %directory for the file field %name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', ['%directory' => $destination, '%name' => $element['#field_name']]);
  1223. $form_state->setError($element, t('The file could not be uploaded.'));
  1224. return FALSE;
  1225. }
  1226. // Save attached files to the database.
  1227. $files_uploaded = $element['#multiple'] && count(array_filter($file_upload)) > 0;
  1228. $files_uploaded |= !$element['#multiple'] && !empty($file_upload);
  1229. if ($files_uploaded) {
  1230. if (!$files = _file_save_upload_from_form($element, $form_state)) {
  1231. \Drupal::logger('file')->notice('The file upload failed. %upload', ['%upload' => $upload_name]);
  1232. return [];
  1233. }
  1234. // Value callback expects FIDs to be keys.
  1235. $files = array_filter($files);
  1236. $fids = array_map(function ($file) {
  1237. return $file->id();
  1238. }, $files);
  1239. return empty($files) ? [] : array_combine($fids, $files);
  1240. }
  1241. return [];
  1242. }
  1243. /**
  1244. * Prepares variables for file form widget templates.
  1245. *
  1246. * Default template: file-managed-file.html.twig.
  1247. *
  1248. * @param array $variables
  1249. * An associative array containing:
  1250. * - element: A render element representing the file.
  1251. */
  1252. function template_preprocess_file_managed_file(&$variables) {
  1253. $element = $variables['element'];
  1254. $variables['attributes'] = [];
  1255. if (isset($element['#id'])) {
  1256. $variables['attributes']['id'] = $element['#id'];
  1257. }
  1258. if (!empty($element['#attributes']['class'])) {
  1259. $variables['attributes']['class'] = (array) $element['#attributes']['class'];
  1260. }
  1261. }
  1262. /**
  1263. * Prepares variables for file link templates.
  1264. *
  1265. * Default template: file-link.html.twig.
  1266. *
  1267. * @param array $variables
  1268. * An associative array containing:
  1269. * - file: A file object to which the link will be created.
  1270. * - icon_directory: (optional) A path to a directory of icons to be used for
  1271. * files. Defaults to the value of the "icon.directory" variable.
  1272. * - description: A description to be displayed instead of the filename.
  1273. * - attributes: An associative array of attributes to be placed in the a tag.
  1274. */
  1275. function template_preprocess_file_link(&$variables) {
  1276. $file = $variables['file'];
  1277. $options = [];
  1278. $file_entity = ($file instanceof File) ? $file : File::load($file->fid);
  1279. // @todo Wrap in file_url_transform_relative(). This is currently
  1280. // impossible. As a work-around, we currently add the 'url.site' cache context
  1281. // to ensure different file URLs are generated for different sites in a
  1282. // multisite setup, including HTTP and HTTPS versions of the same site.
  1283. // Fix in https://www.drupal.org/node/2646744.
  1284. $url = file_create_url($file_entity->getFileUri());
  1285. $variables['#cache']['contexts'][] = 'url.site';
  1286. $mime_type = $file->getMimeType();
  1287. // Set options as per anchor format described at
  1288. // http://microformats.org/wiki/file-format-examples
  1289. $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();
  1290. // Use the description as the link text if available.
  1291. if (empty($variables['description'])) {
  1292. $link_text = $file_entity->getFilename();
  1293. }
  1294. else {
  1295. $link_text = $variables['description'];
  1296. $options['attributes']['title'] = $file_entity->getFilename();
  1297. }
  1298. // Classes to add to the file field for icons.
  1299. $classes = [
  1300. 'file',
  1301. // Add a specific class for each and every mime type.
  1302. 'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']),
  1303. // Add a more general class for groups of well known MIME types.
  1304. 'file--' . file_icon_class($mime_type),
  1305. ];
  1306. // Set file classes to the options array.
  1307. $variables['attributes'] = new Attribute($variables['attributes']);
  1308. $variables['attributes']->addClass($classes);
  1309. $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
  1310. }
  1311. /**
  1312. * Gets a class for the icon for a MIME type.
  1313. *
  1314. * @param string $mime_type
  1315. * A MIME type.
  1316. *
  1317. * @return string
  1318. * A class associated with the file.
  1319. */
  1320. function file_icon_class($mime_type) {
  1321. // Search for a group with the files MIME type.
  1322. $generic_mime = (string) file_icon_map($mime_type);
  1323. if (!empty($generic_mime)) {
  1324. return $generic_mime;
  1325. }
  1326. // Use generic icons for each category that provides such icons.
  1327. foreach (['audio', 'image', 'text', 'video'] as $category) {
  1328. if (strpos($mime_type, $category) === 0) {
  1329. return $category;
  1330. }
  1331. }
  1332. // If there's no generic icon for the type the general class.
  1333. return 'general';
  1334. }
  1335. /**
  1336. * Determines the generic icon MIME package based on a file's MIME type.
  1337. *
  1338. * @param string $mime_type
  1339. * A MIME type.
  1340. *
  1341. * @return string|false
  1342. * The generic icon MIME package expected for this file.
  1343. */
  1344. function file_icon_map($mime_type) {
  1345. switch ($mime_type) {
  1346. // Word document types.
  1347. case 'application/msword':
  1348. case 'application/vnd.ms-word.document.macroEnabled.12':
  1349. case 'application/vnd.oasis.opendocument.text':
  1350. case 'application/vnd.oasis.opendocument.text-template':
  1351. case 'application/vnd.oasis.opendocument.text-master':
  1352. case 'application/vnd.oasis.opendocument.text-web':
  1353. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  1354. case 'application/vnd.stardivision.writer':
  1355. case 'application/vnd.sun.xml.writer':
  1356. case 'application/vnd.sun.xml.writer.template':
  1357. case 'application/vnd.sun.xml.writer.global':
  1358. case 'application/vnd.wordperfect':
  1359. case 'application/x-abiword':
  1360. case 'application/x-applix-word':
  1361. case 'application/x-kword':
  1362. case 'application/x-kword-crypt':
  1363. return 'x-office-document';
  1364. // Spreadsheet document types.
  1365. case 'application/vnd.ms-excel':
  1366. case 'application/vnd.ms-excel.sheet.macroEnabled.12':
  1367. case 'application/vnd.oasis.opendocument.spreadsheet':
  1368. case 'application/vnd.oasis.opendocument.spreadsheet-template':
  1369. case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
  1370. case 'application/vnd.stardivision.calc':
  1371. case 'application/vnd.sun.xml.calc':
  1372. case 'application/vnd.sun.xml.calc.template':
  1373. case 'application/vnd.lotus-1-2-3':
  1374. case 'application/x-applix-spreadsheet':
  1375. case 'application/x-gnumeric':
  1376. case 'application/x-kspread':
  1377. case 'application/x-kspread-crypt':
  1378. return 'x-office-spreadsheet';
  1379. // Presentation document types.
  1380. case 'application/vnd.ms-powerpoint':
  1381. case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
  1382. case 'application/vnd.oasis.opendocument.presentation':
  1383. case 'application/vnd.oasis.opendocument.presentation-template':
  1384. case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
  1385. case 'application/vnd.stardivision.impress':
  1386. case 'application/vnd.sun.xml.impress':
  1387. case 'application/vnd.sun.xml.impress.template':
  1388. case 'application/x-kpresenter':
  1389. return 'x-office-presentation';
  1390. // Compressed archive types.
  1391. case 'application/zip':
  1392. case 'application/x-zip':
  1393. case 'application/stuffit':
  1394. case 'application/x-stuffit':
  1395. case 'application/x-7z-compressed':
  1396. case 'application/x-ace':
  1397. case 'application/x-arj':
  1398. case 'application/x-bzip':
  1399. case 'application/x-bzip-compressed-tar':
  1400. case 'application/x-compress':
  1401. case 'application/x-compressed-tar':
  1402. case 'application/x-cpio-compressed':
  1403. case 'application/x-deb':
  1404. case 'application/x-gzip':
  1405. case 'application/x-java-archive':
  1406. case 'application/x-lha':
  1407. case 'application/x-lhz':
  1408. case 'application/x-lzop':
  1409. case 'application/x-rar':
  1410. case 'application/x-rpm':
  1411. case 'application/x-tzo':
  1412. case 'application/x-tar':
  1413. case 'application/x-tarz':
  1414. case 'application/x-tgz':
  1415. return 'package-x-generic';
  1416. // Script file types.
  1417. case 'application/ecmascript':
  1418. case 'application/javascript':
  1419. case 'application/mathematica':
  1420. case 'application/vnd.mozilla.xul+xml':
  1421. case 'application/x-asp':
  1422. case 'application/x-awk':
  1423. case 'application/x-cgi':
  1424. case 'application/x-csh':
  1425. case 'application/x-m4':
  1426. case 'application/x-perl':
  1427. case 'application/x-php':
  1428. case 'application/x-ruby':
  1429. case 'application/x-shellscript':
  1430. case 'text/vnd.wap.wmlscript':
  1431. case 'text/x-emacs-lisp':
  1432. case 'text/x-haskell':
  1433. case 'text/x-literate-haskell':
  1434. case 'text/x-lua':
  1435. case 'text/x-makefile':
  1436. case 'text/x-matlab':
  1437. case 'text/x-python':
  1438. case 'text/x-sql':
  1439. case 'text/x-tcl':
  1440. return 'text-x-script';
  1441. // HTML aliases.
  1442. case 'application/xhtml+xml':
  1443. return 'text-html';
  1444. // Executable types.
  1445. case 'application/x-macbinary':
  1446. case 'application/x-ms-dos-executable':
  1447. case 'application/x-pef-executable':
  1448. return 'application-x-executable';
  1449. // Acrobat types
  1450. case 'application/pdf':
  1451. case 'application/x-pdf':
  1452. case 'applications/vnd.pdf':
  1453. case 'text/pdf':
  1454. case 'text/x-pdf':
  1455. return 'application-pdf';
  1456. default:
  1457. return FALSE;
  1458. }
  1459. }
  1460. /**
  1461. * Retrieves a list of references to a file.
  1462. *
  1463. * @param \Drupal\file\FileInterface $file
  1464. * A file entity.
  1465. * @param \Drupal\Core\Field\FieldDefinitionInterface|null $field
  1466. * (optional) A field definition to be used for this check. If given,
  1467. * limits the reference check to the given field. Defaults to NULL.
  1468. * @param int $age
  1469. * (optional) A constant that specifies which references to count. Use
  1470. * EntityStorageInterface::FIELD_LOAD_REVISION (the default) to retrieve all
  1471. * references within all revisions or
  1472. * EntityStorageInterface::FIELD_LOAD_CURRENT to retrieve references only in
  1473. * the current revisions of all entities that have references to this file.
  1474. * @param string $field_type
  1475. * (optional) The name of a field type. If given, limits the reference check
  1476. * to fields of the given type. If both $field and $field_type are given but
  1477. * $field is not the same type as $field_type, an empty array will be
  1478. * returned. Defaults to 'file'.
  1479. *
  1480. * @return array
  1481. * A multidimensional array. The keys are field_name, entity_type,
  1482. * entity_id and the value is an entity referencing this file.
  1483. *
  1484. * @ingroup file
  1485. */
  1486. function file_get_file_references(FileInterface $file, FieldDefinitionInterface $field = NULL, $age = EntityStorageInterface::FIELD_LOAD_REVISION, $field_type = 'file') {
  1487. $references = &drupal_static(__FUNCTION__, []);
  1488. $field_columns = &drupal_static(__FUNCTION__ . ':field_columns', []);
  1489. // Fill the static cache, disregard $field and $field_type for now.
  1490. if (!isset($references[$file->id()][$age])) {
  1491. $references[$file->id()][$age] = [];
  1492. $usage_list = \Drupal::service('file.usage')->listUsage($file);
  1493. $file_usage_list = isset($usage_list['file']) ? $usage_list['file'] : [];
  1494. foreach ($file_usage_list as $entity_type_id => $entity_ids) {
  1495. $entities = \Drupal::entityTypeManager()
  1496. ->getStorage($entity_type_id)->loadMultiple(array_keys($entity_ids));
  1497. foreach ($entities as $entity) {
  1498. $bundle = $entity->bundle();
  1499. // We need to find file fields for this entity type and bundle.
  1500. if (!isset($file_fields[$entity_type_id][$bundle])) {
  1501. $file_fields[$entity_type_id][$bundle] = [];
  1502. // This contains the possible field names.
  1503. foreach ($entity->getFieldDefinitions() as $field_name => $field_definition) {
  1504. // If this is the first time this field type is seen, check
  1505. // whether it references files.
  1506. if (!isset($field_columns[$field_definition->getType()])) {
  1507. $field_columns[$field_definition->getType()] = file_field_find_file_reference_column($field_definition);
  1508. }
  1509. // If the field type does reference files then record it.
  1510. if ($field_columns[$field_definition->getType()]) {
  1511. $file_fields[$entity_type_id][$bundle][$field_name] = $field_columns[$field_definition->getType()];
  1512. }
  1513. }
  1514. }
  1515. foreach ($file_fields[$entity_type_id][$bundle] as $field_name => $field_column) {
  1516. // Iterate over the field items to find the referenced file and field
  1517. // name. This will fail if the usage checked is in a non-current
  1518. // revision because field items are from the current
  1519. // revision.
  1520. // We also iterate over all translations because a file can be linked
  1521. // to a language other than the default.
  1522. foreach ($entity->getTranslationLanguages() as $langcode => $language) {
  1523. foreach ($entity->getTranslation($langcode)->get($field_name) as $item) {
  1524. if ($file->id() == $item->{$field_column}) {
  1525. $references[$file->id()][$age][$field_name][$entity_type_id][$entity->id()] = $entity;
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. }
  1531. }
  1532. }
  1533. }
  1534. $return = $references[$file->id()][$age];
  1535. // Filter the static cache down to the requested entries. The usual static
  1536. // cache is very small so this will be very fast.
  1537. if ($field || $field_type) {
  1538. foreach ($return as $field_name => $data) {
  1539. foreach (array_keys($data) as $entity_type_id) {
  1540. $field_storage_definitions = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type_id);
  1541. $current_field = $field_storage_definitions[$field_name];
  1542. if (($field_type && $current_field->getType() != $field_type) || ($field && $field->uuid() != $current_field->uuid())) {
  1543. unset($return[$field_name][$entity_type_id]);
  1544. }
  1545. }
  1546. }
  1547. }
  1548. return $return;
  1549. }
  1550. /**
  1551. * Formats human-readable version of file status.
  1552. *
  1553. * @param int|null $choice
  1554. * (optional) An integer status code. If not set, all statuses are returned.
  1555. * Defaults to NULL.
  1556. *
  1557. * @return \Drupal\Core\StringTranslation\TranslatableMarkup|\Drupal\Core\StringTranslation\TranslatableMarkup[]
  1558. * An array of file statuses or a specified status if $choice is set.
  1559. */
  1560. function _views_file_status($choice = NULL) {
  1561. $status = [
  1562. 0 => t('Temporary'),
  1563. FILE_STATUS_PERMANENT => t('Permanent'),
  1564. ];
  1565. if (isset($choice)) {
  1566. return isset($status[$choice]) ? $status[$choice] : t('Unknown');
  1567. }
  1568. return $status;
  1569. }