]>
git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Core/Picture.php
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
10 * Copyright © 2006-2013 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
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.
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.
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/>.
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
35 * @link http://galette.tuxfamily.org
38 namespace Galette\Core
;
40 use Analog\Analog
as Analog
;
41 use Galette\Entity\Adherent
;
49 * @author Frédéric Jaqcuot <unknown@unknow.com>
50 * @author Johan Cwiklinski <johan@x-tnd.be>
51 * @copyright 2006-2013 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
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;
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
;
70 /*private $_bad_chars = array(
71 '\.', '\\\\', "'", ' ', '\/', ':', '\*', '\?', '"', '<', '>', '|'
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(
90 private $_allowed_extensions = array('jpeg', 'jpg', 'png', 'gif');
91 private $_allowed_mimes = array(
92 'jpg' => 'image/jpeg',
97 protected $tbl_prefix = '';
102 protected $optimal_height;
103 protected $optimal_width;
104 protected $file_path;
107 protected $has_picture = true;
108 protected $store_path = GALETTE_PHOTOS_PATH
;
109 protected $max_width = 200;
110 protected $max_height = 200;
113 * Default constructor.
115 * @param int $id_adh the id of the member
117 public function __construct( $id_adh='' )
119 // '!==' needed, otherwise ''==0
120 if ( $id_adh !== '' ) {
122 if ( !isset ($this->db_id
) ) {
123 $this->db_id
= $id_adh;
126 //if file does not exists on the FileSystem, check for it in the database
127 if ( !$this->_checkFileOnFS() ) {
128 $this->_checkFileInDB();
132 // if we still have no picture, take the default one
133 if ( $this->file_path
=='' ) {
134 $this->getDefaultPicture();
137 //we should not have an empty file_path, but...
138 if ( $this->file_path
!== '' ) {
144 * "Magic" function called on unserialize
148 public function __wakeup()
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();
158 // if we still have no picture, take the default one
159 if ( $this->file_path
=='' ) {
160 $this->getDefaultPicture();
163 //we should not have an empty file_path, but...
164 if ( $this->file_path
!== '' ) {
170 * Check if current file is present on the File System
172 * @return boolean true if file is present on FS, false otherwise
174 private function _checkFileOnFS()
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';
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';
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';
197 * Check if current file is present in the database,
198 * and copy it to the File System
200 * @return boolean true if file is present in the DB, false otherwise
202 private function _checkFileInDB()
207 $select = $this->getCheckFileQuery();
208 $results = $zdb->execute($select);
209 $pic = $results->current();
210 //what's $pic if no result?
211 if ( $pic !== false ) {
212 // we must regenerate the picture file
213 $file_wo_ext = $this->store_path
. $this->id
;
215 $file_wo_ext . '.' . $pic->format
,
219 $this->format
= $pic->format
;
220 switch($this->format
) {
222 $this->mime
= 'image/jpeg';
225 $this->mime
= 'image/png';
228 $this->mime
= 'image/gif';
231 $this->file_path
= $file_wo_ext . '.' . $this->format
;
234 } catch (\Exception
$e) {
240 * Returns the relevant query to check if picture exists in database.
242 * @return string SELECT query
244 protected function getCheckFileQuery()
247 $class = get_class($this);
249 $select = $zdb->select($this->tbl_prefix
. $class::TABLE
);
256 $select->where(array($class::PK
=> $this->db_id
));
261 * Gets the default picture to show, anyways
265 protected function getDefaultPicture()
267 $this->file_path
= _CURRENT_TEMPLATE_PATH
. 'images/default.png';
268 $this->format
= 'png';
269 $this->mime
= 'image/png';
270 $this->has_picture
= false;
278 private function _setSizes()
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;
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;
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;
302 * Set header and displays the picture.
304 * @return object the binary file
306 public function display()
308 header('Content-type: '.$this->mime
);
309 header('Content-Length: ' . filesize($this->file_path
));
312 readfile($this->file_path
);
316 * Deletes a picture, from both database and filesystem
318 * @param boolean $transaction Whether to use a transaction here or not
320 * @return boolean true if image was successfully deleted, false otherwise
322 public function delete($transaction = true)
325 $class = get_class($this);
328 if ( $transaction === true ) {
329 $zdb->connection
->beginTransaction();
332 $delete = $zdb->delete($class::TABLE
);
334 $class::PK
. ' = ' . $this->db_id
336 $del = $zdb->execute($delete);
338 if ( !$del->getCount() > 0 ) {
340 'Unable to remove picture database entry for ' . $this->db_id
,
343 //it may be possible image is missing in the database.
344 //let's try to remove file anyway.
347 $file_wo_ext = $this->store_path
. $this->id
;
349 // take back default picture
350 $this->getDefaultPicture();
356 if ( file_exists($file_wo_ext . '.jpg') ) {
357 //return unlink($file_wo_ext . '.jpg');
358 $_file = $file_wo_ext . '.jpg';
359 $success = unlink($_file);
360 } elseif ( file_exists($file_wo_ext . '.png') ) {
361 //return unlink($file_wo_ext . '.png');
362 $_file = $file_wo_ext . '.png';
363 $success = unlink($_file);
364 } elseif ( file_exists($file_wo_ext . '.gif') ) {
365 //return unlink($file_wo_ext . '.gif');
366 $_file = $file_wo_ext . '.gif';
367 $success = unlink($_file);
370 if ( $_file !== null && $success !== true ) {
371 //unable to remove file that exists!
372 if ( $transaction === true ) {
373 $zdb->connection
->rollBack();
376 'The file ' . $_file .
377 ' was found on the disk but cannot be removed.',
382 if ( $transaction === true ) {
383 $zdb->connection
->commit();
387 } catch (\Exception
$e) {
388 if ( $transaction === true ) {
389 $zdb->connection
->rollBack();
392 'An error occured attempting to delete picture ' . $this->db_id
.
393 'from database | ' . $e->getMessage(),
401 * Stores an image on the disk and in the database
403 * @param object $file the uploaded file
404 * @param boolean $ajax If the image cames from an ajax call (dnd)
406 * @return true|false result of the storage process
408 public function store($file, $ajax = false)
411 - fix max size (by preferences ?)
412 - make possible to store images in database, filesystem or both
416 $class = get_class($this);
418 $name = $file['name'];
419 $tmpfile = $file['tmp_name'];
421 //First, does the file have a valid name?
422 $reg = "/^(.[^" . implode('', $this->_bad_chars
) . "]+)\.(" .
423 implode('|', $this->_allowed_extensions
) . ")$/i";
424 if ( preg_match($reg, $name, $matches) ) {
426 '[' . $class . '] Filename and extension are OK, proceed.',
429 $extension = strtolower($matches[2]);
430 if ( $extension == 'jpeg' ) {
431 //jpeg is an allowed extension,
432 //but we change it to jpg to reduce further tests :)
436 $erreg = "/^(.[^" . implode('', $this->_bad_chars
) . "]+)\.(.*)/i";
437 $m = preg_match($erreg, $name, $errmatches);
439 $err_msg = '[' . $class . '] ';
441 //ok, we got a good filename and an extension. Extension is bad :)
442 $err_msg .= 'Invalid extension for file ' . $name . '.';
443 $ret = self
::INVALID_EXTENSION
;
445 $err_msg = 'Invalid filename `' . $name . '` (Tip: ';
446 $err_msg .= preg_replace(
448 htmlentities($this->getbadChars()),
449 "file name should not contain any of: %s). "
451 $ret = self
::INVALID_FILE
;
461 //Second, let's check file size
462 if ( $file['size'] > ( $class::MAX_FILE_SIZE
* 1024 ) ) {
464 '[' . $class . '] File is too big (' . ( $file['size'] * 1024 ) .
465 'Ko for maximum authorized ' . ( $class::MAX_FILE_SIZE
* 1024 ) .
469 return self
::FILE_TOO_BIG
;
471 Analog
::log('[' . $class . '] Filesize is OK, proceed', Analog
::DEBUG
);
474 $current = getimagesize($tmpfile);
476 if ( !in_array($current['mime'], $this->_allowed_mimes
) ) {
478 '[' . $class . '] Mimetype `' . $current['mime'] . '` not allowed',
481 return self
::MIME_NOT_ALLOWED
;
484 '[' . $class . '] Mimetype is allowed, proceed',
491 $new_file = $this->store_path
.
492 $this->id
. '.' . $extension;
493 if ( $ajax === true ) {
494 rename($tmpfile, $new_file);
496 move_uploaded_file($tmpfile, $new_file);
499 // current[0] gives width ; current[1] gives height
500 if ( $current[0] > $this->max_width ||
$current[1] > $this->max_height
) {
501 /** FIXME: what if image cannot be resized?
502 Should'nt we want to stop the process here? */
503 $this->_resizeImage($new_file, $extension);
506 //store file in database
507 $f = fopen($new_file, 'r');
509 while ( $r=fread($f, 8192) ) {
515 $insert = $zdb->insert($this->tbl_prefix
. $class::TABLE
);
516 $stmt = $zdb->sql
->prepareStatementForSqlObject($insert);
517 $container = $stmt->getParameterContainer();
518 $container->offsetSet(
522 $container->offsetSet(
527 $container->offsetSet(
531 $stmt->setParameterContainer($container);
535 $class::PK
=> $this->_db_id
,
536 'picture' => $picture,
537 'format' => $extension
540 } catch (\Exception
$e) {
542 'An error occured storing picture in database: ' .
546 return self
::SQL_ERROR
;
553 * Resize the image if it exceed max allowed sizes
555 * @param string $source the source image
556 * @param string $ext file's extension
557 * @param string $dest the destination image.
558 * If null, we'll use the source image. Defaults to null
562 private function _resizeImage($source, $ext, $dest = null)
564 $class = get_class($this);
566 if (function_exists("gd_info")) {
568 $h = $this->max_height
;
569 $w = $this->max_width
;
570 if ( $dest == null ) {
574 switch(strtolower($ext)) {
576 if (!$gdinfo['JPEG Support']) {
578 '[' . $class . '] GD has no JPEG Support - ' .
579 'pictures could not be resized!',
586 if (!$gdinfo['PNG Support']) {
588 '[' . $class . '] GD has no PNG Support - ' .
589 'pictures could not be resized!',
596 if (!$gdinfo['GIF Create Support']) {
598 '[' . $class . '] GD has no GIF Support - ' .
599 'pictures could not be resized!',
609 list($cur_width, $cur_height, $cur_type, $curattr)
610 = getimagesize($source);
612 $ratio = $cur_width / $cur_height;
614 // calculate image size according to ratio
615 if ($cur_width>$cur_height) {
621 $thumb = imagecreatetruecolor($w, $h);
624 $image = ImageCreateFromJpeg($source);
626 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
628 imagejpeg($thumb, $dest);
631 $image = ImageCreateFromPng($source);
632 // Turn off alpha blending and set alpha flag. That prevent alpha
633 // transparency to be saved as an arbitrary color (black in my tests)
634 imagealphablending($thumb, false);
635 imagealphablending($image, false);
636 imagesavealpha($thumb, true);
637 imagesavealpha($image, true);
639 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
641 imagepng($thumb, $dest);
644 $image = ImageCreateFromGif($source);
646 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
648 imagegif($thumb, $dest);
653 '[' . $class . '] GD is not present - ' .
654 'pictures could not be resized!',
661 * Returns current file optimal height (resized)
663 * @return int optimal height
665 public function getOptimalHeight()
667 return round($this->optimal_height
);
671 * Returns current file height
673 * @return int current height
675 public function getHeight()
677 return $this->height
;
681 * Returns current file optimal width (resized)
683 * @return int optimal width
685 public function getOptimalWidth()
687 return $this->optimal_width
;
691 * Returns current file width
693 * @return int current width
695 public function getWidth()
701 * Returns current file format
705 public function getFormat()
707 return $this->format
;
711 * Have we got a picture ?
713 * @return bool True if a picture matches adherent's id, false otherwise
715 public function hasPicture()
717 return $this->has_picture
;
721 * Returns unauthorized characters litteral values quoted, comma separated values
723 * @return string comma separated disallowed characters
725 public function getBadChars()
728 foreach ( $this->_bad_chars
as $char=>$regchar ) {
729 $ret .= '`' . $char . '`, ';
735 * Returns allowed extensions
737 * @return string comma separated allowed extensiosn
739 public function getAllowedExts()
741 return implode(', ', $this->_allowed_extensions
);
745 * Return the array of allowed mime types
749 public function getAllowedMimeTypes()
751 return $this->_allowed_mimes
;
755 * Returns current file full path
757 * @return string full file path
759 public function getPath()
761 return $this->file_path
;
765 * Returns current mime type
769 public function getMime()
775 * Return textual error message
777 * @param int $code The error code
779 * @return string Localized message
781 public function getErrorMessage($code)
783 $error = _T("An error occued.");
785 case self
::INVALID_FILE
:
786 $error = _T("File name is invalid, it should not contain any special character or space.");
788 case self
::INVALID_EXTENSION
:
789 $error = preg_replace(
791 $this->getAllowedExts(),
792 _T("- File extension is not allowed, only %s files are.")
795 case self
::FILE_TOO_BIG
:
796 $error = preg_replace(
799 _T("File is too big. Maximum allowed size is %dKo")
802 case self
::MIME_NOT_ALLOWED
:
803 /** FIXME: should be more descriptive */
804 $error = _T("Mime-Type not allowed");
806 case self
::SQL_ERROR
:
807 case self
::SQL_BLOB_ERROR
:
808 $error = _T("An SQL error has occured.");
816 * Return textual error message send by PHP after upload attempt
818 * @param int $error_code The error code
820 * @return string Localized message
822 public function getPhpErrorMessage($error_code)
824 switch ($error_code) {
825 case UPLOAD_ERR_INI_SIZE
:
826 return _T("The uploaded file exceeds the upload_max_filesize directive in php.ini");
827 case UPLOAD_ERR_FORM_SIZE
:
828 return _T("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form");
829 case UPLOAD_ERR_PARTIAL
:
830 return _T("The uploaded file was only partially uploaded");
831 case UPLOAD_ERR_NO_FILE
:
832 return _T("No file was uploaded");
833 case UPLOAD_ERR_NO_TMP_DIR
:
834 return _T("Missing a temporary folder");
835 case UPLOAD_ERR_CANT_WRITE
:
836 return _T("Failed to write file to disk");
837 case UPLOAD_ERR_EXTENSION
:
838 return _T("File upload stopped by extension");
840 return _T("Unknown upload error");