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