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