file.module 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. }
  835. // Add files to the cache.
  836. $upload_cache[$form_field_name] = $files;
  837. return isset($delta) ? $files[$delta] : $files;
  838. }
  839. /**
  840. * Determines the preferred upload progress implementation.
  841. *
  842. * @return string|false
  843. * A string indicating which upload progress system is available. Either "apc"
  844. * or "uploadprogress". If neither are available, returns FALSE.
  845. */
  846. function file_progress_implementation() {
  847. static $implementation;
  848. if (!isset($implementation)) {
  849. $implementation = FALSE;
  850. // We prefer the PECL extension uploadprogress because it supports multiple
  851. // simultaneous uploads. APCu only supports one at a time.
  852. if (extension_loaded('uploadprogress')) {
  853. $implementation = 'uploadprogress';
  854. }
  855. elseif (version_compare(PHP_VERSION, '7', '<') && extension_loaded('apc') && ini_get('apc.rfc1867')) {
  856. $implementation = 'apc';
  857. }
  858. }
  859. return $implementation;
  860. }
  861. /**
  862. * Implements hook_ENTITY_TYPE_predelete() for file entities.
  863. */
  864. function file_file_predelete(File $file) {
  865. // @todo Remove references to a file that is in-use.
  866. }
  867. /**
  868. * Implements hook_tokens().
  869. */
  870. function file_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  871. $token_service = \Drupal::token();
  872. $url_options = ['absolute' => TRUE];
  873. if (isset($options['langcode'])) {
  874. $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
  875. $langcode = $options['langcode'];
  876. }
  877. else {
  878. $langcode = NULL;
  879. }
  880. $replacements = [];
  881. if ($type == 'file' && !empty($data['file'])) {
  882. /** @var \Drupal\file\FileInterface $file */
  883. $file = $data['file'];
  884. foreach ($tokens as $name => $original) {
  885. switch ($name) {
  886. // Basic keys and values.
  887. case 'fid':
  888. $replacements[$original] = $file->id();
  889. break;
  890. // Essential file data
  891. case 'name':
  892. $replacements[$original] = $file->getFilename();
  893. break;
  894. case 'path':
  895. $replacements[$original] = $file->getFileUri();
  896. break;
  897. case 'mime':
  898. $replacements[$original] = $file->getMimeType();
  899. break;
  900. case 'size':
  901. $replacements[$original] = format_size($file->getSize());
  902. break;
  903. case 'url':
  904. // Ideally, this would use file_url_transform_relative(), but because
  905. // tokens are also often used in e-mails, it's better to keep absolute
  906. // file URLs. The 'url.site' cache context is associated to ensure the
  907. // correct absolute URL is used in case of a multisite setup.
  908. $replacements[$original] = file_create_url($file->getFileUri());
  909. $bubbleable_metadata->addCacheContexts(['url.site']);
  910. break;
  911. // These tokens are default variations on the chained tokens handled below.
  912. case 'created':
  913. $date_format = DateFormat::load('medium');
  914. $bubbleable_metadata->addCacheableDependency($date_format);
  915. $replacements[$original] = format_date($file->getCreatedTime(), 'medium', '', NULL, $langcode);
  916. break;
  917. case 'changed':
  918. $date_format = DateFormat::load('medium');
  919. $bubbleable_metadata = $bubbleable_metadata->addCacheableDependency($date_format);
  920. $replacements[$original] = format_date($file->getChangedTime(), 'medium', '', NULL, $langcode);
  921. break;
  922. case 'owner':
  923. $owner = $file->getOwner();
  924. $bubbleable_metadata->addCacheableDependency($owner);
  925. $name = $owner->label();
  926. $replacements[$original] = $name;
  927. break;
  928. }
  929. }
  930. if ($date_tokens = $token_service->findWithPrefix($tokens, 'created')) {
  931. $replacements += $token_service->generate('date', $date_tokens, ['date' => $file->getCreatedTime()], $options, $bubbleable_metadata);
  932. }
  933. if ($date_tokens = $token_service->findWithPrefix($tokens, 'changed')) {
  934. $replacements += $token_service->generate('date', $date_tokens, ['date' => $file->getChangedTime()], $options, $bubbleable_metadata);
  935. }
  936. if (($owner_tokens = $token_service->findWithPrefix($tokens, 'owner')) && $file->getOwner()) {
  937. $replacements += $token_service->generate('user', $owner_tokens, ['user' => $file->getOwner()], $options, $bubbleable_metadata);
  938. }
  939. }
  940. return $replacements;
  941. }
  942. /**
  943. * Implements hook_token_info().
  944. */
  945. function file_token_info() {
  946. $types['file'] = [
  947. 'name' => t("Files"),
  948. 'description' => t("Tokens related to uploaded files."),
  949. 'needs-data' => 'file',
  950. ];
  951. // File related tokens.
  952. $file['fid'] = [
  953. 'name' => t("File ID"),
  954. 'description' => t("The unique ID of the uploaded file."),
  955. ];
  956. $file['name'] = [
  957. 'name' => t("File name"),
  958. 'description' => t("The name of the file on disk."),
  959. ];
  960. $file['path'] = [
  961. 'name' => t("Path"),
  962. 'description' => t("The location of the file relative to Drupal root."),
  963. ];
  964. $file['mime'] = [
  965. 'name' => t("MIME type"),
  966. 'description' => t("The MIME type of the file."),
  967. ];
  968. $file['size'] = [
  969. 'name' => t("File size"),
  970. 'description' => t("The size of the file."),
  971. ];
  972. $file['url'] = [
  973. 'name' => t("URL"),
  974. 'description' => t("The web-accessible URL for the file."),
  975. ];
  976. $file['created'] = [
  977. 'name' => t("Created"),
  978. 'description' => t("The date the file created."),
  979. 'type' => 'date',
  980. ];
  981. $file['changed'] = [
  982. 'name' => t("Changed"),
  983. 'description' => t("The date the file was most recently changed."),
  984. 'type' => 'date',
  985. ];
  986. $file['owner'] = [
  987. 'name' => t("Owner"),
  988. 'description' => t("The user who originally uploaded the file."),
  989. 'type' => 'user',
  990. ];
  991. return [
  992. 'types' => $types,
  993. 'tokens' => [
  994. 'file' => $file,
  995. ],
  996. ];
  997. }
  998. /**
  999. * Form submission handler for upload / remove buttons of managed_file elements.
  1000. *
  1001. * @see \Drupal\file\Element\ManagedFile::processManagedFile()
  1002. */
  1003. function file_managed_file_submit($form, FormStateInterface $form_state) {
  1004. // Determine whether it was the upload or the remove button that was clicked,
  1005. // and set $element to the managed_file element that contains that button.
  1006. $parents = $form_state->getTriggeringElement()['#array_parents'];
  1007. $button_key = array_pop($parents);
  1008. $element = NestedArray::getValue($form, $parents);
  1009. // No action is needed here for the upload button, because all file uploads on
  1010. // the form are processed by \Drupal\file\Element\ManagedFile::valueCallback()
  1011. // regardless of which button was clicked. Action is needed here for the
  1012. // remove button, because we only remove a file in response to its remove
  1013. // button being clicked.
  1014. if ($button_key == 'remove_button') {
  1015. $fids = array_keys($element['#files']);
  1016. // Get files that will be removed.
  1017. if ($element['#multiple']) {
  1018. $remove_fids = [];
  1019. foreach (Element::children($element) as $name) {
  1020. if (strpos($name, 'file_') === 0 && $element[$name]['selected']['#value']) {
  1021. $remove_fids[] = (int) substr($name, 5);
  1022. }
  1023. }
  1024. $fids = array_diff($fids, $remove_fids);
  1025. }
  1026. else {
  1027. // If we deal with single upload element remove the file and set
  1028. // element's value to empty array (file could not be removed from
  1029. // element if we don't do that).
  1030. $remove_fids = $fids;
  1031. $fids = [];
  1032. }
  1033. foreach ($remove_fids as $fid) {
  1034. // If it's a temporary file we can safely remove it immediately, otherwise
  1035. // it's up to the implementing module to remove usages of files to have them
  1036. // removed.
  1037. if ($element['#files'][$fid] && $element['#files'][$fid]->isTemporary()) {
  1038. $element['#files'][$fid]->delete();
  1039. }
  1040. }
  1041. // Update both $form_state->getValues() and FormState::$input to reflect
  1042. // that the file has been removed, so that the form is rebuilt correctly.
  1043. // $form_state->getValues() must be updated in case additional submit
  1044. // handlers run, and for form building functions that run during the
  1045. // rebuild, such as when the managed_file element is part of a field widget.
  1046. // FormState::$input must be updated so that
  1047. // \Drupal\file\Element\ManagedFile::valueCallback() has correct information
  1048. // during the rebuild.
  1049. $form_state->setValueForElement($element['fids'], implode(' ', $fids));
  1050. NestedArray::setValue($form_state->getUserInput(), $element['fids']['#parents'], implode(' ', $fids));
  1051. }
  1052. // Set the form to rebuild so that $form is correctly updated in response to
  1053. // processing the file removal. Since this function did not change $form_state
  1054. // if the upload button was clicked, a rebuild isn't necessary in that
  1055. // situation and calling $form_state->disableRedirect() would suffice.
  1056. // However, we choose to always rebuild, to keep the form processing workflow
  1057. // consistent between the two buttons.
  1058. $form_state->setRebuild();
  1059. }
  1060. /**
  1061. * Saves any files that have been uploaded into a managed_file element.
  1062. *
  1063. * @param array $element
  1064. * The FAPI element whose values are being saved.
  1065. * @param \Drupal\Core\Form\FormStateInterface $form_state
  1066. * The current state of the form.
  1067. *
  1068. * @return array|false
  1069. * An array of file entities for each file that was saved, keyed by its file
  1070. * ID. Each array element contains a file entity. Function returns FALSE if
  1071. * upload directory could not be created or no files were uploaded.
  1072. */
  1073. function file_managed_file_save_upload($element, FormStateInterface $form_state) {
  1074. $upload_name = implode('_', $element['#parents']);
  1075. $all_files = \Drupal::request()->files->get('files', []);
  1076. if (empty($all_files[$upload_name])) {
  1077. return FALSE;
  1078. }
  1079. $file_upload = $all_files[$upload_name];
  1080. $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
  1081. if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
  1082. \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']]);
  1083. $form_state->setError($element, t('The file could not be uploaded.'));
  1084. return FALSE;
  1085. }
  1086. // Save attached files to the database.
  1087. $files_uploaded = $element['#multiple'] && count(array_filter($file_upload)) > 0;
  1088. $files_uploaded |= !$element['#multiple'] && !empty($file_upload);
  1089. if ($files_uploaded) {
  1090. if (!$files = file_save_upload($upload_name, $element['#upload_validators'], $destination)) {
  1091. \Drupal::logger('file')->notice('The file upload failed. %upload', ['%upload' => $upload_name]);
  1092. $form_state->setError($element, t('Files in the @name field were unable to be uploaded.', ['@name' => $element['#title']]));
  1093. return [];
  1094. }
  1095. // Value callback expects FIDs to be keys.
  1096. $files = array_filter($files);
  1097. $fids = array_map(function($file) { return $file->id(); }, $files);
  1098. return empty($files) ? [] : array_combine($fids, $files);
  1099. }
  1100. return [];
  1101. }
  1102. /**
  1103. * Prepares variables for file form widget templates.
  1104. *
  1105. * Default template: file-managed-file.html.twig.
  1106. *
  1107. * @param array $variables
  1108. * An associative array containing:
  1109. * - element: A render element representing the file.
  1110. */
  1111. function template_preprocess_file_managed_file(&$variables) {
  1112. $element = $variables['element'];
  1113. $variables['attributes'] = [];
  1114. if (isset($element['#id'])) {
  1115. $variables['attributes']['id'] = $element['#id'];
  1116. }
  1117. if (!empty($element['#attributes']['class'])) {
  1118. $variables['attributes']['class'] = (array) $element['#attributes']['class'];
  1119. }
  1120. }
  1121. /**
  1122. * Prepares variables for file link templates.
  1123. *
  1124. * Default template: file-link.html.twig.
  1125. *
  1126. * @param array $variables
  1127. * An associative array containing:
  1128. * - file: A file object to which the link will be created.
  1129. * - icon_directory: (optional) A path to a directory of icons to be used for
  1130. * files. Defaults to the value of the "icon.directory" variable.
  1131. * - description: A description to be displayed instead of the filename.
  1132. * - attributes: An associative array of attributes to be placed in the a tag.
  1133. */
  1134. function template_preprocess_file_link(&$variables) {
  1135. $file = $variables['file'];
  1136. $options = [];
  1137. $file_entity = ($file instanceof File) ? $file : File::load($file->fid);
  1138. // @todo Wrap in file_url_transform_relative(). This is currently
  1139. // impossible. As a work-around, we currently add the 'url.site' cache context
  1140. // to ensure different file URLs are generated for different sites in a
  1141. // multisite setup, including HTTP and HTTPS versions of the same site.
  1142. // Fix in https://www.drupal.org/node/2646744.
  1143. $url = file_create_url($file_entity->getFileUri());
  1144. $variables['#cache']['contexts'][] = 'url.site';
  1145. $mime_type = $file->getMimeType();
  1146. // Set options as per anchor format described at
  1147. // http://microformats.org/wiki/file-format-examples
  1148. $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();
  1149. // Use the description as the link text if available.
  1150. if (empty($variables['description'])) {
  1151. $link_text = $file_entity->getFilename();
  1152. }
  1153. else {
  1154. $link_text = $variables['description'];
  1155. $options['attributes']['title'] = $file_entity->getFilename();
  1156. }
  1157. // Classes to add to the file field for icons.
  1158. $classes = [
  1159. 'file',
  1160. // Add a specific class for each and every mime type.
  1161. 'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']),
  1162. // Add a more general class for groups of well known MIME types.
  1163. 'file--' . file_icon_class($mime_type),
  1164. ];
  1165. // Set file classes to the options array.
  1166. $variables['attributes'] = new Attribute($variables['attributes']);
  1167. $variables['attributes']->addClass($classes);
  1168. $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
  1169. }
  1170. /**
  1171. * Gets a class for the icon for a MIME type.
  1172. *
  1173. * @param string $mime_type
  1174. * A MIME type.
  1175. *
  1176. * @return string
  1177. * A class associated with the file.
  1178. */
  1179. function file_icon_class($mime_type) {
  1180. // Search for a group with the files MIME type.
  1181. $generic_mime = (string) file_icon_map($mime_type);
  1182. if (!empty($generic_mime)) {
  1183. return $generic_mime;
  1184. }
  1185. // Use generic icons for each category that provides such icons.
  1186. foreach (['audio', 'image', 'text', 'video'] as $category) {
  1187. if (strpos($mime_type, $category) === 0) {
  1188. return $category;
  1189. }
  1190. }
  1191. // If there's no generic icon for the type the general class.
  1192. return 'general';
  1193. }
  1194. /**
  1195. * Determines the generic icon MIME package based on a file's MIME type.
  1196. *
  1197. * @param string $mime_type
  1198. * A MIME type.
  1199. *
  1200. * @return string|false
  1201. * The generic icon MIME package expected for this file.
  1202. */
  1203. function file_icon_map($mime_type) {
  1204. switch ($mime_type) {
  1205. // Word document types.
  1206. case 'application/msword':
  1207. case 'application/vnd.ms-word.document.macroEnabled.12':
  1208. case 'application/vnd.oasis.opendocument.text':
  1209. case 'application/vnd.oasis.opendocument.text-template':
  1210. case 'application/vnd.oasis.opendocument.text-master':
  1211. case 'application/vnd.oasis.opendocument.text-web':
  1212. case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
  1213. case 'application/vnd.stardivision.writer':
  1214. case 'application/vnd.sun.xml.writer':
  1215. case 'application/vnd.sun.xml.writer.template':
  1216. case 'application/vnd.sun.xml.writer.global':
  1217. case 'application/vnd.wordperfect':
  1218. case 'application/x-abiword':
  1219. case 'application/x-applix-word':
  1220. case 'application/x-kword':
  1221. case 'application/x-kword-crypt':
  1222. return 'x-office-document';
  1223. // Spreadsheet document types.
  1224. case 'application/vnd.ms-excel':
  1225. case 'application/vnd.ms-excel.sheet.macroEnabled.12':
  1226. case 'application/vnd.oasis.opendocument.spreadsheet':
  1227. case 'application/vnd.oasis.opendocument.spreadsheet-template':
  1228. case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
  1229. case 'application/vnd.stardivision.calc':
  1230. case 'application/vnd.sun.xml.calc':
  1231. case 'application/vnd.sun.xml.calc.template':
  1232. case 'application/vnd.lotus-1-2-3':
  1233. case 'application/x-applix-spreadsheet':
  1234. case 'application/x-gnumeric':
  1235. case 'application/x-kspread':
  1236. case 'application/x-kspread-crypt':
  1237. return 'x-office-spreadsheet';
  1238. // Presentation document types.
  1239. case 'application/vnd.ms-powerpoint':
  1240. case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
  1241. case 'application/vnd.oasis.opendocument.presentation':
  1242. case 'application/vnd.oasis.opendocument.presentation-template':
  1243. case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
  1244. case 'application/vnd.stardivision.impress':
  1245. case 'application/vnd.sun.xml.impress':
  1246. case 'application/vnd.sun.xml.impress.template':
  1247. case 'application/x-kpresenter':
  1248. return 'x-office-presentation';
  1249. // Compressed archive types.
  1250. case 'application/zip':
  1251. case 'application/x-zip':
  1252. case 'application/stuffit':
  1253. case 'application/x-stuffit':
  1254. case 'application/x-7z-compressed':
  1255. case 'application/x-ace':
  1256. case 'application/x-arj':
  1257. case 'application/x-bzip':
  1258. case 'application/x-bzip-compressed-tar':
  1259. case 'application/x-compress':
  1260. case 'application/x-compressed-tar':
  1261. case 'application/x-cpio-compressed':
  1262. case 'application/x-deb':
  1263. case 'application/x-gzip':
  1264. case 'application/x-java-archive':
  1265. case 'application/x-lha':
  1266. case 'application/x-lhz':
  1267. case 'application/x-lzop':
  1268. case 'application/x-rar':
  1269. case 'application/x-rpm':
  1270. case 'application/x-tzo':
  1271. case 'application/x-tar':
  1272. case 'application/x-tarz':
  1273. case 'application/x-tgz':
  1274. return 'package-x-generic';
  1275. // Script file types.
  1276. case 'application/ecmascript':
  1277. case 'application/javascript':
  1278. case 'application/mathematica':
  1279. case 'application/vnd.mozilla.xul+xml':
  1280. case 'application/x-asp':
  1281. case 'application/x-awk':
  1282. case 'application/x-cgi':
  1283. case 'application/x-csh':
  1284. case 'application/x-m4':
  1285. case 'application/x-perl':
  1286. case 'application/x-php':
  1287. case 'application/x-ruby':
  1288. case 'application/x-shellscript':
  1289. case 'text/vnd.wap.wmlscript':
  1290. case 'text/x-emacs-lisp':
  1291. case 'text/x-haskell':
  1292. case 'text/x-literate-haskell':
  1293. case 'text/x-lua':
  1294. case 'text/x-makefile':
  1295. case 'text/x-matlab':
  1296. case 'text/x-python':
  1297. case 'text/x-sql':
  1298. case 'text/x-tcl':
  1299. return 'text-x-script';
  1300. // HTML aliases.
  1301. case 'application/xhtml+xml':
  1302. return 'text-html';
  1303. // Executable types.
  1304. case 'application/x-macbinary':
  1305. case 'application/x-ms-dos-executable':
  1306. case 'application/x-pef-executable':
  1307. return 'application-x-executable';
  1308. // Acrobat types
  1309. case 'application/pdf':
  1310. case 'application/x-pdf':
  1311. case 'applications/vnd.pdf':
  1312. case 'text/pdf':
  1313. case 'text/x-pdf':
  1314. return 'application-pdf';
  1315. default:
  1316. return FALSE;
  1317. }
  1318. }
  1319. /**
  1320. * Retrieves a list of references to a file.
  1321. *
  1322. * @param \Drupal\file\FileInterface $file
  1323. * A file entity.
  1324. * @param \Drupal\Core\Field\FieldDefinitionInterface|null $field
  1325. * (optional) A field definition to be used for this check. If given,
  1326. * limits the reference check to the given field. Defaults to NULL.
  1327. * @param int $age
  1328. * (optional) A constant that specifies which references to count. Use
  1329. * EntityStorageInterface::FIELD_LOAD_REVISION (the default) to retrieve all
  1330. * references within all revisions or
  1331. * EntityStorageInterface::FIELD_LOAD_CURRENT to retrieve references only in
  1332. * the current revisions of all entities that have references to this file.
  1333. * @param string $field_type
  1334. * (optional) The name of a field type. If given, limits the reference check
  1335. * to fields of the given type. If both $field and $field_type are given but
  1336. * $field is not the same type as $field_type, an empty array will be
  1337. * returned. Defaults to 'file'.
  1338. *
  1339. * @return array
  1340. * A multidimensional array. The keys are field_name, entity_type,
  1341. * entity_id and the value is an entity referencing this file.
  1342. *
  1343. * @ingroup file
  1344. */
  1345. function file_get_file_references(FileInterface $file, FieldDefinitionInterface $field = NULL, $age = EntityStorageInterface::FIELD_LOAD_REVISION, $field_type = 'file') {
  1346. $references = &drupal_static(__FUNCTION__, []);
  1347. $field_columns = &drupal_static(__FUNCTION__ . ':field_columns', []);
  1348. // Fill the static cache, disregard $field and $field_type for now.
  1349. if (!isset($references[$file->id()][$age])) {
  1350. $references[$file->id()][$age] = [];
  1351. $usage_list = \Drupal::service('file.usage')->listUsage($file);
  1352. $file_usage_list = isset($usage_list['file']) ? $usage_list['file'] : [];
  1353. foreach ($file_usage_list as $entity_type_id => $entity_ids) {
  1354. $entities = \Drupal::entityTypeManager()
  1355. ->getStorage($entity_type_id)->loadMultiple(array_keys($entity_ids));
  1356. foreach ($entities as $entity) {
  1357. $bundle = $entity->bundle();
  1358. // We need to find file fields for this entity type and bundle.
  1359. if (!isset($file_fields[$entity_type_id][$bundle])) {
  1360. $file_fields[$entity_type_id][$bundle] = [];
  1361. // This contains the possible field names.
  1362. foreach ($entity->getFieldDefinitions() as $field_name => $field_definition) {
  1363. // If this is the first time this field type is seen, check
  1364. // whether it references files.
  1365. if (!isset($field_columns[$field_definition->getType()])) {
  1366. $field_columns[$field_definition->getType()] = file_field_find_file_reference_column($field_definition);
  1367. }
  1368. // If the field type does reference files then record it.
  1369. if ($field_columns[$field_definition->getType()]) {
  1370. $file_fields[$entity_type_id][$bundle][$field_name] = $field_columns[$field_definition->getType()];
  1371. }
  1372. }
  1373. }
  1374. foreach ($file_fields[$entity_type_id][$bundle] as $field_name => $field_column) {
  1375. // Iterate over the field items to find the referenced file and field
  1376. // name. This will fail if the usage checked is in a non-current
  1377. // revision because field items are from the current
  1378. // revision.
  1379. // We also iterate over all translations because a file can be linked
  1380. // to a language other than the default.
  1381. foreach ($entity->getTranslationLanguages() as $langcode => $language) {
  1382. foreach ($entity->getTranslation($langcode)->get($field_name) as $item) {
  1383. if ($file->id() == $item->{$field_column}) {
  1384. $references[$file->id()][$age][$field_name][$entity_type_id][$entity->id()] = $entity;
  1385. break;
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. }
  1392. }
  1393. $return = $references[$file->id()][$age];
  1394. // Filter the static cache down to the requested entries. The usual static
  1395. // cache is very small so this will be very fast.
  1396. if ($field || $field_type) {
  1397. foreach ($return as $field_name => $data) {
  1398. foreach (array_keys($data) as $entity_type_id) {
  1399. $field_storage_definitions = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type_id);
  1400. $current_field = $field_storage_definitions[$field_name];
  1401. if (($field_type && $current_field->getType() != $field_type) || ($field && $field->uuid() != $current_field->uuid())) {
  1402. unset($return[$field_name][$entity_type_id]);
  1403. }
  1404. }
  1405. }
  1406. }
  1407. return $return;
  1408. }
  1409. /**
  1410. * Formats human-readable version of file status.
  1411. *
  1412. * @param int|null $choice
  1413. * (optional) An integer status code. If not set, all statuses are returned.
  1414. * Defaults to NULL.
  1415. *
  1416. * @return \Drupal\Core\StringTranslation\TranslatableMarkup|\Drupal\Core\StringTranslation\TranslatableMarkup[]
  1417. * An array of file statuses or a specified status if $choice is set.
  1418. */
  1419. function _views_file_status($choice = NULL) {
  1420. $status = [
  1421. 0 => t('Temporary'),
  1422. FILE_STATUS_PERMANENT => t('Permanent'),
  1423. ];
  1424. if (isset($choice)) {
  1425. return isset($status[$choice]) ? $status[$choice] : t('Unknown');
  1426. }
  1427. return $status;
  1428. }