]> git.mxchange.org Git - friendica.git/blob - src/Object/Photo.php
Merge pull request #4029 from annando/update-pubkey
[friendica.git] / src / Object / Photo.php
1 <?php
2 /**
3  * @file src/Object/Photo.php
4  * @brief This file contains the Photo 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\System;
12 use Friendica\Database\DBM;
13 use dba;
14 use Exception;
15 use Imagick;
16 use ImagickPixel;
17
18 require_once "include/photos.php";
19
20 /**
21  * Class to handle Photos
22  */
23 class Photo
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 = array(
47                                 'image/jpeg' => 'jpg',
48                                 'image/png' => 'png',
49                                 'image/gif' => 'gif'
50                         );
51                 } else {
52                         $t = array();
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 arr With with image formats (mime type as key)
115          */
116         public static function getFormatsMap()
117         {
118                 $m = array(
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[$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 scaleImage($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
342                 if ($this->isImagick()) {
343                         /*
344                          * If it is not animated, there will be only one iteration here,
345                          * so don't bother checking
346                          */
347                         // Don't forget to go back to the first frame
348                         $this->image->setFirstIterator();
349                         do {
350                                 // FIXME - implement horizantal bias for scaling as in followin GD functions
351                                 // to allow very tall images to be constrained only horizontally.
352
353                                 $this->image->scaleImage($dest_width, $dest_height);
354                         } while ($this->image->nextImage());
355
356                         // These may not be necessary any more
357                         $this->width  = $this->image->getImageWidth();
358                         $this->height = $this->image->getImageHeight();
359
360                         return;
361                 }
362
363
364                 $dest = imagecreatetruecolor($dest_width, $dest_height);
365                 imagealphablending($dest, false);
366                 imagesavealpha($dest, true);
367                 if ($this->type=='image/png') {
368                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
369                 }
370                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
371                 if ($this->image) {
372                         imagedestroy($this->image);
373                 }
374                 $this->image = $dest;
375                 $this->width  = imagesx($this->image);
376                 $this->height = imagesy($this->image);
377         }
378
379         /**
380          * @param integer $degrees degrees to rotate image
381          * @return mixed
382          */
383         public function rotate($degrees)
384         {
385                 if (!$this->isValid()) {
386                         return false;
387                 }
388
389                 if ($this->isImagick()) {
390                         $this->image->setFirstIterator();
391                         do {
392                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
393                         } while ($this->image->nextImage());
394                         return;
395                 }
396
397                 // if script dies at this point check memory_limit setting in php.ini
398                 $this->image  = imagerotate($this->image, $degrees, 0);
399                 $this->width  = imagesx($this->image);
400                 $this->height = imagesy($this->image);
401         }
402
403         /**
404          * @param boolean $horiz optional, default true
405          * @param boolean $vert  optional, default false
406          * @return mixed
407          */
408         public function flip($horiz = true, $vert = false)
409         {
410                 if (!$this->isValid()) {
411                         return false;
412                 }
413
414                 if ($this->isImagick()) {
415                         $this->image->setFirstIterator();
416                         do {
417                                 if ($horiz) {
418                                         $this->image->flipImage();
419                                 }
420                                 if ($vert) {
421                                         $this->image->flopImage();
422                                 }
423                         } while ($this->image->nextImage());
424                         return;
425                 }
426
427                 $w = imagesx($this->image);
428                 $h = imagesy($this->image);
429                 $flipped = imagecreate($w, $h);
430                 if ($horiz) {
431                         for ($x = 0; $x < $w; $x++) {
432                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
433                         }
434                 }
435                 if ($vert) {
436                         for ($y = 0; $y < $h; $y++) {
437                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
438                         }
439                 }
440                 $this->image = $flipped;
441         }
442
443         /**
444          * @param string $filename filename
445          * @return mixed
446          */
447         public function orient($filename)
448         {
449                 if ($this->isImagick()) {
450                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
451                         $orientation = $this->image->getImageOrientation();
452                         switch ($orientation) {
453                                 case Imagick::ORIENTATION_BOTTOMRIGHT:
454                                         $this->image->rotateimage("#000", 180);
455                                         break;
456                                 case Imagick::ORIENTATION_RIGHTTOP:
457                                         $this->image->rotateimage("#000", 90);
458                                         break;
459                                 case Imagick::ORIENTATION_LEFTBOTTOM:
460                                         $this->image->rotateimage("#000", -90);
461                                         break;
462                         }
463
464                         $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
465                         return true;
466                 }
467                 // based off comment on http://php.net/manual/en/function.imagerotate.php
468
469                 if (!$this->isValid()) {
470                         return false;
471                 }
472
473                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
474                         return;
475                 }
476
477                 $exif = @exif_read_data($filename, null, true);
478                 if (!$exif) {
479                         return;
480                 }
481
482                 $ort = $exif['IFD0']['Orientation'];
483
484                 switch ($ort) {
485                         case 1: // nothing
486                                 break;
487
488                         case 2: // horizontal flip
489                                 $this->flip();
490                                 break;
491
492                         case 3: // 180 rotate left
493                                 $this->rotate(180);
494                                 break;
495
496                         case 4: // vertical flip
497                                 $this->flip(false, true);
498                                 break;
499
500                         case 5: // vertical flip + 90 rotate right
501                                 $this->flip(false, true);
502                                 $this->rotate(-90);
503                                 break;
504
505                         case 6: // 90 rotate right
506                                 $this->rotate(-90);
507                                 break;
508
509                         case 7: // horizontal flip + 90 rotate right
510                                 $this->flip();
511                                 $this->rotate(-90);
512                                 break;
513
514                         case 8: // 90 rotate left
515                                 $this->rotate(90);
516                                 break;
517                 }
518
519                 //      logger('exif: ' . print_r($exif,true));
520                 return $exif;
521         }
522
523         /**
524          * @param integer $min minimum dimension
525          * @return mixed
526          */
527         public function scaleImageUp($min)
528         {
529                 if (!$this->isValid()) {
530                         return false;
531                 }
532
533                 $width = $this->getWidth();
534                 $height = $this->getHeight();
535
536                 $dest_width = $dest_height = 0;
537
538                 if ((!$width)|| (!$height)) {
539                         return false;
540                 }
541
542                 if ($width < $min && $height < $min) {
543                         if ($width > $height) {
544                                 $dest_width = $min;
545                                 $dest_height = intval(($height * $min) / $width);
546                         } else {
547                                 $dest_width = intval(($width * $min) / $height);
548                                 $dest_height = $min;
549                         }
550                 } else {
551                         if ($width < $min) {
552                                 $dest_width = $min;
553                                 $dest_height = intval(($height * $min) / $width);
554                         } else {
555                                 if ($height < $min) {
556                                         $dest_width = intval(($width * $min) / $height);
557                                         $dest_height = $min;
558                                 } else {
559                                         $dest_width = $width;
560                                         $dest_height = $height;
561                                 }
562                         }
563                 }
564
565                 if ($this->isImagick()) {
566                         return $this->scaleImage($dest_width, $dest_height);
567                 }
568
569                 $dest = imagecreatetruecolor($dest_width, $dest_height);
570                 imagealphablending($dest, false);
571                 imagesavealpha($dest, true);
572                 if ($this->type=='image/png') {
573                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
574                 }
575                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
576                 if ($this->image) {
577                         imagedestroy($this->image);
578                 }
579                 $this->image = $dest;
580                 $this->width  = imagesx($this->image);
581                 $this->height = imagesy($this->image);
582         }
583
584         /**
585          * @param integer $dim dimension
586          * @return mixed
587          */
588         public function scaleImageSquare($dim)
589         {
590                 if (!$this->isValid()) {
591                         return false;
592                 }
593
594                 if ($this->isImagick()) {
595                         $this->image->setFirstIterator();
596                         do {
597                                 $this->image->scaleImage($dim, $dim);
598                         } while ($this->image->nextImage());
599                         return;
600                 }
601
602                 $dest = imagecreatetruecolor($dim, $dim);
603                 imagealphablending($dest, false);
604                 imagesavealpha($dest, true);
605                 if ($this->type=='image/png') {
606                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
607                 }
608                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
609                 if ($this->image) {
610                         imagedestroy($this->image);
611                 }
612                 $this->image = $dest;
613                 $this->width  = imagesx($this->image);
614                 $this->height = imagesy($this->image);
615         }
616
617         /**
618          * @param integer $max maximum
619          * @param integer $x   x coordinate
620          * @param integer $y   y coordinate
621          * @param integer $w   width
622          * @param integer $h   height
623          * @return mixed
624          */
625         public function cropImage($max, $x, $y, $w, $h)
626         {
627                 if (!$this->isValid()) {
628                         return false;
629                 }
630
631                 if ($this->isImagick()) {
632                         $this->image->setFirstIterator();
633                         do {
634                                 $this->image->cropImage($w, $h, $x, $y);
635                                 /*
636                                  * We need to remove the canva,
637                                  * or the image is not resized to the crop:
638                                  * http://php.net/manual/en/imagick.cropimage.php#97232
639                                  */
640                                 $this->image->setImagePage(0, 0, 0, 0);
641                         } while ($this->image->nextImage());
642                         return $this->scaleImage($max);
643                 }
644
645                 $dest = imagecreatetruecolor($max, $max);
646                 imagealphablending($dest, false);
647                 imagesavealpha($dest, true);
648                 if ($this->type=='image/png') {
649                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
650                 }
651                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
652                 if ($this->image) {
653                         imagedestroy($this->image);
654                 }
655                 $this->image = $dest;
656                 $this->width  = imagesx($this->image);
657                 $this->height = imagesy($this->image);
658         }
659
660         /**
661          * @param string $path file path
662          * @return mixed
663          */
664         public function saveImage($path)
665         {
666                 if (!$this->isValid()) {
667                         return false;
668                 }
669
670                 $string = $this->imageString();
671
672                 $a = get_app();
673
674                 $stamp1 = microtime(true);
675                 file_put_contents($path, $string);
676                 $a->save_timestamp($stamp1, "file");
677         }
678
679         /**
680          * @return mixed
681          */
682         public function imageString()
683         {
684                 if (!$this->isValid()) {
685                         return false;
686                 }
687
688                 if ($this->isImagick()) {
689                         /* Clean it */
690                         $this->image = $this->image->deconstructImages();
691                         $string = $this->image->getImagesBlob();
692                         return $string;
693                 }
694
695                 $quality = false;
696
697                 ob_start();
698
699                 // Enable interlacing
700                 imageinterlace($this->image, true);
701
702                 switch ($this->getType()) {
703                         case "image/png":
704                                 $quality = Config::get('system', 'png_quality');
705                                 if ((!$quality) || ($quality > 9)) {
706                                         $quality = PNG_QUALITY;
707                                 }
708                                 imagepng($this->image, null, $quality);
709                                 break;
710                         case "image/jpeg":
711                                 $quality = Config::get('system', 'jpeg_quality');
712                                 if ((!$quality) || ($quality > 100)) {
713                                         $quality = JPEG_QUALITY;
714                                 }
715                                 imagejpeg($this->image, null, $quality);
716                 }
717                 $string = ob_get_contents();
718                 ob_end_clean();
719
720                 return $string;
721         }
722
723         /**
724          * @param integer $uid       uid
725          * @param integer $cid       cid
726          * @param integer $rid       rid
727          * @param string  $filename  filename
728          * @param string  $album     album name
729          * @param integer $scale     scale
730          * @param integer $profile   optional, default = 0
731          * @param string  $allow_cid optional, default = ''
732          * @param string  $allow_gid optional, default = ''
733          * @param string  $deny_cid  optional, default = ''
734          * @param string  $deny_gid  optional, default = ''
735          * @param string  $desc      optional, default = ''
736          * @return object
737          */
738         public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
739         {
740                 $r = dba::select('photo', array('guid'), array("`resource-id` = ? AND `guid` != ?", $rid, ''), array('limit' => 1));
741                 if (DBM::is_result($r)) {
742                         $guid = $r['guid'];
743                 } else {
744                         $guid = get_guid();
745                 }
746
747                 $x = dba::select('photo', array('id'), array('resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale), array('limit' => 1));
748
749                 $fields = array('uid' => $uid, 'contact-id' => $cid, 'guid' => $guid, 'resource-id' => $rid, 'created' => datetime_convert(), 'edited' => datetime_convert(),
750                                 'filename' => basename($filename), 'type' => $this->getType(), 'album' => $album, 'height' => $this->getHeight(), 'width' => $this->getWidth(),
751                                 'datasize' => strlen($this->imageString()), 'data' => $this->imageString(), 'scale' => $scale, 'profile' => $profile,
752                                 'allow_cid' => $allow_cid, 'allow_gid' => $allow_gid, 'deny_cid' => $deny_cid, 'deny_gid' => $deny_gid, 'desc' => $desc);
753
754                 if (DBM::is_result($x)) {
755                         $r = dba::update('photo', $fields, array('id' => $x['id']));
756                 } else {
757                         $r = dba::insert('photo', $fields);
758                 }
759
760                 return $r;
761         }
762
763         /**
764          * Guess image mimetype from filename or from Content-Type header
765          *
766          * @param string  $filename Image filename
767          * @param boolean $fromcurl Check Content-Type header from curl request
768          *
769          * @return object
770          */
771         public static function guessImageType($filename, $fromcurl = false)
772         {
773                 logger('Photo: guessImageType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
774                 $type = null;
775                 if ($fromcurl) {
776                         $a = get_app();
777                         $headers=array();
778                         $h = explode("\n", $a->get_curl_headers());
779                         foreach ($h as $l) {
780                                 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
781                                 $headers[$k] = $v;
782                         }
783                         if (array_key_exists('Content-Type', $headers))
784                                 $type = $headers['Content-Type'];
785                 }
786                 if (is_null($type)) {
787                         // Guessing from extension? Isn't that... dangerous?
788                         if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
789                                 /**
790                                  * Well, this not much better,
791                                  * but at least it comes from the data inside the image,
792                                  * we won't be tricked by a manipulated extension
793                                  */
794                                 $image = new Imagick($filename);
795                                 $type = $image->getImageMimeType();
796                                 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
797                         } else {
798                                 $ext = pathinfo($filename, PATHINFO_EXTENSION);
799                                 $types = self::supportedTypes();
800                                 $type = "image/jpeg";
801                                 foreach ($types as $m => $e) {
802                                         if ($ext == $e) {
803                                                 $type = $m;
804                                         }
805                                 }
806                         }
807                 }
808                 logger('Photo: guessImageType: type='.$type, LOGGER_DEBUG);
809                 return $type;
810         }
811
812         /**
813          * @param string  $photo         photo
814          * @param integer $uid           user id
815          * @param integer $cid           contact id
816          * @param boolean $quit_on_error optional, default false
817          * @return array
818          */
819         public static function importProfilePhoto($photo, $uid, $cid, $quit_on_error = false)
820         {
821                 $r = dba::select(
822                         'photo',
823                         array('resource-id'),
824                         array('uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos'),
825                         array('limit' => 1)
826                 );
827
828                 if (DBM::is_result($r) && strlen($r['resource-id'])) {
829                         $hash = $r['resource-id'];
830                 } else {
831                         $hash = photo_new_resource();
832                 }
833         
834                 $photo_failure = false;
835         
836                 $filename = basename($photo);
837                 $img_str = fetch_url($photo, true);
838         
839                 if ($quit_on_error && ($img_str == "")) {
840                         return false;
841                 }
842         
843                 $type = self::guessImageType($photo, true);
844                 $img = new Photo($img_str, $type);
845                 if ($img->isValid()) {
846                         $img->scaleImageSquare(175);
847         
848                         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4);
849         
850                         if ($r === false) {
851                                 $photo_failure = true;
852                         }
853         
854                         $img->scaleImage(80);
855         
856                         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5);
857         
858                         if ($r === false) {
859                                 $photo_failure = true;
860                         }
861         
862                         $img->scaleImage(48);
863         
864                         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6);
865         
866                         if ($r === false) {
867                                 $photo_failure = true;
868                         }
869         
870                         $suffix = '?ts='.time();
871         
872                         $photo = System::baseUrl() . '/photo/' . $hash . '-4.' . $img->getExt() . $suffix;
873                         $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $img->getExt() . $suffix;
874                         $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $img->getExt() . $suffix;
875         
876                         // Remove the cached photo
877                         $a = get_app();
878                         $basepath = $a->get_basepath();
879         
880                         if (is_dir($basepath."/photo")) {
881                                 $filename = $basepath.'/photo/'.$hash.'-4.'.$img->getExt();
882                                 if (file_exists($filename)) {
883                                         unlink($filename);
884                                 }
885                                 $filename = $basepath.'/photo/'.$hash.'-5.'.$img->getExt();
886                                 if (file_exists($filename)) {
887                                         unlink($filename);
888                                 }
889                                 $filename = $basepath.'/photo/'.$hash.'-6.'.$img->getExt();
890                                 if (file_exists($filename)) {
891                                         unlink($filename);
892                                 }
893                         }
894                 } else {
895                         $photo_failure = true;
896                 }
897         
898                 if ($photo_failure && $quit_on_error) {
899                         return false;
900                 }
901         
902                 if ($photo_failure) {
903                         $photo = System::baseUrl() . '/images/person-175.jpg';
904                         $thumb = System::baseUrl() . '/images/person-80.jpg';
905                         $micro = System::baseUrl() . '/images/person-48.jpg';
906                 }
907         
908                 return array($photo, $thumb, $micro);
909         }
910
911         /**
912          * @param string $url url
913          * @return object
914          */
915         public static function getInfoFromURL($url)
916         {
917                 $data = array();
918         
919                 $data = Cache::get($url);
920         
921                 if (is_null($data) || !$data || !is_array($data)) {
922                         $img_str = fetch_url($url, true, $redirects, 4);
923                         $filesize = strlen($img_str);
924         
925                         if (function_exists("getimagesizefromstring")) {
926                                 $data = getimagesizefromstring($img_str);
927                         } else {
928                                 $tempfile = tempnam(get_temppath(), "cache");
929         
930                                 $a = get_app();
931                                 $stamp1 = microtime(true);
932                                 file_put_contents($tempfile, $img_str);
933                                 $a->save_timestamp($stamp1, "file");
934         
935                                 $data = getimagesize($tempfile);
936                                 unlink($tempfile);
937                         }
938         
939                         if ($data) {
940                                 $data["size"] = $filesize;
941                         }
942         
943                         Cache::set($url, $data);
944                 }
945         
946                 return $data;
947         }
948
949         /**
950          * @param integer $width  width
951          * @param integer $height height
952          * @param integer $max    max
953          * @return array
954          */
955         public static function scaleImageTo($width, $height, $max)
956         {
957                 $dest_width = $dest_height = 0;
958         
959                 if ((!$width) || (!$height)) {
960                         return false;
961                 }
962         
963                 if ($width > $max && $height > $max) {
964                         // very tall image (greater than 16:9)
965                         // constrain the width - let the height float.
966         
967                         if ((($height * 9) / 16) > $width) {
968                                 $dest_width = $max;
969                                 $dest_height = intval(($height * $max) / $width);
970                         } elseif ($width > $height) {
971                                 // else constrain both dimensions
972                                 $dest_width = $max;
973                                 $dest_height = intval(($height * $max) / $width);
974                         } else {
975                                 $dest_width = intval(($width * $max) / $height);
976                                 $dest_height = $max;
977                         }
978                 } else {
979                         if ($width > $max) {
980                                 $dest_width = $max;
981                                 $dest_height = intval(($height * $max) / $width);
982                         } else {
983                                 if ($height > $max) {
984                                         // very tall image (greater than 16:9)
985                                         // but width is OK - don't do anything
986         
987                                         if ((($height * 9) / 16) > $width) {
988                                                 $dest_width = $width;
989                                                 $dest_height = $height;
990                                         } else {
991                                                 $dest_width = intval(($width * $max) / $height);
992                                                 $dest_height = $max;
993                                         }
994                                 } else {
995                                         $dest_width = $width;
996                                         $dest_height = $height;
997                                 }
998                         }
999                 }
1000                 return array("width" => $dest_width, "height" => $dest_height);
1001         }
1002
1003         /**
1004          * @brief This function is used by the fromgplus addon
1005          * @param object  $a         App
1006          * @param integer $uid       user id
1007          * @param string  $imagedata optional, default empty
1008          * @param string  $url       optional, default empty
1009          * @return array
1010          */
1011         public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
1012         {
1013                 $r = q(
1014                         "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
1015                         WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
1016                         intval($uid)
1017                 );
1018         
1019                 if (!DBM::is_result($r)) {
1020                         logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
1021                         return(array());
1022                 }
1023         
1024                 $page_owner_nick  = $r[0]['nickname'];
1025         
1026                 /// @TODO
1027                 /// $default_cid      = $r[0]['id'];
1028                 /// $community_page   = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1029         
1030                 if ((strlen($imagedata) == 0) && ($url == "")) {
1031                         logger("No image data and no url provided", LOGGER_DEBUG);
1032                         return(array());
1033                 } elseif (strlen($imagedata) == 0) {
1034                         logger("Uploading picture from ".$url, LOGGER_DEBUG);
1035         
1036                         $stamp1 = microtime(true);
1037                         $imagedata = @file_get_contents($url);
1038                         $a->save_timestamp($stamp1, "file");
1039                 }
1040         
1041                 $maximagesize = Config::get('system', 'maximagesize');
1042         
1043                 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
1044                         logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
1045                         return(array());
1046                 }
1047         
1048                 $tempfile = tempnam(get_temppath(), "cache");
1049         
1050                 $stamp1 = microtime(true);
1051                 file_put_contents($tempfile, $imagedata);
1052                 $a->save_timestamp($stamp1, "file");
1053         
1054                 $data = getimagesize($tempfile);
1055         
1056                 if (!isset($data["mime"])) {
1057                         unlink($tempfile);
1058                         logger("File is no picture", LOGGER_DEBUG);
1059                         return(array());
1060                 }
1061         
1062                 $ph = new Photo($imagedata, $data["mime"]);
1063         
1064                 if (!$ph->isValid()) {
1065                         unlink($tempfile);
1066                         logger("Picture is no valid picture", LOGGER_DEBUG);
1067                         return(array());
1068                 }
1069         
1070                 $ph->orient($tempfile);
1071                 unlink($tempfile);
1072         
1073                 $max_length = Config::get('system', 'max_image_length');
1074                 if (! $max_length) {
1075                         $max_length = MAX_IMAGE_LENGTH;
1076                 }
1077
1078                 if ($max_length > 0) {
1079                         $ph->scaleImage($max_length);
1080                 }
1081         
1082                 $width = $ph->getWidth();
1083                 $height = $ph->getHeight();
1084         
1085                 $hash = photo_new_resource();
1086         
1087                 $smallest = 0;
1088         
1089                 // Pictures are always public by now
1090                 //$defperm = '<'.$default_cid.'>';
1091                 $defperm = "";
1092                 $visitor = 0;
1093         
1094                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
1095         
1096                 if (!$r) {
1097                         logger("Picture couldn't be stored", LOGGER_DEBUG);
1098                         return(array());
1099                 }
1100         
1101                 $image = array("page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
1102                         "full" => System::baseUrl()."/photo/{$hash}-0.".$ph->getExt());
1103         
1104                 if ($width > 800 || $height > 800) {
1105                         $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$ph->getExt();
1106                 }
1107         
1108                 if ($width > 640 || $height > 640) {
1109                         $ph->scaleImage(640);
1110                         $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
1111                         if ($r) {
1112                                 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$ph->getExt();
1113                         }
1114                 }
1115         
1116                 if ($width > 320 || $height > 320) {
1117                         $ph->scaleImage(320);
1118                         $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
1119                         if ($r) {
1120                                 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$ph->getExt();
1121                         }
1122                 }
1123         
1124                 if ($width > 160 && $height > 160) {
1125                         $x = 0;
1126                         $y = 0;
1127                 
1128                         $min = $ph->getWidth();
1129                         if ($min > 160) {
1130                                 $x = ($min - 160) / 2;
1131                         }
1132                 
1133                         if ($ph->getHeight() < $min) {
1134                                 $min = $ph->getHeight();
1135                                 if ($min > 160) {
1136                                         $y = ($min - 160) / 2;
1137                                 }
1138                         }
1139         
1140                         $min = 160;
1141                         $ph->cropImage(160, $x, $y, $min, $min);
1142                 
1143                         $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
1144                         if ($r) {
1145                                 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$ph->getExt();
1146                         }
1147                 }
1148         
1149                 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1150                 $image["preview"] = $image["full"];
1151         
1152                 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1153                 //if (isset($image["thumb"]))
1154                 //  $image["preview"] = $image["thumb"];
1155         
1156                 // Unsure, if this should be activated or deactivated
1157                 //if (isset($image["small"]))
1158                 //  $image["preview"] = $image["small"];
1159         
1160                 if (isset($image["medium"])) {
1161                         $image["preview"] = $image["medium"];
1162                 }
1163         
1164                 return($image);
1165         }
1166 }