file.api.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * @file
  4. * Hooks for file module.
  5. */
  6. /**
  7. * @addtogroup hooks
  8. * @{
  9. */
  10. /**
  11. * Check that files meet a given criteria.
  12. *
  13. * This hook lets modules perform additional validation on files. They're able
  14. * to report a failure by returning one or more error messages.
  15. *
  16. * @param \Drupal\file\FileInterface $file
  17. * The file entity being validated.
  18. *
  19. * @return array
  20. * An array of error messages. If there are no problems with the file return
  21. * an empty array.
  22. *
  23. * @see file_validate()
  24. */
  25. function hook_file_validate(Drupal\file\FileInterface $file) {
  26. $errors = [];
  27. if (!$file->getFilename()) {
  28. $errors[] = t("The file's name is empty. Please give a name to the file.");
  29. }
  30. if (strlen($file->getFilename()) > 255) {
  31. $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  32. }
  33. return $errors;
  34. }
  35. /**
  36. * Respond to a file that has been copied.
  37. *
  38. * @param \Drupal\file\FileInterface $file
  39. * The newly copied file entity.
  40. * @param \Drupal\file\FileInterface $source
  41. * The original file before the copy.
  42. *
  43. * @see file_copy()
  44. */
  45. function hook_file_copy(Drupal\file\FileInterface $file, Drupal\file\FileInterface $source) {
  46. // Make sure that the file name starts with the owner's user name.
  47. if (strpos($file->getFilename(), $file->getOwner()->name) !== 0) {
  48. $file->setFilename($file->getOwner()->name . '_' . $file->getFilename());
  49. $file->save();
  50. \Drupal::logger('file')->notice('Copied file %source has been renamed to %destination', ['%source' => $source->filename, '%destination' => $file->getFilename()]);
  51. }
  52. }
  53. /**
  54. * Respond to a file that has been moved.
  55. *
  56. * @param \Drupal\file\FileInterface $file
  57. * The updated file entity after the move.
  58. * @param \Drupal\file\FileInterface $source
  59. * The original file entity before the move.
  60. *
  61. * @see file_move()
  62. */
  63. function hook_file_move(Drupal\file\FileInterface $file, Drupal\file\FileInterface $source) {
  64. // Make sure that the file name starts with the owner's user name.
  65. if (strpos($file->getFilename(), $file->getOwner()->name) !== 0) {
  66. $file->setFilename($file->getOwner()->name . '_' . $file->getFilename());
  67. $file->save();
  68. \Drupal::logger('file')->notice('Moved file %source has been renamed to %destination', ['%source' => $source->filename, '%destination' => $file->getFilename()]);
  69. }
  70. }
  71. /**
  72. * @} End of "addtogroup hooks".
  73. */