]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Core/Picture.php
Image were no longer regenerated from database; fixes #463
[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-2012 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-2012 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 Galette\Entity\Adherent;
41 use Galette\Common\KLogger as KLogger;
42
43 /**
44 * Picture handling
45 *
46 * @name Picture
47 * @category Core
48 * @package Galette
49 * @author Frédéric Jaqcuot <unknown@unknow.com>
50 * @author Johan Cwiklinski <johan@x-tnd.be>
51 * @copyright 2006-2012 The Galette Team
52 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
53 * @link http://galette.tuxfamily.org
54 */
55 class Picture
56 {
57 //constants that will not be overrided
58 const INVALID_FILE = -1;
59 const INVALID_EXTENSION = -2;
60 const FILE_TOO_BIG = -3;
61 const MIME_NOT_ALLOWED = -4;
62 const SQL_ERROR = -5;
63 const SQL_BLOB_ERROR = -6;
64 //constants that can be overrided
65 //(do not use self::CONSTANT, but get_class[$this]::CONSTANT)
66 const MAX_FILE_SIZE = 1024;
67 const TABLE = 'pictures';
68 const PK = Adherent::PK;
69
70 /*private $_bad_chars = array(
71 '\.', '\\\\', "'", ' ', '\/', ':', '\*', '\?', '"', '<', '>', '|'
72 );*/
73 //array keys contain litteral value of each forbidden character
74 //(to be used when showing an error).
75 //Maybe is there a better way to handle this...
76 private $_bad_chars = array(
77 '.' => '\.',
78 '\\' => '\\\\',
79 "'" => "'",
80 ' ' => ' ',
81 '/' => '\/',
82 ':' => ':',
83 '*' => '\*',
84 '?' => '\?',
85 '"' => '"',
86 '<' => '<',
87 '>' => '>',
88 '|' => '|'
89 );
90 private $_allowed_extensions = array('jpeg', 'jpg', 'png', 'gif');
91 private $_allowed_mimes = array(
92 'jpg' => 'image/jpeg',
93 'png' => 'image/png',
94 'gif' => 'image/gif'
95 );
96
97 protected $tbl_prefix = '';
98
99 protected $id;
100 protected $height;
101 protected $width;
102 protected $optimal_height;
103 protected $optimal_width;
104 protected $file_path;
105 protected $format;
106 protected $mime;
107 protected $has_picture = true;
108 protected $store_path = GALETTE_PHOTOS_PATH;
109 protected $max_width = 200;
110 protected $max_height = 200;
111
112 /**
113 * Default constructor.
114 *
115 * @param int $id_adh the id of the member
116 */
117 public function __construct( $id_adh='' )
118 {
119 // '!==' needed, otherwise ''==0
120 if ( $id_adh !== '' ) {
121 $this->id = $id_adh;
122 if ( !isset ($this->db_id) ) {
123 $this->db_id = $id_adh;
124 }
125
126 //if file does not exists on the FileSystem, check for it in the database
127 if ( !$this->_checkFileOnFS() ) {
128 $this->_checkFileInDB();
129 }
130 }
131
132 // if we still have no picture, take the default one
133 if ( $this->file_path=='' ) {
134 $this->getDefaultPicture();
135 }
136
137 //we should not have an empty file_path, but...
138 if ( $this->file_path !== '' ) {
139 $this->_setSizes();
140 }
141 }
142
143 /**
144 * "Magic" function called on unserialize
145 *
146 * @return void
147 */
148 public function __wakeup()
149 {
150 //if file has been deleted since we store our object in the session,
151 //we try to retrieve it
152 if ( !$this->_checkFileOnFS() ) {
153 //if file does not exists on the FileSystem,
154 //check for it in the database
155 //$this->_checkFileInDB();
156 }
157
158 // if we still have no picture, take the default one
159 if ( $this->file_path=='' ) {
160 $this->getDefaultPicture();
161 }
162
163 //we should not have an empty file_path, but...
164 if ( $this->file_path !== '' ) {
165 $this->_setSizes();
166 }
167 }
168
169 /**
170 * Check if current file is present on the File System
171 *
172 * @return boolean true if file is present on FS, false otherwise
173 */
174 private function _checkFileOnFS()
175 {
176 $file_wo_ext = $this->store_path . $this->id;
177 if ( file_exists($file_wo_ext . '.jpg') ) {
178 $this->file_path = $file_wo_ext . '.jpg';
179 $this->format = 'jpg';
180 $this->mime = 'image/jpeg';
181 return true;
182 } elseif ( file_exists($file_wo_ext . '.png') ) {
183 $this->file_path = $file_wo_ext . '.png';
184 $this->format = 'png';
185 $this->mime = 'image/png';
186 return true;
187 } elseif ( file_exists($file_wo_ext . '.gif') ) {
188 $this->file_path = $file_wo_ext . '.gif';
189 $this->format = 'gif';
190 $this->mime = 'image/gif';
191 return true;
192 }
193 return false;
194 }
195
196 /**
197 * Check if current file is present in the database,
198 * and copy it to the File System
199 *
200 * @return boolean true if file is present in the DB, false otherwise
201 */
202 private function _checkFileInDB()
203 {
204 global $zdb;
205
206 try {
207 $select = $this->getCheckFileQuery();
208 $pic = $zdb->db->fetchRow($select);
209 //what's $pic if no result?
210 if ( $pic !== false ) {
211 // we must regenerate the picture file
212 $file_wo_ext = $this->store_path . $this->id;
213 file_put_contents(
214 $file_wo_ext . '.' . $pic->format,
215 $pic->picture
216 );
217
218 $this->format = $pic->format;
219 switch($this->format) {
220 case 'jpg':
221 $this->mime = 'image/jpeg';
222 break;
223 case 'png':
224 $this->mime = 'image/png';
225 break;
226 case 'gif':
227 $this->mime = 'image/gif';
228 break;
229 }
230 $this->file_path = $file_wo_ext . '.' . $this->format;
231 return true;
232 }
233 } catch (\Exception $e) {
234 return false;
235 }
236 }
237
238 /**
239 * Returns the relevant query to check if picture exists in database.
240 *
241 * @return string SELECT query
242 */
243 protected function getCheckFileQuery()
244 {
245 global $zdb;
246 $class = get_class($this);
247
248 $select = new \Zend_Db_Select($zdb->db);
249 $select->from(
250 array(PREFIX_DB . $this->tbl_prefix . $class::TABLE),
251 array(
252 'picture',
253 'format'
254 )
255 );
256 $select->where($class::PK . ' = ?', $this->db_id);
257 return $select;
258 }
259
260 /**
261 * Gets the default picture to show, anyways
262 *
263 * @return void
264 */
265 protected function getDefaultPicture()
266 {
267 $this->file_path = _CURRENT_TEMPLATE_PATH . 'images/default.png';
268 $this->format = 'png';
269 $this->mime = 'image/png';
270 $this->has_picture = false;
271 }
272
273 /**
274 * Set picture sizes
275 *
276 * @return void
277 */
278 private function _setSizes()
279 {
280 list($width, $height) = getimagesize($this->file_path);
281 $this->height = $height;
282 $this->width = $width;
283 $this->optimal_height = $height;
284 $this->optimal_width = $width;
285
286 if ($this->height > $this->width) {
287 if ($this->height > $this->max_height) {
288 $ratio = $this->max_height / $this->height;
289 $this->optimal_height = $this->max_height;
290 $this->optimal_width = $this->width * $ratio;
291 }
292 } else {
293 if ($this->width > $this->max_width) {
294 $ratio = $this->max_width / $this->width;
295 $this->optimal_width = $this->max_width;
296 $this->optimal_height = $this->height * $ratio;
297 }
298 }
299 }
300
301 /**
302 * Set header and displays the picture.
303 *
304 * @return object the binary file
305 */
306 public function display()
307 {
308 header('Content-type: '.$this->mime);
309 header('Content-Length: ' . filesize($this->file_path));
310 ob_clean();
311 flush();
312 readfile($this->file_path);
313 }
314
315 /**
316 * Deletes a picture, from both database and filesystem
317 *
318 * @param boolean $transaction Whether to use a transaction here or not
319 *
320 * @return boolean true if image was successfully deleted, false otherwise
321 */
322 public function delete($transaction = true)
323 {
324 global $zdb, $log;
325 $class = get_class($this);
326
327 try {
328 if ( $transaction === true ) {
329 $zdb->db->beginTransaction();
330 }
331 $del = $zdb->db->delete(
332 PREFIX_DB . $this->tbl_prefix . $class::TABLE,
333 $zdb->db->quoteInto($class::PK . ' = ?', $this->db_id)
334 );
335 if ( $del > 0 ) {
336 $file_wo_ext = $this->store_path . $this->id;
337
338 // take back default picture
339 $this->getDefaultPicture();
340 // fix sizes
341 $this->_setSizes();
342
343 $success = false;
344 $_file = null;
345 if ( file_exists($file_wo_ext . '.jpg') ) {
346 //return unlink($file_wo_ext . '.jpg');
347 $_file = $file_wo_ext . '.jpg';
348 $success = unlink($_file);
349 } elseif ( file_exists($file_wo_ext . '.png') ) {
350 //return unlink($file_wo_ext . '.png');
351 $_file = $file_wo_ext . '.png';
352 $success = unlink($_file);
353 } elseif ( file_exists($file_wo_ext . '.gif') ) {
354 //return unlink($file_wo_ext . '.gif');
355 $_file = $file_wo_ext . '.gif';
356 $success = unlink($_file);
357 }
358
359 if ( $_file !== null && $success !== true ) {
360 //unable to remove file that exists!
361 if ( $transaction === true ) {
362 $zdb->db->rollBack();
363 }
364 $log->log(
365 'The file ' . $_file . ' was found on the disk but cannot be removed.',
366 KLogger::ERR
367 );
368 return false;
369 } else {
370 if ( $transaction === true ) {
371 $zdb->db->commit();
372 }
373 return true;
374 }
375 } else {
376 $log->log(
377 'Unable to remove picture database entry for ' . $this->db_id,
378 KLogger::ERR
379 );
380 if ( $transaction === true ) {
381 //properly ends transaction
382 $zdb->db->rollBack();
383 }
384 return false;
385 }
386
387
388 } catch (\Exception $e) {
389 if ( $transaction === true ) {
390 $zdb->db->rollBack();
391 }
392 $log->log(
393 'An error occured attempting to delete picture ' . $this->db_id .
394 'from database | ' . $e->getMessage(),
395 KLogger::ERR
396 );
397 return false;
398 }
399 }
400
401 /**
402 * Stores an image on the disk and in the database
403 *
404 * @param object $file the uploaded file
405 * @param boolean $ajax If the image cames from an ajax call (dnd)
406 *
407 * @return true|false result of the storage process
408 */
409 public function store($file, $ajax = false)
410 {
411 /** TODO:
412 - fix max size (by preferences ?)
413 - make possible to store images in database, filesystem or both
414 */
415 global $zdb, $log;
416
417 $class = get_class($this);
418
419 $name = $file['name'];
420 $tmpfile = $file['tmp_name'];
421
422 //First, does the file have a valid name?
423 $reg = "/^(.[^" . implode('', $this->_bad_chars) . "]+)\.(" .
424 implode('|', $this->_allowed_extensions) . ")$/i";
425 if ( preg_match($reg, $name, $matches) ) {
426 $log->log(
427 '[' . $class . '] Filename and extension are OK, proceed.',
428 KLogger::DEBUG
429 );
430 $extension = $matches[2];
431 if ( $extension == 'jpeg' ) {
432 //jpeg is an allowed extension,
433 //but we change it to jpg to reduce further tests :)
434 $extension = 'jpg';
435 }
436 } else {
437 $erreg = "/^(.[^" . implode('', $this->_bad_chars) . "]+)\.(.*)/i";
438 $m = preg_match($erreg, $name, $errmatches);
439
440 $err_msg = '[' . $class . '] ';
441 if ( $m == 1 ) {
442 //ok, we got a good filename and an extension. Extension is bad :)
443 $err_msg .= 'Invalid extension for file ' . $name . '.';
444 $ret = self::INVALID_EXTENSION;
445 } else {
446 $err_msg = 'Invalid filename `' . $name . '` (Tip: ';
447 $err_msg .= preg_replace(
448 '|%s|',
449 htmlentities($this->getbadChars()),
450 "file name should not contain any of: %s). "
451 );
452 $ret = self::INVALID_FILE;
453 }
454
455 $log->log(
456 $err_msg,
457 KLogger::ERR
458 );
459 return $ret;
460 }
461
462 //Second, let's check file size
463 if ( $file['size'] > ( $class::MAX_FILE_SIZE * 1024 ) ) {
464 $log->log(
465 '[' . $class . '] File is too big (' . ( $file['size'] * 1024 ) .
466 'Ko for maximum authorized ' . ( $class::MAX_FILE_SIZE * 1024 ) .
467 'Ko',
468 KLogger::ERR
469 );
470 return self::FILE_TOO_BIG;
471 } else {
472 $log->log('[' . $class . '] Filesize is OK, proceed', KLogger::DEBUG);
473 }
474
475 $current = getimagesize($tmpfile);
476
477 if ( !in_array($current['mime'], $this->_allowed_mimes) ) {
478 $log->log(
479 '[' . $class . '] Mimetype `' . $current['mime'] . '` not allowed',
480 KLogger::ERR
481 );
482 return self::MIME_NOT_ALLOWED;
483 } else {
484 $log->log(
485 '[' . $class . '] Mimetype is allowed, proceed',
486 KLogger::DEBUG
487 );
488 }
489
490 $this->delete();
491
492 $new_file = $this->store_path .
493 $this->id . '.' . $extension;
494 if ( $ajax === true ) {
495 rename($tmpfile, $new_file);
496 } else {
497 move_uploaded_file($tmpfile, $new_file);
498 }
499
500 // current[0] gives width ; current[1] gives height
501 if ( $current[0] > $this->max_width || $current[1] > $this->max_height ) {
502 /** FIXME: what if image cannot be resized?
503 Should'nt we want to stop the process here? */
504 $this->_resizeImage($new_file, $extension);
505 }
506
507 //store file in database
508 $f = fopen($new_file, 'r');
509 $picture = '';
510 while ( $r=fread($f, 8192) ) {
511 $picture .= $r;
512 }
513 fclose($f);
514
515 try {
516 $stmt = $zdb->db->prepare(
517 'INSERT INTO ' . PREFIX_DB .
518 $this->tbl_prefix . $class::TABLE . ' (' . $class::PK .
519 ', picture, format) VALUES (:id, :picture, :format)'
520 );
521
522 $stmt->bindParam('id', $this->db_id);
523 $stmt->bindParam('picture', $picture, \PDO::PARAM_LOB);
524 $stmt->bindParam('format', $extension);
525 $stmt->execute();
526 } catch (\Exception $e) {
527 /** FIXME */
528 $log->log(
529 'An error occured storing picture in database: ' .
530 $e->getMessage(),
531 KLogger::ERR
532 );
533 return self::SQL_ERROR;
534 }
535
536 return true;
537 }
538
539 /**
540 * Resize the image if it exceed max allowed sizes
541 *
542 * @param string $source the source image
543 * @param string $ext file's extension
544 * @param string $dest the destination image.
545 * If null, we'll use the source image. Defaults to null
546 *
547 * @return void
548 */
549 private function _resizeImage($source, $ext, $dest = null)
550 {
551 global $log;
552 $class = get_class($this);
553
554 if (function_exists("gd_info")) {
555 $gdinfo = gd_info();
556 $h = $this->max_height;
557 $w = $this->max_width;
558 if ( $dest == null ) {
559 $dest = $source;
560 }
561
562 switch(strtolower($ext)) {
563 case 'jpg':
564 if (!$gdinfo['JPEG Support']) {
565 $log->log(
566 '[' . $class . '] GD has no JPEG Support - ' .
567 'pictures could not be resized!',
568 KLogger::ERR
569 );
570 return false;
571 }
572 break;
573 case 'png':
574 if (!$gdinfo['PNG Support']) {
575 $log->log(
576 '[' . $class . '] GD has no PNG Support - ' .
577 'pictures could not be resized!',
578 KLogger::ERR
579 );
580 return false;
581 }
582 break;
583 case 'gif':
584 if (!$gdinfo['GIF Create Support']) {
585 $log->log(
586 '[' . $class . '] GD has no GIF Support - ' .
587 'pictures could not be resized!',
588 KLogger::ERR
589 );
590 return false;
591 }
592 break;
593 default:
594 return false;
595 }
596
597 list($cur_width, $cur_height, $cur_type, $curattr)
598 = getimagesize($source);
599
600 $ratio = $cur_width / $cur_height;
601
602 // calculate image size according to ratio
603 if ($cur_width>$cur_height) {
604 $h = $w/$ratio;
605 } else {
606 $w = $h*$ratio;
607 }
608
609 $thumb = imagecreatetruecolor($w, $h);
610 switch($ext) {
611 case 'jpg':
612 $image = ImageCreateFromJpeg($source);
613 imagecopyresampled(
614 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
615 );
616 imagejpeg($thumb, $dest);
617 break;
618 case 'png':
619 $image = ImageCreateFromPng($source);
620 // Turn off alpha blending and set alpha flag. That prevent alpha
621 // transparency to be saved as an arbitrary color (black in my tests)
622 imagealphablending($thumb, false);
623 imagealphablending($image, false);
624 imagesavealpha($thumb, true);
625 imagesavealpha($image, true);
626 imagecopyresampled(
627 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
628 );
629 imagepng($thumb, $dest);
630 break;
631 case 'gif':
632 $image = ImageCreateFromGif($source);
633 imagecopyresampled(
634 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
635 );
636 imagegif($thumb, $dest);
637 break;
638 }
639 } else {
640 $log->log(
641 '[' . $class . '] GD is not present - ' .
642 'pictures could not be resized!',
643 KLogger::ERR
644 );
645 }
646 }
647
648 /* GETTERS */
649 /**
650 * Returns current file optimal height (resized)
651 *
652 * @return int optimal height
653 */
654 public function getOptimalHeight()
655 {
656 return round($this->optimal_height);
657 }
658
659 /**
660 * Returns current file height
661 *
662 * @return int current height
663 */
664 public function getHeight()
665 {
666 return $this->height;
667 }
668
669 /**
670 * Returns current file optimal width (resized)
671 *
672 * @return int optimal width
673 */
674 public function getOptimalWidth()
675 {
676 return $this->optimal_width;
677 }
678
679 /**
680 * Returns current file width
681 *
682 * @return int current width
683 */
684 public function getWidth()
685 {
686 return $this->width;
687 }
688
689 /**
690 * Returns current file format
691 *
692 * @return string
693 */
694 public function getFormat()
695 {
696 return $this->format;
697 }
698
699 /**
700 * Have we got a picture ?
701 *
702 * @return bool True if a picture matches adherent's id, false otherwise
703 */
704 public function hasPicture()
705 {
706 return $this->has_picture;
707 }
708
709 /**
710 * Returns unauthorized characters litteral values quoted, comma separated values
711 *
712 * @return string comma separated disallowed characters
713 */
714 public function getBadChars()
715 {
716 $ret = '';
717 foreach ( $this->_bad_chars as $char=>$regchar ) {
718 $ret .= '`' . $char . '`, ';
719 }
720 return $ret;
721 }
722
723 /**
724 * Returns allowed extensions
725 *
726 * @return string comma separated allowed extensiosn
727 */
728 public function getAllowedExts()
729 {
730 return implode(', ', $this->_allowed_extensions);
731 }
732
733 /**
734 * Return the array of allowed mime types
735 *
736 * @return array
737 */
738 public function getAllowedMimeTypes()
739 {
740 return $this->_allowed_mimes;
741 }
742
743 /**
744 * Returns current file full path
745 *
746 * @return string full file path
747 */
748 public function getPath()
749 {
750 return $this->file_path;
751 }
752
753 /**
754 * Returns current mime type
755 *
756 * @return string
757 */
758 public function getMime()
759 {
760 return $this->mime;
761 }
762
763 /**
764 * Return textual error message
765 *
766 * @param int $code The error code
767 *
768 * @return string Localized message
769 */
770 public function getErrorMessage($code)
771 {
772 $error = _T("An error occued.");
773 switch( $code ) {
774 case self::INVALID_FILE:
775 $error = _T("File name is invalid, it should not contain any special character or space.");
776 break;
777 case self::INVALID_EXTENSION:
778 $error = preg_replace(
779 '|%s|',
780 $this->getAllowedExts(),
781 _T("- File extension is not allowed, only %s files are.")
782 );
783 break;
784 case self::FILE_TOO_BIG:
785 $error = preg_replace(
786 '|%d|',
787 self::MAX_FILE_SIZE,
788 _T("File is too big. Maximum allowed size is %d")
789 );
790 break;
791 case self::MIME_NOT_ALLOWED:
792 /** FIXME: should be more descriptive */
793 $error = _T("Mime-Type not allowed");
794 break;
795 case self::SQL_ERROR:
796 case self::SQL_BLOB_ERROR:
797 $error = _T("An SQL error has occured.");
798 break;
799
800 }
801 return $error;
802 }
803
804 /**
805 * Return textual erro rmessage send by PHP after upload attempt
806 *
807 * @param int $error_code The error code
808 *
809 * @return string Localized message
810 */
811 public function getPhpErrorMessage($error_code)
812 {
813 switch ($error_code) {
814 case UPLOAD_ERR_INI_SIZE:
815 return _T("The uploaded file exceeds the upload_max_filesize directive in php.ini");
816 case UPLOAD_ERR_FORM_SIZE:
817 return _T("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form");
818 case UPLOAD_ERR_PARTIAL:
819 return _T("The uploaded file was only partially uploaded");
820 case UPLOAD_ERR_NO_FILE:
821 return _T("No file was uploaded");
822 case UPLOAD_ERR_NO_TMP_DIR:
823 return _T("Missing a temporary folder");
824 case UPLOAD_ERR_CANT_WRITE:
825 return _T("Failed to write file to disk");
826 case UPLOAD_ERR_EXTENSION:
827 return _T("File upload stopped by extension");
828 default:
829 return _T("Unknown upload error");
830 }
831 }
832 }
833 ?>