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 // based off comment on http://php.net/manual/en/function.imagerotate.php
350 if(!$this->is_valid())
353 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
356 $exif = @exif_read_data($filename);
361 $ort = $exif['Orientation'];
368 case 2: // horizontal flip
372 case 3: // 180 rotate left
376 case 4: // vertical flip
377 $this->flip(false, true);
380 case 5: // vertical flip + 90 rotate right
381 $this->flip(false, true);
385 case 6: // 90 rotate right
389 case 7: // horizontal flip + 90 rotate right
394 case 8: // 90 rotate left
402 public function scaleImageUp($min) {
403 if(!$this->is_valid())
407 $width = $this->getWidth();
408 $height = $this->getHeight();
410 $dest_width = $dest_height = 0;
412 if((! $width)|| (! $height))
415 if($width < $min && $height < $min) {
416 if($width > $height) {
418 $dest_height = intval(( $height * $min ) / $width);
421 $dest_width = intval(( $width * $min ) / $height);
426 if( $width < $min ) {
428 $dest_height = intval(( $height * $min ) / $width);
431 if( $height < $min ) {
432 $dest_width = intval(( $width * $min ) / $height);
436 $dest_width = $width;
437 $dest_height = $height;
442 if($this->is_imagick())
443 return $this->scaleImage($dest_width,$dest_height);
445 $dest = imagecreatetruecolor( $dest_width, $dest_height );
446 imagealphablending($dest, false);
447 imagesavealpha($dest, true);
448 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
449 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
451 imagedestroy($this->image);
452 $this->image = $dest;
453 $this->width = imagesx($this->image);
454 $this->height = imagesy($this->image);
459 public function scaleImageSquare($dim) {
460 if(!$this->is_valid())
463 if($this->is_imagick()) {
464 $this->image->setFirstIterator();
466 $this->image->scaleImage($dim, $dim);
467 } while ($this->image->nextImage());
471 $dest = imagecreatetruecolor( $dim, $dim );
472 imagealphablending($dest, false);
473 imagesavealpha($dest, true);
474 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
475 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
477 imagedestroy($this->image);
478 $this->image = $dest;
479 $this->width = imagesx($this->image);
480 $this->height = imagesy($this->image);
484 public function cropImage($max,$x,$y,$w,$h) {
485 if(!$this->is_valid())
488 if($this->is_imagick()) {
489 $this->image->setFirstIterator();
491 $this->image->cropImage($w, $h, $x, $y);
493 * We need to remove the canva,
494 * or the image is not resized to the crop:
495 * http://php.net/manual/en/imagick.cropimage.php#97232
497 $this->image->setImagePage(0, 0, 0, 0);
498 } while ($this->image->nextImage());
499 return $this->scaleImage($max);
502 $dest = imagecreatetruecolor( $max, $max );
503 imagealphablending($dest, false);
504 imagesavealpha($dest, true);
505 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
506 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
508 imagedestroy($this->image);
509 $this->image = $dest;
510 $this->width = imagesx($this->image);
511 $this->height = imagesy($this->image);
514 public function saveImage($path) {
515 if(!$this->is_valid())
518 $string = $this->imageString();
519 file_put_contents($path, $string);
522 public function imageString() {
523 if(!$this->is_valid())
526 if($this->is_imagick()) {
528 $this->image = $this->image->deconstructImages();
529 $string = $this->image->getImagesBlob();
537 // Enable interlacing
538 imageinterlace($this->image, true);
540 switch($this->getType()){
542 $quality = get_config('system','png_quality');
543 if((! $quality) || ($quality > 9))
544 $quality = PNG_QUALITY;
545 imagepng($this->image,NULL, $quality);
548 $quality = get_config('system','jpeg_quality');
549 if((! $quality) || ($quality > 100))
550 $quality = JPEG_QUALITY;
551 imagejpeg($this->image,NULL,$quality);
553 $string = ob_get_contents();
561 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
563 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
567 $guid = $r[0]['guid'];
571 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
578 $r = q("UPDATE `photo`
582 `resource-id` = '%s',
604 dbesc(datetime_convert()),
605 dbesc(datetime_convert()),
606 dbesc(basename($filename)),
607 dbesc($this->getType()),
609 intval($this->getHeight()),
610 intval($this->getWidth()),
611 dbesc(strlen($this->imageString())),
612 dbesc($this->imageString()),
623 $r = q("INSERT INTO `photo`
624 ( `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` )
625 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%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()),
653 * Guess image mimetype from filename or from Content-Type header
655 * @arg $filename string Image filename
656 * @arg $fromcurl boolean Check Content-Type header from curl request
658 function guess_image_type($filename, $fromcurl=false) {
659 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
664 $h = explode("\n",$a->get_curl_headers());
666 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
669 if (array_key_exists('Content-Type', $headers))
670 $type = $headers['Content-Type'];
673 // Guessing from extension? Isn't that... dangerous?
674 if(class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
676 * Well, this not much better,
677 * but at least it comes from the data inside the image,
678 * we won't be tricked by a manipulated extension
680 $image = new Imagick($filename);
681 $type = $image->getImageMimeType();
682 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
684 $ext = pathinfo($filename, PATHINFO_EXTENSION);
685 $types = Photo::supportedTypes();
686 $type = "image/jpeg";
687 foreach ($types as $m=>$e){
688 if ($ext==$e) $type = $m;
692 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
697 function import_profile_photo($photo,$uid,$cid) {
701 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
705 if(count($r) && strlen($r[0]['resource-id'])) {
706 $hash = $r[0]['resource-id'];
709 $hash = photo_new_resource();
712 $photo_failure = false;
714 $filename = basename($photo);
715 $img_str = fetch_url($photo,true);
717 $type = guess_image_type($photo,true);
718 $img = new Photo($img_str, $type);
719 if($img->is_valid()) {
721 $img->scaleImageSquare(175);
723 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
726 $photo_failure = true;
728 $img->scaleImage(80);
730 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
733 $photo_failure = true;
735 $img->scaleImage(48);
737 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
740 $photo_failure = true;
742 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
743 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
744 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
747 $photo_failure = true;
750 $photo = $a->get_baseurl() . '/images/person-175.jpg';
751 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
752 $micro = $a->get_baseurl() . '/images/person-48.jpg';
755 return(array($photo,$thumb,$micro));
759 function get_photo_info($url) {
762 $data = Cache::get($url);
764 if (is_null($data)) {
765 $img_str = fetch_url($url, true, $redirects, 4);
767 $filesize = strlen($img_str);
769 $tempfile = tempnam(get_temppath(), "cache");
770 file_put_contents($tempfile, $img_str);
771 $data = getimagesize($tempfile);
775 $data["size"] = $filesize;
777 Cache::set($url, serialize($data));
779 $data = unserialize($data);
784 function scale_image($width, $height, $max) {
786 $dest_width = $dest_height = 0;
788 if((!$width) || (!$height))
791 if($width > $max && $height > $max) {
793 // very tall image (greater than 16:9)
794 // constrain the width - let the height float.
796 if((($height * 9) / 16) > $width) {
798 $dest_height = intval(( $height * $max ) / $width);
799 } elseif($width > $height) {
800 // else constrain both dimensions
802 $dest_height = intval(( $height * $max ) / $width);
804 $dest_width = intval(( $width * $max ) / $height);
808 if( $width > $max ) {
810 $dest_height = intval(( $height * $max ) / $width);
812 if( $height > $max ) {
814 // very tall image (greater than 16:9)
815 // but width is OK - don't do anything
817 if((($height * 9) / 16) > $width) {
818 $dest_width = $width;
819 $dest_height = $height;
821 $dest_width = intval(( $width * $max ) / $height);
825 $dest_width = $width;
826 $dest_height = $height;
830 return array("width" => $dest_width, "height" => $dest_height);
833 function store_photo($a, $uid, $imagedata = "", $url = "") {
834 $r = q("SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
835 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1",
839 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
843 $page_owner_nick = $r[0]['nickname'];
846 // $default_cid = $r[0]['id'];
847 // $community_page = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
849 if ((strlen($imagedata) == 0) AND ($url == "")) {
850 logger("No image data and no url provided", LOGGER_DEBUG);
852 } elseif (strlen($imagedata) == 0) {
853 logger("Uploading picture from ".$url, LOGGER_DEBUG);
854 $imagedata = @file_get_contents($url);
857 $maximagesize = get_config('system','maximagesize');
859 if(($maximagesize) && (strlen($imagedata) > $maximagesize)) {
860 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
865 $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
869 $limit = service_class_fetch($uid,'photo_upload_limit');
871 if(($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
872 logger("Image exceeds personal limit of uid ".$uid, LOGGER_DEBUG);
877 $tempfile = tempnam(get_temppath(), "cache");
878 file_put_contents($tempfile, $imagedata);
879 $data = getimagesize($tempfile);
881 if (!isset($data["mime"])) {
883 logger("File is no picture", LOGGER_DEBUG);
887 $ph = new Photo($imagedata, $data["mime"]);
889 if(!$ph->is_valid()) {
891 logger("Picture is no valid picture", LOGGER_DEBUG);
895 $ph->orient($tempfile);
898 $max_length = get_config('system','max_image_length');
900 $max_length = MAX_IMAGE_LENGTH;
902 $ph->scaleImage($max_length);
904 $width = $ph->getWidth();
905 $height = $ph->getHeight();
907 $hash = photo_new_resource();
911 // Pictures are always public by now
912 //$defperm = '<'.$default_cid.'>';
916 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
919 logger("Picture couldn't be stored", LOGGER_DEBUG);
923 $image = array("page" => $a->get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
924 "full" => $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
926 if($width > 800 || $height > 800)
927 $image["large"] = $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt();
929 if($width > 640 || $height > 640) {
930 $ph->scaleImage(640);
931 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
933 $image["medium"] = $a->get_baseurl()."/photo/{$hash}-1.".$ph->getExt();
936 if($width > 320 || $height > 320) {
937 $ph->scaleImage(320);
938 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
940 $image["small"] = $a->get_baseurl()."/photo/{$hash}-2.".$ph->getExt();
943 if($width > 160 AND $height > 160) {
947 $min = $ph->getWidth();
949 $x = ($min - 160) / 2;
951 if ($ph->getHeight() < $min) {
952 $min = $ph->getHeight();
954 $y = ($min - 160) / 2;
958 $ph->cropImage(160, $x, $y, $min, $min);
960 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
962 $image["thumb"] = $a->get_baseurl()."/photo/{$hash}-3.".$ph->getExt();
965 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
966 $image["preview"] = $image["full"];
968 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
969 //if (isset($image["thumb"]))
970 // $image["preview"] = $image["thumb"];
972 // Unsure, if this should be activated or deactivated
973 //if (isset($image["small"]))
974 // $image["preview"] = $image["small"];
976 if (isset($image["medium"]))
977 $image["preview"] = $image["medium"];