ImageFileHandler.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace Gregwar\Captcha;
  3. use Symfony\Component\Finder\Finder;
  4. /**
  5. * Handles actions related to captcha image files including saving and garbage collection
  6. *
  7. * @author Gregwar <g.passault@gmail.com>
  8. * @author Jeremy Livingston <jeremy@quizzle.com>
  9. */
  10. class ImageFileHandler
  11. {
  12. /**
  13. * Name of folder for captcha images
  14. * @var string
  15. */
  16. protected $imageFolder;
  17. /**
  18. * Absolute path to public web folder
  19. * @var string
  20. */
  21. protected $webPath;
  22. /**
  23. * Frequency of garbage collection in fractions of 1
  24. * @var int
  25. */
  26. protected $gcFreq;
  27. /**
  28. * Maximum age of images in minutes
  29. * @var int
  30. */
  31. protected $expiration;
  32. /**
  33. * @param $imageFolder
  34. * @param $webPath
  35. * @param $gcFreq
  36. * @param $expiration
  37. */
  38. public function __construct($imageFolder, $webPath, $gcFreq, $expiration)
  39. {
  40. $this->imageFolder = $imageFolder;
  41. $this->webPath = $webPath;
  42. $this->gcFreq = $gcFreq;
  43. $this->expiration = $expiration;
  44. }
  45. /**
  46. * Saves the provided image content as a file
  47. *
  48. * @param string $contents
  49. *
  50. * @return string
  51. */
  52. public function saveAsFile($contents)
  53. {
  54. $this->createFolderIfMissing();
  55. $filename = md5(uniqid()) . '.jpg';
  56. $filePath = $this->webPath . '/' . $this->imageFolder . '/' . $filename;
  57. imagejpeg($contents, $filePath, 15);
  58. return '/' . $this->imageFolder . '/' . $filename;
  59. }
  60. /**
  61. * Randomly runs garbage collection on the image directory
  62. *
  63. * @return bool
  64. */
  65. public function collectGarbage()
  66. {
  67. if (!mt_rand(1, $this->gcFreq) == 1) {
  68. return false;
  69. }
  70. $this->createFolderIfMissing();
  71. $finder = new Finder();
  72. $criteria = sprintf('<= now - %s minutes', $this->expiration);
  73. $finder->in($this->webPath . '/' . $this->imageFolder)
  74. ->date($criteria);
  75. foreach ($finder->files() as $file) {
  76. unlink($file->getPathname());
  77. }
  78. return true;
  79. }
  80. /**
  81. * Creates the folder if it doesn't exist
  82. */
  83. protected function createFolderIfMissing()
  84. {
  85. if (!file_exists($this->webPath . '/' . $this->imageFolder)) {
  86. mkdir($this->webPath . '/' . $this->imageFolder, 0755);
  87. }
  88. }
  89. }