]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
Merge pull request #1724 from rabuzarus/theme_uid
[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);
375
376                 if(! $exif)
377                         return;
378
379         $ort = $exif['Orientation'];
380
381         switch($ort)
382         {
383             case 1: // nothing
384                 break;
385
386             case 2: // horizontal flip
387                 $this->flip();
388                 break;
389
390             case 3: // 180 rotate left
391                 $this->rotate(180);
392                 break;
393
394             case 4: // vertical flip
395                 $this->flip(false, true);
396                 break;
397
398             case 5: // vertical flip + 90 rotate right
399                 $this->flip(false, true);
400                 $this->rotate(-90);
401                 break;
402
403             case 6: // 90 rotate right
404                 $this->rotate(-90);
405                 break;
406
407             case 7: // horizontal flip + 90 rotate right
408                 $this->flip();
409                 $this->rotate(-90);
410                 break;
411
412             case 8:    // 90 rotate left
413                 $this->rotate(90);
414                 break;
415         }
416     }
417
418
419
420     public function scaleImageUp($min) {
421         if(!$this->is_valid())
422             return FALSE;
423
424
425         $width = $this->getWidth();
426         $height = $this->getHeight();
427
428         $dest_width = $dest_height = 0;
429
430         if((! $width)|| (! $height))
431             return FALSE;
432
433         if($width < $min && $height < $min) {
434             if($width > $height) {
435                 $dest_width = $min;
436                 $dest_height = intval(( $height * $min ) / $width);
437             }
438             else {
439                 $dest_width = intval(( $width * $min ) / $height);
440                 $dest_height = $min;
441             }
442         }
443         else {
444             if( $width < $min ) {
445                 $dest_width = $min;
446                 $dest_height = intval(( $height * $min ) / $width);
447             }
448             else {
449                 if( $height < $min ) {
450                     $dest_width = intval(( $width * $min ) / $height);
451                     $dest_height = $min;
452                 }
453                 else {
454                     $dest_width = $width;
455                     $dest_height = $height;
456                 }
457             }
458         }
459
460         if($this->is_imagick())
461             return $this->scaleImage($dest_width,$dest_height);
462
463         $dest = imagecreatetruecolor( $dest_width, $dest_height );
464         imagealphablending($dest, false);
465         imagesavealpha($dest, true);
466         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
467         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
468         if($this->image)
469             imagedestroy($this->image);
470         $this->image = $dest;
471         $this->width  = imagesx($this->image);
472         $this->height = imagesy($this->image);
473     }
474
475
476
477     public function scaleImageSquare($dim) {
478         if(!$this->is_valid())
479             return FALSE;
480
481         if($this->is_imagick()) {
482             $this->image->setFirstIterator();
483             do {
484                 $this->image->scaleImage($dim, $dim);
485             } while ($this->image->nextImage());
486             return;
487         }
488
489         $dest = imagecreatetruecolor( $dim, $dim );
490         imagealphablending($dest, false);
491         imagesavealpha($dest, true);
492         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
493         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
494         if($this->image)
495             imagedestroy($this->image);
496         $this->image = $dest;
497         $this->width  = imagesx($this->image);
498         $this->height = imagesy($this->image);
499     }
500
501
502     public function cropImage($max,$x,$y,$w,$h) {
503         if(!$this->is_valid())
504             return FALSE;
505
506                 if($this->is_imagick()) {
507                         $this->image->setFirstIterator();
508                         do {
509                                 $this->image->cropImage($w, $h, $x, $y);
510                                 /**
511                                  * We need to remove the canva,
512                                  * or the image is not resized to the crop:
513                                  * http://php.net/manual/en/imagick.cropimage.php#97232
514                                  */
515                                 $this->image->setImagePage(0, 0, 0, 0);
516                         } while ($this->image->nextImage());
517                         return $this->scaleImage($max);
518                 }
519
520         $dest = imagecreatetruecolor( $max, $max );
521         imagealphablending($dest, false);
522         imagesavealpha($dest, true);
523         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
524         imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
525         if($this->image)
526             imagedestroy($this->image);
527         $this->image = $dest;
528         $this->width  = imagesx($this->image);
529         $this->height = imagesy($this->image);
530     }
531
532     public function saveImage($path) {
533         if(!$this->is_valid())
534             return FALSE;
535
536         $string = $this->imageString();
537
538         $a = get_app();
539
540         $stamp1 = microtime(true);
541         file_put_contents($path, $string);
542         $a->save_timestamp($stamp1, "file");
543     }
544
545     public function imageString() {
546         if(!$this->is_valid())
547             return FALSE;
548
549         if($this->is_imagick()) {
550             /* Clean it */
551             $this->image = $this->image->deconstructImages();
552             $string = $this->image->getImagesBlob();
553             return $string;
554         }
555
556         $quality = FALSE;
557
558         ob_start();
559
560         // Enable interlacing
561         imageinterlace($this->image, true);
562
563         switch($this->getType()){
564             case "image/png":
565                 $quality = get_config('system','png_quality');
566                 if((! $quality) || ($quality > 9))
567                     $quality = PNG_QUALITY;
568                 imagepng($this->image,NULL, $quality);
569                 break;
570             case "image/jpeg":
571                 $quality = get_config('system','jpeg_quality');
572                 if((! $quality) || ($quality > 100))
573                     $quality = JPEG_QUALITY;
574                 imagejpeg($this->image,NULL,$quality);
575         }
576         $string = ob_get_contents();
577         ob_end_clean();
578
579         return $string;
580     }
581
582
583
584     public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
585
586         $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
587             dbesc($rid)
588         );
589         if(count($r))
590             $guid = $r[0]['guid'];
591         else
592             $guid = get_guid();
593
594         $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
595                 dbesc($rid),
596                 intval($uid),
597                 intval($cid),
598                 intval($scale)
599         );
600         if(count($x)) {
601             $r = q("UPDATE `photo`
602                 set `uid` = %d,
603                 `contact-id` = %d,
604                 `guid` = '%s',
605                 `resource-id` = '%s',
606                 `created` = '%s',
607                 `edited` = '%s',
608                 `filename` = '%s',
609                 `type` = '%s',
610                 `album` = '%s',
611                 `height` = %d,
612                 `width` = %d,
613                                 `datasize` = %d,
614                 `data` = '%s',
615                 `scale` = %d,
616                 `profile` = %d,
617                 `allow_cid` = '%s',
618                 `allow_gid` = '%s',
619                 `deny_cid` = '%s',
620                 `deny_gid` = '%s'
621                 where id = %d",
622
623                 intval($uid),
624                 intval($cid),
625                 dbesc($guid),
626                 dbesc($rid),
627                 dbesc(datetime_convert()),
628                 dbesc(datetime_convert()),
629                 dbesc(basename($filename)),
630                 dbesc($this->getType()),
631                 dbesc($album),
632                 intval($this->getHeight()),
633                 intval($this->getWidth()),
634                                 dbesc(strlen($this->imageString())),
635                 dbesc($this->imageString()),
636                 intval($scale),
637                 intval($profile),
638                 dbesc($allow_cid),
639                 dbesc($allow_gid),
640                 dbesc($deny_cid),
641                 dbesc($deny_gid),
642                 intval($x[0]['id'])
643             );
644         }
645         else {
646             $r = q("INSERT INTO `photo`
647                 ( `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` )
648                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
649                 intval($uid),
650                 intval($cid),
651                 dbesc($guid),
652                 dbesc($rid),
653                 dbesc(datetime_convert()),
654                 dbesc(datetime_convert()),
655                 dbesc(basename($filename)),
656                 dbesc($this->getType()),
657                 dbesc($album),
658                 intval($this->getHeight()),
659                 intval($this->getWidth()),
660                                 dbesc(strlen($this->imageString())),
661                 dbesc($this->imageString()),
662                 intval($scale),
663                 intval($profile),
664                 dbesc($allow_cid),
665                 dbesc($allow_gid),
666                 dbesc($deny_cid),
667                 dbesc($deny_gid)
668             );
669         }
670         return $r;
671     }
672 }}
673
674
675 /**
676  * Guess image mimetype from filename or from Content-Type header
677  *
678  * @arg $filename string Image filename
679  * @arg $fromcurl boolean Check Content-Type header from curl request
680  */
681 function guess_image_type($filename, $fromcurl=false) {
682     logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
683     $type = null;
684     if ($fromcurl) {
685         $a = get_app();
686         $headers=array();
687         $h = explode("\n",$a->get_curl_headers());
688         foreach ($h as $l) {
689             list($k,$v) = array_map("trim", explode(":", trim($l), 2));
690             $headers[$k] = $v;
691         }
692         if (array_key_exists('Content-Type', $headers))
693             $type = $headers['Content-Type'];
694     }
695     if (is_null($type)){
696         // Guessing from extension? Isn't that... dangerous?
697         if(class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
698             /**
699              * Well, this not much better,
700              * but at least it comes from the data inside the image,
701              * we won't be tricked by a manipulated extension
702              */
703             $image = new Imagick($filename);
704             $type = $image->getImageMimeType();
705             $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
706         } else {
707             $ext = pathinfo($filename, PATHINFO_EXTENSION);
708             $types = Photo::supportedTypes();
709             $type = "image/jpeg";
710             foreach ($types as $m=>$e){
711                 if ($ext==$e) $type = $m;
712             }
713         }
714     }
715     logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
716     return $type;
717
718 }
719
720 function import_profile_photo($photo,$uid,$cid) {
721
722     $a = get_app();
723
724     $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
725         intval($uid),
726         intval($cid)
727     );
728     if(count($r) && strlen($r[0]['resource-id'])) {
729         $hash = $r[0]['resource-id'];
730     }
731     else {
732         $hash = photo_new_resource();
733     }
734
735     $photo_failure = false;
736
737     $filename = basename($photo);
738     $img_str = fetch_url($photo,true);
739
740     $type = guess_image_type($photo,true);
741     $img = new Photo($img_str, $type);
742     if($img->is_valid()) {
743
744         $img->scaleImageSquare(175);
745
746         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
747
748         if($r === false)
749             $photo_failure = true;
750
751         $img->scaleImage(80);
752
753         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
754
755         if($r === false)
756             $photo_failure = true;
757
758         $img->scaleImage(48);
759
760         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
761
762         if($r === false)
763             $photo_failure = true;
764
765         $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
766         $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
767         $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
768     }
769     else
770         $photo_failure = true;
771
772     if($photo_failure) {
773         $photo = $a->get_baseurl() . '/images/person-175.jpg';
774         $thumb = $a->get_baseurl() . '/images/person-80.jpg';
775         $micro = $a->get_baseurl() . '/images/person-48.jpg';
776     }
777
778     return(array($photo,$thumb,$micro));
779
780 }
781
782 function get_photo_info($url) {
783         $data = array();
784
785         $data = Cache::get($url);
786
787         if (is_null($data)) {
788                 $img_str = fetch_url($url, true, $redirects, 4);
789
790                 $filesize = strlen($img_str);
791
792                 $tempfile = tempnam(get_temppath(), "cache");
793
794                 $a = get_app();
795                 $stamp1 = microtime(true);
796                 file_put_contents($tempfile, $img_str);
797                 $a->save_timestamp($stamp1, "file");
798
799                 $data = getimagesize($tempfile);
800                 unlink($tempfile);
801
802                 if ($data)
803                         $data["size"] = $filesize;
804
805                 Cache::set($url, serialize($data));
806         } else
807                 $data = unserialize($data);
808
809         return $data;
810 }
811
812 function scale_image($width, $height, $max) {
813
814         $dest_width = $dest_height = 0;
815
816         if((!$width) || (!$height))
817                 return FALSE;
818
819         if($width > $max && $height > $max) {
820
821                 // very tall image (greater than 16:9)
822                 // constrain the width - let the height float.
823
824                 if((($height * 9) / 16) > $width) {
825                         $dest_width = $max;
826                         $dest_height = intval(( $height * $max ) / $width);
827                 } elseif($width > $height) {
828                         // else constrain both dimensions
829                         $dest_width = $max;
830                         $dest_height = intval(( $height * $max ) / $width);
831                 }  else {
832                         $dest_width = intval(( $width * $max ) / $height);
833                         $dest_height = $max;
834                 }
835         } else {
836                 if( $width > $max ) {
837                         $dest_width = $max;
838                         $dest_height = intval(( $height * $max ) / $width);
839                 }  else {
840                         if( $height > $max ) {
841
842                                 // very tall image (greater than 16:9)
843                                 // but width is OK - don't do anything
844
845                                 if((($height * 9) / 16) > $width) {
846                                         $dest_width = $width;
847                                         $dest_height = $height;
848                                 } else {
849                                         $dest_width = intval(( $width * $max ) / $height);
850                                         $dest_height = $max;
851                                 }
852                         } else {
853                                 $dest_width = $width;
854                                 $dest_height = $height;
855                         }
856                 }
857         }
858         return array("width" => $dest_width, "height" => $dest_height);
859 }
860
861 function store_photo($a, $uid, $imagedata = "", $url = "") {
862         $r = q("SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
863                 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1",
864                 intval($uid));
865
866         if(!count($r)) {
867                 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
868                 return(array());
869         }
870
871         $page_owner_nick  = $r[0]['nickname'];
872
873 //      To-Do:
874 //      $default_cid      = $r[0]['id'];
875 //      $community_page   = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
876
877         if ((strlen($imagedata) == 0) AND ($url == "")) {
878                 logger("No image data and no url provided", LOGGER_DEBUG);
879                 return(array());
880         } elseif (strlen($imagedata) == 0) {
881                 logger("Uploading picture from ".$url, LOGGER_DEBUG);
882
883                 $stamp1 = microtime(true);
884                 $imagedata = @file_get_contents($url);
885                 $a->save_timestamp($stamp1, "file");
886         }
887
888         $maximagesize = get_config('system','maximagesize');
889
890         if(($maximagesize) && (strlen($imagedata) > $maximagesize)) {
891                 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
892                 return(array());
893         }
894
895 /*
896         $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
897                 intval($uid)
898         );
899
900         $limit = service_class_fetch($uid,'photo_upload_limit');
901
902         if(($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
903                 logger("Image exceeds personal limit of uid ".$uid, LOGGER_DEBUG);
904                 return(array());
905         }
906 */
907
908         $tempfile = tempnam(get_temppath(), "cache");
909
910         $stamp1 = microtime(true);
911         file_put_contents($tempfile, $imagedata);
912         $a->save_timestamp($stamp1, "file");
913
914         $data = getimagesize($tempfile);
915
916         if (!isset($data["mime"])) {
917                 unlink($tempfile);
918                 logger("File is no picture", LOGGER_DEBUG);
919                 return(array());
920         }
921
922         $ph = new Photo($imagedata, $data["mime"]);
923
924         if(!$ph->is_valid()) {
925                 unlink($tempfile);
926                 logger("Picture is no valid picture", LOGGER_DEBUG);
927                 return(array());
928         }
929
930         $ph->orient($tempfile);
931         unlink($tempfile);
932
933         $max_length = get_config('system','max_image_length');
934         if(! $max_length)
935                 $max_length = MAX_IMAGE_LENGTH;
936         if($max_length > 0)
937                 $ph->scaleImage($max_length);
938
939         $width = $ph->getWidth();
940         $height = $ph->getHeight();
941
942         $hash = photo_new_resource();
943
944         $smallest = 0;
945
946         // Pictures are always public by now
947         //$defperm = '<'.$default_cid.'>';
948         $defperm = "";
949         $visitor   = 0;
950
951         $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
952
953         if(!$r) {
954                 logger("Picture couldn't be stored", LOGGER_DEBUG);
955                 return(array());
956         }
957
958         $image = array("page" => $a->get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
959                         "full" => $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
960
961         if($width > 800 || $height > 800)
962                 $image["large"] = $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt();
963
964         if($width > 640 || $height > 640) {
965                 $ph->scaleImage(640);
966                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
967                 if($r)
968                         $image["medium"] = $a->get_baseurl()."/photo/{$hash}-1.".$ph->getExt();
969         }
970
971         if($width > 320 || $height > 320) {
972                 $ph->scaleImage(320);
973                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
974                 if($r)
975                         $image["small"] = $a->get_baseurl()."/photo/{$hash}-2.".$ph->getExt();
976         }
977
978         if($width > 160 AND $height > 160) {
979                 $x = 0;
980                 $y = 0;
981
982                 $min = $ph->getWidth();
983                 if ($min > 160)
984                         $x = ($min - 160) / 2;
985
986                 if ($ph->getHeight() < $min) {
987                         $min = $ph->getHeight();
988                         if ($min > 160)
989                                 $y = ($min - 160) / 2;
990                 }
991
992                 $min = 160;
993                 $ph->cropImage(160, $x, $y, $min, $min);
994
995                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
996                 if($r)
997                         $image["thumb"] = $a->get_baseurl()."/photo/{$hash}-3.".$ph->getExt();
998         }
999
1000         // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1001         $image["preview"] = $image["full"];
1002
1003         // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1004         //if (isset($image["thumb"]))
1005         //      $image["preview"] = $image["thumb"];
1006
1007         // Unsure, if this should be activated or deactivated
1008         //if (isset($image["small"]))
1009         //      $image["preview"] = $image["small"];
1010
1011         if (isset($image["medium"]))
1012                 $image["preview"] = $image["medium"];
1013
1014         return($image);
1015 }
1016