]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Core/Picture.php
Fix typo on occurred
[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-2014 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 Jaqcuot <unknown@unknow.com>
31 * @author Johan Cwiklinski <johan@x-tnd.be>
32 * @copyright 2006-2014 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 * @version SVN: $Id$
35 * @link http://galette.tuxfamily.org
36 */
37
38 namespace Galette\Core;
39
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 Jaqcuot <unknown@unknow.com>
53 * @author Johan Cwiklinski <johan@x-tnd.be>
54 * @copyright 2006-2014 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 const SQL_ERROR = -10;
64 const SQL_BLOB_ERROR = -11;
65 //constants that can be overrided
66 //(do not use self::CONSTANT, but get_class[$this]::CONSTANT)
67 const TABLE = 'pictures';
68 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 (\Exception $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 * Set header and displays the picture.
294 *
295 * @return object the binary file
296 */
297 public function display()
298 {
299 header('Content-type: '.$this->mime);
300 header('Content-Length: ' . filesize($this->file_path));
301 ob_clean();
302 flush();
303 readfile($this->file_path);
304 }
305
306 /**
307 * Deletes a picture, from both database and filesystem
308 *
309 * @param boolean $transaction Whether to use a transaction here or not
310 *
311 * @return boolean true if image was successfully deleted, false otherwise
312 */
313 public function delete($transaction = true)
314 {
315 global $zdb;
316 $class = get_class($this);
317
318 try {
319 if ($transaction === true) {
320 $zdb->connection->beginTransaction();
321 }
322
323 $delete = $zdb->delete($this->tbl_prefix . $class::TABLE);
324 $delete->where(
325 $class::PK . ' = ' . $this->db_id
326 );
327 $del = $zdb->execute($delete);
328
329 if (!$del->count() > 0) {
330 Analog::log(
331 'Unable to remove picture database entry for ' . $this->db_id,
332 Analog::ERROR
333 );
334 //it may be possible image is missing in the database.
335 //let's try to remove file anyway.
336 }
337
338 $file_wo_ext = $this->store_path . $this->id;
339
340 // take back default picture
341 $this->getDefaultPicture();
342 // fix sizes
343 $this->setSizes();
344
345 $success = false;
346 $_file = null;
347 if (file_exists($file_wo_ext . '.jpg')) {
348 //return unlink($file_wo_ext . '.jpg');
349 $_file = $file_wo_ext . '.jpg';
350 $success = unlink($_file);
351 } elseif (file_exists($file_wo_ext . '.png')) {
352 //return unlink($file_wo_ext . '.png');
353 $_file = $file_wo_ext . '.png';
354 $success = unlink($_file);
355 } elseif (file_exists($file_wo_ext . '.gif')) {
356 //return unlink($file_wo_ext . '.gif');
357 $_file = $file_wo_ext . '.gif';
358 $success = unlink($_file);
359 }
360
361 if ($_file !== null && $success !== true) {
362 //unable to remove file that exists!
363 if ($transaction === true) {
364 $zdb->connection->rollBack();
365 }
366 Analog::log(
367 'The file ' . $_file .
368 ' was found on the disk but cannot be removed.',
369 Analog::ERROR
370 );
371 return false;
372 } else {
373 if ($transaction === true) {
374 $zdb->connection->commit();
375 }
376 $this->has_picture = false;
377 return true;
378 }
379 } catch (\Exception $e) {
380 if ($transaction === true) {
381 $zdb->connection->rollBack();
382 }
383 Analog::log(
384 'An error occurred attempting to delete picture ' . $this->db_id .
385 'from database | ' . $e->getMessage(),
386 Analog::ERROR
387 );
388 return false;
389 }
390 }
391
392 /**
393 * Stores an image on the disk and in the database
394 *
395 * @param object $file the uploaded file
396 * @param boolean $ajax If the image cames from an ajax call (dnd)
397 *
398 * @return true|false result of the storage process
399 */
400 public function store($file, $ajax = false)
401 {
402 /** TODO: fix max size (by preferences ?) */
403 global $zdb;
404
405 $class = get_class($this);
406
407 $name = $file['name'];
408 $tmpfile = $file['tmp_name'];
409
410 //First, does the file have a valid name?
411 $reg = "/^([^" . implode('', $this->bad_chars) . "]+)\.(" .
412 implode('|', $this->allowed_extensions) . ")$/i";
413 if (preg_match($reg, $name, $matches)) {
414 Analog::log(
415 '[' . $class . '] Filename and extension are OK, proceed.',
416 Analog::DEBUG
417 );
418 $extension = strtolower($matches[2]);
419 if ($extension == 'jpeg') {
420 //jpeg is an allowed extension,
421 //but we change it to jpg to reduce further tests :)
422 $extension = 'jpg';
423 }
424 } else {
425 $erreg = "/^([^" . implode('', $this->bad_chars) . "]+)\.(.*)/i";
426 $m = preg_match($erreg, $name, $errmatches);
427
428 $err_msg = '[' . $class . '] ';
429 if ($m == 1) {
430 //ok, we got a good filename and an extension. Extension is bad :)
431 $err_msg .= 'Invalid extension for file ' . $name . '.';
432 $ret = self::INVALID_EXTENSION;
433 } else {
434 $err_msg = 'Invalid filename `' . $name . '` (Tip: ';
435 $err_msg .= preg_replace(
436 '|%s|',
437 htmlentities($this->getBadChars()),
438 "file name should not contain any of: %s). "
439 );
440 $ret = self::INVALID_FILENAME;
441 }
442
443 Analog::log(
444 $err_msg,
445 Analog::ERROR
446 );
447 return $ret;
448 }
449
450 //Second, let's check file size
451 if ($file['size'] > ( $this->maxlenght * 1024 )) {
452 Analog::log(
453 '[' . $class . '] File is too big (' . ( $file['size'] * 1024 ) .
454 'Ko for maximum authorized ' . ( $this->maxlenght * 1024 ) .
455 'Ko',
456 Analog::ERROR
457 );
458 return self::FILE_TOO_BIG;
459 } else {
460 Analog::log('[' . $class . '] Filesize is OK, proceed', Analog::DEBUG);
461 }
462
463 $current = getimagesize($tmpfile);
464
465 if (!in_array($current['mime'], $this->allowed_mimes)) {
466 Analog::log(
467 '[' . $class . '] Mimetype `' . $current['mime'] . '` not allowed',
468 Analog::ERROR
469 );
470 return self::MIME_NOT_ALLOWED;
471 } else {
472 Analog::log(
473 '[' . $class . '] Mimetype is allowed, proceed',
474 Analog::DEBUG
475 );
476 }
477
478 $this->delete();
479
480 $new_file = $this->store_path .
481 $this->id . '.' . $extension;
482 if ($ajax === true) {
483 rename($tmpfile, $new_file);
484 } else {
485 move_uploaded_file($tmpfile, $new_file);
486 }
487
488 // current[0] gives width ; current[1] gives height
489 if ($current[0] > $this->max_width || $current[1] > $this->max_height) {
490 /** FIXME: what if image cannot be resized?
491 Should'nt we want to stop the process here? */
492 $this->resizeImage($new_file, $extension);
493 }
494
495 return $this->storeInDb($zdb, $this->db_id, $new_file, $extension);
496 }
497
498 /**
499 * Stores an image in the database
500 *
501 * @param Db $zdb Database instance
502 * @param int $id Member ID
503 * @param string $file File path on disk
504 * @param string $ext File extension
505 *
506 * @return boolean
507 */
508 private function storeInDb(Db $zdb, $id, $file, $ext)
509 {
510 $f = fopen($file, 'r');
511 $picture = '';
512 while ($r=fread($f, 8192)) {
513 $picture .= $r;
514 }
515 fclose($f);
516
517 $class = get_class($this);
518
519 try {
520 $zdb->connection->beginTransaction();
521 $stmt = $this->insert_stmt;
522 if ($stmt == null) {
523 $insert = $zdb->insert($this->tbl_prefix . $class::TABLE);
524 $insert->values(
525 array(
526 $class::PK => ':id',
527 'picture' => ':picture',
528 'format' => ':format'
529 )
530 );
531 $stmt = $zdb->sql->prepareStatementForSqlObject($insert);
532 $container = $stmt->getParameterContainer();
533 $container->offsetSet(
534 $class::PK,
535 ':id'
536 );
537 $container->offsetSet(
538 'picture',
539 ':picture',
540 $container::TYPE_LOB
541 );
542 $container->offsetSet(
543 'format',
544 ':format'
545 );
546 $stmt->setParameterContainer($container);
547 $this->insert_stmt = $stmt;
548 }
549
550 $stmt->execute(
551 array(
552 $class::PK => $id,
553 'picture' => $picture,
554 'format' => $ext
555 )
556 );
557 $zdb->connection->commit();
558 $this->has_picture = true;
559 } catch (\Exception $e) {
560 $zdb->connection->rollBack();
561 Analog::log(
562 'An error occurred storing picture in database: ' .
563 $e->getMessage(),
564 Analog::ERROR
565 );
566 return self::SQL_ERROR;
567 }
568
569 return true;
570 }
571
572 /**
573 * Check for missing images in database
574 *
575 * @param Db $zdb Database instance
576 *
577 * @return void
578 */
579 public function missingInDb(Db $zdb)
580 {
581 $existing_disk = array();
582
583 //retrieve files on disk
584 if ($handle = opendir($this->store_path)) {
585 while (false !== ($entry = readdir($handle))) {
586 $reg = "/^(\d+)\.(" .
587 implode('|', $this->allowed_extensions) . ")$/i";
588 if (preg_match($reg, $entry, $matches)) {
589 $id = $matches[1];
590 $extension = strtolower($matches[2]);
591 if ($extension == 'jpeg') {
592 //jpeg is an allowed extension,
593 //but we change it to jpg to reduce further tests :)
594 $extension = 'jpg';
595 }
596 $existing_disk[$id] = array(
597 'name' => $entry,
598 'id' => $id,
599 'ext' => $extension
600 );
601 }
602 }
603 closedir($handle);
604
605 if (count($existing_disk) === 0) {
606 //no image on disk, nothing to do :)
607 return;
608 }
609
610 //retrieve files in database
611 $class = get_class($this);
612 $select = $zdb->select($this->tbl_prefix . $class::TABLE);
613 $select
614 ->columns(array($class::PK))
615 ->where->in($class::PK, array_keys($existing_disk));
616
617 $results = $zdb->execute($select);
618
619 $existing_db = array();
620 foreach ($results as $result) {
621 $existing_db[] = (int)$result[self::PK];
622 }
623
624 $existing_diff = array_diff(array_keys($existing_disk), $existing_db);
625
626 //retrieve valid members ids
627 $members = new Members();
628 $valids = $members->getArrayList(
629 $existing_diff,
630 null,
631 false,
632 false,
633 array(self::PK)
634 );
635
636 foreach ($valids as $valid) {
637 $file = $existing_disk[$valid->id_adh];
638 $this->storeInDb(
639 $zdb,
640 $file['id'],
641 $this->store_path . $file['id'] . '.' . $file['ext'],
642 $file['ext']
643 );
644 }
645 } else {
646 Analog::log(
647 'Something went wrong opening images directory ' .
648 $this->store_path,
649 Analog::ERROR
650 );
651 }
652 }
653
654 /**
655 * Resize the image if it exceed max allowed sizes
656 *
657 * @param string $source the source image
658 * @param string $ext file's extension
659 * @param string $dest the destination image.
660 * If null, we'll use the source image. Defaults to null
661 *
662 * @return void
663 */
664 private function resizeImage($source, $ext, $dest = null)
665 {
666 $class = get_class($this);
667
668 if (function_exists("gd_info")) {
669 $gdinfo = gd_info();
670 $h = $this->max_height;
671 $w = $this->max_width;
672 if ($dest == null) {
673 $dest = $source;
674 }
675
676 switch (strtolower($ext)) {
677 case 'jpg':
678 if (!$gdinfo['JPEG Support']) {
679 Analog::log(
680 '[' . $class . '] GD has no JPEG Support - ' .
681 'pictures could not be resized!',
682 Analog::ERROR
683 );
684 return false;
685 }
686 break;
687 case 'png':
688 if (!$gdinfo['PNG Support']) {
689 Analog::log(
690 '[' . $class . '] GD has no PNG Support - ' .
691 'pictures could not be resized!',
692 Analog::ERROR
693 );
694 return false;
695 }
696 break;
697 case 'gif':
698 if (!$gdinfo['GIF Create Support']) {
699 Analog::log(
700 '[' . $class . '] GD has no GIF Support - ' .
701 'pictures could not be resized!',
702 Analog::ERROR
703 );
704 return false;
705 }
706 break;
707 default:
708 return false;
709 }
710
711 list($cur_width, $cur_height, $cur_type, $curattr)
712 = getimagesize($source);
713
714 $ratio = $cur_width / $cur_height;
715
716 // calculate image size according to ratio
717 if ($cur_width>$cur_height) {
718 $h = $w/$ratio;
719 } else {
720 $w = $h*$ratio;
721 }
722
723 $thumb = imagecreatetruecolor($w, $h);
724 switch ($ext) {
725 case 'jpg':
726 $image = ImageCreateFromJpeg($source);
727 imagecopyresampled($thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height);
728 imagejpeg($thumb, $dest);
729 break;
730 case 'png':
731 $image = ImageCreateFromPng($source);
732 // Turn off alpha blending and set alpha flag. That prevent alpha
733 // transparency to be saved as an arbitrary color (black in my tests)
734 imagealphablending($thumb, false);
735 imagealphablending($image, false);
736 imagesavealpha($thumb, true);
737 imagesavealpha($image, true);
738 imagecopyresampled($thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height);
739 imagepng($thumb, $dest);
740 break;
741 case 'gif':
742 $image = ImageCreateFromGif($source);
743 imagecopyresampled($thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height);
744 imagegif($thumb, $dest);
745 break;
746 }
747 } else {
748 Analog::log(
749 '[' . $class . '] GD is not present - ' .
750 'pictures could not be resized!',
751 Analog::ERROR
752 );
753 }
754 }
755
756 /**
757 * Returns current file optimal height (resized)
758 *
759 * @return int optimal height
760 */
761 public function getOptimalHeight()
762 {
763 return (int)round($this->optimal_height, 1);
764 }
765
766 /**
767 * Returns current file height
768 *
769 * @return int current height
770 */
771 public function getHeight()
772 {
773 return $this->height;
774 }
775
776 /**
777 * Returns current file optimal width (resized)
778 *
779 * @return int optimal width
780 */
781 public function getOptimalWidth()
782 {
783 return (int)round($this->optimal_width, 1);
784 }
785
786 /**
787 * Returns current file width
788 *
789 * @return int current width
790 */
791 public function getWidth()
792 {
793 return $this->width;
794 }
795
796 /**
797 * Returns current file format
798 *
799 * @return string
800 */
801 public function getFormat()
802 {
803 return $this->format;
804 }
805
806 /**
807 * Have we got a picture ?
808 *
809 * @return bool True if a picture matches adherent's id, false otherwise
810 */
811 public function hasPicture()
812 {
813 return $this->has_picture;
814 }
815
816 /**
817 * Returns current file full path
818 *
819 * @return string full file path
820 */
821 public function getPath()
822 {
823 return $this->file_path;
824 }
825
826 /**
827 * Returns current mime type
828 *
829 * @return string
830 */
831 public function getMime()
832 {
833 return $this->mime;
834 }
835
836 /**
837 * Return textual error message
838 *
839 * @param int $code The error code
840 *
841 * @return string Localized message
842 */
843 public function getErrorMessage($code)
844 {
845 $error = null;
846 switch ($code) {
847 case self::SQL_ERROR:
848 case self::SQL_BLOB_ERROR:
849 $error = _T("An SQL error has occurred.");
850 break;
851 }
852
853 if ($error === null) {
854 $error = $this->getErrorMessageFromCode($code);
855 }
856
857 return $error;
858 }
859 }