]> Raphaël G. Git Repositories - packbundle/blob - Controller/ImageController.php
Add captcha controller
[packbundle] / Controller / ImageController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle\Controller;
13
14 use Symfony\Component\HttpFoundation\HeaderUtils;
15 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
18 use Symfony\Component\Filesystem\Filesystem;
19 use Symfony\Component\HttpFoundation\BinaryFileResponse;
20 use Symfony\Component\HttpFoundation\Request;
21 use Symfony\Component\HttpFoundation\Response;
22 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
23 use Symfony\Component\Routing\RequestContext;
24 use Symfony\Contracts\Service\ServiceSubscriberInterface;
25
26 use Rapsys\PackBundle\Util\ImageUtil;
27 use Rapsys\PackBundle\Util\SluggerUtil;
28
29 /**
30 * {@inheritdoc}
31 */
32 class ImageController extends AbstractController implements ServiceSubscriberInterface {
33 /**
34 * The cache path
35 */
36 protected string $cache;
37
38 /**
39 * The ContainerInterface instance
40 *
41 * @var ContainerInterface
42 */
43 protected $container;
44
45 /**
46 * The ImageUtil instance
47 */
48 protected ImageUtil $image;
49
50 /**
51 * The public path
52 */
53 protected string $path;
54
55 /**
56 * The SluggerUtil instance
57 */
58 protected SluggerUtil $slugger;
59
60 /**
61 * Creates a new image controller
62 *
63 * @param ContainerInterface $container The ContainerInterface instance
64 * @param ImageUtil $image The MapUtil instance
65 * @param SluggerUtil $slugger The SluggerUtil instance
66 * @param string $cache The cache path
67 * @param string $path The public path
68 * @param string $prefix The prefix
69 */
70 function __construct(ContainerInterface $container, ImageUtil $image, SluggerUtil $slugger, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'image') {
71 //Set cache
72 $this->cache = $cache.'/'.$prefix;
73
74 //Set container
75 $this->container = $container;
76
77 //Set image
78 $this->image = $image;
79
80 //Set path
81 $this->path = $path.'/'.$prefix;
82
83 //Set slugger
84 $this->slugger = $slugger;
85 }
86
87 /**
88 * Return captcha image
89 *
90 * @param Request $request The Request instance
91 * @param string $hash The hash
92 * @param int $updated The updated timestamp
93 * @param string $equation The shorted equation
94 * @param int $width The width
95 * @param int $height The height
96 * @return Response The rendered image
97 */
98 public function captcha(Request $request, string $hash, int $updated, string $equation, int $width, int $height): Response {
99 //Without matching hash
100 if ($hash !== $this->slugger->serialize([$updated, $equation, $width, $height])) {
101 //Throw new exception
102 throw new NotFoundHttpException(sprintf('Unable to match captcha hash: %s', $hash));
103 }
104
105 //Set hashed tree
106 $hashed = array_reverse(str_split(strval($updated)));
107
108 //Set captcha
109 $captcha = $this->path.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$equation.'/'.$width.'x'.$height.'.jpeg';
110
111 //Unshort equation
112 $equation = $this->slugger->unshort($equation);
113
114 //Without captcha up to date file
115 if (!is_file($captcha) || !($mtime = stat($captcha)['mtime']) || $mtime < $updated) {
116 //Without existing captcha path
117 if (!is_dir($dir = dirname($captcha))) {
118 //Create filesystem object
119 $filesystem = new Filesystem();
120
121 try {
122 //Create path
123 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
124 //XXX: on CoW filesystems execute a chattr +C before filling
125 $filesystem->mkdir($dir, 0775);
126 } catch (IOExceptionInterface $e) {
127 //Throw error
128 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
129 }
130 }
131
132 //Create image instance
133 $image = new \Imagick();
134
135 //Add imagick draw instance
136 //XXX: see https://www.php.net/manual/fr/imagick.examples-1.php#example-3916
137 $draw = new \ImagickDraw();
138
139 //Set text antialias
140 $draw->setTextAntialias(true);
141
142 //Set stroke antialias
143 $draw->setStrokeAntialias(true);
144
145 //Set text alignment
146 $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
147
148 //Set gravity
149 $draw->setGravity(\Imagick::GRAVITY_CENTER);
150
151 //Set fill color
152 $draw->setFillColor($this->image->captchaFill);
153
154 //Set stroke color
155 $draw->setStrokeColor($this->image->captchaStroke);
156
157 //Set font size
158 $draw->setFontSize($this->image->captchaFontSize/1.5);
159
160 //Set stroke width
161 $draw->setStrokeWidth($this->image->captchaStrokeWidth / 2);
162
163 //Set rotation
164 $draw->rotate($rotate = (rand(25, 75)*(rand(0,1)?-.1:.1)));
165
166 //Get font metrics
167 $metrics2 = $image->queryFontMetrics($draw, strval('stop spam'));
168
169 //Add annotation
170 $draw->annotation($width / 2 - ceil(rand(intval(-$metrics2['textWidth']), intval($metrics2['textWidth'])) / 2) - abs($rotate), ceil($metrics2['textHeight'] + $metrics2['descender'] + $metrics2['ascender']) / 2 - $this->image->captchaStrokeWidth - $rotate, strval('stop spam'));
171
172 //Set rotation
173 $draw->rotate(-$rotate);
174
175 //Set font size
176 $draw->setFontSize($this->image->captchaFontSize);
177
178 //Set stroke width
179 $draw->setStrokeWidth($this->image->captchaStrokeWidth);
180
181 //Set rotation
182 $draw->rotate($rotate = (rand(25, 50)*(rand(0,1)?-.1:.1)));
183
184 //Get font metrics
185 $metrics = $image->queryFontMetrics($draw, strval($equation));
186
187 //Add annotation
188 $draw->annotation($width / 2, ceil($metrics['textHeight'] + $metrics['descender'] + $metrics['ascender']) / 2 - $this->image->captchaStrokeWidth, strval($equation));
189
190 //Set rotation
191 $draw->rotate(-$rotate);
192
193 //Add new image
194 #$image->newImage(intval(ceil($metrics['textWidth'])), intval(ceil($metrics['textHeight'] + $metrics['descender'])), new \ImagickPixel($this->image->captchaBackground), 'jpeg');
195 $image->newImage($width, $height, new \ImagickPixel($this->image->captchaBackground), 'jpeg');
196
197 //Draw on image
198 $image->drawImage($draw);
199
200 //Strip image exif data and properties
201 $image->stripImage();
202
203 //Set compression quality
204 $image->setImageCompressionQuality(70);
205
206 //Save captcha
207 if (!$image->writeImage($captcha)) {
208 //Throw error
209 throw new \Exception(sprintf('Unable to write image "%s"', $captcha));
210 }
211
212 //Set mtime
213 $mtime = stat($captcha)['mtime'];
214 }
215
216 //Read captcha from cache
217 $response = new BinaryFileResponse($captcha);
218
219 //Set file name
220 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'captcha-stop-spam-'.str_replace([' ', '*', '+'], ['-', 'mul', 'add'], $equation).'-'.$width.'x'.$height.'.jpeg');
221
222 //Set etag
223 $response->setEtag(md5($hash));
224
225 //Set last modified
226 $response->setLastModified(\DateTime::createFromFormat('U', strval($mtime)));
227
228 //Set as public
229 $response->setPublic();
230
231 //Return 304 response if not modified
232 $response->isNotModified($request);
233
234 //Return response
235 return $response;
236 }
237
238 /**
239 * Return thumb image
240 *
241 * @param Request $request The Request instance
242 * @param string $hash The hash
243 * @param int $updated The updated timestamp
244 * @param string $path The image path
245 * @param int $width The width
246 * @param int $height The height
247 * @return Response The rendered image
248 */
249 public function thumb(Request $request, string $hash, int $updated, string $path, int $width, int $height): Response {
250 //Without matching hash
251 if ($hash !== $this->slugger->serialize([$updated, $path, $width, $height])) {
252 //Throw new exception
253 throw new NotFoundHttpException(sprintf('Unable to match thumb hash: %s', $hash));
254 }
255
256 //Set hashed tree
257 $hashed = array_reverse(str_split(strval($updated)));
258
259 //Set thumb
260 $thumb = $this->path.'/'.$hashed[0].'/'.$hashed[1].'/'.$hashed[2].'/'.$updated.'/'.$path.'/'.$width.'x'.$height.'.jpeg';
261
262 //Unshort path
263 $path = $this->slugger->unshort($path);
264
265 //Without thumb up to date file
266 if (!is_file($thumb) || !($mtime = stat($thumb)['mtime']) || $mtime < $updated) {
267 //Without existing thumb path
268 if (!is_dir($dir = dirname($thumb))) {
269 //Create filesystem object
270 $filesystem = new Filesystem();
271
272 try {
273 //Create path
274 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
275 //XXX: on CoW filesystems execute a chattr +C before filling
276 $filesystem->mkdir($dir, 0775);
277 } catch (IOExceptionInterface $e) {
278 //Throw error
279 throw new \Exception(sprintf('Output path "%s" do not exists and unable to create it', $dir), 0, $e);
280 }
281 }
282
283 //Create image instance
284 $image = new \Imagick();
285
286 //Read image
287 $image->readImage(realpath($path));
288
289 //Crop using aspect ratio
290 //XXX: for better result upload image directly in aspect ratio :)
291 $image->cropThumbnailImage($width, $height);
292
293 //Strip image exif data and properties
294 $image->stripImage();
295
296 //Set compression quality
297 //TODO: ajust that
298 $image->setImageCompressionQuality(70);
299
300 //Save thumb
301 if (!$image->writeImage($thumb)) {
302 //Throw error
303 throw new \Exception(sprintf('Unable to write image "%s"', $thumb));
304 }
305
306 //Set mtime
307 $mtime = stat($thumb)['mtime'];
308 }
309
310 //Read thumb from cache
311 $response = new BinaryFileResponse($thumb);
312
313 //Set file name
314 $response->setContentDisposition(HeaderUtils::DISPOSITION_INLINE, 'thumb-'.str_replace('/', '_', $path).'-'.$width.'x'.$height.'.jpeg');
315
316 //Set etag
317 $response->setEtag(md5($hash));
318
319 //Set last modified
320 $response->setLastModified(\DateTime::createFromFormat('U', strval($mtime)));
321
322 //Set as public
323 $response->setPublic();
324
325 //Return 304 response if not modified
326 $response->isNotModified($request);
327
328 //Return response
329 return $response;
330 }
331 }