]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Core/Picture.php
Use prepared statement rather than direct SQL
[galette.git] / galette / lib / Galette / Core / Picture.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Picture handling
7 *
8 * PHP version 5
9 *
10 * Copyright © 2006-2021 The Galette Team
11 *
12 * This file is part of Galette (http://galette.tuxfamily.org).
13 *
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
26 *
27 * @category Core
28 * @package Galette
29 *
30 * @author Frédéric Jacquot <unknown@unknow.com>
31 * @author Johan Cwiklinski <johan@x-tnd.be>
32 * @copyright 2006-2021 The Galette Team
33 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
34 * @link http://galette.tuxfamily.org
35 */
36
37 namespace Galette\Core;
38
39 use Throwable;
40 use Analog\Analog;
41 use Galette\Entity\Adherent;
42 use Galette\Repository\Members;
43 use Galette\IO\FileInterface;
44 use Galette\IO\FileTrait;
45
46 /**
47 * Picture handling
48 *
49 * @name Picture
50 * @category Core
51 * @package Galette
52 * @author Frédéric Jacquot <unknown@unknow.com>
53 * @author Johan Cwiklinski <johan@x-tnd.be>
54 * @copyright 2006-2021 The Galette Team
55 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
56 * @link http://galette.tuxfamily.org
57 */
58 class Picture implements FileInterface
59 {
60 use FileTrait;
61
62 //constants that will not be overrided
63 public const SQL_ERROR = -10;
64 public const SQL_BLOB_ERROR = -11;
65 //constants that can be overrided
66 //(do not use self::CONSTANT, but get_class[$this]::CONSTANT)
67 public const TABLE = 'pictures';
68 public const PK = Adherent::PK;
69
70 protected $tbl_prefix = '';
71
72 protected $id;
73 protected $height;
74 protected $width;
75 protected $optimal_height;
76 protected $optimal_width;
77 protected $file_path;
78 protected $format;
79 protected $mime;
80 protected $has_picture = false;
81 protected $store_path = GALETTE_PHOTOS_PATH;
82 protected $max_width = 200;
83 protected $max_height = 200;
84 private $insert_stmt;
85
86 /**
87 * Default constructor.
88 *
89 * @param int $id_adh the id of the member
90 */
91 public function __construct($id_adh = '')
92 {
93
94 $this->init(
95 null,
96 array('jpeg', 'jpg', 'png', 'gif'),
97 array(
98 'jpg' => 'image/jpeg',
99 'png' => 'image/png',
100 'gif' => 'image/gif'
101 )
102 );
103
104 // '!==' needed, otherwise ''==0
105 if ($id_adh !== '' && $id_adh !== null) {
106 $this->id = $id_adh;
107 if (!isset($this->db_id)) {
108 $this->db_id = $id_adh;
109 }
110
111 //if file does not exists on the FileSystem, check for it in the database
112 if (!$this->checkFileOnFS()) {
113 if ($this->checkFileInDB()) {
114 $this->has_picture = true;
115 }
116 } else {
117 $this->has_picture = true;
118 }
119 }
120
121 // if we still have no picture, take the default one
122 if (empty($this->file_path)) {
123 $this->getDefaultPicture();
124 }
125
126 //we should not have an empty file_path, but...
127 if (!empty($this->file_path)) {
128 $this->setSizes();
129 }
130 }
131
132 /**
133 * "Magic" function called on unserialize
134 *
135 * @return void
136 */
137 public function __wakeup()
138 {
139 //if file has been deleted since we store our object in the session,
140 //we try to retrieve it
141 if (!$this->checkFileOnFS()) {
142 //if file does not exists on the FileSystem,
143 //check for it in the database
144 //$this->checkFileInDB();
145 } else {
146 $this->has_picture = false;
147 }
148
149 // if we still have no picture, take the default one
150 if (empty($this->file_path)) {
151 $this->getDefaultPicture();
152 }
153
154 //we should not have an empty file_path, but...
155 if (!empty($this->file_path)) {
156 $this->setSizes();
157 }
158 }
159
160 /**
161 * Check if current file is present on the File System
162 *
163 * @return boolean true if file is present on FS, false otherwise
164 */
165 private function checkFileOnFS()
166 {
167 $file_wo_ext = $this->store_path . $this->id;
168 if (file_exists($file_wo_ext . '.jpg')) {
169 $this->file_path = realpath($file_wo_ext . '.jpg');
170 $this->format = 'jpg';
171 $this->mime = 'image/jpeg';
172 return true;
173 } elseif (file_exists($file_wo_ext . '.png')) {
174 $this->file_path = realpath($file_wo_ext . '.png');
175 $this->format = 'png';
176 $this->mime = 'image/png';
177 return true;
178 } elseif (file_exists($file_wo_ext . '.gif')) {
179 $this->file_path = realpath($file_wo_ext . '.gif');
180 $this->format = 'gif';
181 $this->mime = 'image/gif';
182 return true;
183 }
184 return false;
185 }
186
187 /**
188 * Check if current file is present in the database,
189 * and copy it to the File System
190 *
191 * @return boolean true if file is present in the DB, false otherwise
192 */
193 private function checkFileInDB()
194 {
195 global $zdb;
196
197 try {
198 $select = $this->getCheckFileQuery();
199 $results = $zdb->execute($select);
200 $pic = $results->current();
201
202 if ($pic) {
203 // we must regenerate the picture file
204 $file_wo_ext = $this->store_path . $this->id;
205 file_put_contents(
206 $file_wo_ext . '.' . $pic->format,
207 $pic->picture
208 );
209
210 $this->format = $pic->format;
211 switch ($this->format) {
212 case 'jpg':
213 $this->mime = 'image/jpeg';
214 break;
215 case 'png':
216 $this->mime = 'image/png';
217 break;
218 case 'gif':
219 $this->mime = 'image/gif';
220 break;
221 }
222 $this->file_path = realpath($file_wo_ext . '.' . $this->format);
223 return true;
224 }
225 } catch (Throwable $e) {
226 return false;
227 }
228 }
229
230 /**
231 * Returns the relevant query to check if picture exists in database.
232 *
233 * @return string SELECT query
234 */
235 protected function getCheckFileQuery()
236 {
237 global $zdb;
238 $class = get_class($this);
239
240 $select = $zdb->select($this->tbl_prefix . $class::TABLE);
241 $select->columns(
242 array(
243 'picture',
244 'format'
245 )
246 );
247 $select->where(array($class::PK => $this->db_id));
248 return $select;
249 }
250
251 /**
252 * Gets the default picture to show, anyways
253 *
254 * @return void
255 */
256 protected function getDefaultPicture()
257 {
258 $this->file_path = realpath(_CURRENT_THEME_PATH . 'images/default.png');
259 $this->format = 'png';
260 $this->mime = 'image/png';
261 $this->has_picture = false;
262 }
263
264 /**
265 * Set picture sizes
266 *
267 * @return void
268 */
269 private function setSizes()
270 {
271 list($width, $height) = getimagesize($this->file_path);
272 $this->height = $height;
273 $this->width = $width;
274 $this->optimal_height = $height;
275 $this->optimal_width = $width;
276
277 if ($this->height > $this->width) {
278 if ($this->height > $this->max_height) {
279 $ratio = $this->max_height / $this->height;
280 $this->optimal_height = $this->max_height;
281 $this->optimal_width = $this->width * $ratio;
282 }
283 } else {
284 if ($this->width > $this->max_width) {
285 $ratio = $this->max_width / $this->width;
286 $this->optimal_width = $this->max_width;
287 $this->optimal_height = $this->height * $ratio;
288 }
289 }
290 }
291
292 /**
293 * Get image file contents
294 *
295 * @return mixed
296 */
297 public function getContents()
298 {
299 readfile($this->file_path);
300 }
301
302 /**
303 * Set header and displays the picture.
304 *
305 * @param Response $response Reponse
306 *
307 * @return object the binary file
308 */
309 public function display(\Slim\Http\Response $response)
310 {
311 $response = $response->withHeader('Content-Type', $this->mime)
312 ->withHeader('Content-Transfer-Encoding', 'binary')
313 ->withHeader('Expires', '0')
314 ->withHeader('Cache-Control', 'must-revalidate')
315 ->withHeader('Pragma', 'public');
316
317 $stream = fopen('php://memory', 'r+');
318 fwrite($stream, file_get_contents($this->file_path));
319 rewind($stream);
320
321 return $response->withBody(new \Slim\Http\Stream($stream));
322 }
323
324 /**
325 * Deletes a picture, from both database and filesystem
326 *
327 * @param boolean $transaction Whether to use a transaction here or not
328 *
329 * @return boolean true if image was successfully deleted, false otherwise
330 */
331 public function delete($transaction = true)
332 {
333 global $zdb;
334 $class = get_class($this);
335
336 try {
337 if ($transaction === true) {
338 $zdb->connection->beginTransaction();
339 }
340
341 $delete = $zdb->delete($this->tbl_prefix . $class::TABLE);
342 $delete->where([$class::PK => $this->db_id]);
343 $del = $zdb->execute($delete);
344
345 if (!$del->count() > 0) {
346 Analog::log(
347 'Unable to remove picture database entry for ' . $this->db_id,
348 Analog::ERROR
349 );
350 //it may be possible image is missing in the database.
351 //let's try to remove file anyway.
352 }
353
354 $file_wo_ext = $this->store_path . $this->id;
355
356 // take back default picture
357 $this->getDefaultPicture();
358 // fix sizes
359 $this->setSizes();
360
361 $success = false;
362 $_file = null;
363 if (file_exists($file_wo_ext . '.jpg')) {
364 //return unlink($file_wo_ext . '.jpg');
365 $_file = $file_wo_ext . '.jpg';
366 $success = unlink($_file);
367 } elseif (file_exists($file_wo_ext . '.png')) {
368 //return unlink($file_wo_ext . '.png');
369 $_file = $file_wo_ext . '.png';
370 $success = unlink($_file);
371 } elseif (file_exists($file_wo_ext . '.gif')) {
372 //return unlink($file_wo_ext . '.gif');
373 $_file = $file_wo_ext . '.gif';
374 $success = unlink($_file);
375 }
376
377 if ($_file !== null && $success !== true) {
378 //unable to remove file that exists!
379 if ($transaction === true) {
380 $zdb->connection->rollBack();
381 }
382 Analog::log(
383 'The file ' . $_file .
384 ' was found on the disk but cannot be removed.',
385 Analog::ERROR
386 );
387 return false;
388 } else {
389 if ($transaction === true) {
390 $zdb->connection->commit();
391 }
392 $this->has_picture = false;
393 return true;
394 }
395 } catch (Throwable $e) {
396 if ($transaction === true) {
397 $zdb->connection->rollBack();
398 }
399 Analog::log(
400 'An error occurred attempting to delete picture ' . $this->db_id .
401 'from database | ' . $e->getMessage(),
402 Analog::ERROR
403 );
404 return false;
405 }
406 }
407
408 /**
409 * Stores an image on the disk and in the database
410 *
411 * @param object $file the uploaded file
412 * @param boolean $ajax If the image cames from an ajax call (dnd)
413 *
414 * @return true|false result of the storage process
415 */
416 public function store($file, $ajax = false)
417 {
418 /** TODO: fix max size (by preferences ?) */
419 global $zdb;
420
421 $class = get_class($this);
422
423 $name = $file['name'];
424 $tmpfile = $file['tmp_name'];
425
426 //First, does the file have a valid name?
427 $reg = "/^([^" . implode('', $this->bad_chars) . "]+)\.(" .
428 implode('|', $this->allowed_extensions) . ")$/i";
429 if (preg_match($reg, $name, $matches)) {
430 Analog::log(
431 '[' . $class . '] Filename and extension are OK, proceed.',
432 Analog::DEBUG
433 );
434 $extension = strtolower($matches[2]);
435 if ($extension == 'jpeg') {
436 //jpeg is an allowed extension,
437 //but we change it to jpg to reduce further tests :)
438 $extension = 'jpg';
439 }
440 } else {
441 $erreg = "/^([^" . implode('', $this->bad_chars) . "]+)\.(.*)/i";
442 $m = preg_match($erreg, $name, $errmatches);
443
444 $err_msg = '[' . $class . '] ';
445 if ($m == 1) {
446 //ok, we got a good filename and an extension. Extension is bad :)
447 $err_msg .= 'Invalid extension for file ' . $name . '.';
448 $ret = self::INVALID_EXTENSION;
449 } else {
450 $err_msg = 'Invalid filename `' . $name . '` (Tip: ';
451 $err_msg .= preg_replace(
452 '|%s|',
453 htmlentities($this->getBadChars()),
454 "file name should not contain any of: %s). "
455 );
456 $ret = self::INVALID_FILENAME;
457 }
458
459 Analog::log(
460 $err_msg,
461 Analog::ERROR
462 );
463 return $ret;
464 }
465
466 //Second, let's check file size
467 if ($file['size'] > ($this->maxlenght * 1024)) {
468 Analog::log(
469 '[' . $class . '] File is too big (' . ($file['size'] * 1024) .
470 'Ko for maximum authorized ' . ($this->maxlenght * 1024) .
471 'Ko',
472 Analog::ERROR
473 );
474 return self::FILE_TOO_BIG;
475 } else {
476 Analog::log('[' . $class . '] Filesize is OK, proceed', Analog::DEBUG);
477 }
478
479 $current = getimagesize($tmpfile);
480
481 if (!in_array($current['mime'], $this->allowed_mimes)) {
482 Analog::log(
483 '[' . $class . '] Mimetype `' . $current['mime'] . '` not allowed',
484 Analog::ERROR
485 );
486 return self::MIME_NOT_ALLOWED;
487 } else {
488 Analog::log(
489 '[' . $class . '] Mimetype is allowed, proceed',
490 Analog::DEBUG
491 );
492 }
493
494 $this->delete();
495
496 $new_file = $this->store_path .
497 $this->id . '.' . $extension;
498 if ($ajax === true) {
499 rename($tmpfile, $new_file);
500 } else {
501 move_uploaded_file($tmpfile, $new_file);
502 }
503
504 // current[0] gives width ; current[1] gives height
505 if ($current[0] > $this->max_width || $current[1] > $this->max_height) {
506 /** FIXME: what if image cannot be resized?
507 Should'nt we want to stop the process here? */
508 $this->resizeImage($new_file, $extension);
509 }
510
511 return $this->storeInDb($zdb, $this->db_id, $new_file, $extension);
512 }
513
514 /**
515 * Stores an image in the database
516 *
517 * @param Db $zdb Database instance
518 * @param int $id Member ID
519 * @param string $file File path on disk
520 * @param string $ext File extension
521 *
522 * @return boolean
523 */
524 private function storeInDb(Db $zdb, $id, $file, $ext)
525 {
526 $f = fopen($file, 'r');
527 $picture = '';
528 while ($r = fread($f, 8192)) {
529 $picture .= $r;
530 }
531 fclose($f);
532
533 $class = get_class($this);
534
535 try {
536 $zdb->connection->beginTransaction();
537 $stmt = $this->insert_stmt;
538 if ($stmt == null) {
539 $insert = $zdb->insert($this->tbl_prefix . $class::TABLE);
540 $insert->values(
541 array(
542 $class::PK => ':' . $class::PK,
543 'picture' => ':picture',
544 'format' => ':format'
545 )
546 );
547 $stmt = $zdb->sql->prepareStatementForSqlObject($insert);
548 $container = $stmt->getParameterContainer();
549 $container->offsetSet(
550 'picture', //'picture',
551 ':picture',
552 $container::TYPE_LOB
553 );
554 $stmt->setParameterContainer($container);
555 $this->insert_stmt = $stmt;
556 }
557
558 $stmt->execute(
559 array(
560 $class::PK => $id,
561 'picture' => $picture,
562 'format' => $ext
563 )
564 );
565 $zdb->connection->commit();
566 $this->has_picture = true;
567 } catch (Throwable $e) {
568 $zdb->connection->rollBack();
569 Analog::log(
570 'An error occurred storing picture in database: ' .
571 $e->getMessage(),
572 Analog::ERROR
573 );
574 return self::SQL_ERROR;
575 }
576
577 return true;
578 }
579
580 /**
581 * Check for missing images in database
582 *
583 * @param Db $zdb Database instance
584 *
585 * @return void
586 */
587 public function missingInDb(Db $zdb)
588 {
589 $existing_disk = array();
590
591 //retrieve files on disk
592 if ($handle = opendir($this->store_path)) {
593 while (false !== ($entry = readdir($handle))) {
594 $reg = "/^(\d+)\.(" .
595 implode('|', $this->allowed_extensions) . ")$/i";
596 if (preg_match($reg, $entry, $matches)) {
597 $id = $matches[1];
598 $extension = strtolower($matches[2]);
599 if ($extension == 'jpeg') {
600 //jpeg is an allowed extension,
601 //but we change it to jpg to reduce further tests :)
602 $extension = 'jpg';
603 }
604 $existing_disk[$id] = array(
605 'name' => $entry,
606 'id' => $id,
607 'ext' => $extension
608 );
609 }
610 }
611 closedir($handle);
612
613 if (count($existing_disk) === 0) {
614 //no image on disk, nothing to do :)
615 return;
616 }
617
618 //retrieve files in database
619 $class = get_class($this);
620 $select = $zdb->select($this->tbl_prefix . $class::TABLE);
621 $select
622 ->columns(array($class::PK))
623 ->where->in($class::PK, array_keys($existing_disk));
624
625 $results = $zdb->execute($select);
626
627 $existing_db = array();
628 foreach ($results as $result) {
629 $existing_db[] = (int)$result[self::PK];
630 }
631
632 $existing_diff = array_diff(array_keys($existing_disk), $existing_db);
633
634 //retrieve valid members ids
635 $members = new Members();
636 $valids = $members->getArrayList(
637 $existing_diff,
638 null,
639 false,
640 false,
641 array(self::PK)
642 );
643
644 foreach ($valids as $valid) {
645 $file = $existing_disk[$valid->id_adh];
646 $this->storeInDb(
647 $zdb,
648 $file['id'],
649 $this->store_path . $file['id'] . '.' . $file['ext'],
650 $file['ext']
651 );
652 }
653 } else {
654 Analog::log(
655 'Something went wrong opening images directory ' .
656 $this->store_path,
657 Analog::ERROR
658 );
659 }
660 }
661
662 /**
663 * Resize the image if it exceed max allowed sizes
664 *
665 * @param string $source the source image
666 * @param string $ext file's extension
667 * @param string $dest the destination image.
668 * If null, we'll use the source image. Defaults to null
669 *
670 * @return void
671 */
672 private function resizeImage($source, $ext, $dest = null)
673 {
674 $class = get_class($this);
675
676 if (function_exists("gd_info")) {
677 $gdinfo = gd_info();
678 $h = $this->max_height;
679 $w = $this->max_width;
680 if ($dest == null) {
681 $dest = $source;
682 }
683
684 switch (strtolower($ext)) {
685 case 'jpg':
686 if (!$gdinfo['JPEG Support']) {
687 Analog::log(
688 '[' . $class . '] GD has no JPEG Support - ' .
689 'pictures could not be resized!',
690 Analog::ERROR
691 );
692 return false;
693 }
694 break;
695 case 'png':
696 if (!$gdinfo['PNG Support']) {
697 Analog::log(
698 '[' . $class . '] GD has no PNG Support - ' .
699 'pictures could not be resized!',
700 Analog::ERROR
701 );
702 return false;
703 }
704 break;
705 case 'gif':
706 if (!$gdinfo['GIF Create Support']) {
707 Analog::log(
708 '[' . $class . '] GD has no GIF Support - ' .
709 'pictures could not be resized!',
710 Analog::ERROR
711 );
712 return false;
713 }
714 break;
715 default:
716 return false;
717 }
718
719 list($cur_width, $cur_height, $cur_type, $curattr)
720 = getimagesize($source);
721
722 $ratio = $cur_width / $cur_height;
723
724 // calculate image size according to ratio
725 if ($cur_width > $cur_height) {
726 $h = $w / $ratio;
727 } else {
728 $w = $h * $ratio;
729 }
730
731 $thumb = imagecreatetruecolor($w, $h);
732 switch ($ext) {
733 case 'jpg':
734 $image = imagecreatefromjpeg($source);
735 imagecopyresampled($thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height);
736 imagejpeg($thumb, $dest);
737 break;
738 case 'png':
739 $image = imagecreatefrompng($source);
740 // Turn off alpha blending and set alpha flag. That prevent alpha
741 // transparency to be saved as an arbitrary color (black in my tests)
742 imagealphablending($thumb, false);
743 imagealphablending($image, false);
744 imagesavealpha($thumb, true);
745 imagesavealpha($image, true);
746 imagecopyresampled($thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height);
747 imagepng($thumb, $dest);
748 break;
749 case 'gif':
750 $image = imagecreatefromgif($source);
751 imagecopyresampled($thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height);
752 imagegif($thumb, $dest);
753 break;
754 }
755 } else {
756 Analog::log(
757 '[' . $class . '] GD is not present - ' .
758 'pictures could not be resized!',
759 Analog::ERROR
760 );
761 }
762 }
763
764 /**
765 * Returns current file optimal height (resized)
766 *
767 * @return int optimal height
768 */
769 public function getOptimalHeight()
770 {
771 return (int)round($this->optimal_height, 1);
772 }
773
774 /**
775 * Returns current file height
776 *
777 * @return int current height
778 */
779 public function getHeight()
780 {
781 return $this->height;
782 }
783
784 /**
785 * Returns current file optimal width (resized)
786 *
787 * @return int optimal width
788 */
789 public function getOptimalWidth()
790 {
791 return (int)round($this->optimal_width, 1);
792 }
793
794 /**
795 * Returns current file width
796 *
797 * @return int current width
798 */
799 public function getWidth()
800 {
801 return $this->width;
802 }
803
804 /**
805 * Returns current file format
806 *
807 * @return string
808 */
809 public function getFormat()
810 {
811 return $this->format;
812 }
813
814 /**
815 * Have we got a picture ?
816 *
817 * @return bool True if a picture matches adherent's id, false otherwise
818 */
819 public function hasPicture()
820 {
821 return $this->has_picture;
822 }
823
824 /**
825 * Returns current file full path
826 *
827 * @return string full file path
828 */
829 public function getPath()
830 {
831 return $this->file_path;
832 }
833
834 /**
835 * Returns current mime type
836 *
837 * @return string
838 */
839 public function getMime()
840 {
841 return $this->mime;
842 }
843
844 /**
845 * Return textual error message
846 *
847 * @param int $code The error code
848 *
849 * @return string Localized message
850 */
851 public function getErrorMessage($code)
852 {
853 $error = null;
854 switch ($code) {
855 case self::SQL_ERROR:
856 case self::SQL_BLOB_ERROR:
857 $error = _T("An SQL error has occurred.");
858 break;
859 }
860
861 if ($error === null) {
862 $error = $this->getErrorMessageFromCode($code);
863 }
864
865 return $error;
866 }
867 }