]> git.mxchange.org Git - friendica.git/blob - src/Object/Image.php
Add 'addon' folder as 'Friendica\Addon' namespace for autoload
[friendica.git] / src / Object / Image.php
1 <?php
2 /**
3  * @file src/Object/Image.php
4  * @brief This file contains the Image class for image processing
5  */
6 namespace Friendica\Object;
7
8 use Friendica\App;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Photo;
17 use Friendica\Util\Network;
18 use Exception;
19 use Imagick;
20 use ImagickPixel;
21
22 /**
23  * Class to handle images
24  */
25 class Image
26 {
27         private $image;
28
29         /*
30          * Put back gd stuff, not everybody have Imagick
31          */
32         private $imagick;
33         private $width;
34         private $height;
35         private $valid;
36         private $type;
37         private $types;
38
39         /**
40          * @brief supported mimetypes and corresponding file extensions
41          * @return array
42          */
43         public static function supportedTypes()
44         {
45                 if (class_exists('Imagick')) {
46                         // Imagick::queryFormats won't help us a lot there...
47                         // At least, not yet, other parts of friendica uses this array
48                         $t = [
49                                 'image/jpeg' => 'jpg',
50                                 'image/png' => 'png',
51                                 'image/gif' => 'gif'
52                         ];
53                 } else {
54                         $t = [];
55                         $t['image/jpeg'] ='jpg';
56                         if (imagetypes() & IMG_PNG) {
57                                 $t['image/png'] = 'png';
58                         }
59                 }
60
61                 return $t;
62         }
63
64         /**
65          * @brief Constructor
66          * @param object  $data data
67          * @param boolean $type optional, default null
68          * @return object
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 object $data data
130          * @return boolean
131          */
132         private function loadData($data)
133         {
134                 if ($this->isImagick()) {
135                         $this->image = new Imagick();
136                         try {
137                                 $this->image->readImageBlob($data);
138                         } catch (Exception $e) {
139                                 // Imagick couldn't use the data
140                                 return false;
141                         }
142
143                         /*
144                          * Setup the image to the format it will be saved to
145                          */
146                         $map = self::getFormatsMap();
147                         $format = $map[$this->type];
148                         $this->image->setFormat($format);
149
150                         // Always coalesce, if it is not a multi-frame image it won't hurt anyway
151                         $this->image = $this->image->coalesceImages();
152
153                         /*
154                          * setup the compression here, so we'll do it only once
155                          */
156                         switch ($this->getType()) {
157                                 case "image/png":
158                                         $quality = Config::get('system', 'png_quality');
159                                         if ((! $quality) || ($quality > 9)) {
160                                                 $quality = PNG_QUALITY;
161                                         }
162                                         /*
163                                          * From http://www.imagemagick.org/script/command-line-options.php#quality:
164                                          *
165                                          * 'For the MNG and PNG image formats, the quality value sets
166                                          * the zlib compression level (quality / 10) and filter-type (quality % 10).
167                                          * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
168                                          * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
169                                          */
170                                         $quality = $quality * 10;
171                                         $this->image->setCompressionQuality($quality);
172                                         break;
173                                 case "image/jpeg":
174                                         $quality = Config::get('system', 'jpeg_quality');
175                                         if ((! $quality) || ($quality > 100)) {
176                                                 $quality = JPEG_QUALITY;
177                                         }
178                                         $this->image->setCompressionQuality($quality);
179                         }
180
181                         // The 'width' and 'height' properties are only used by non-Imagick routines.
182                         $this->width  = $this->image->getImageWidth();
183                         $this->height = $this->image->getImageHeight();
184                         $this->valid  = true;
185
186                         return true;
187                 }
188
189                 $this->valid = false;
190                 $this->image = @imagecreatefromstring($data);
191                 if ($this->image !== false) {
192                         $this->width  = imagesx($this->image);
193                         $this->height = imagesy($this->image);
194                         $this->valid  = true;
195                         imagealphablending($this->image, false);
196                         imagesavealpha($this->image, true);
197
198                         return true;
199                 }
200
201                 return false;
202         }
203
204         /**
205          * @return boolean
206          */
207         public function isValid()
208         {
209                 if ($this->isImagick()) {
210                         return ($this->image !== false);
211                 }
212                 return $this->valid;
213         }
214
215         /**
216          * @return mixed
217          */
218         public function getWidth()
219         {
220                 if (!$this->isValid()) {
221                         return false;
222                 }
223
224                 if ($this->isImagick()) {
225                         return $this->image->getImageWidth();
226                 }
227                 return $this->width;
228         }
229
230         /**
231          * @return mixed
232          */
233         public function getHeight()
234         {
235                 if (!$this->isValid()) {
236                         return false;
237                 }
238
239                 if ($this->isImagick()) {
240                         return $this->image->getImageHeight();
241                 }
242                 return $this->height;
243         }
244
245         /**
246          * @return mixed
247          */
248         public function getImage()
249         {
250                 if (!$this->isValid()) {
251                         return false;
252                 }
253
254                 if ($this->isImagick()) {
255                         /* Clean it */
256                         $this->image = $this->image->deconstructImages();
257                         return $this->image;
258                 }
259                 return $this->image;
260         }
261
262         /**
263          * @return mixed
264          */
265         public function getType()
266         {
267                 if (!$this->isValid()) {
268                         return false;
269                 }
270
271                 return $this->type;
272         }
273
274         /**
275          * @return mixed
276          */
277         public function getExt()
278         {
279                 if (!$this->isValid()) {
280                         return false;
281                 }
282
283                 return $this->types[$this->getType()];
284         }
285
286         /**
287          * @param integer $max max dimension
288          * @return mixed
289          */
290         public function scaleDown($max)
291         {
292                 if (!$this->isValid()) {
293                         return false;
294                 }
295
296                 $width = $this->getWidth();
297                 $height = $this->getHeight();
298
299                 $dest_width = $dest_height = 0;
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                 $dest_width = $dest_height = 0;
504
505                 if ((!$width)|| (!$height)) {
506                         return false;
507                 }
508
509                 if ($width < $min && $height < $min) {
510                         if ($width > $height) {
511                                 $dest_width = $min;
512                                 $dest_height = intval(($height * $min) / $width);
513                         } else {
514                                 $dest_width = intval(($width * $min) / $height);
515                                 $dest_height = $min;
516                         }
517                 } else {
518                         if ($width < $min) {
519                                 $dest_width = $min;
520                                 $dest_height = intval(($height * $min) / $width);
521                         } else {
522                                 if ($height < $min) {
523                                         $dest_width = intval(($width * $min) / $height);
524                                         $dest_height = $min;
525                                 } else {
526                                         $dest_width = $width;
527                                         $dest_height = $height;
528                                 }
529                         }
530                 }
531
532                 return $this->scale($dest_width, $dest_height);
533         }
534
535         /**
536          * @param integer $dim dimension
537          * @return mixed
538          */
539         public function scaleToSquare($dim)
540         {
541                 if (!$this->isValid()) {
542                         return false;
543                 }
544
545                 return $this->scale($dim, $dim);
546         }
547
548         /**
549          * @brief Scale image to target dimensions
550          *
551          * @param int $dest_width
552          * @param int $dest_height
553          * @return boolean
554          */
555         private function scale($dest_width, $dest_height)
556         {
557                 if (!$this->isValid()) {
558                         return false;
559                 }
560
561                 if ($this->isImagick()) {
562                         /*
563                          * If it is not animated, there will be only one iteration here,
564                          * so don't bother checking
565                          */
566                         // Don't forget to go back to the first frame
567                         $this->image->setFirstIterator();
568                         do {
569                                 // FIXME - implement horizontal bias for scaling as in following GD functions
570                                 // to allow very tall images to be constrained only horizontally.
571                                 $this->image->scaleImage($dest_width, $dest_height);
572                         } while ($this->image->nextImage());
573
574                         // These may not be necessary anymore
575                         $this->width  = $this->image->getImageWidth();
576                         $this->height = $this->image->getImageHeight();
577                 } else {
578                         $dest = imagecreatetruecolor($dest_width, $dest_height);
579                         imagealphablending($dest, false);
580                         imagesavealpha($dest, true);
581
582                         if ($this->type=='image/png') {
583                                 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
584                         }
585
586                         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
587
588                         if ($this->image) {
589                                 imagedestroy($this->image);
590                         }
591
592                         $this->image = $dest;
593                         $this->width  = imagesx($this->image);
594                         $this->height = imagesy($this->image);
595                 }
596
597                 return true;
598         }
599
600         /**
601          * @param integer $max maximum
602          * @param integer $x   x coordinate
603          * @param integer $y   y coordinate
604          * @param integer $w   width
605          * @param integer $h   height
606          * @return mixed
607          */
608         public function crop($max, $x, $y, $w, $h)
609         {
610                 if (!$this->isValid()) {
611                         return false;
612                 }
613
614                 if ($this->isImagick()) {
615                         $this->image->setFirstIterator();
616                         do {
617                                 $this->image->cropImage($w, $h, $x, $y);
618                                 /*
619                                  * We need to remove the canva,
620                                  * or the image is not resized to the crop:
621                                  * http://php.net/manual/en/imagick.cropimage.php#97232
622                                  */
623                                 $this->image->setImagePage(0, 0, 0, 0);
624                         } while ($this->image->nextImage());
625                         return $this->scaleDown($max);
626                 }
627
628                 $dest = imagecreatetruecolor($max, $max);
629                 imagealphablending($dest, false);
630                 imagesavealpha($dest, true);
631                 if ($this->type=='image/png') {
632                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
633                 }
634                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
635                 if ($this->image) {
636                         imagedestroy($this->image);
637                 }
638                 $this->image = $dest;
639                 $this->width  = imagesx($this->image);
640                 $this->height = imagesy($this->image);
641         }
642
643         /**
644          * @param string $path file path
645          * @return mixed
646          */
647         public function saveToFilePath($path)
648         {
649                 if (!$this->isValid()) {
650                         return false;
651                 }
652
653                 $string = $this->asString();
654
655                 $a = \get_app();
656
657                 $stamp1 = microtime(true);
658                 file_put_contents($path, $string);
659                 $a->saveTimestamp($stamp1, "file");
660         }
661
662         /**
663          * @brief Magic method allowing string casting of an Image object
664          *
665          * Ex: $data = $Image->asString();
666          * can be replaced by
667          * $data = (string) $Image;
668          *
669          * @return string
670          */
671         public function __toString() {
672                 return $this->asString();
673         }
674
675         /**
676          * @return mixed
677          */
678         public function asString()
679         {
680                 if (!$this->isValid()) {
681                         return false;
682                 }
683
684                 if ($this->isImagick()) {
685                         /* Clean it */
686                         $this->image = $this->image->deconstructImages();
687                         $string = $this->image->getImagesBlob();
688                         return $string;
689                 }
690
691                 $quality = false;
692
693                 ob_start();
694
695                 // Enable interlacing
696                 imageinterlace($this->image, true);
697
698                 switch ($this->getType()) {
699                         case "image/png":
700                                 $quality = Config::get('system', 'png_quality');
701                                 if ((!$quality) || ($quality > 9)) {
702                                         $quality = PNG_QUALITY;
703                                 }
704                                 imagepng($this->image, null, $quality);
705                                 break;
706                         case "image/jpeg":
707                                 $quality = Config::get('system', 'jpeg_quality');
708                                 if ((!$quality) || ($quality > 100)) {
709                                         $quality = JPEG_QUALITY;
710                                 }
711                                 imagejpeg($this->image, null, $quality);
712                 }
713                 $string = ob_get_contents();
714                 ob_end_clean();
715
716                 return $string;
717         }
718
719         /**
720          * Guess image mimetype from filename or from Content-Type header
721          *
722          * @param string  $filename Image filename
723          * @param boolean $fromcurl Check Content-Type header from curl request
724          * @param string $header passed headers to take into account
725          *
726          * @return object
727          */
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                         $a = \get_app();
734                         $headers=[];
735                         $h = explode("\n", $header);
736                         foreach ($h as $l) {
737                                 $data = array_map("trim", explode(":", trim($l), 2));
738                                 if (count($data) > 1) {
739                                         list($k,$v) = $data;
740                                         $headers[$k] = $v;
741                                 }
742                         }
743                         if (array_key_exists('Content-Type', $headers))
744                                 $type = $headers['Content-Type'];
745                 }
746                 if (is_null($type)) {
747                         // Guessing from extension? Isn't that... dangerous?
748                         if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
749                                 /**
750                                  * Well, this not much better,
751                                  * but at least it comes from the data inside the image,
752                                  * we won't be tricked by a manipulated extension
753                                  */
754                                 $image = new Imagick($filename);
755                                 $type = $image->getImageMimeType();
756                                 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
757                         } else {
758                                 $ext = pathinfo($filename, PATHINFO_EXTENSION);
759                                 $types = self::supportedTypes();
760                                 $type = "image/jpeg";
761                                 foreach ($types as $m => $e) {
762                                         if ($ext == $e) {
763                                                 $type = $m;
764                                         }
765                                 }
766                         }
767                 }
768                 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
769                 return $type;
770         }
771
772         /**
773          * @param string $url url
774          * @return object
775          */
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                 $dest_width = $dest_height = 0;
832
833                 if ((!$width) || (!$height)) {
834                         return false;
835                 }
836
837                 if ($width > $max && $height > $max) {
838                         // very tall image (greater than 16:9)
839                         // constrain the width - let the height float.
840
841                         if ((($height * 9) / 16) > $width) {
842                                 $dest_width = $max;
843                                 $dest_height = intval(($height * $max) / $width);
844                         } elseif ($width > $height) {
845                                 // else constrain both dimensions
846                                 $dest_width = $max;
847                                 $dest_height = intval(($height * $max) / $width);
848                         } else {
849                                 $dest_width = intval(($width * $max) / $height);
850                                 $dest_height = $max;
851                         }
852                 } else {
853                         if ($width > $max) {
854                                 $dest_width = $max;
855                                 $dest_height = intval(($height * $max) / $width);
856                         } else {
857                                 if ($height > $max) {
858                                         // very tall image (greater than 16:9)
859                                         // but width is OK - don't do anything
860
861                                         if ((($height * 9) / 16) > $width) {
862                                                 $dest_width = $width;
863                                                 $dest_height = $height;
864                                         } else {
865                                                 $dest_width = intval(($width * $max) / $height);
866                                                 $dest_height = $max;
867                                         }
868                                 } else {
869                                         $dest_width = $width;
870                                         $dest_height = $height;
871                                 }
872                         }
873                 }
874                 return ["width" => $dest_width, "height" => $dest_height];
875         }
876
877         /**
878          * @brief This function is used by the fromgplus addon
879          * @param object  $a         App
880          * @param integer $uid       user id
881          * @param string  $imagedata optional, default empty
882          * @param string  $url       optional, default empty
883          * @return array
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'] == Contact::PAGE_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                 $smallest = 0;
962
963                 // Pictures are always public by now
964                 //$defperm = '<'.$default_cid.'>';
965                 $defperm = "";
966                 $visitor = 0;
967
968                 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
969
970                 if (!$r) {
971                         Logger::log("Picture couldn't be stored", Logger::DEBUG);
972                         return([]);
973                 }
974
975                 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
976                         "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
977
978                 if ($width > 800 || $height > 800) {
979                         $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
980                 }
981
982                 if ($width > 640 || $height > 640) {
983                         $Image->scaleDown(640);
984                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
985                         if ($r) {
986                                 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
987                         }
988                 }
989
990                 if ($width > 320 || $height > 320) {
991                         $Image->scaleDown(320);
992                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
993                         if ($r) {
994                                 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
995                         }
996                 }
997
998                 if ($width > 160 && $height > 160) {
999                         $x = 0;
1000                         $y = 0;
1001
1002                         $min = $Image->getWidth();
1003                         if ($min > 160) {
1004                                 $x = ($min - 160) / 2;
1005                         }
1006
1007                         if ($Image->getHeight() < $min) {
1008                                 $min = $Image->getHeight();
1009                                 if ($min > 160) {
1010                                         $y = ($min - 160) / 2;
1011                                 }
1012                         }
1013
1014                         $min = 160;
1015                         $Image->crop(160, $x, $y, $min, $min);
1016
1017                         $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1018                         if ($r) {
1019                                 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1020                         }
1021                 }
1022
1023                 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1024                 $image["preview"] = $image["full"];
1025
1026                 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1027                 //if (isset($image["thumb"]))
1028                 //  $image["preview"] = $image["thumb"];
1029
1030                 // Unsure, if this should be activated or deactivated
1031                 //if (isset($image["small"]))
1032                 //  $image["preview"] = $image["small"];
1033
1034                 if (isset($image["medium"])) {
1035                         $image["preview"] = $image["medium"];
1036                 }
1037
1038                 return($image);
1039         }
1040 }