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