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);
379 $ort = $exif['Orientation'];
386 case 2: // horizontal flip
390 case 3: // 180 rotate left
394 case 4: // vertical flip
395 $this->flip(false, true);
398 case 5: // vertical flip + 90 rotate right
399 $this->flip(false, true);
403 case 6: // 90 rotate right
407 case 7: // horizontal flip + 90 rotate right
412 case 8: // 90 rotate left
420 public function scaleImageUp($min) {
421 if(!$this->is_valid())
425 $width = $this->getWidth();
426 $height = $this->getHeight();
428 $dest_width = $dest_height = 0;
430 if((! $width)|| (! $height))
433 if($width < $min && $height < $min) {
434 if($width > $height) {
436 $dest_height = intval(( $height * $min ) / $width);
439 $dest_width = intval(( $width * $min ) / $height);
444 if( $width < $min ) {
446 $dest_height = intval(( $height * $min ) / $width);
449 if( $height < $min ) {
450 $dest_width = intval(( $width * $min ) / $height);
454 $dest_width = $width;
455 $dest_height = $height;
460 if($this->is_imagick())
461 return $this->scaleImage($dest_width,$dest_height);
463 $dest = imagecreatetruecolor( $dest_width, $dest_height );
464 imagealphablending($dest, false);
465 imagesavealpha($dest, true);
466 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
467 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
469 imagedestroy($this->image);
470 $this->image = $dest;
471 $this->width = imagesx($this->image);
472 $this->height = imagesy($this->image);
477 public function scaleImageSquare($dim) {
478 if(!$this->is_valid())
481 if($this->is_imagick()) {
482 $this->image->setFirstIterator();
484 $this->image->scaleImage($dim, $dim);
485 } while ($this->image->nextImage());
489 $dest = imagecreatetruecolor( $dim, $dim );
490 imagealphablending($dest, false);
491 imagesavealpha($dest, true);
492 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
493 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
495 imagedestroy($this->image);
496 $this->image = $dest;
497 $this->width = imagesx($this->image);
498 $this->height = imagesy($this->image);
502 public function cropImage($max,$x,$y,$w,$h) {
503 if(!$this->is_valid())
506 if($this->is_imagick()) {
507 $this->image->setFirstIterator();
509 $this->image->cropImage($w, $h, $x, $y);
511 * We need to remove the canva,
512 * or the image is not resized to the crop:
513 * http://php.net/manual/en/imagick.cropimage.php#97232
515 $this->image->setImagePage(0, 0, 0, 0);
516 } while ($this->image->nextImage());
517 return $this->scaleImage($max);
520 $dest = imagecreatetruecolor( $max, $max );
521 imagealphablending($dest, false);
522 imagesavealpha($dest, true);
523 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
524 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
526 imagedestroy($this->image);
527 $this->image = $dest;
528 $this->width = imagesx($this->image);
529 $this->height = imagesy($this->image);
532 public function saveImage($path) {
533 if(!$this->is_valid())
536 $string = $this->imageString();
540 $stamp1 = microtime(true);
541 file_put_contents($path, $string);
542 $a->save_timestamp($stamp1, "file");
545 public function imageString() {
546 if(!$this->is_valid())
549 if($this->is_imagick()) {
551 $this->image = $this->image->deconstructImages();
552 $string = $this->image->getImagesBlob();
560 // Enable interlacing
561 imageinterlace($this->image, true);
563 switch($this->getType()){
565 $quality = get_config('system','png_quality');
566 if((! $quality) || ($quality > 9))
567 $quality = PNG_QUALITY;
568 imagepng($this->image,NULL, $quality);
571 $quality = get_config('system','jpeg_quality');
572 if((! $quality) || ($quality > 100))
573 $quality = JPEG_QUALITY;
574 imagejpeg($this->image,NULL,$quality);
576 $string = ob_get_contents();
584 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
586 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
590 $guid = $r[0]['guid'];
594 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
601 $r = q("UPDATE `photo`
605 `resource-id` = '%s',
627 dbesc(datetime_convert()),
628 dbesc(datetime_convert()),
629 dbesc(basename($filename)),
630 dbesc($this->getType()),
632 intval($this->getHeight()),
633 intval($this->getWidth()),
634 dbesc(strlen($this->imageString())),
635 dbesc($this->imageString()),
646 $r = q("INSERT INTO `photo`
647 ( `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` )
648 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
653 dbesc(datetime_convert()),
654 dbesc(datetime_convert()),
655 dbesc(basename($filename)),
656 dbesc($this->getType()),
658 intval($this->getHeight()),
659 intval($this->getWidth()),
660 dbesc(strlen($this->imageString())),
661 dbesc($this->imageString()),
676 * Guess image mimetype from filename or from Content-Type header
678 * @arg $filename string Image filename
679 * @arg $fromcurl boolean Check Content-Type header from curl request
681 function guess_image_type($filename, $fromcurl=false) {
682 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
687 $h = explode("\n",$a->get_curl_headers());
689 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
692 if (array_key_exists('Content-Type', $headers))
693 $type = $headers['Content-Type'];
696 // Guessing from extension? Isn't that... dangerous?
697 if(class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
699 * Well, this not much better,
700 * but at least it comes from the data inside the image,
701 * we won't be tricked by a manipulated extension
703 $image = new Imagick($filename);
704 $type = $image->getImageMimeType();
705 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
707 $ext = pathinfo($filename, PATHINFO_EXTENSION);
708 $types = Photo::supportedTypes();
709 $type = "image/jpeg";
710 foreach ($types as $m=>$e){
711 if ($ext==$e) $type = $m;
715 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
720 function import_profile_photo($photo,$uid,$cid) {
724 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
728 if(count($r) && strlen($r[0]['resource-id'])) {
729 $hash = $r[0]['resource-id'];
732 $hash = photo_new_resource();
735 $photo_failure = false;
737 $filename = basename($photo);
738 $img_str = fetch_url($photo,true);
740 $type = guess_image_type($photo,true);
741 $img = new Photo($img_str, $type);
742 if($img->is_valid()) {
744 $img->scaleImageSquare(175);
746 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
749 $photo_failure = true;
751 $img->scaleImage(80);
753 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
756 $photo_failure = true;
758 $img->scaleImage(48);
760 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
763 $photo_failure = true;
765 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
766 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
767 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
770 $photo_failure = true;
773 $photo = $a->get_baseurl() . '/images/person-175.jpg';
774 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
775 $micro = $a->get_baseurl() . '/images/person-48.jpg';
778 return(array($photo,$thumb,$micro));
782 function get_photo_info($url) {
785 $data = Cache::get($url);
787 if (is_null($data)) {
788 $img_str = fetch_url($url, true, $redirects, 4);
790 $filesize = strlen($img_str);
792 $tempfile = tempnam(get_temppath(), "cache");
795 $stamp1 = microtime(true);
796 file_put_contents($tempfile, $img_str);
797 $a->save_timestamp($stamp1, "file");
799 $data = getimagesize($tempfile);
803 $data["size"] = $filesize;
805 Cache::set($url, serialize($data));
807 $data = unserialize($data);
812 function scale_image($width, $height, $max) {
814 $dest_width = $dest_height = 0;
816 if((!$width) || (!$height))
819 if($width > $max && $height > $max) {
821 // very tall image (greater than 16:9)
822 // constrain the width - let the height float.
824 if((($height * 9) / 16) > $width) {
826 $dest_height = intval(( $height * $max ) / $width);
827 } elseif($width > $height) {
828 // else constrain both dimensions
830 $dest_height = intval(( $height * $max ) / $width);
832 $dest_width = intval(( $width * $max ) / $height);
836 if( $width > $max ) {
838 $dest_height = intval(( $height * $max ) / $width);
840 if( $height > $max ) {
842 // very tall image (greater than 16:9)
843 // but width is OK - don't do anything
845 if((($height * 9) / 16) > $width) {
846 $dest_width = $width;
847 $dest_height = $height;
849 $dest_width = intval(( $width * $max ) / $height);
853 $dest_width = $width;
854 $dest_height = $height;
858 return array("width" => $dest_width, "height" => $dest_height);
861 function store_photo($a, $uid, $imagedata = "", $url = "") {
862 $r = q("SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
863 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1",
867 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
871 $page_owner_nick = $r[0]['nickname'];
874 // $default_cid = $r[0]['id'];
875 // $community_page = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
877 if ((strlen($imagedata) == 0) AND ($url == "")) {
878 logger("No image data and no url provided", LOGGER_DEBUG);
880 } elseif (strlen($imagedata) == 0) {
881 logger("Uploading picture from ".$url, LOGGER_DEBUG);
883 $stamp1 = microtime(true);
884 $imagedata = @file_get_contents($url);
885 $a->save_timestamp($stamp1, "file");
888 $maximagesize = get_config('system','maximagesize');
890 if(($maximagesize) && (strlen($imagedata) > $maximagesize)) {
891 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
896 $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
900 $limit = service_class_fetch($uid,'photo_upload_limit');
902 if(($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
903 logger("Image exceeds personal limit of uid ".$uid, LOGGER_DEBUG);
908 $tempfile = tempnam(get_temppath(), "cache");
910 $stamp1 = microtime(true);
911 file_put_contents($tempfile, $imagedata);
912 $a->save_timestamp($stamp1, "file");
914 $data = getimagesize($tempfile);
916 if (!isset($data["mime"])) {
918 logger("File is no picture", LOGGER_DEBUG);
922 $ph = new Photo($imagedata, $data["mime"]);
924 if(!$ph->is_valid()) {
926 logger("Picture is no valid picture", LOGGER_DEBUG);
930 $ph->orient($tempfile);
933 $max_length = get_config('system','max_image_length');
935 $max_length = MAX_IMAGE_LENGTH;
937 $ph->scaleImage($max_length);
939 $width = $ph->getWidth();
940 $height = $ph->getHeight();
942 $hash = photo_new_resource();
946 // Pictures are always public by now
947 //$defperm = '<'.$default_cid.'>';
951 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
954 logger("Picture couldn't be stored", LOGGER_DEBUG);
958 $image = array("page" => $a->get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
959 "full" => $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
961 if($width > 800 || $height > 800)
962 $image["large"] = $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt();
964 if($width > 640 || $height > 640) {
965 $ph->scaleImage(640);
966 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
968 $image["medium"] = $a->get_baseurl()."/photo/{$hash}-1.".$ph->getExt();
971 if($width > 320 || $height > 320) {
972 $ph->scaleImage(320);
973 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
975 $image["small"] = $a->get_baseurl()."/photo/{$hash}-2.".$ph->getExt();
978 if($width > 160 AND $height > 160) {
982 $min = $ph->getWidth();
984 $x = ($min - 160) / 2;
986 if ($ph->getHeight() < $min) {
987 $min = $ph->getHeight();
989 $y = ($min - 160) / 2;
993 $ph->cropImage(160, $x, $y, $min, $min);
995 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
997 $image["thumb"] = $a->get_baseurl()."/photo/{$hash}-3.".$ph->getExt();
1000 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1001 $image["preview"] = $image["full"];
1003 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1004 //if (isset($image["thumb"]))
1005 // $image["preview"] = $image["thumb"];
1007 // Unsure, if this should be activated or deactivated
1008 //if (isset($image["small"]))
1009 // $image["preview"] = $image["small"];
1011 if (isset($image["medium"]))
1012 $image["preview"] = $image["medium"];