]>
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
;
42 use Galette\Entity\Adherent
;
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
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;
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
;
71 /*private $_bad_chars = array(
72 '\.', '\\\\', "'", ' ', '\/', ':', '\*', '\?', '"', '<', '>', '|'
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(
91 private $_allowed_extensions = array('jpeg', 'jpg', 'png', 'gif');
92 private $_allowed_mimes = array(
93 'jpg' => 'image/jpeg',
98 protected $tbl_prefix = '';
103 protected $optimal_height;
104 protected $optimal_width;
105 protected $file_path;
108 protected $has_picture = true;
109 protected $store_path = GALETTE_PHOTOS_PATH
;
110 protected $max_width = 200;
111 protected $max_height = 200;
114 * Default constructor.
116 * @param int $id_adh the id of the member
118 public function __construct( $id_adh='' )
120 // '!==' needed, otherwise ''==0
121 if ( $id_adh !== '' ) {
123 if ( !isset ($this->db_id
) ) {
124 $this->db_id
= $id_adh;
127 //if file does not exists on the FileSystem, check for it in the database
128 if ( !$this->_checkFileOnFS() ) {
129 $this->_checkFileInDB();
133 // if we still have no picture, take the default one
134 if ( $this->file_path
=='' ) {
135 $this->getDefaultPicture();
138 //we should not have an empty file_path, but...
139 if ( $this->file_path
!== '' ) {
145 * "Magic" function called on unserialize
149 public function __wakeup()
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();
159 // if we still have no picture, take the default one
160 if ( $this->file_path
=='' ) {
161 $this->getDefaultPicture();
164 //we should not have an empty file_path, but...
165 if ( $this->file_path
!== '' ) {
171 * Check if current file is present on the File System
173 * @return boolean true if file is present on FS, false otherwise
175 private function _checkFileOnFS()
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';
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';
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';
198 * Check if current file is present in the database,
199 * and copy it to the File System
201 * @return boolean true if file is present in the DB, false otherwise
203 private function _checkFileInDB()
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
;
216 $file_wo_ext . '.' . $pic->format
,
220 $this->format
= $pic->format
;
221 switch($this->format
) {
223 $this->mime
= 'image/jpeg';
226 $this->mime
= 'image/png';
229 $this->mime
= 'image/gif';
232 $this->file_path
= $file_wo_ext . '.' . $this->format
;
235 } catch (\Exception
$e) {
241 * Returns the relevant query to check if picture exists in database.
243 * @return string SELECT query
245 protected function getCheckFileQuery()
248 $class = get_class($this);
250 $select = $zdb->select($this->tbl_prefix
. $class::TABLE
);
257 $select->where(array($class::PK
=> $this->db_id
));
262 * Gets the default picture to show, anyways
266 protected function getDefaultPicture()
268 $this->file_path
= _CURRENT_TEMPLATE_PATH
. 'images/default.png';
269 $this->format
= 'png';
270 $this->mime
= 'image/png';
271 $this->has_picture
= false;
279 private function _setSizes()
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;
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;
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;
303 * Set header and displays the picture.
305 * @return object the binary file
307 public function display()
309 header('Content-type: '.$this->mime
);
310 header('Content-Length: ' . filesize($this->file_path
));
313 readfile($this->file_path
);
317 * Deletes a picture, from both database and filesystem
319 * @param boolean $transaction Whether to use a transaction here or not
321 * @return boolean true if image was successfully deleted, false otherwise
323 public function delete($transaction = true)
326 $class = get_class($this);
329 if ( $transaction === true ) {
330 $zdb->connection
->beginTransaction();
333 $delete = $zdb->delete($class::TABLE
);
335 $class::PK
. ' = ' . $this->db_id
337 $del = $zdb->execute($delete);
339 if ( !$del->getCount() > 0 ) {
341 'Unable to remove picture database entry for ' . $this->db_id
,
344 //it may be possible image is missing in the database.
345 //let's try to remove file anyway.
348 $file_wo_ext = $this->store_path
. $this->id
;
350 // take back default picture
351 $this->getDefaultPicture();
357 if ( file_exists($file_wo_ext . '.jpg') ) {
358 //return unlink($file_wo_ext . '.jpg');
359 $_file = $file_wo_ext . '.jpg';
360 $success = unlink($_file);
361 } elseif ( file_exists($file_wo_ext . '.png') ) {
362 //return unlink($file_wo_ext . '.png');
363 $_file = $file_wo_ext . '.png';
364 $success = unlink($_file);
365 } elseif ( file_exists($file_wo_ext . '.gif') ) {
366 //return unlink($file_wo_ext . '.gif');
367 $_file = $file_wo_ext . '.gif';
368 $success = unlink($_file);
371 if ( $_file !== null && $success !== true ) {
372 //unable to remove file that exists!
373 if ( $transaction === true ) {
374 $zdb->connection
->rollBack();
377 'The file ' . $_file .
378 ' was found on the disk but cannot be removed.',
383 if ( $transaction === true ) {
384 $zdb->connection
->commit();
388 } catch (\Exception
$e) {
389 if ( $transaction === true ) {
390 $zdb->connection
->rollBack();
393 'An error occured attempting to delete picture ' . $this->db_id
.
394 'from database | ' . $e->getMessage(),
402 * Stores an image on the disk and in the database
404 * @param object $file the uploaded file
405 * @param boolean $ajax If the image cames from an ajax call (dnd)
407 * @return true|false result of the storage process
409 public function store($file, $ajax = false)
412 - fix max size (by preferences ?)
413 - make possible to store images in database, filesystem or both
417 $class = get_class($this);
419 $name = $file['name'];
420 $tmpfile = $file['tmp_name'];
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) ) {
427 '[' . $class . '] Filename and extension are OK, proceed.',
430 $extension = strtolower($matches[2]);
431 if ( $extension == 'jpeg' ) {
432 //jpeg is an allowed extension,
433 //but we change it to jpg to reduce further tests :)
437 $erreg = "/^(.[^" . implode('', $this->_bad_chars
) . "]+)\.(.*)/i";
438 $m = preg_match($erreg, $name, $errmatches);
440 $err_msg = '[' . $class . '] ';
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
;
446 $err_msg = 'Invalid filename `' . $name . '` (Tip: ';
447 $err_msg .= preg_replace(
449 htmlentities($this->getbadChars()),
450 "file name should not contain any of: %s). "
452 $ret = self
::INVALID_FILE
;
462 //Second, let's check file size
463 if ( $file['size'] > ( $class::MAX_FILE_SIZE
* 1024 ) ) {
465 '[' . $class . '] File is too big (' . ( $file['size'] * 1024 ) .
466 'Ko for maximum authorized ' . ( $class::MAX_FILE_SIZE
* 1024 ) .
470 return self
::FILE_TOO_BIG
;
472 Analog
::log('[' . $class . '] Filesize is OK, proceed', Analog
::DEBUG
);
475 $current = getimagesize($tmpfile);
477 if ( !in_array($current['mime'], $this->_allowed_mimes
) ) {
479 '[' . $class . '] Mimetype `' . $current['mime'] . '` not allowed',
482 return self
::MIME_NOT_ALLOWED
;
485 '[' . $class . '] Mimetype is allowed, proceed',
492 $new_file = $this->store_path
.
493 $this->id
. '.' . $extension;
494 if ( $ajax === true ) {
495 rename($tmpfile, $new_file);
497 move_uploaded_file($tmpfile, $new_file);
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);
507 //store file in database
508 $f = fopen($new_file, 'r');
510 while ( $r=fread($f, 8192) ) {
516 $insert = $zdb->insert($this->tbl_prefix
. $class::TABLE
);
520 'picture' => ':picture',
521 'format' => ':format'
524 $stmt = $sql->prepareStatementForSqlObject($insert);
528 $class::PK
=> $this->_db_id
,
529 'picture' => $picture,
530 'format' => $extension
533 } catch (\Exception
$e) {
535 'An error occured storing picture in database: ' .
539 return self
::SQL_ERROR
;
546 * Resize the image if it exceed max allowed sizes
548 * @param string $source the source image
549 * @param string $ext file's extension
550 * @param string $dest the destination image.
551 * If null, we'll use the source image. Defaults to null
555 private function _resizeImage($source, $ext, $dest = null)
557 $class = get_class($this);
559 if (function_exists("gd_info")) {
561 $h = $this->max_height
;
562 $w = $this->max_width
;
563 if ( $dest == null ) {
567 switch(strtolower($ext)) {
569 if (!$gdinfo['JPEG Support']) {
571 '[' . $class . '] GD has no JPEG Support - ' .
572 'pictures could not be resized!',
579 if (!$gdinfo['PNG Support']) {
581 '[' . $class . '] GD has no PNG Support - ' .
582 'pictures could not be resized!',
589 if (!$gdinfo['GIF Create Support']) {
591 '[' . $class . '] GD has no GIF Support - ' .
592 'pictures could not be resized!',
602 list($cur_width, $cur_height, $cur_type, $curattr)
603 = getimagesize($source);
605 $ratio = $cur_width / $cur_height;
607 // calculate image size according to ratio
608 if ($cur_width>$cur_height) {
614 $thumb = imagecreatetruecolor($w, $h);
617 $image = ImageCreateFromJpeg($source);
619 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
621 imagejpeg($thumb, $dest);
624 $image = ImageCreateFromPng($source);
625 // Turn off alpha blending and set alpha flag. That prevent alpha
626 // transparency to be saved as an arbitrary color (black in my tests)
627 imagealphablending($thumb, false);
628 imagealphablending($image, false);
629 imagesavealpha($thumb, true);
630 imagesavealpha($image, true);
632 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
634 imagepng($thumb, $dest);
637 $image = ImageCreateFromGif($source);
639 $thumb, $image, 0, 0, 0, 0, $w, $h, $cur_width, $cur_height
641 imagegif($thumb, $dest);
646 '[' . $class . '] GD is not present - ' .
647 'pictures could not be resized!',
654 * Returns current file optimal height (resized)
656 * @return int optimal height
658 public function getOptimalHeight()
660 return round($this->optimal_height
);
664 * Returns current file height
666 * @return int current height
668 public function getHeight()
670 return $this->height
;
674 * Returns current file optimal width (resized)
676 * @return int optimal width
678 public function getOptimalWidth()
680 return $this->optimal_width
;
684 * Returns current file width
686 * @return int current width
688 public function getWidth()
694 * Returns current file format
698 public function getFormat()
700 return $this->format
;
704 * Have we got a picture ?
706 * @return bool True if a picture matches adherent's id, false otherwise
708 public function hasPicture()
710 return $this->has_picture
;
714 * Returns unauthorized characters litteral values quoted, comma separated values
716 * @return string comma separated disallowed characters
718 public function getBadChars()
721 foreach ( $this->_bad_chars
as $char=>$regchar ) {
722 $ret .= '`' . $char . '`, ';
728 * Returns allowed extensions
730 * @return string comma separated allowed extensiosn
732 public function getAllowedExts()
734 return implode(', ', $this->_allowed_extensions
);
738 * Return the array of allowed mime types
742 public function getAllowedMimeTypes()
744 return $this->_allowed_mimes
;
748 * Returns current file full path
750 * @return string full file path
752 public function getPath()
754 return $this->file_path
;
758 * Returns current mime type
762 public function getMime()
768 * Return textual error message
770 * @param int $code The error code
772 * @return string Localized message
774 public function getErrorMessage($code)
776 $error = _T("An error occued.");
778 case self
::INVALID_FILE
:
779 $error = _T("File name is invalid, it should not contain any special character or space.");
781 case self
::INVALID_EXTENSION
:
782 $error = preg_replace(
784 $this->getAllowedExts(),
785 _T("- File extension is not allowed, only %s files are.")
788 case self
::FILE_TOO_BIG
:
789 $error = preg_replace(
792 _T("File is too big. Maximum allowed size is %dKo")
795 case self
::MIME_NOT_ALLOWED
:
796 /** FIXME: should be more descriptive */
797 $error = _T("Mime-Type not allowed");
799 case self
::SQL_ERROR
:
800 case self
::SQL_BLOB_ERROR
:
801 $error = _T("An SQL error has occured.");
809 * Return textual error message send by PHP after upload attempt
811 * @param int $error_code The error code
813 * @return string Localized message
815 public function getPhpErrorMessage($error_code)
817 switch ($error_code) {
818 case UPLOAD_ERR_INI_SIZE
:
819 return _T("The uploaded file exceeds the upload_max_filesize directive in php.ini");
820 case UPLOAD_ERR_FORM_SIZE
:
821 return _T("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form");
822 case UPLOAD_ERR_PARTIAL
:
823 return _T("The uploaded file was only partially uploaded");
824 case UPLOAD_ERR_NO_FILE
:
825 return _T("No file was uploaded");
826 case UPLOAD_ERR_NO_TMP_DIR
:
827 return _T("Missing a temporary folder");
828 case UPLOAD_ERR_CANT_WRITE
:
829 return _T("Failed to write file to disk");
830 case UPLOAD_ERR_EXTENSION
:
831 return _T("File upload stopped by extension");
833 return _T("Unknown upload error");