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