]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
Typo in notifier.
[friendica.git] / include / Photo.php
1 <?php
2
3 if(! class_exists("Photo")) {
4 class Photo {
5
6     private $image;
7
8     /**
9      * Put back gd stuff, not everybody have Imagick
10      */
11     private $imagick;
12     private $width;
13     private $height;
14     private $valid;
15     private $type;
16     private $types;
17
18     /**
19      * supported mimetypes and corresponding file extensions
20      */
21     static function supportedTypes() {
22         if(class_exists('Imagick')) {
23             /**
24              * Imagick::queryFormats won't help us a lot there...
25              * At least, not yet, other parts of friendica uses this array
26              */
27             $t = array(
28                 'image/jpeg' => 'jpg',
29                 'image/png' => 'png',
30                 'image/gif' => 'gif'
31             );
32         } else {
33             $t = array();
34             $t['image/jpeg'] ='jpg';
35             if (imagetypes() & IMG_PNG) $t['image/png'] = 'png';
36         }
37
38         return $t;
39     }
40
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)){
45             $type='image/jpeg';
46         }
47         $this->type = $type;
48
49         if($this->is_imagick()) {
50             $this->image = new Imagick();
51             $this->image->readImageBlob($data);
52
53             /**
54              * Setup the image to the format it will be saved to
55              */
56             $map = $this->get_FormatsMap();
57             $format = $map[$type];
58             $this->image->setFormat($format);
59
60             // Always coalesce, if it is not a multi-frame image it won't hurt anyway
61             $this->image = $this->image->coalesceImages();
62
63             /**
64              * setup the compression here, so we'll do it only once
65              */
66             switch($this->getType()){
67                 case "image/png":
68                     $quality = get_config('system','png_quality');
69                     if((! $quality) || ($quality > 9))
70                         $quality = PNG_QUALITY;
71                     /**
72                      * From http://www.imagemagick.org/script/command-line-options.php#quality:
73                      *
74                      * 'For the MNG and PNG image formats, the quality value sets
75                      * the zlib compression level (quality / 10) and filter-type (quality % 10).
76                      * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
77                      * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
78                      */
79                     $quality = $quality * 10;
80                     $this->image->setCompressionQuality($quality);
81                     break;
82                 case "image/jpeg":
83                     $quality = get_config('system','jpeg_quality');
84                     if((! $quality) || ($quality > 100))
85                         $quality = JPEG_QUALITY;
86                     $this->image->setCompressionQuality($quality);
87             }
88         } else {
89             $this->valid = false;
90             $this->image = @imagecreatefromstring($data);
91             if($this->image !== FALSE) {
92                 $this->width  = imagesx($this->image);
93                 $this->height = imagesy($this->image);
94                 $this->valid  = true;
95                 imagealphablending($this->image, false);
96                 imagesavealpha($this->image, true);
97             }
98         }
99     }
100
101     public function __destruct() {
102         if($this->image) {
103             if($this->is_imagick()) {
104                 $this->image->clear();
105                 $this->image->destroy();
106                 return;
107             }
108             imagedestroy($this->image);
109         }
110     }
111
112     public function is_imagick() {
113         return $this->imagick;
114     }
115
116     /**
117      * Maps Mime types to Imagick formats
118      */
119     public function get_FormatsMap() {
120         $m = array(
121             'image/jpeg' => 'JPG',
122             'image/png' => 'PNG',
123             'image/gif' => 'GIF'
124         );
125         return $m;
126     }
127
128     public function is_valid() {
129         if($this->is_imagick())
130             return ($this->image !== FALSE);
131         return $this->valid;
132     }
133
134     public function getWidth() {
135         if(!$this->is_valid())
136             return FALSE;
137
138         if($this->is_imagick())
139             return $this->image->getImageWidth();
140         return $this->width;
141     }
142
143     public function getHeight() {
144         if(!$this->is_valid())
145             return FALSE;
146
147         if($this->is_imagick())
148             return $this->image->getImageHeight();
149         return $this->height;
150     }
151
152     public function getImage() {
153         if(!$this->is_valid())
154             return FALSE;
155
156         if($this->is_imagick()) {
157             /* Clean it */
158             $this->image = $this->image->deconstructImages();
159             return $this->image;
160         }
161         return $this->image;
162     }
163
164     public function getType() {
165         if(!$this->is_valid())
166             return FALSE;
167
168         return $this->type;
169     }
170
171     public function getExt() {
172         if(!$this->is_valid())
173             return FALSE;
174
175         return $this->types[$this->getType()];
176     }
177
178     public function scaleImage($max) {
179         if(!$this->is_valid())
180             return FALSE;
181
182         if($this->is_imagick()) {
183             /**
184              * If it is not animated, there will be only one iteration here,
185              * so don't bother checking
186              */
187             // Don't forget to go back to the first frame
188             $this->image->setFirstIterator();
189             do {
190                 $this->image->resizeImage($max, $max, imagick::FILTER_LANCZOS, 1, true);
191             } while ($this->image->nextImage());
192             return;
193         }
194
195         $width = $this->width;
196         $height = $this->height;
197
198         $dest_width = $dest_height = 0;
199
200         if((! $width)|| (! $height))
201             return FALSE;
202
203         if($width > $max && $height > $max) {
204             if($width > $height) {
205                 $dest_width = $max;
206                 $dest_height = intval(( $height * $max ) / $width);
207             }
208             else {
209                 $dest_width = intval(( $width * $max ) / $height);
210                 $dest_height = $max;
211             }
212         }
213         else {
214             if( $width > $max ) {
215                 $dest_width = $max;
216                 $dest_height = intval(( $height * $max ) / $width);
217             }
218             else {
219                 if( $height > $max ) {
220                     $dest_width = intval(( $width * $max ) / $height);
221                     $dest_height = $max;
222                 }
223                 else {
224                     $dest_width = $width;
225                     $dest_height = $height;
226                 }
227             }
228         }
229
230
231         $dest = imagecreatetruecolor( $dest_width, $dest_height );
232         imagealphablending($dest, false);
233         imagesavealpha($dest, true);
234         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
235         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
236         if($this->image)
237             imagedestroy($this->image);
238         $this->image = $dest;
239         $this->width  = imagesx($this->image);
240         $this->height = imagesy($this->image);
241     }
242
243     public function rotate($degrees) {
244         if(!$this->is_valid())
245             return FALSE;
246
247         if($this->is_imagick()) {
248             $this->image->setFirstIterator();
249             do {
250                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
251             } while ($this->image->nextImage());
252             return;
253         }
254
255         $this->image  = imagerotate($this->image,$degrees,0);
256         $this->width  = imagesx($this->image);
257         $this->height = imagesy($this->image);
258     }
259
260     public function flip($horiz = true, $vert = false) {
261         if(!$this->is_valid())
262             return FALSE;
263
264         if($this->is_imagick()) {
265             $this->image->setFirstIterator();
266             do {
267                 if($horiz) $this->image->flipImage();
268                 if($vert) $this->image->flopImage();
269             } while ($this->image->nextImage());
270             return;
271         }
272
273         $w = imagesx($this->image);
274         $h = imagesy($this->image);
275         $flipped = imagecreate($w, $h);
276         if($horiz) {
277             for ($x = 0; $x < $w; $x++) {
278                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
279             }
280         }
281         if($vert) {
282             for ($y = 0; $y < $h; $y++) {
283                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
284             }
285         }
286         $this->image = $flipped;
287     }
288
289     public function orient($filename) {
290         // based off comment on http://php.net/manual/en/function.imagerotate.php
291
292         if(!$this->is_valid())
293             return FALSE;
294
295         if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
296             return;
297
298         $exif = @exif_read_data($filename);
299
300                 if(! $exif)
301                         return;
302
303         $ort = $exif['Orientation'];
304
305         switch($ort)
306         {
307             case 1: // nothing
308                 break;
309
310             case 2: // horizontal flip
311                 $this->flip();
312                 break;
313
314             case 3: // 180 rotate left
315                 $this->rotate(180);
316                 break;
317
318             case 4: // vertical flip
319                 $this->flip(false, true);
320                 break;
321
322             case 5: // vertical flip + 90 rotate right
323                 $this->flip(false, true);
324                 $this->rotate(-90);
325                 break;
326
327             case 6: // 90 rotate right
328                 $this->rotate(-90);
329                 break;
330
331             case 7: // horizontal flip + 90 rotate right
332                 $this->flip();
333                 $this->rotate(-90);
334                 break;
335
336             case 8:    // 90 rotate left
337                 $this->rotate(90);
338                 break;
339         }
340     }
341
342
343
344     public function scaleImageUp($min) {
345         if(!$this->is_valid())
346             return FALSE;
347
348         if($this->is_imagick())
349             return $this->scaleImage($min);
350
351         $width = $this->width;
352         $height = $this->height;
353
354         $dest_width = $dest_height = 0;
355
356         if((! $width)|| (! $height))
357             return FALSE;
358
359         if($width < $min && $height < $min) {
360             if($width > $height) {
361                 $dest_width = $min;
362                 $dest_height = intval(( $height * $min ) / $width);
363             }
364             else {
365                 $dest_width = intval(( $width * $min ) / $height);
366                 $dest_height = $min;
367             }
368         }
369         else {
370             if( $width < $min ) {
371                 $dest_width = $min;
372                 $dest_height = intval(( $height * $min ) / $width);
373             }
374             else {
375                 if( $height < $min ) {
376                     $dest_width = intval(( $width * $min ) / $height);
377                     $dest_height = $min;
378                 }
379                 else {
380                     $dest_width = $width;
381                     $dest_height = $height;
382                 }
383             }
384         }
385
386
387         $dest = imagecreatetruecolor( $dest_width, $dest_height );
388         imagealphablending($dest, false);
389         imagesavealpha($dest, true);
390         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
391         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
392         if($this->image)
393             imagedestroy($this->image);
394         $this->image = $dest;
395         $this->width  = imagesx($this->image);
396         $this->height = imagesy($this->image);
397     }
398
399
400
401     public function scaleImageSquare($dim) {
402         if(!$this->is_valid())
403             return FALSE;
404
405         if($this->is_imagick()) {
406             $this->image->setFirstIterator();
407             do {
408                 $this->image->resizeImage($dim, $dim, imagick::FILTER_LANCZOS, 1, false);
409             } while ($this->image->nextImage());
410             return;
411         }
412
413         $dest = imagecreatetruecolor( $dim, $dim );
414         imagealphablending($dest, false);
415         imagesavealpha($dest, true);
416         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
417         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
418         if($this->image)
419             imagedestroy($this->image);
420         $this->image = $dest;
421         $this->width  = imagesx($this->image);
422         $this->height = imagesy($this->image);
423     }
424
425
426     public function cropImage($max,$x,$y,$w,$h) {
427         if(!$this->is_valid())
428             return FALSE;
429
430         if($this->is_imagick()) {
431             $this->image->setFirstIterator();
432             do {
433                 $this->image->cropImage($w, $h, $x, $y);
434                 /**
435                  * We need to remove the canva,
436                  * or the image is not resized to the crop:
437                  * http://php.net/manual/en/imagick.cropimage.php#97232
438                  */
439                 $this->image->setImagePage(0, 0, 0, 0);
440             } while ($this->image->nextImage());
441             return $this->scaleImage($max);
442         }
443
444         $dest = imagecreatetruecolor( $max, $max );
445         imagealphablending($dest, false);
446         imagesavealpha($dest, true);
447         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
448         imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
449         if($this->image)
450             imagedestroy($this->image);
451         $this->image = $dest;
452         $this->width  = imagesx($this->image);
453         $this->height = imagesy($this->image);
454     }
455
456     public function saveImage($path) {
457         if(!$this->is_valid())
458             return FALSE;
459
460         $string = $this->imageString();
461         file_put_contents($path, $string);
462     }
463
464     public function imageString() {
465         if(!$this->is_valid())
466             return FALSE;
467
468         if($this->is_imagick()) {
469             /* Clean it */
470             $this->image = $this->image->deconstructImages();
471             $string = $this->image->getImagesBlob();
472             return $string;
473         }
474
475         $quality = FALSE;
476
477         ob_start();
478
479         switch($this->getType()){
480             case "image/png":
481                 $quality = get_config('system','png_quality');
482                 if((! $quality) || ($quality > 9))
483                     $quality = PNG_QUALITY;
484                 imagepng($this->image,NULL, $quality);
485                 break;
486             case "image/jpeg":
487                 $quality = get_config('system','jpeg_quality');
488                 if((! $quality) || ($quality > 100))
489                     $quality = JPEG_QUALITY;
490                 imagejpeg($this->image,NULL,$quality);
491         }
492         $string = ob_get_contents();
493         ob_end_clean();
494
495         return $string;
496     }
497
498
499
500     public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
501
502         $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
503             dbesc($rid)
504         );
505         if(count($r))
506             $guid = $r[0]['guid'];
507         else
508             $guid = get_guid();
509
510         $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
511                 dbesc($rid),
512                 intval($uid),
513                 intval($cid),
514                 intval($scale)
515         );
516         if(count($x)) {
517             $r = q("UPDATE `photo`
518                 set `uid` = %d,
519                 `contact-id` = %d,
520                 `guid` = '%s',
521                 `resource-id` = '%s',
522                 `created` = '%s',
523                 `edited` = '%s',
524                 `filename` = '%s',
525                 `type` = '%s',
526                 `album` = '%s',
527                 `height` = %d,
528                 `width` = %d,
529                 `data` = '%s',
530                 `scale` = %d,
531                 `profile` = %d,
532                 `allow_cid` = '%s',
533                 `allow_gid` = '%s',
534                 `deny_cid` = '%s',
535                 `deny_gid` = '%s'
536                 where id = %d limit 1",
537
538                 intval($uid),
539                 intval($cid),
540                 dbesc($guid),
541                 dbesc($rid),
542                 dbesc(datetime_convert()),
543                 dbesc(datetime_convert()),
544                 dbesc(basename($filename)),
545                 dbesc($this->getType()),
546                 dbesc($album),
547                 intval($this->getHeight()),
548                 intval($this->getWidth()),
549                 dbesc($this->imageString()),
550                 intval($scale),
551                 intval($profile),
552                 dbesc($allow_cid),
553                 dbesc($allow_gid),
554                 dbesc($deny_cid),
555                 dbesc($deny_gid),
556                 intval($x[0]['id'])
557             );
558         }
559         else {
560             $r = q("INSERT INTO `photo`
561                 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
562                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
563                 intval($uid),
564                 intval($cid),
565                 dbesc($guid),
566                 dbesc($rid),
567                 dbesc(datetime_convert()),
568                 dbesc(datetime_convert()),
569                 dbesc(basename($filename)),
570                 dbesc($this->getType()),
571                 dbesc($album),
572                 intval($this->getHeight()),
573                 intval($this->getWidth()),
574                 dbesc($this->imageString()),
575                 intval($scale),
576                 intval($profile),
577                 dbesc($allow_cid),
578                 dbesc($allow_gid),
579                 dbesc($deny_cid),
580                 dbesc($deny_gid)
581             );
582         }
583         return $r;
584     }
585 }}
586
587
588 /**
589  * Guess image mimetype from filename or from Content-Type header
590  *
591  * @arg $filename string Image filename
592  * @arg $fromcurl boolean Check Content-Type header from curl request
593  */
594 function guess_image_type($filename, $fromcurl=false) {
595     logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
596     $type = null;
597     if ($fromcurl) {
598         $a = get_app();
599         $headers=array();
600         $h = explode("\n",$a->get_curl_headers());
601         foreach ($h as $l) {
602             list($k,$v) = array_map("trim", explode(":", trim($l), 2));
603             $headers[$k] = $v;
604         }
605         if (array_key_exists('Content-Type', $headers))
606             $type = $headers['Content-Type'];
607     }
608     if (is_null($type)){
609         // Guessing from extension? Isn't that... dangerous?
610         if(class_exists('Imagick')) {
611             /**
612              * Well, this not much better,
613              * but at least it comes from the data inside the image,
614              * we won't be tricked by a manipulated extension
615              */
616             $image = new Imagick($filename);
617             $type = $image->getImageMimeType();
618         } else {
619             $ext = pathinfo($filename, PATHINFO_EXTENSION);
620             $types = Photo::supportedTypes();
621             $type = "image/jpeg";
622             foreach ($types as $m=>$e){
623                 if ($ext==$e) $type = $m;
624             }
625         }
626     }
627     logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
628     return $type;
629
630 }
631
632 function import_profile_photo($photo,$uid,$cid) {
633
634     $a = get_app();
635
636     $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
637         intval($uid),
638         intval($cid)
639     );
640     if(count($r)) {
641         $hash = $r[0]['resource-id'];
642     }
643     else {
644         $hash = photo_new_resource();
645     }
646
647     $photo_failure = false;
648
649     $filename = basename($photo);
650     $img_str = fetch_url($photo,true);
651
652     $type = guess_image_type($photo,true);
653     $img = new Photo($img_str, $type);
654     if($img->is_valid()) {
655
656         $img->scaleImageSquare(175);
657
658         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
659
660         if($r === false)
661             $photo_failure = true;
662
663         $img->scaleImage(80);
664
665         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
666
667         if($r === false)
668             $photo_failure = true;
669
670         $img->scaleImage(48);
671
672         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
673
674         if($r === false)
675             $photo_failure = true;
676
677         $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
678         $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
679         $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
680     }
681     else
682         $photo_failure = true;
683
684     if($photo_failure) {
685         $photo = $a->get_baseurl() . '/images/person-175.jpg';
686         $thumb = $a->get_baseurl() . '/images/person-80.jpg';
687         $micro = $a->get_baseurl() . '/images/person-48.jpg';
688     }
689
690     return(array($photo,$thumb,$micro));
691
692 }