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