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