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