3 if(! class_exists("Photo")) {
9 * Put back gd stuff, not everybody have Imagick
19 * supported mimetypes and corresponding file extensions
21 static function supportedTypes() {
22 if(class_exists('Imagick')) {
24 * Imagick::queryFormats won't help us a lot there...
25 * At least, not yet, other parts of friendica uses this array
28 'image/jpeg' => 'jpg',
34 $t['image/jpeg'] ='jpg';
35 if (imagetypes() & IMG_PNG) $t['image/png'] = 'png';
41 public function __construct($data, $type=null) {
42 $this->imagick = class_exists('Imagick');
43 $this->types = $this->supportedTypes();
44 if (!array_key_exists($type,$this->types)){
49 if($this->is_imagick() && $this->load_data($data)) {
52 // Failed to load with Imagick, fallback
53 $this->imagick = false;
55 return $this->load_data($data);
58 public function __destruct() {
60 if($this->is_imagick()) {
61 $this->image->clear();
62 $this->image->destroy();
65 imagedestroy($this->image);
69 public function is_imagick() {
70 return $this->imagick;
74 * Maps Mime types to Imagick formats
76 public function get_FormatsMap() {
78 'image/jpeg' => 'JPG',
85 private function load_data($data) {
86 if($this->is_imagick()) {
87 $this->image = new Imagick();
89 $this->image->readImageBlob($data);
91 catch (Exception $e) {
92 // Imagick couldn't use the data
97 * Setup the image to the format it will be saved to
99 $map = $this->get_FormatsMap();
100 $format = $map[$type];
101 $this->image->setFormat($format);
103 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
104 $this->image = $this->image->coalesceImages();
107 * setup the compression here, so we'll do it only once
109 switch($this->getType()){
111 $quality = get_config('system','png_quality');
112 if((! $quality) || ($quality > 9))
113 $quality = PNG_QUALITY;
115 * From http://www.imagemagick.org/script/command-line-options.php#quality:
117 * 'For the MNG and PNG image formats, the quality value sets
118 * the zlib compression level (quality / 10) and filter-type (quality % 10).
119 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
120 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
122 $quality = $quality * 10;
123 $this->image->setCompressionQuality($quality);
126 $quality = get_config('system','jpeg_quality');
127 if((! $quality) || ($quality > 100))
128 $quality = JPEG_QUALITY;
129 $this->image->setCompressionQuality($quality);
132 // The 'width' and 'height' properties are only used by non-Imagick routines.
133 $this->width = $this->image->getImageWidth();
134 $this->height = $this->image->getImageHeight();
140 $this->valid = false;
141 $this->image = @imagecreatefromstring($data);
142 if($this->image !== FALSE) {
143 $this->width = imagesx($this->image);
144 $this->height = imagesy($this->image);
146 imagealphablending($this->image, false);
147 imagesavealpha($this->image, true);
155 public function is_valid() {
156 if($this->is_imagick())
157 return ($this->image !== FALSE);
161 public function getWidth() {
162 if(!$this->is_valid())
165 if($this->is_imagick())
166 return $this->image->getImageWidth();
170 public function getHeight() {
171 if(!$this->is_valid())
174 if($this->is_imagick())
175 return $this->image->getImageHeight();
176 return $this->height;
179 public function getImage() {
180 if(!$this->is_valid())
183 if($this->is_imagick()) {
185 $this->image = $this->image->deconstructImages();
191 public function getType() {
192 if(!$this->is_valid())
198 public function getExt() {
199 if(!$this->is_valid())
202 return $this->types[$this->getType()];
205 public function scaleImage($max) {
206 if(!$this->is_valid())
209 $width = $this->getWidth();
210 $height = $this->getHeight();
212 $dest_width = $dest_height = 0;
214 if((! $width)|| (! $height))
217 if($width > $max && $height > $max) {
219 // very tall image (greater than 16:9)
220 // constrain the width - let the height float.
222 if((($height * 9) / 16) > $width) {
224 $dest_height = intval(( $height * $max ) / $width);
227 // else constrain both dimensions
229 elseif($width > $height) {
231 $dest_height = intval(( $height * $max ) / $width);
234 $dest_width = intval(( $width * $max ) / $height);
239 if( $width > $max ) {
241 $dest_height = intval(( $height * $max ) / $width);
244 if( $height > $max ) {
246 // very tall image (greater than 16:9)
247 // but width is OK - don't do anything
249 if((($height * 9) / 16) > $width) {
250 $dest_width = $width;
251 $dest_height = $height;
254 $dest_width = intval(( $width * $max ) / $height);
259 $dest_width = $width;
260 $dest_height = $height;
266 if($this->is_imagick()) {
268 * If it is not animated, there will be only one iteration here,
269 * so don't bother checking
271 // Don't forget to go back to the first frame
272 $this->image->setFirstIterator();
275 // FIXME - implement horizantal bias for scaling as in followin GD functions
276 // to allow very tall images to be constrained only horizontally.
278 $this->image->scaleImage($dest_width, $dest_height);
279 } while ($this->image->nextImage());
281 // These may not be necessary any more
282 $this->width = $this->image->getImageWidth();
283 $this->height = $this->image->getImageHeight();
289 $dest = imagecreatetruecolor( $dest_width, $dest_height );
290 imagealphablending($dest, false);
291 imagesavealpha($dest, true);
292 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
293 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
295 imagedestroy($this->image);
296 $this->image = $dest;
297 $this->width = imagesx($this->image);
298 $this->height = imagesy($this->image);
301 public function rotate($degrees) {
302 if(!$this->is_valid())
305 if($this->is_imagick()) {
306 $this->image->setFirstIterator();
308 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
309 } while ($this->image->nextImage());
313 $this->image = imagerotate($this->image,$degrees,0);
314 $this->width = imagesx($this->image);
315 $this->height = imagesy($this->image);
318 public function flip($horiz = true, $vert = false) {
319 if(!$this->is_valid())
322 if($this->is_imagick()) {
323 $this->image->setFirstIterator();
325 if($horiz) $this->image->flipImage();
326 if($vert) $this->image->flopImage();
327 } while ($this->image->nextImage());
331 $w = imagesx($this->image);
332 $h = imagesy($this->image);
333 $flipped = imagecreate($w, $h);
335 for ($x = 0; $x < $w; $x++) {
336 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
340 for ($y = 0; $y < $h; $y++) {
341 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
344 $this->image = $flipped;
347 public function orient($filename) {
348 if ($this->is_imagick()) {
349 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
350 $orientation = $this->image->getImageOrientation();
351 switch ($orientation) {
352 case imagick::ORIENTATION_BOTTOMRIGHT:
353 $this->image->rotateimage("#000", 180);
355 case imagick::ORIENTATION_RIGHTTOP:
356 $this->image->rotateimage("#000", 90);
358 case imagick::ORIENTATION_LEFTBOTTOM:
359 $this->image->rotateimage("#000", -90);
363 $this->image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
366 // based off comment on http://php.net/manual/en/function.imagerotate.php
368 if(!$this->is_valid())
371 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
374 $exif = @exif_read_data($filename,null,true);
378 $ort = $exif['IFD0']['Orientation'];
385 case 2: // horizontal flip
389 case 3: // 180 rotate left
393 case 4: // vertical flip
394 $this->flip(false, true);
397 case 5: // vertical flip + 90 rotate right
398 $this->flip(false, true);
402 case 6: // 90 rotate right
406 case 7: // horizontal flip + 90 rotate right
411 case 8: // 90 rotate left
416 // logger('exif: ' . print_r($exif,true));
423 public function scaleImageUp($min) {
424 if(!$this->is_valid())
428 $width = $this->getWidth();
429 $height = $this->getHeight();
431 $dest_width = $dest_height = 0;
433 if((! $width)|| (! $height))
436 if($width < $min && $height < $min) {
437 if($width > $height) {
439 $dest_height = intval(( $height * $min ) / $width);
442 $dest_width = intval(( $width * $min ) / $height);
447 if( $width < $min ) {
449 $dest_height = intval(( $height * $min ) / $width);
452 if( $height < $min ) {
453 $dest_width = intval(( $width * $min ) / $height);
457 $dest_width = $width;
458 $dest_height = $height;
463 if($this->is_imagick())
464 return $this->scaleImage($dest_width,$dest_height);
466 $dest = imagecreatetruecolor( $dest_width, $dest_height );
467 imagealphablending($dest, false);
468 imagesavealpha($dest, true);
469 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
470 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
472 imagedestroy($this->image);
473 $this->image = $dest;
474 $this->width = imagesx($this->image);
475 $this->height = imagesy($this->image);
480 public function scaleImageSquare($dim) {
481 if(!$this->is_valid())
484 if($this->is_imagick()) {
485 $this->image->setFirstIterator();
487 $this->image->scaleImage($dim, $dim);
488 } while ($this->image->nextImage());
492 $dest = imagecreatetruecolor( $dim, $dim );
493 imagealphablending($dest, false);
494 imagesavealpha($dest, true);
495 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
496 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
498 imagedestroy($this->image);
499 $this->image = $dest;
500 $this->width = imagesx($this->image);
501 $this->height = imagesy($this->image);
505 public function cropImage($max,$x,$y,$w,$h) {
506 if(!$this->is_valid())
509 if($this->is_imagick()) {
510 $this->image->setFirstIterator();
512 $this->image->cropImage($w, $h, $x, $y);
514 * We need to remove the canva,
515 * or the image is not resized to the crop:
516 * http://php.net/manual/en/imagick.cropimage.php#97232
518 $this->image->setImagePage(0, 0, 0, 0);
519 } while ($this->image->nextImage());
520 return $this->scaleImage($max);
523 $dest = imagecreatetruecolor( $max, $max );
524 imagealphablending($dest, false);
525 imagesavealpha($dest, true);
526 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
527 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
529 imagedestroy($this->image);
530 $this->image = $dest;
531 $this->width = imagesx($this->image);
532 $this->height = imagesy($this->image);
535 public function saveImage($path) {
536 if(!$this->is_valid())
539 $string = $this->imageString();
543 $stamp1 = microtime(true);
544 file_put_contents($path, $string);
545 $a->save_timestamp($stamp1, "file");
548 public function imageString() {
549 if(!$this->is_valid())
552 if($this->is_imagick()) {
554 $this->image = $this->image->deconstructImages();
555 $string = $this->image->getImagesBlob();
563 // Enable interlacing
564 imageinterlace($this->image, true);
566 switch($this->getType()){
568 $quality = get_config('system','png_quality');
569 if((! $quality) || ($quality > 9))
570 $quality = PNG_QUALITY;
571 imagepng($this->image,NULL, $quality);
574 $quality = get_config('system','jpeg_quality');
575 if((! $quality) || ($quality > 100))
576 $quality = JPEG_QUALITY;
577 imagejpeg($this->image,NULL,$quality);
579 $string = ob_get_contents();
587 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
589 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
593 $guid = $r[0]['guid'];
597 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
604 $r = q("UPDATE `photo`
608 `resource-id` = '%s',
630 dbesc(datetime_convert()),
631 dbesc(datetime_convert()),
632 dbesc(basename($filename)),
633 dbesc($this->getType()),
635 intval($this->getHeight()),
636 intval($this->getWidth()),
637 dbesc(strlen($this->imageString())),
638 dbesc($this->imageString()),
649 $r = q("INSERT INTO `photo`
650 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `datasize`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
651 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
656 dbesc(datetime_convert()),
657 dbesc(datetime_convert()),
658 dbesc(basename($filename)),
659 dbesc($this->getType()),
661 intval($this->getHeight()),
662 intval($this->getWidth()),
663 dbesc(strlen($this->imageString())),
664 dbesc($this->imageString()),
679 * Guess image mimetype from filename or from Content-Type header
681 * @arg $filename string Image filename
682 * @arg $fromcurl boolean Check Content-Type header from curl request
684 function guess_image_type($filename, $fromcurl=false) {
685 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
690 $h = explode("\n",$a->get_curl_headers());
692 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
695 if (array_key_exists('Content-Type', $headers))
696 $type = $headers['Content-Type'];
699 // Guessing from extension? Isn't that... dangerous?
700 if(class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
702 * Well, this not much better,
703 * but at least it comes from the data inside the image,
704 * we won't be tricked by a manipulated extension
706 $image = new Imagick($filename);
707 $type = $image->getImageMimeType();
708 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
710 $ext = pathinfo($filename, PATHINFO_EXTENSION);
711 $types = Photo::supportedTypes();
712 $type = "image/jpeg";
713 foreach ($types as $m=>$e){
714 if ($ext==$e) $type = $m;
718 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
724 * @brief Updates the avatar links in a contact only if needed
726 * @param string $avatar Link to avatar picture
727 * @param int $uid User id of contact owner
728 * @param int $cid Contact id
729 * @param bool $force force picture update
731 * @return array Returns array of the different avatar sizes
733 function update_contact_avatar($avatar,$uid,$cid, $force = false) {
735 $r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
739 $data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
741 if (($r[0]["avatar"] != $avatar) OR $force) {
742 $photos = import_profile_photo($avatar,$uid,$cid, true);
745 q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
746 dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
747 dbesc(datetime_convert()), intval($cid));
755 function import_profile_photo($photo,$uid,$cid, $quit_on_error = false) {
759 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
763 if(count($r) && strlen($r[0]['resource-id'])) {
764 $hash = $r[0]['resource-id'];
766 $hash = photo_new_resource();
769 $photo_failure = false;
771 $filename = basename($photo);
772 $img_str = fetch_url($photo,true);
774 if ($quit_on_error AND ($img_str == ""))
777 $type = guess_image_type($photo,true);
778 $img = new Photo($img_str, $type);
779 if($img->is_valid()) {
781 $img->scaleImageSquare(175);
783 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
786 $photo_failure = true;
788 $img->scaleImage(80);
790 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
793 $photo_failure = true;
795 $img->scaleImage(48);
797 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
800 $photo_failure = true;
802 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
803 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
804 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
806 $photo_failure = true;
808 if($photo_failure AND $quit_on_error)
812 $photo = $a->get_baseurl() . '/images/person-175.jpg';
813 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
814 $micro = $a->get_baseurl() . '/images/person-48.jpg';
817 return(array($photo,$thumb,$micro));
821 function get_photo_info($url) {
824 $data = Cache::get($url);
826 // Unserialise to be able to check in the next step if the cached data is alright.
828 $data = unserialize($data);
830 if (is_null($data) OR !$data) {
831 $img_str = fetch_url($url, true, $redirects, 4);
832 $filesize = strlen($img_str);
834 if (function_exists("getimagesizefromstring"))
835 $data = getimagesizefromstring($img_str);
837 $tempfile = tempnam(get_temppath(), "cache");
840 $stamp1 = microtime(true);
841 file_put_contents($tempfile, $img_str);
842 $a->save_timestamp($stamp1, "file");
844 $data = getimagesize($tempfile);
849 $data["size"] = $filesize;
851 Cache::set($url, serialize($data));
857 function scale_image($width, $height, $max) {
859 $dest_width = $dest_height = 0;
861 if((!$width) || (!$height))
864 if($width > $max && $height > $max) {
866 // very tall image (greater than 16:9)
867 // constrain the width - let the height float.
869 if((($height * 9) / 16) > $width) {
871 $dest_height = intval(( $height * $max ) / $width);
872 } elseif($width > $height) {
873 // else constrain both dimensions
875 $dest_height = intval(( $height * $max ) / $width);
877 $dest_width = intval(( $width * $max ) / $height);
881 if( $width > $max ) {
883 $dest_height = intval(( $height * $max ) / $width);
885 if( $height > $max ) {
887 // very tall image (greater than 16:9)
888 // but width is OK - don't do anything
890 if((($height * 9) / 16) > $width) {
891 $dest_width = $width;
892 $dest_height = $height;
894 $dest_width = intval(( $width * $max ) / $height);
898 $dest_width = $width;
899 $dest_height = $height;
903 return array("width" => $dest_width, "height" => $dest_height);
906 function store_photo($a, $uid, $imagedata = "", $url = "") {
907 $r = q("SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
908 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1",
912 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
916 $page_owner_nick = $r[0]['nickname'];
919 /// $default_cid = $r[0]['id'];
920 /// $community_page = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
922 if ((strlen($imagedata) == 0) AND ($url == "")) {
923 logger("No image data and no url provided", LOGGER_DEBUG);
925 } elseif (strlen($imagedata) == 0) {
926 logger("Uploading picture from ".$url, LOGGER_DEBUG);
928 $stamp1 = microtime(true);
929 $imagedata = @file_get_contents($url);
930 $a->save_timestamp($stamp1, "file");
933 $maximagesize = get_config('system','maximagesize');
935 if(($maximagesize) && (strlen($imagedata) > $maximagesize)) {
936 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
941 $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
945 $limit = service_class_fetch($uid,'photo_upload_limit');
947 if(($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
948 logger("Image exceeds personal limit of uid ".$uid, LOGGER_DEBUG);
953 $tempfile = tempnam(get_temppath(), "cache");
955 $stamp1 = microtime(true);
956 file_put_contents($tempfile, $imagedata);
957 $a->save_timestamp($stamp1, "file");
959 $data = getimagesize($tempfile);
961 if (!isset($data["mime"])) {
963 logger("File is no picture", LOGGER_DEBUG);
967 $ph = new Photo($imagedata, $data["mime"]);
969 if(!$ph->is_valid()) {
971 logger("Picture is no valid picture", LOGGER_DEBUG);
975 $ph->orient($tempfile);
978 $max_length = get_config('system','max_image_length');
980 $max_length = MAX_IMAGE_LENGTH;
982 $ph->scaleImage($max_length);
984 $width = $ph->getWidth();
985 $height = $ph->getHeight();
987 $hash = photo_new_resource();
991 // Pictures are always public by now
992 //$defperm = '<'.$default_cid.'>';
996 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
999 logger("Picture couldn't be stored", LOGGER_DEBUG);
1003 $image = array("page" => $a->get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
1004 "full" => $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
1006 if($width > 800 || $height > 800)
1007 $image["large"] = $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt();
1009 if($width > 640 || $height > 640) {
1010 $ph->scaleImage(640);
1011 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
1013 $image["medium"] = $a->get_baseurl()."/photo/{$hash}-1.".$ph->getExt();
1016 if($width > 320 || $height > 320) {
1017 $ph->scaleImage(320);
1018 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
1020 $image["small"] = $a->get_baseurl()."/photo/{$hash}-2.".$ph->getExt();
1023 if($width > 160 AND $height > 160) {
1027 $min = $ph->getWidth();
1029 $x = ($min - 160) / 2;
1031 if ($ph->getHeight() < $min) {
1032 $min = $ph->getHeight();
1034 $y = ($min - 160) / 2;
1038 $ph->cropImage(160, $x, $y, $min, $min);
1040 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
1042 $image["thumb"] = $a->get_baseurl()."/photo/{$hash}-3.".$ph->getExt();
1045 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1046 $image["preview"] = $image["full"];
1048 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1049 //if (isset($image["thumb"]))
1050 // $image["preview"] = $image["thumb"];
1052 // Unsure, if this should be activated or deactivated
1053 //if (isset($image["small"]))
1054 // $image["preview"] = $image["small"];
1056 if (isset($image["medium"]))
1057 $image["preview"] = $image["medium"];