]> git.mxchange.org Git - friendica.git/blob - src/Object/Image.php
Merge pull request #6678 from rabuzarus/20190217_-_fix_magicLinks_mentions
[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 Exception;
9 use Friendica\App;
10 use Friendica\Core\Cache;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Photo;
17 use Friendica\Util\Network;
18 use Imagick;
19 use ImagickPixel;
20
21 /**
22  * Class to handle images
23  */
24 class Image
25 {
26         /** @var Imagick|resource */
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                 if ((! $width)|| (! $height)) {
303                         return false;
304                 }
305
306                 if ($width > $max && $height > $max) {
307                         // very tall image (greater than 16:9)
308                         // constrain the width - let the height float.
309
310                         if ((($height * 9) / 16) > $width) {
311                                 $dest_width = $max;
312                                 $dest_height = intval(($height * $max) / $width);
313                         } elseif ($width > $height) {
314                                 // else constrain both dimensions
315                                 $dest_width = $max;
316                                 $dest_height = intval(($height * $max) / $width);
317                         } else {
318                                 $dest_width = intval(($width * $max) / $height);
319                                 $dest_height = $max;
320                         }
321                 } else {
322                         if ($width > $max) {
323                                 $dest_width = $max;
324                                 $dest_height = intval(($height * $max) / $width);
325                         } else {
326                                 if ($height > $max) {
327                                         // very tall image (greater than 16:9)
328                                         // but width is OK - don't do anything
329
330                                         if ((($height * 9) / 16) > $width) {
331                                                 $dest_width = $width;
332                                                 $dest_height = $height;
333                                         } else {
334                                                 $dest_width = intval(($width * $max) / $height);
335                                                 $dest_height = $max;
336                                         }
337                                 } else {
338                                         $dest_width = $width;
339                                         $dest_height = $height;
340                                 }
341                         }
342                 }
343
344                 return $this->scale($dest_width, $dest_height);
345         }
346
347         /**
348          * @param integer $degrees degrees to rotate image
349          * @return mixed
350          */
351         public function rotate($degrees)
352         {
353                 if (!$this->isValid()) {
354                         return false;
355                 }
356
357                 if ($this->isImagick()) {
358                         $this->image->setFirstIterator();
359                         do {
360                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
361                         } while ($this->image->nextImage());
362                         return;
363                 }
364
365                 // if script dies at this point check memory_limit setting in php.ini
366                 $this->image  = imagerotate($this->image, $degrees, 0);
367                 $this->width  = imagesx($this->image);
368                 $this->height = imagesy($this->image);
369         }
370
371         /**
372          * @param boolean $horiz optional, default true
373          * @param boolean $vert  optional, default false
374          * @return mixed
375          */
376         public function flip($horiz = true, $vert = false)
377         {
378                 if (!$this->isValid()) {
379                         return false;
380                 }
381
382                 if ($this->isImagick()) {
383                         $this->image->setFirstIterator();
384                         do {
385                                 if ($horiz) {
386                                         $this->image->flipImage();
387                                 }
388                                 if ($vert) {
389                                         $this->image->flopImage();
390                                 }
391                         } while ($this->image->nextImage());
392                         return;
393                 }
394
395                 $w = imagesx($this->image);
396                 $h = imagesy($this->image);
397                 $flipped = imagecreate($w, $h);
398                 if ($horiz) {
399                         for ($x = 0; $x < $w; $x++) {
400                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
401                         }
402                 }
403                 if ($vert) {
404                         for ($y = 0; $y < $h; $y++) {
405                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
406                         }
407                 }
408                 $this->image = $flipped;
409         }
410
411         /**
412          * @param string $filename filename
413          * @return mixed
414          */
415         public function orient($filename)
416         {
417                 if ($this->isImagick()) {
418                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
419                         $orientation = $this->image->getImageOrientation();
420                         switch ($orientation) {
421                                 case Imagick::ORIENTATION_BOTTOMRIGHT:
422                                         $this->image->rotateimage("#000", 180);
423                                         break;
424                                 case Imagick::ORIENTATION_RIGHTTOP:
425                                         $this->image->rotateimage("#000", 90);
426                                         break;
427                                 case Imagick::ORIENTATION_LEFTBOTTOM:
428                                         $this->image->rotateimage("#000", -90);
429                                         break;
430                         }
431
432                         $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
433                         return true;
434                 }
435                 // based off comment on http://php.net/manual/en/function.imagerotate.php
436
437                 if (!$this->isValid()) {
438                         return false;
439                 }
440
441                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
442                         return;
443                 }
444
445                 $exif = @exif_read_data($filename, null, true);
446                 if (!$exif) {
447                         return;
448                 }
449
450                 $ort = $exif['IFD0']['Orientation'];
451
452                 switch ($ort) {
453                         case 1: // nothing
454                                 break;
455
456                         case 2: // horizontal flip
457                                 $this->flip();
458                                 break;
459
460                         case 3: // 180 rotate left
461                                 $this->rotate(180);
462                                 break;
463
464                         case 4: // vertical flip
465                                 $this->flip(false, true);
466                                 break;
467
468                         case 5: // vertical flip + 90 rotate right
469                                 $this->flip(false, true);
470                                 $this->rotate(-90);
471                                 break;
472
473                         case 6: // 90 rotate right
474                                 $this->rotate(-90);
475                                 break;
476
477                         case 7: // horizontal flip + 90 rotate right
478                                 $this->flip();
479                                 $this->rotate(-90);
480                                 break;
481
482                         case 8: // 90 rotate left
483                                 $this->rotate(90);
484                                 break;
485                 }
486
487                 //      Logger::log('exif: ' . print_r($exif,true));
488                 return $exif;
489         }
490
491         /**
492          * @param integer $min minimum dimension
493          * @return mixed
494          */
495         public function scaleUp($min)
496         {
497                 if (!$this->isValid()) {
498                         return false;
499                 }
500
501                 $width = $this->getWidth();
502                 $height = $this->getHeight();
503
504                 if ((!$width)|| (!$height)) {
505                         return false;
506                 }
507
508                 if ($width < $min && $height < $min) {
509                         if ($width > $height) {
510                                 $dest_width = $min;
511                                 $dest_height = intval(($height * $min) / $width);
512                         } else {
513                                 $dest_width = intval(($width * $min) / $height);
514                                 $dest_height = $min;
515                         }
516                 } else {
517                         if ($width < $min) {
518                                 $dest_width = $min;
519                                 $dest_height = intval(($height * $min) / $width);
520                         } else {
521                                 if ($height < $min) {
522                                         $dest_width = intval(($width * $min) / $height);
523                                         $dest_height = $min;
524                                 } else {
525                                         $dest_width = $width;
526                                         $dest_height = $height;
527                                 }
528                         }
529                 }
530
531                 return $this->scale($dest_width, $dest_height);
532         }
533
534         /**
535          * @param integer $dim dimension
536          * @return mixed
537          */
538         public function scaleToSquare($dim)
539         {
540                 if (!$this->isValid()) {
541                         return false;
542                 }
543
544                 return $this->scale($dim, $dim);
545         }
546
547         /**
548          * @brief Scale image to target dimensions
549          *
550          * @param int $dest_width
551          * @param int $dest_height
552          * @return boolean
553          */
554         private function scale($dest_width, $dest_height)
555         {
556                 if (!$this->isValid()) {
557                         return false;
558                 }
559
560                 if ($this->isImagick()) {
561                         /*
562                          * If it is not animated, there will be only one iteration here,
563                          * so don't bother checking
564                          */
565                         // Don't forget to go back to the first frame
566                         $this->image->setFirstIterator();
567                         do {
568                                 // FIXME - implement horizontal bias for scaling as in following GD functions
569                                 // to allow very tall images to be constrained only horizontally.
570                                 $this->image->scaleImage($dest_width, $dest_height);
571                         } while ($this->image->nextImage());
572
573                         // These may not be necessary anymore
574                         $this->width  = $this->image->getImageWidth();
575                         $this->height = $this->image->getImageHeight();
576                 } else {
577                         $dest = imagecreatetruecolor($dest_width, $dest_height);
578                         imagealphablending($dest, false);
579                         imagesavealpha($dest, true);
580
581                         if ($this->type=='image/png') {
582                                 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
583                         }
584
585                         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
586
587                         if ($this->image) {
588                                 imagedestroy($this->image);
589                         }
590
591                         $this->image = $dest;
592                         $this->width  = imagesx($this->image);
593                         $this->height = imagesy($this->image);
594                 }
595
596                 return true;
597         }
598
599         /**
600          * @param integer $max maximum
601          * @param integer $x   x coordinate
602          * @param integer $y   y coordinate
603          * @param integer $w   width
604          * @param integer $h   height
605          * @return mixed
606          */
607         public function crop($max, $x, $y, $w, $h)
608         {
609                 if (!$this->isValid()) {
610                         return false;
611                 }
612
613                 if ($this->isImagick()) {
614                         $this->image->setFirstIterator();
615                         do {
616                                 $this->image->cropImage($w, $h, $x, $y);
617                                 /*
618                                  * We need to remove the canva,
619                                  * or the image is not resized to the crop:
620                                  * http://php.net/manual/en/imagick.cropimage.php#97232
621                                  */
622                                 $this->image->setImagePage(0, 0, 0, 0);
623                         } while ($this->image->nextImage());
624                         return $this->scaleDown($max);
625                 }
626
627                 $dest = imagecreatetruecolor($max, $max);
628                 imagealphablending($dest, false);
629                 imagesavealpha($dest, true);
630                 if ($this->type=='image/png') {
631                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
632                 }
633                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
634                 if ($this->image) {
635                         imagedestroy($this->image);
636                 }
637                 $this->image = $dest;
638                 $this->width  = imagesx($this->image);
639                 $this->height = imagesy($this->image);
640         }
641
642         /**
643          * @param string $path file path
644          * @return mixed
645          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
646          */
647         public function saveToFilePath($path)
648         {
649                 if (!$this->isValid()) {
650                         return false;
651                 }
652
653                 $string = $this->asString();
654
655                 $a = \get_app();
656
657                 $stamp1 = microtime(true);
658                 file_put_contents($path, $string);
659                 $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
660         }
661
662         /**
663          * @brief Magic method allowing string casting of an Image object
664          *
665          * Ex: $data = $Image->asString();
666          * can be replaced by
667          * $data = (string) $Image;
668          *
669          * @return string
670          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
671          */
672         public function __toString() {
673                 return $this->asString();
674         }
675
676         /**
677          * @return mixed
678          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679          */
680         public function asString()
681         {
682                 if (!$this->isValid()) {
683                         return false;
684                 }
685
686                 if ($this->isImagick()) {
687                         /* Clean it */
688                         $this->image = $this->image->deconstructImages();
689                         $string = $this->image->getImagesBlob();
690                         return $string;
691                 }
692
693                 ob_start();
694
695                 // Enable interlacing
696                 imageinterlace($this->image, true);
697
698                 switch ($this->getType()) {
699                         case "image/png":
700                                 $quality = Config::get('system', 'png_quality');
701                                 if ((!$quality) || ($quality > 9)) {
702                                         $quality = PNG_QUALITY;
703                                 }
704                                 imagepng($this->image, null, $quality);
705                                 break;
706                         case "image/jpeg":
707                                 $quality = Config::get('system', 'jpeg_quality');
708                                 if ((!$quality) || ($quality > 100)) {
709                                         $quality = JPEG_QUALITY;
710                                 }
711                                 imagejpeg($this->image, null, $quality);
712                 }
713                 $string = ob_get_contents();
714                 ob_end_clean();
715
716                 return $string;
717         }
718
719         /**
720          * Guess image mimetype from filename or from Content-Type header
721          *
722          * @param string  $filename Image filename
723          * @param boolean $fromcurl Check Content-Type header from curl request
724          * @param string  $header   passed headers to take into account
725          *
726          * @return object
727          * @throws \ImagickException
728          */
729         public static function guessType($filename, $fromcurl = false, $header = '')
730         {
731                 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
732                 $type = null;
733                 if ($fromcurl) {
734                         $headers=[];
735                         $h = explode("\n", $header);
736                         foreach ($h as $l) {
737                                 $data = array_map("trim", explode(":", trim($l), 2));
738                                 if (count($data) > 1) {
739                                         list($k,$v) = $data;
740                                         $headers[$k] = $v;
741                                 }
742                         }
743                         if (array_key_exists('Content-Type', $headers))
744                                 $type = $headers['Content-Type'];
745                 }
746                 if (is_null($type)) {
747                         // Guessing from extension? Isn't that... dangerous?
748                         if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
749                                 /**
750                                  * Well, this not much better,
751                                  * but at least it comes from the data inside the image,
752                                  * we won't be tricked by a manipulated extension
753                                  */
754                                 $image = new Imagick($filename);
755                                 $type = $image->getImageMimeType();
756                                 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
757                         } else {
758                                 $ext = pathinfo($filename, PATHINFO_EXTENSION);
759                                 $types = self::supportedTypes();
760                                 $type = "image/jpeg";
761                                 foreach ($types as $m => $e) {
762                                         if ($ext == $e) {
763                                                 $type = $m;
764                                         }
765                                 }
766                         }
767                 }
768                 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
769                 return $type;
770         }
771
772         /**
773          * @param string $url url
774          * @return object
775          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
776          */
777         public static function getInfoFromURL($url)
778         {
779                 $data = [];
780
781                 if (empty($url)) {
782                         return $data;
783                 }
784
785                 $data = Cache::get($url);
786
787                 if (is_null($data) || !$data || !is_array($data)) {
788                         $img_str = Network::fetchUrl($url, true, $redirects, 4);
789
790                         if (!$img_str) {
791                                 return false;
792                         }
793
794                         $filesize = strlen($img_str);
795
796                         try {
797                                 if (function_exists("getimagesizefromstring")) {
798                                         $data = @getimagesizefromstring($img_str);
799                                 } else {
800                                         $tempfile = tempnam(get_temppath(), "cache");
801
802                                         $a = \get_app();
803                                         $stamp1 = microtime(true);
804                                         file_put_contents($tempfile, $img_str);
805                                         $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
806
807                                         $data = getimagesize($tempfile);
808                                         unlink($tempfile);
809                                 }
810                         } catch (Exception $e) {
811                                 return false;
812                         }
813
814                         if ($data) {
815                                 $data["size"] = $filesize;
816                         }
817
818                         Cache::set($url, $data);
819                 }
820
821                 return $data;
822         }
823
824         /**
825          * @param integer $width  width
826          * @param integer $height height
827          * @param integer $max    max
828          * @return array
829          */
830         public static function getScalingDimensions($width, $height, $max)
831         {
832                 if ((!$width) || (!$height)) {
833                         return false;
834                 }
835
836                 if ($width > $max && $height > $max) {
837                         // very tall image (greater than 16:9)
838                         // constrain the width - let the height float.
839
840                         if ((($height * 9) / 16) > $width) {
841                                 $dest_width = $max;
842                                 $dest_height = intval(($height * $max) / $width);
843                         } elseif ($width > $height) {
844                                 // else constrain both dimensions
845                                 $dest_width = $max;
846                                 $dest_height = intval(($height * $max) / $width);
847                         } else {
848                                 $dest_width = intval(($width * $max) / $height);
849                                 $dest_height = $max;
850                         }
851                 } else {
852                         if ($width > $max) {
853                                 $dest_width = $max;
854                                 $dest_height = intval(($height * $max) / $width);
855                         } else {
856                                 if ($height > $max) {
857                                         // very tall image (greater than 16:9)
858                                         // but width is OK - don't do anything
859
860                                         if ((($height * 9) / 16) > $width) {
861                                                 $dest_width = $width;
862                                                 $dest_height = $height;
863                                         } else {
864                                                 $dest_width = intval(($width * $max) / $height);
865                                                 $dest_height = $max;
866                                         }
867                                 } else {
868                                         $dest_width = $width;
869                                         $dest_height = $height;
870                                 }
871                         }
872                 }
873                 return ["width" => $dest_width, "height" => $dest_height];
874         }
875
876         /**
877          * @brief This function is used by the fromgplus addon
878          * @param App     $a         App
879          * @param integer $uid       user id
880          * @param string  $imagedata optional, default empty
881          * @param string  $url       optional, default empty
882          * @return array
883          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
884          * @throws \ImagickException
885          */
886         public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
887         {
888                 $r = q(
889                         "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
890                         WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
891                         intval($uid)
892                 );
893
894                 if (!DBA::isResult($r)) {
895                         Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
896                         return([]);
897                 }
898
899                 $page_owner_nick  = $r[0]['nickname'];
900
901                 /// @TODO
902                 /// $default_cid      = $r[0]['id'];
903                 /// $community_page   = (($r[0]['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
904
905                 if ((strlen($imagedata) == 0) && ($url == "")) {
906                         Logger::log("No image data and no url provided", Logger::DEBUG);
907                         return([]);
908                 } elseif (strlen($imagedata) == 0) {
909                         Logger::log("Uploading picture from ".$url, Logger::DEBUG);
910
911                         $stamp1 = microtime(true);
912                         $imagedata = @file_get_contents($url);
913                         $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
914                 }
915
916                 $maximagesize = Config::get('system', 'maximagesize');
917
918                 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
919                         Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
920                         return([]);
921                 }
922
923                 $tempfile = tempnam(get_temppath(), "cache");
924
925                 $stamp1 = microtime(true);
926                 file_put_contents($tempfile, $imagedata);
927                 $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
928
929                 $data = getimagesize($tempfile);
930
931                 if (!isset($data["mime"])) {
932                         unlink($tempfile);
933                         Logger::log("File is no picture", Logger::DEBUG);
934                         return([]);
935                 }
936
937                 $Image = new Image($imagedata, $data["mime"]);
938
939                 if (!$Image->isValid()) {
940                         unlink($tempfile);
941                         Logger::log("Picture is no valid picture", Logger::DEBUG);
942                         return([]);
943                 }
944
945                 $Image->orient($tempfile);
946                 unlink($tempfile);
947
948                 $max_length = Config::get('system', 'max_image_length');
949                 if (! $max_length) {
950                         $max_length = MAX_IMAGE_LENGTH;
951                 }
952
953                 if ($max_length > 0) {
954                         $Image->scaleDown($max_length);
955                 }
956
957                 $width = $Image->getWidth();
958                 $height = $Image->getHeight();
959
960                 $hash = Photo::newResource();
961
962                 // Pictures are always public by now
963                 //$defperm = '<'.$default_cid.'>';
964                 $defperm = "";
965                 $visitor = 0;
966
967                 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
968
969                 if (!$r) {
970                         Logger::log("Picture couldn't be stored", Logger::DEBUG);
971                         return([]);
972                 }
973
974                 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
975                         "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
976
977                 if ($width > 800 || $height > 800) {
978                         $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
979                 }
980
981                 if ($width > 640 || $height > 640) {
982                         $Image->scaleDown(640);
983                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
984                         if ($r) {
985                                 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
986                         }
987                 }
988
989                 if ($width > 320 || $height > 320) {
990                         $Image->scaleDown(320);
991                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
992                         if ($r) {
993                                 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
994                         }
995                 }
996
997                 if ($width > 160 && $height > 160) {
998                         $x = 0;
999                         $y = 0;
1000
1001                         $min = $Image->getWidth();
1002                         if ($min > 160) {
1003                                 $x = ($min - 160) / 2;
1004                         }
1005
1006                         if ($Image->getHeight() < $min) {
1007                                 $min = $Image->getHeight();
1008                                 if ($min > 160) {
1009                                         $y = ($min - 160) / 2;
1010                                 }
1011                         }
1012
1013                         $min = 160;
1014                         $Image->crop(160, $x, $y, $min, $min);
1015
1016                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1017                         if ($r) {
1018                                 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1019                         }
1020                 }
1021
1022                 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1023                 $image["preview"] = $image["full"];
1024
1025                 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1026                 //if (isset($image["thumb"]))
1027                 //  $image["preview"] = $image["thumb"];
1028
1029                 // Unsure, if this should be activated or deactivated
1030                 //if (isset($image["small"]))
1031                 //  $image["preview"] = $image["small"];
1032
1033                 if (isset($image["medium"])) {
1034                         $image["preview"] = $image["medium"];
1035                 }
1036
1037                 return($image);
1038         }
1039 }