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