file.module 62 KB

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