]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
Merge pull request #3373 from strk/expire-login-later
[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                 return $r;
711         }
712 }
713
714
715 /**
716  * Guess image mimetype from filename or from Content-Type header
717  *
718  * @arg $filename string Image filename
719  * @arg $fromcurl boolean Check Content-Type header from curl request
720  */
721 function guess_image_type($filename, $fromcurl=false) {
722         logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
723         $type = null;
724         if ($fromcurl) {
725                 $a = get_app();
726                 $headers=array();
727                 $h = explode("\n",$a->get_curl_headers());
728                 foreach ($h as $l) {
729                         list($k,$v) = array_map("trim", explode(":", trim($l), 2));
730                         $headers[$k] = $v;
731                 }
732                 if (array_key_exists('Content-Type', $headers))
733                         $type = $headers['Content-Type'];
734         }
735         if (is_null($type)){
736                 // Guessing from extension? Isn't that... dangerous?
737                 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
738                         /**
739                          * Well, this not much better,
740                          * but at least it comes from the data inside the image,
741                          * we won't be tricked by a manipulated extension
742                          */
743                         $image = new Imagick($filename);
744                         $type = $image->getImageMimeType();
745                         $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
746                 } else {
747                         $ext = pathinfo($filename, PATHINFO_EXTENSION);
748                         $types = Photo::supportedTypes();
749                         $type = "image/jpeg";
750                         foreach ($types as $m => $e){
751                                 if ($ext == $e) {
752                                         $type = $m;
753                                 }
754                         }
755                 }
756         }
757         logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
758         return $type;
759
760 }
761
762 /**
763  * @brief Updates the avatar links in a contact only if needed
764  *
765  * @param string $avatar Link to avatar picture
766  * @param int $uid User id of contact owner
767  * @param int $cid Contact id
768  * @param bool $force force picture update
769  *
770  * @return array Returns array of the different avatar sizes
771  */
772 function update_contact_avatar($avatar, $uid, $cid, $force = false) {
773
774         $r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
775         if (!dbm::is_result($r)) {
776                 return false;
777         } else {
778                 $data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
779         }
780
781         if (($r[0]["avatar"] != $avatar) OR $force) {
782                 $photos = import_profile_photo($avatar, $uid, $cid, true);
783
784                 if ($photos) {
785                         q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
786                                 dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
787                                 dbesc(datetime_convert()), intval($cid));
788                         return $photos;
789                 }
790         }
791
792         return $data;
793 }
794
795 function import_profile_photo($photo, $uid, $cid, $quit_on_error = false) {
796
797         $r = q("SELECT `resource-id` FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `scale` = 4 AND `album` = 'Contact Photos' LIMIT 1",
798                 intval($uid),
799                 intval($cid)
800         );
801         if (dbm::is_result($r) && strlen($r[0]['resource-id'])) {
802                 $hash = $r[0]['resource-id'];
803         } else {
804                 $hash = photo_new_resource();
805         }
806
807         $photo_failure = false;
808
809         $filename = basename($photo);
810         $img_str = fetch_url($photo, true);
811
812         if ($quit_on_error AND ($img_str == "")) {
813                 return false;
814         }
815
816         $type = guess_image_type($photo, true);
817         $img = new Photo($img_str, $type);
818         if ($img->is_valid()) {
819
820                 $img->scaleImageSquare(175);
821
822                 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4);
823
824                 if ($r === false)
825                         $photo_failure = true;
826
827                 $img->scaleImage(80);
828
829                 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5);
830
831                 if ($r === false)
832                         $photo_failure = true;
833
834                 $img->scaleImage(48);
835
836                 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6);
837
838                 if ($r === false) {
839                         $photo_failure = true;
840                 }
841
842                 $photo = App::get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
843                 $thumb = App::get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
844                 $micro = App::get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
845         } else {
846                 $photo_failure = true;
847         }
848
849         if ($photo_failure AND $quit_on_error) {
850                 return false;
851         }
852
853         if ($photo_failure) {
854                 $photo = App::get_baseurl() . '/images/person-175.jpg';
855                 $thumb = App::get_baseurl() . '/images/person-80.jpg';
856                 $micro = App::get_baseurl() . '/images/person-48.jpg';
857         }
858
859         return(array($photo,$thumb,$micro));
860
861 }
862
863 function get_photo_info($url) {
864         $data = array();
865
866         $data = Cache::get($url);
867
868         if (is_null($data) OR !$data OR !is_array($data)) {
869                 $img_str = fetch_url($url, true, $redirects, 4);
870                 $filesize = strlen($img_str);
871
872                 if (function_exists("getimagesizefromstring")) {
873                         $data = getimagesizefromstring($img_str);
874                 } else {
875                         $tempfile = tempnam(get_temppath(), "cache");
876
877                         $a = get_app();
878                         $stamp1 = microtime(true);
879                         file_put_contents($tempfile, $img_str);
880                         $a->save_timestamp($stamp1, "file");
881
882                         $data = getimagesize($tempfile);
883                         unlink($tempfile);
884                 }
885
886                 if ($data) {
887                         $data["size"] = $filesize;
888                 }
889
890                 Cache::set($url, $data);
891         }
892
893         return $data;
894 }
895
896 function scale_image($width, $height, $max) {
897
898         $dest_width = $dest_height = 0;
899
900         if ((!$width) || (!$height)) {
901                 return false;
902         }
903
904         if ($width > $max && $height > $max) {
905
906                 // very tall image (greater than 16:9)
907                 // constrain the width - let the height float.
908
909                 if ((($height * 9) / 16) > $width) {
910                         $dest_width = $max;
911                         $dest_height = intval(($height * $max) / $width);
912                 } elseif ($width > $height) {
913                         // else constrain both dimensions
914                         $dest_width = $max;
915                         $dest_height = intval(($height * $max) / $width);
916                 } else {
917                         $dest_width = intval(($width * $max) / $height);
918                         $dest_height = $max;
919                 }
920         } else {
921                 if ($width > $max) {
922                         $dest_width = $max;
923                         $dest_height = intval(($height * $max) / $width);
924                 } else {
925                         if ($height > $max) {
926
927                                 // very tall image (greater than 16:9)
928                                 // but width is OK - don't do anything
929
930                                 if ((($height * 9) / 16) > $width) {
931                                         $dest_width = $width;
932                                         $dest_height = $height;
933                                 } else {
934                                         $dest_width = intval(($width * $max) / $height);
935                                         $dest_height = $max;
936                                 }
937                         } else {
938                                 $dest_width = $width;
939                                 $dest_height = $height;
940                         }
941                 }
942         }
943         return array("width" => $dest_width, "height" => $dest_height);
944 }
945
946 function store_photo(App $a, $uid, $imagedata = "", $url = "") {
947         $r = q("SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
948                 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
949                 intval($uid));
950
951         if (!dbm::is_result($r)) {
952                 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
953                 return(array());
954         }
955
956         $page_owner_nick  = $r[0]['nickname'];
957
958         /// @TODO
959         /// $default_cid      = $r[0]['id'];
960         /// $community_page   = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
961
962         if ((strlen($imagedata) == 0) AND ($url == "")) {
963                 logger("No image data and no url provided", LOGGER_DEBUG);
964                 return(array());
965         } elseif (strlen($imagedata) == 0) {
966                 logger("Uploading picture from ".$url, LOGGER_DEBUG);
967
968                 $stamp1 = microtime(true);
969                 $imagedata = @file_get_contents($url);
970                 $a->save_timestamp($stamp1, "file");
971         }
972
973         $maximagesize = get_config('system', 'maximagesize');
974
975         if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
976                 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
977                 return(array());
978         }
979
980 /*
981         $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
982                 intval($uid)
983         );
984
985         $limit = service_class_fetch($uid,'photo_upload_limit');
986
987         if (($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
988                 logger("Image exceeds personal limit of uid ".$uid, LOGGER_DEBUG);
989                 return(array());
990         }
991 */
992
993         $tempfile = tempnam(get_temppath(), "cache");
994
995         $stamp1 = microtime(true);
996         file_put_contents($tempfile, $imagedata);
997         $a->save_timestamp($stamp1, "file");
998
999         $data = getimagesize($tempfile);
1000
1001         if (!isset($data["mime"])) {
1002                 unlink($tempfile);
1003                 logger("File is no picture", LOGGER_DEBUG);
1004                 return(array());
1005         }
1006
1007         $ph = new Photo($imagedata, $data["mime"]);
1008
1009         if (!$ph->is_valid()) {
1010                 unlink($tempfile);
1011                 logger("Picture is no valid picture", LOGGER_DEBUG);
1012                 return(array());
1013         }
1014
1015         $ph->orient($tempfile);
1016         unlink($tempfile);
1017
1018         $max_length = get_config('system', 'max_image_length');
1019         if (! $max_length) {
1020                 $max_length = MAX_IMAGE_LENGTH;
1021         }
1022         if ($max_length > 0) {
1023                 $ph->scaleImage($max_length);
1024         }
1025
1026         $width = $ph->getWidth();
1027         $height = $ph->getHeight();
1028
1029         $hash = photo_new_resource();
1030
1031         $smallest = 0;
1032
1033         // Pictures are always public by now
1034         //$defperm = '<'.$default_cid.'>';
1035         $defperm = "";
1036         $visitor = 0;
1037
1038         $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
1039
1040         if (!$r) {
1041                 logger("Picture couldn't be stored", LOGGER_DEBUG);
1042                 return(array());
1043         }
1044
1045         $image = array("page" => App::get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
1046                         "full" => App::get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
1047
1048         if ($width > 800 || $height > 800) {
1049                 $image["large"] = App::get_baseurl()."/photo/{$hash}-0.".$ph->getExt();
1050         }
1051
1052         if ($width > 640 || $height > 640) {
1053                 $ph->scaleImage(640);
1054                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
1055                 if ($r) {
1056                         $image["medium"] = App::get_baseurl()."/photo/{$hash}-1.".$ph->getExt();
1057                 }
1058         }
1059
1060         if ($width > 320 || $height > 320) {
1061                 $ph->scaleImage(320);
1062                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
1063                 if ($r) {
1064                         $image["small"] = App::get_baseurl()."/photo/{$hash}-2.".$ph->getExt();
1065                 }
1066         }
1067
1068         if ($width > 160 AND $height > 160) {
1069                 $x = 0;
1070                 $y = 0;
1071
1072                 $min = $ph->getWidth();
1073                 if ($min > 160) {
1074                         $x = ($min - 160) / 2;
1075                 }
1076
1077                 if ($ph->getHeight() < $min) {
1078                         $min = $ph->getHeight();
1079                         if ($min > 160) {
1080                                 $y = ($min - 160) / 2;
1081                         }
1082                 }
1083
1084                 $min = 160;
1085                 $ph->cropImage(160, $x, $y, $min, $min);
1086
1087                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
1088                 if ($r) {
1089                         $image["thumb"] = App::get_baseurl()."/photo/{$hash}-3.".$ph->getExt();
1090                 }
1091         }
1092
1093         // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1094         $image["preview"] = $image["full"];
1095
1096         // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1097         //if (isset($image["thumb"]))
1098         //      $image["preview"] = $image["thumb"];
1099
1100         // Unsure, if this should be activated or deactivated
1101         //if (isset($image["small"]))
1102         //      $image["preview"] = $image["small"];
1103
1104         if (isset($image["medium"])) {
1105                 $image["preview"] = $image["medium"];
1106         }
1107
1108         return($image);
1109 }