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