]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
Merge pull request #442 from fermionic/frost-image-upload-and-post-local-time
[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         $ort = $exif['Orientation'];
300
301         switch($ort)
302         {
303             case 1: // nothing
304                 break;
305
306             case 2: // horizontal flip
307                 $this->flip();
308                 break;
309
310             case 3: // 180 rotate left
311                 $this->rotate(180);
312                 break;
313
314             case 4: // vertical flip
315                 $this->flip(false, true);
316                 break;
317
318             case 5: // vertical flip + 90 rotate right
319                 $this->flip(false, true);
320                 $this->rotate(-90);
321                 break;
322
323             case 6: // 90 rotate right
324                 $this->rotate(-90);
325                 break;
326
327             case 7: // horizontal flip + 90 rotate right
328                 $this->flip();
329                 $this->rotate(-90);
330                 break;
331
332             case 8:    // 90 rotate left
333                 $this->rotate(90);
334                 break;
335         }
336     }
337
338
339
340     public function scaleImageUp($min) {
341         if(!$this->is_valid())
342             return FALSE;
343
344         if($this->is_imagick())
345             return $this->scaleImage($min);
346
347         $width = $this->width;
348         $height = $this->height;
349
350         $dest_width = $dest_height = 0;
351
352         if((! $width)|| (! $height))
353             return FALSE;
354
355         if($width < $min && $height < $min) {
356             if($width > $height) {
357                 $dest_width = $min;
358                 $dest_height = intval(( $height * $min ) / $width);
359             }
360             else {
361                 $dest_width = intval(( $width * $min ) / $height);
362                 $dest_height = $min;
363             }
364         }
365         else {
366             if( $width < $min ) {
367                 $dest_width = $min;
368                 $dest_height = intval(( $height * $min ) / $width);
369             }
370             else {
371                 if( $height < $min ) {
372                     $dest_width = intval(( $width * $min ) / $height);
373                     $dest_height = $min;
374                 }
375                 else {
376                     $dest_width = $width;
377                     $dest_height = $height;
378                 }
379             }
380         }
381
382
383         $dest = imagecreatetruecolor( $dest_width, $dest_height );
384         imagealphablending($dest, false);
385         imagesavealpha($dest, true);
386         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
387         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
388         if($this->image)
389             imagedestroy($this->image);
390         $this->image = $dest;
391         $this->width  = imagesx($this->image);
392         $this->height = imagesy($this->image);
393     }
394
395
396
397     public function scaleImageSquare($dim) {
398         if(!$this->is_valid())
399             return FALSE;
400
401         if($this->is_imagick()) {
402             $this->image->setFirstIterator();
403             do {
404                 $this->image->resizeImage($dim, $dim, imagick::FILTER_LANCZOS, 1, false);
405             } while ($this->image->nextImage());
406             return;
407         }
408
409         $dest = imagecreatetruecolor( $dim, $dim );
410         imagealphablending($dest, false);
411         imagesavealpha($dest, true);
412         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
413         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
414         if($this->image)
415             imagedestroy($this->image);
416         $this->image = $dest;
417         $this->width  = imagesx($this->image);
418         $this->height = imagesy($this->image);
419     }
420
421
422     public function cropImage($max,$x,$y,$w,$h) {
423         if(!$this->is_valid())
424             return FALSE;
425
426         if($this->is_imagick()) {
427             $this->image->setFirstIterator();
428             do {
429                 $this->image->cropImage($w, $h, $x, $y);
430                 /**
431                  * We need to remove the canva,
432                  * or the image is not resized to the crop:
433                  * http://php.net/manual/en/imagick.cropimage.php#97232
434                  */
435                 $this->image->setImagePage(0, 0, 0, 0);
436             } while ($this->image->nextImage());
437             return $this->scaleImage($max);
438         }
439
440         $dest = imagecreatetruecolor( $max, $max );
441         imagealphablending($dest, false);
442         imagesavealpha($dest, true);
443         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
444         imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
445         if($this->image)
446             imagedestroy($this->image);
447         $this->image = $dest;
448         $this->width  = imagesx($this->image);
449         $this->height = imagesy($this->image);
450     }
451
452     public function saveImage($path) {
453         if(!$this->is_valid())
454             return FALSE;
455
456         $string = $this->imageString();
457         file_put_contents($path, $string);
458     }
459
460     public function imageString() {
461         if(!$this->is_valid())
462             return FALSE;
463
464         if($this->is_imagick()) {
465             /* Clean it */
466             $this->image = $this->image->deconstructImages();
467             $string = $this->image->getImagesBlob();
468             return $string;
469         }
470
471         $quality = FALSE;
472
473         ob_start();
474
475         switch($this->getType()){
476             case "image/png":
477                 $quality = get_config('system','png_quality');
478                 if((! $quality) || ($quality > 9))
479                     $quality = PNG_QUALITY;
480                 imagepng($this->image,NULL, $quality);
481                 break;
482             case "image/jpeg":
483                 $quality = get_config('system','jpeg_quality');
484                 if((! $quality) || ($quality > 100))
485                     $quality = JPEG_QUALITY;
486                 imagejpeg($this->image,NULL,$quality);
487         }
488         $string = ob_get_contents();
489         ob_end_clean();
490
491         return $string;
492     }
493
494
495
496     public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
497
498         $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
499             dbesc($rid)
500         );
501         if(count($r))
502             $guid = $r[0]['guid'];
503         else
504             $guid = get_guid();
505
506         $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
507                 dbesc($rid),
508                 intval($uid),
509                 intval($cid),
510                 intval($scale)
511         );
512         if(count($x)) {
513             $r = q("UPDATE `photo`
514                 set `uid` = %d,
515                 `contact-id` = %d,
516                 `guid` = '%s',
517                 `resource-id` = '%s',
518                 `created` = '%s',
519                 `edited` = '%s',
520                 `filename` = '%s',
521                 `type` = '%s',
522                 `album` = '%s',
523                 `height` = %d,
524                 `width` = %d,
525                 `data` = '%s',
526                 `scale` = %d,
527                 `profile` = %d,
528                 `allow_cid` = '%s',
529                 `allow_gid` = '%s',
530                 `deny_cid` = '%s',
531                 `deny_gid` = '%s'
532                 where id = %d limit 1",
533
534                 intval($uid),
535                 intval($cid),
536                 dbesc($guid),
537                 dbesc($rid),
538                 dbesc(datetime_convert()),
539                 dbesc(datetime_convert()),
540                 dbesc(basename($filename)),
541                 dbesc($this->getType()),
542                 dbesc($album),
543                 intval($this->getHeight()),
544                 intval($this->getWidth()),
545                 dbesc($this->imageString()),
546                 intval($scale),
547                 intval($profile),
548                 dbesc($allow_cid),
549                 dbesc($allow_gid),
550                 dbesc($deny_cid),
551                 dbesc($deny_gid),
552                 intval($x[0]['id'])
553             );
554         }
555         else {
556             $r = q("INSERT INTO `photo`
557                 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
558                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
559                 intval($uid),
560                 intval($cid),
561                 dbesc($guid),
562                 dbesc($rid),
563                 dbesc(datetime_convert()),
564                 dbesc(datetime_convert()),
565                 dbesc(basename($filename)),
566                 dbesc($this->getType()),
567                 dbesc($album),
568                 intval($this->getHeight()),
569                 intval($this->getWidth()),
570                 dbesc($this->imageString()),
571                 intval($scale),
572                 intval($profile),
573                 dbesc($allow_cid),
574                 dbesc($allow_gid),
575                 dbesc($deny_cid),
576                 dbesc($deny_gid)
577             );
578         }
579         return $r;
580     }
581 }}
582
583
584 /**
585  * Guess image mimetype from filename or from Content-Type header
586  *
587  * @arg $filename string Image filename
588  * @arg $fromcurl boolean Check Content-Type header from curl request
589  */
590 function guess_image_type($filename, $fromcurl=false) {
591     logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
592     $type = null;
593     if ($fromcurl) {
594         $a = get_app();
595         $headers=array();
596         $h = explode("\n",$a->get_curl_headers());
597         foreach ($h as $l) {
598             list($k,$v) = array_map("trim", explode(":", trim($l), 2));
599             $headers[$k] = $v;
600         }
601         if (array_key_exists('Content-Type', $headers))
602             $type = $headers['Content-Type'];
603     }
604     if (is_null($type)){
605         // Guessing from extension? Isn't that... dangerous?
606         if(class_exists('Imagick')) {
607             /**
608              * Well, this not much better,
609              * but at least it comes from the data inside the image,
610              * we won't be tricked by a manipulated extension
611              */
612             $image = new Imagick($filename);
613             $type = $image->getImageMimeType();
614         } else {
615             $ext = pathinfo($filename, PATHINFO_EXTENSION);
616             $types = Photo::supportedTypes();
617             $type = "image/jpeg";
618             foreach ($types as $m=>$e){
619                 if ($ext==$e) $type = $m;
620             }
621         }
622     }
623     logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
624     return $type;
625
626 }
627
628 function import_profile_photo($photo,$uid,$cid) {
629
630     $a = get_app();
631
632     $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
633         intval($uid),
634         intval($cid)
635     );
636     if(count($r)) {
637         $hash = $r[0]['resource-id'];
638     }
639     else {
640         $hash = photo_new_resource();
641     }
642
643     $photo_failure = false;
644
645     $filename = basename($photo);
646     $img_str = fetch_url($photo,true);
647
648     $type = guess_image_type($photo,true);
649     $img = new Photo($img_str, $type);
650     if($img->is_valid()) {
651
652         $img->scaleImageSquare(175);
653
654         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
655
656         if($r === false)
657             $photo_failure = true;
658
659         $img->scaleImage(80);
660
661         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
662
663         if($r === false)
664             $photo_failure = true;
665
666         $img->scaleImage(48);
667
668         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
669
670         if($r === false)
671             $photo_failure = true;
672
673         $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
674         $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
675         $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
676     }
677     else
678         $photo_failure = true;
679
680     if($photo_failure) {
681         $photo = $a->get_baseurl() . '/images/person-175.jpg';
682         $thumb = $a->get_baseurl() . '/images/person-80.jpg';
683         $micro = $a->get_baseurl() . '/images/person-48.jpg';
684     }
685
686     return(array($photo,$thumb,$micro));
687
688 }