]> git.mxchange.org Git - friendica.git/blob - src/Object/Image.php
dfda0634cc1392eccd5fa04c50432957831073b4
[friendica.git] / src / Object / Image.php
1 <?php
2 /**
3  * @file src/Object/Image.php
4  * @brief This file contains the Image class for image processing
5  */
6 namespace Friendica\Object;
7
8 use Friendica\App;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Photo;
17 use Friendica\Util\Network;
18 use Exception;
19 use Imagick;
20 use ImagickPixel;
21
22 /**
23  * Class to handle images
24  */
25 class Image
26 {
27         private $image;
28
29         /*
30          * Put back gd stuff, not everybody have Imagick
31          */
32         private $imagick;
33         private $width;
34         private $height;
35         private $valid;
36         private $type;
37         private $types;
38
39         /**
40          * @brief supported mimetypes and corresponding file extensions
41          * @return array
42          */
43         public static function supportedTypes()
44         {
45                 if (class_exists('Imagick')) {
46                         // Imagick::queryFormats won't help us a lot there...
47                         // At least, not yet, other parts of friendica uses this array
48                         $t = [
49                                 'image/jpeg' => 'jpg',
50                                 'image/png' => 'png',
51                                 'image/gif' => 'gif'
52                         ];
53                 } else {
54                         $t = [];
55                         $t['image/jpeg'] ='jpg';
56                         if (imagetypes() & IMG_PNG) {
57                                 $t['image/png'] = 'png';
58                         }
59                 }
60
61                 return $t;
62         }
63
64         /**
65          * @brief Constructor
66          * @param string  $data
67          * @param boolean $type optional, default null
68          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69          * @throws \ImagickException
70          */
71         public function __construct($data, $type = null)
72         {
73                 $this->imagick = class_exists('Imagick');
74                 $this->types = static::supportedTypes();
75                 if (!array_key_exists($type, $this->types)) {
76                         $type='image/jpeg';
77                 }
78                 $this->type = $type;
79
80                 if ($this->isImagick() && $this->loadData($data)) {
81                         return true;
82                 } else {
83                         // Failed to load with Imagick, fallback
84                         $this->imagick = false;
85                 }
86                 return $this->loadData($data);
87         }
88
89         /**
90          * @brief Destructor
91          * @return void
92          */
93         public function __destruct()
94         {
95                 if ($this->image) {
96                         if ($this->isImagick()) {
97                                 $this->image->clear();
98                                 $this->image->destroy();
99                                 return;
100                         }
101                         if (is_resource($this->image)) {
102                                 imagedestroy($this->image);
103                         }
104                 }
105         }
106
107         /**
108          * @return boolean
109          */
110         public function isImagick()
111         {
112                 return $this->imagick;
113         }
114
115         /**
116          * @brief Maps Mime types to Imagick formats
117          * @return array With with image formats (mime type as key)
118          */
119         public static function getFormatsMap()
120         {
121                 $m = [
122                         'image/jpeg' => 'JPG',
123                         'image/png' => 'PNG',
124                         'image/gif' => 'GIF'
125                 ];
126                 return $m;
127         }
128
129         /**
130          * @param string $data data
131          * @return boolean
132          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133          * @throws \ImagickException
134          */
135         private function loadData($data)
136         {
137                 if ($this->isImagick()) {
138                         $this->image = new Imagick();
139                         try {
140                                 $this->image->readImageBlob($data);
141                         } catch (Exception $e) {
142                                 // Imagick couldn't use the data
143                                 return false;
144                         }
145
146                         /*
147                          * Setup the image to the format it will be saved to
148                          */
149                         $map = self::getFormatsMap();
150                         $format = $map[$this->type];
151                         $this->image->setFormat($format);
152
153                         // Always coalesce, if it is not a multi-frame image it won't hurt anyway
154                         $this->image = $this->image->coalesceImages();
155
156                         /*
157                          * setup the compression here, so we'll do it only once
158                          */
159                         switch ($this->getType()) {
160                                 case "image/png":
161                                         $quality = Config::get('system', 'png_quality');
162                                         if ((! $quality) || ($quality > 9)) {
163                                                 $quality = PNG_QUALITY;
164                                         }
165                                         /*
166                                          * From http://www.imagemagick.org/script/command-line-options.php#quality:
167                                          *
168                                          * 'For the MNG and PNG image formats, the quality value sets
169                                          * the zlib compression level (quality / 10) and filter-type (quality % 10).
170                                          * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
171                                          * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
172                                          */
173                                         $quality = $quality * 10;
174                                         $this->image->setCompressionQuality($quality);
175                                         break;
176                                 case "image/jpeg":
177                                         $quality = Config::get('system', 'jpeg_quality');
178                                         if ((! $quality) || ($quality > 100)) {
179                                                 $quality = JPEG_QUALITY;
180                                         }
181                                         $this->image->setCompressionQuality($quality);
182                         }
183
184                         // The 'width' and 'height' properties are only used by non-Imagick routines.
185                         $this->width  = $this->image->getImageWidth();
186                         $this->height = $this->image->getImageHeight();
187                         $this->valid  = true;
188
189                         return true;
190                 }
191
192                 $this->valid = false;
193                 $this->image = @imagecreatefromstring($data);
194                 if ($this->image !== false) {
195                         $this->width  = imagesx($this->image);
196                         $this->height = imagesy($this->image);
197                         $this->valid  = true;
198                         imagealphablending($this->image, false);
199                         imagesavealpha($this->image, true);
200
201                         return true;
202                 }
203
204                 return false;
205         }
206
207         /**
208          * @return boolean
209          */
210         public function isValid()
211         {
212                 if ($this->isImagick()) {
213                         return ($this->image !== false);
214                 }
215                 return $this->valid;
216         }
217
218         /**
219          * @return mixed
220          */
221         public function getWidth()
222         {
223                 if (!$this->isValid()) {
224                         return false;
225                 }
226
227                 if ($this->isImagick()) {
228                         return $this->image->getImageWidth();
229                 }
230                 return $this->width;
231         }
232
233         /**
234          * @return mixed
235          */
236         public function getHeight()
237         {
238                 if (!$this->isValid()) {
239                         return false;
240                 }
241
242                 if ($this->isImagick()) {
243                         return $this->image->getImageHeight();
244                 }
245                 return $this->height;
246         }
247
248         /**
249          * @return mixed
250          */
251         public function getImage()
252         {
253                 if (!$this->isValid()) {
254                         return false;
255                 }
256
257                 if ($this->isImagick()) {
258                         /* Clean it */
259                         $this->image = $this->image->deconstructImages();
260                         return $this->image;
261                 }
262                 return $this->image;
263         }
264
265         /**
266          * @return mixed
267          */
268         public function getType()
269         {
270                 if (!$this->isValid()) {
271                         return false;
272                 }
273
274                 return $this->type;
275         }
276
277         /**
278          * @return mixed
279          */
280         public function getExt()
281         {
282                 if (!$this->isValid()) {
283                         return false;
284                 }
285
286                 return $this->types[$this->getType()];
287         }
288
289         /**
290          * @param integer $max max dimension
291          * @return mixed
292          */
293         public function scaleDown($max)
294         {
295                 if (!$this->isValid()) {
296                         return false;
297                 }
298
299                 $width = $this->getWidth();
300                 $height = $this->getHeight();
301
302                 $dest_width = $dest_height = 0;
303
304                 if ((! $width)|| (! $height)) {
305                         return false;
306                 }
307
308                 if ($width > $max && $height > $max) {
309                         // very tall image (greater than 16:9)
310                         // constrain the width - let the height float.
311
312                         if ((($height * 9) / 16) > $width) {
313                                 $dest_width = $max;
314                                 $dest_height = intval(($height * $max) / $width);
315                         } elseif ($width > $height) {
316                                 // else constrain both dimensions
317                                 $dest_width = $max;
318                                 $dest_height = intval(($height * $max) / $width);
319                         } else {
320                                 $dest_width = intval(($width * $max) / $height);
321                                 $dest_height = $max;
322                         }
323                 } else {
324                         if ($width > $max) {
325                                 $dest_width = $max;
326                                 $dest_height = intval(($height * $max) / $width);
327                         } else {
328                                 if ($height > $max) {
329                                         // very tall image (greater than 16:9)
330                                         // but width is OK - don't do anything
331
332                                         if ((($height * 9) / 16) > $width) {
333                                                 $dest_width = $width;
334                                                 $dest_height = $height;
335                                         } else {
336                                                 $dest_width = intval(($width * $max) / $height);
337                                                 $dest_height = $max;
338                                         }
339                                 } else {
340                                         $dest_width = $width;
341                                         $dest_height = $height;
342                                 }
343                         }
344                 }
345
346                 return $this->scale($dest_width, $dest_height);
347         }
348
349         /**
350          * @param integer $degrees degrees to rotate image
351          * @return mixed
352          */
353         public function rotate($degrees)
354         {
355                 if (!$this->isValid()) {
356                         return false;
357                 }
358
359                 if ($this->isImagick()) {
360                         $this->image->setFirstIterator();
361                         do {
362                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
363                         } while ($this->image->nextImage());
364                         return;
365                 }
366
367                 // if script dies at this point check memory_limit setting in php.ini
368                 $this->image  = imagerotate($this->image, $degrees, 0);
369                 $this->width  = imagesx($this->image);
370                 $this->height = imagesy($this->image);
371         }
372
373         /**
374          * @param boolean $horiz optional, default true
375          * @param boolean $vert  optional, default false
376          * @return mixed
377          */
378         public function flip($horiz = true, $vert = false)
379         {
380                 if (!$this->isValid()) {
381                         return false;
382                 }
383
384                 if ($this->isImagick()) {
385                         $this->image->setFirstIterator();
386                         do {
387                                 if ($horiz) {
388                                         $this->image->flipImage();
389                                 }
390                                 if ($vert) {
391                                         $this->image->flopImage();
392                                 }
393                         } while ($this->image->nextImage());
394                         return;
395                 }
396
397                 $w = imagesx($this->image);
398                 $h = imagesy($this->image);
399                 $flipped = imagecreate($w, $h);
400                 if ($horiz) {
401                         for ($x = 0; $x < $w; $x++) {
402                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
403                         }
404                 }
405                 if ($vert) {
406                         for ($y = 0; $y < $h; $y++) {
407                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
408                         }
409                 }
410                 $this->image = $flipped;
411         }
412
413         /**
414          * @param string $filename filename
415          * @return mixed
416          */
417         public function orient($filename)
418         {
419                 if ($this->isImagick()) {
420                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
421                         $orientation = $this->image->getImageOrientation();
422                         switch ($orientation) {
423                                 case Imagick::ORIENTATION_BOTTOMRIGHT:
424                                         $this->image->rotateimage("#000", 180);
425                                         break;
426                                 case Imagick::ORIENTATION_RIGHTTOP:
427                                         $this->image->rotateimage("#000", 90);
428                                         break;
429                                 case Imagick::ORIENTATION_LEFTBOTTOM:
430                                         $this->image->rotateimage("#000", -90);
431                                         break;
432                         }
433
434                         $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
435                         return true;
436                 }
437                 // based off comment on http://php.net/manual/en/function.imagerotate.php
438
439                 if (!$this->isValid()) {
440                         return false;
441                 }
442
443                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
444                         return;
445                 }
446
447                 $exif = @exif_read_data($filename, null, true);
448                 if (!$exif) {
449                         return;
450                 }
451
452                 $ort = $exif['IFD0']['Orientation'];
453
454                 switch ($ort) {
455                         case 1: // nothing
456                                 break;
457
458                         case 2: // horizontal flip
459                                 $this->flip();
460                                 break;
461
462                         case 3: // 180 rotate left
463                                 $this->rotate(180);
464                                 break;
465
466                         case 4: // vertical flip
467                                 $this->flip(false, true);
468                                 break;
469
470                         case 5: // vertical flip + 90 rotate right
471                                 $this->flip(false, true);
472                                 $this->rotate(-90);
473                                 break;
474
475                         case 6: // 90 rotate right
476                                 $this->rotate(-90);
477                                 break;
478
479                         case 7: // horizontal flip + 90 rotate right
480                                 $this->flip();
481                                 $this->rotate(-90);
482                                 break;
483
484                         case 8: // 90 rotate left
485                                 $this->rotate(90);
486                                 break;
487                 }
488
489                 //      Logger::log('exif: ' . print_r($exif,true));
490                 return $exif;
491         }
492
493         /**
494          * @param integer $min minimum dimension
495          * @return mixed
496          */
497         public function scaleUp($min)
498         {
499                 if (!$this->isValid()) {
500                         return false;
501                 }
502
503                 $width = $this->getWidth();
504                 $height = $this->getHeight();
505
506                 $dest_width = $dest_height = 0;
507
508                 if ((!$width)|| (!$height)) {
509                         return false;
510                 }
511
512                 if ($width < $min && $height < $min) {
513                         if ($width > $height) {
514                                 $dest_width = $min;
515                                 $dest_height = intval(($height * $min) / $width);
516                         } else {
517                                 $dest_width = intval(($width * $min) / $height);
518                                 $dest_height = $min;
519                         }
520                 } else {
521                         if ($width < $min) {
522                                 $dest_width = $min;
523                                 $dest_height = intval(($height * $min) / $width);
524                         } else {
525                                 if ($height < $min) {
526                                         $dest_width = intval(($width * $min) / $height);
527                                         $dest_height = $min;
528                                 } else {
529                                         $dest_width = $width;
530                                         $dest_height = $height;
531                                 }
532                         }
533                 }
534
535                 return $this->scale($dest_width, $dest_height);
536         }
537
538         /**
539          * @param integer $dim dimension
540          * @return mixed
541          */
542         public function scaleToSquare($dim)
543         {
544                 if (!$this->isValid()) {
545                         return false;
546                 }
547
548                 return $this->scale($dim, $dim);
549         }
550
551         /**
552          * @brief Scale image to target dimensions
553          *
554          * @param int $dest_width
555          * @param int $dest_height
556          * @return boolean
557          */
558         private function scale($dest_width, $dest_height)
559         {
560                 if (!$this->isValid()) {
561                         return false;
562                 }
563
564                 if ($this->isImagick()) {
565                         /*
566                          * If it is not animated, there will be only one iteration here,
567                          * so don't bother checking
568                          */
569                         // Don't forget to go back to the first frame
570                         $this->image->setFirstIterator();
571                         do {
572                                 // FIXME - implement horizontal bias for scaling as in following GD functions
573                                 // to allow very tall images to be constrained only horizontally.
574                                 $this->image->scaleImage($dest_width, $dest_height);
575                         } while ($this->image->nextImage());
576
577                         // These may not be necessary anymore
578                         $this->width  = $this->image->getImageWidth();
579                         $this->height = $this->image->getImageHeight();
580                 } else {
581                         $dest = imagecreatetruecolor($dest_width, $dest_height);
582                         imagealphablending($dest, false);
583                         imagesavealpha($dest, true);
584
585                         if ($this->type=='image/png') {
586                                 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
587                         }
588
589                         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
590
591                         if ($this->image) {
592                                 imagedestroy($this->image);
593                         }
594
595                         $this->image = $dest;
596                         $this->width  = imagesx($this->image);
597                         $this->height = imagesy($this->image);
598                 }
599
600                 return true;
601         }
602
603         /**
604          * @param integer $max maximum
605          * @param integer $x   x coordinate
606          * @param integer $y   y coordinate
607          * @param integer $w   width
608          * @param integer $h   height
609          * @return mixed
610          */
611         public function crop($max, $x, $y, $w, $h)
612         {
613                 if (!$this->isValid()) {
614                         return false;
615                 }
616
617                 if ($this->isImagick()) {
618                         $this->image->setFirstIterator();
619                         do {
620                                 $this->image->cropImage($w, $h, $x, $y);
621                                 /*
622                                  * We need to remove the canva,
623                                  * or the image is not resized to the crop:
624                                  * http://php.net/manual/en/imagick.cropimage.php#97232
625                                  */
626                                 $this->image->setImagePage(0, 0, 0, 0);
627                         } while ($this->image->nextImage());
628                         return $this->scaleDown($max);
629                 }
630
631                 $dest = imagecreatetruecolor($max, $max);
632                 imagealphablending($dest, false);
633                 imagesavealpha($dest, true);
634                 if ($this->type=='image/png') {
635                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
636                 }
637                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
638                 if ($this->image) {
639                         imagedestroy($this->image);
640                 }
641                 $this->image = $dest;
642                 $this->width  = imagesx($this->image);
643                 $this->height = imagesy($this->image);
644         }
645
646         /**
647          * @param string $path file path
648          * @return mixed
649          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
650          */
651         public function saveToFilePath($path)
652         {
653                 if (!$this->isValid()) {
654                         return false;
655                 }
656
657                 $string = $this->asString();
658
659                 $a = \get_app();
660
661                 $stamp1 = microtime(true);
662                 file_put_contents($path, $string);
663                 $a->saveTimestamp($stamp1, "file");
664         }
665
666         /**
667          * @brief Magic method allowing string casting of an Image object
668          *
669          * Ex: $data = $Image->asString();
670          * can be replaced by
671          * $data = (string) $Image;
672          *
673          * @return string
674          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675          */
676         public function __toString() {
677                 return $this->asString();
678         }
679
680         /**
681          * @return mixed
682          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683          */
684         public function asString()
685         {
686                 if (!$this->isValid()) {
687                         return false;
688                 }
689
690                 if ($this->isImagick()) {
691                         /* Clean it */
692                         $this->image = $this->image->deconstructImages();
693                         $string = $this->image->getImagesBlob();
694                         return $string;
695                 }
696
697                 $quality = false;
698
699                 ob_start();
700
701                 // Enable interlacing
702                 imageinterlace($this->image, true);
703
704                 switch ($this->getType()) {
705                         case "image/png":
706                                 $quality = Config::get('system', 'png_quality');
707                                 if ((!$quality) || ($quality > 9)) {
708                                         $quality = PNG_QUALITY;
709                                 }
710                                 imagepng($this->image, null, $quality);
711                                 break;
712                         case "image/jpeg":
713                                 $quality = Config::get('system', 'jpeg_quality');
714                                 if ((!$quality) || ($quality > 100)) {
715                                         $quality = JPEG_QUALITY;
716                                 }
717                                 imagejpeg($this->image, null, $quality);
718                 }
719                 $string = ob_get_contents();
720                 ob_end_clean();
721
722                 return $string;
723         }
724
725         /**
726          * Guess image mimetype from filename or from Content-Type header
727          *
728          * @param string  $filename Image filename
729          * @param boolean $fromcurl Check Content-Type header from curl request
730          * @param string  $header   passed headers to take into account
731          *
732          * @return object
733          * @throws \ImagickException
734          */
735         public static function guessType($filename, $fromcurl = false, $header = '')
736         {
737                 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
738                 $type = null;
739                 if ($fromcurl) {
740                         $a = \get_app();
741                         $headers=[];
742                         $h = explode("\n", $header);
743                         foreach ($h as $l) {
744                                 $data = array_map("trim", explode(":", trim($l), 2));
745                                 if (count($data) > 1) {
746                                         list($k,$v) = $data;
747                                         $headers[$k] = $v;
748                                 }
749                         }
750                         if (array_key_exists('Content-Type', $headers))
751                                 $type = $headers['Content-Type'];
752                 }
753                 if (is_null($type)) {
754                         // Guessing from extension? Isn't that... dangerous?
755                         if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
756                                 /**
757                                  * Well, this not much better,
758                                  * but at least it comes from the data inside the image,
759                                  * we won't be tricked by a manipulated extension
760                                  */
761                                 $image = new Imagick($filename);
762                                 $type = $image->getImageMimeType();
763                                 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
764                         } else {
765                                 $ext = pathinfo($filename, PATHINFO_EXTENSION);
766                                 $types = self::supportedTypes();
767                                 $type = "image/jpeg";
768                                 foreach ($types as $m => $e) {
769                                         if ($ext == $e) {
770                                                 $type = $m;
771                                         }
772                                 }
773                         }
774                 }
775                 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
776                 return $type;
777         }
778
779         /**
780          * @param string $url url
781          * @return object
782          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
783          */
784         public static function getInfoFromURL($url)
785         {
786                 $data = [];
787
788                 if (empty($url)) {
789                         return $data;
790                 }
791
792                 $data = Cache::get($url);
793
794                 if (is_null($data) || !$data || !is_array($data)) {
795                         $img_str = Network::fetchUrl($url, true, $redirects, 4);
796
797                         if (!$img_str) {
798                                 return false;
799                         }
800
801                         $filesize = strlen($img_str);
802
803                         try {
804                                 if (function_exists("getimagesizefromstring")) {
805                                         $data = @getimagesizefromstring($img_str);
806                                 } else {
807                                         $tempfile = tempnam(get_temppath(), "cache");
808
809                                         $a = \get_app();
810                                         $stamp1 = microtime(true);
811                                         file_put_contents($tempfile, $img_str);
812                                         $a->saveTimestamp($stamp1, "file");
813
814                                         $data = getimagesize($tempfile);
815                                         unlink($tempfile);
816                                 }
817                         } catch (Exception $e) {
818                                 return false;
819                         }
820
821                         if ($data) {
822                                 $data["size"] = $filesize;
823                         }
824
825                         Cache::set($url, $data);
826                 }
827
828                 return $data;
829         }
830
831         /**
832          * @param integer $width  width
833          * @param integer $height height
834          * @param integer $max    max
835          * @return array
836          */
837         public static function getScalingDimensions($width, $height, $max)
838         {
839                 $dest_width = $dest_height = 0;
840
841                 if ((!$width) || (!$height)) {
842                         return false;
843                 }
844
845                 if ($width > $max && $height > $max) {
846                         // very tall image (greater than 16:9)
847                         // constrain the width - let the height float.
848
849                         if ((($height * 9) / 16) > $width) {
850                                 $dest_width = $max;
851                                 $dest_height = intval(($height * $max) / $width);
852                         } elseif ($width > $height) {
853                                 // else constrain both dimensions
854                                 $dest_width = $max;
855                                 $dest_height = intval(($height * $max) / $width);
856                         } else {
857                                 $dest_width = intval(($width * $max) / $height);
858                                 $dest_height = $max;
859                         }
860                 } else {
861                         if ($width > $max) {
862                                 $dest_width = $max;
863                                 $dest_height = intval(($height * $max) / $width);
864                         } else {
865                                 if ($height > $max) {
866                                         // very tall image (greater than 16:9)
867                                         // but width is OK - don't do anything
868
869                                         if ((($height * 9) / 16) > $width) {
870                                                 $dest_width = $width;
871                                                 $dest_height = $height;
872                                         } else {
873                                                 $dest_width = intval(($width * $max) / $height);
874                                                 $dest_height = $max;
875                                         }
876                                 } else {
877                                         $dest_width = $width;
878                                         $dest_height = $height;
879                                 }
880                         }
881                 }
882                 return ["width" => $dest_width, "height" => $dest_height];
883         }
884
885         /**
886          * @brief This function is used by the fromgplus addon
887          * @param App     $a         App
888          * @param integer $uid       user id
889          * @param string  $imagedata optional, default empty
890          * @param string  $url       optional, default empty
891          * @return array
892          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893          * @throws \ImagickException
894          */
895         public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
896         {
897                 $r = q(
898                         "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
899                         WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
900                         intval($uid)
901                 );
902
903                 if (!DBA::isResult($r)) {
904                         Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
905                         return([]);
906                 }
907
908                 $page_owner_nick  = $r[0]['nickname'];
909
910                 /// @TODO
911                 /// $default_cid      = $r[0]['id'];
912                 /// $community_page   = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
913
914                 if ((strlen($imagedata) == 0) && ($url == "")) {
915                         Logger::log("No image data and no url provided", Logger::DEBUG);
916                         return([]);
917                 } elseif (strlen($imagedata) == 0) {
918                         Logger::log("Uploading picture from ".$url, Logger::DEBUG);
919
920                         $stamp1 = microtime(true);
921                         $imagedata = @file_get_contents($url);
922                         $a->saveTimestamp($stamp1, "file");
923                 }
924
925                 $maximagesize = Config::get('system', 'maximagesize');
926
927                 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
928                         Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
929                         return([]);
930                 }
931
932                 $tempfile = tempnam(get_temppath(), "cache");
933
934                 $stamp1 = microtime(true);
935                 file_put_contents($tempfile, $imagedata);
936                 $a->saveTimestamp($stamp1, "file");
937
938                 $data = getimagesize($tempfile);
939
940                 if (!isset($data["mime"])) {
941                         unlink($tempfile);
942                         Logger::log("File is no picture", Logger::DEBUG);
943                         return([]);
944                 }
945
946                 $Image = new Image($imagedata, $data["mime"]);
947
948                 if (!$Image->isValid()) {
949                         unlink($tempfile);
950                         Logger::log("Picture is no valid picture", Logger::DEBUG);
951                         return([]);
952                 }
953
954                 $Image->orient($tempfile);
955                 unlink($tempfile);
956
957                 $max_length = Config::get('system', 'max_image_length');
958                 if (! $max_length) {
959                         $max_length = MAX_IMAGE_LENGTH;
960                 }
961
962                 if ($max_length > 0) {
963                         $Image->scaleDown($max_length);
964                 }
965
966                 $width = $Image->getWidth();
967                 $height = $Image->getHeight();
968
969                 $hash = Photo::newResource();
970
971                 $smallest = 0;
972
973                 // Pictures are always public by now
974                 //$defperm = '<'.$default_cid.'>';
975                 $defperm = "";
976                 $visitor = 0;
977
978                 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
979
980                 if (!$r) {
981                         Logger::log("Picture couldn't be stored", Logger::DEBUG);
982                         return([]);
983                 }
984
985                 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
986                         "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
987
988                 if ($width > 800 || $height > 800) {
989                         $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
990                 }
991
992                 if ($width > 640 || $height > 640) {
993                         $Image->scaleDown(640);
994                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
995                         if ($r) {
996                                 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
997                         }
998                 }
999
1000                 if ($width > 320 || $height > 320) {
1001                         $Image->scaleDown(320);
1002                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
1003                         if ($r) {
1004                                 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
1005                         }
1006                 }
1007
1008                 if ($width > 160 && $height > 160) {
1009                         $x = 0;
1010                         $y = 0;
1011
1012                         $min = $Image->getWidth();
1013                         if ($min > 160) {
1014                                 $x = ($min - 160) / 2;
1015                         }
1016
1017                         if ($Image->getHeight() < $min) {
1018                                 $min = $Image->getHeight();
1019                                 if ($min > 160) {
1020                                         $y = ($min - 160) / 2;
1021                                 }
1022                         }
1023
1024                         $min = 160;
1025                         $Image->crop(160, $x, $y, $min, $min);
1026
1027                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1028                         if ($r) {
1029                                 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1030                         }
1031                 }
1032
1033                 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1034                 $image["preview"] = $image["full"];
1035
1036                 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1037                 //if (isset($image["thumb"]))
1038                 //  $image["preview"] = $image["thumb"];
1039
1040                 // Unsure, if this should be activated or deactivated
1041                 //if (isset($image["small"]))
1042                 //  $image["preview"] = $image["small"];
1043
1044                 if (isset($image["medium"])) {
1045                         $image["preview"] = $image["medium"];
1046                 }
1047
1048                 return($image);
1049         }
1050 }