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