]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
d26dd1684be0f4c7dc3d07175c0c50a3df20a111
[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                         if (is_resource($this->image))
72                                 imagedestroy($this->image);
73                 }
74         }
75
76         public function is_imagick() {
77                 return $this->imagick;
78         }
79
80         /**
81          * @brief Maps Mime types to Imagick formats
82          * @return arr With with image formats (mime type as key)
83          */
84         public function get_FormatsMap() {
85                 $m = array(
86                         'image/jpeg' => 'JPG',
87                         'image/png' => 'PNG',
88                         'image/gif' => 'GIF'
89                 );
90                 return $m;
91         }
92
93         private function load_data($data) {
94                 if ($this->is_imagick()) {
95                         $this->image = new Imagick();
96                         try {
97                                 $this->image->readImageBlob($data);
98                         } catch (Exception $e) {
99                                 // Imagick couldn't use the data
100                                 return false;
101                         }
102
103                         /*
104                          * Setup the image to the format it will be saved to
105                          */
106                         $map = $this->get_FormatsMap();
107                         $format = $map[$type];
108                         $this->image->setFormat($format);
109
110                         // Always coalesce, if it is not a multi-frame image it won't hurt anyway
111                         $this->image = $this->image->coalesceImages();
112
113                         /*
114                          * setup the compression here, so we'll do it only once
115                          */
116                         switch($this->getType()){
117                                 case "image/png":
118                                         $quality = get_config('system', 'png_quality');
119                                         if ((! $quality) || ($quality > 9)) {
120                                                 $quality = PNG_QUALITY;
121                                         }
122                                         /*
123                                          * From http://www.imagemagick.org/script/command-line-options.php#quality:
124                                          *
125                                          * 'For the MNG and PNG image formats, the quality value sets
126                                          * the zlib compression level (quality / 10) and filter-type (quality % 10).
127                                          * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
128                                          * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
129                                          */
130                                         $quality = $quality * 10;
131                                         $this->image->setCompressionQuality($quality);
132                                         break;
133                                 case "image/jpeg":
134                                         $quality = get_config('system', 'jpeg_quality');
135                                         if ((! $quality) || ($quality > 100)) {
136                                                 $quality = JPEG_QUALITY;
137                                         }
138                                         $this->image->setCompressionQuality($quality);
139                         }
140
141                         // The 'width' and 'height' properties are only used by non-Imagick routines.
142                         $this->width  = $this->image->getImageWidth();
143                         $this->height = $this->image->getImageHeight();
144                         $this->valid  = true;
145
146                         return true;
147                 }
148
149                 $this->valid = false;
150                 $this->image = @imagecreatefromstring($data);
151                 if ($this->image !== false) {
152                         $this->width  = imagesx($this->image);
153                         $this->height = imagesy($this->image);
154                         $this->valid  = true;
155                         imagealphablending($this->image, false);
156                         imagesavealpha($this->image, true);
157
158                         return true;
159                 }
160
161                 return false;
162         }
163
164         public function is_valid() {
165                 if ($this->is_imagick()) {
166                         return ($this->image !== false);
167                 }
168                 return $this->valid;
169         }
170
171         public function getWidth() {
172                 if (!$this->is_valid()) {
173                         return false;
174                 }
175
176                 if ($this->is_imagick()) {
177                         return $this->image->getImageWidth();
178                 }
179                 return $this->width;
180         }
181
182         public function getHeight() {
183                 if (!$this->is_valid()) {
184                         return false;
185                 }
186
187                 if ($this->is_imagick()) {
188                         return $this->image->getImageHeight();
189                 }
190                 return $this->height;
191         }
192
193         public function getImage() {
194                 if (!$this->is_valid()) {
195                         return false;
196                 }
197
198                 if ($this->is_imagick()) {
199                         /* Clean it */
200                         $this->image = $this->image->deconstructImages();
201                         return $this->image;
202                 }
203                 return $this->image;
204         }
205
206         public function getType() {
207                 if (!$this->is_valid()) {
208                         return false;
209                 }
210
211                 return $this->type;
212         }
213
214         public function getExt() {
215                 if (!$this->is_valid()) {
216                         return false;
217                 }
218
219                 return $this->types[$this->getType()];
220         }
221
222         public function scaleImage($max) {
223                 if (!$this->is_valid()) {
224                         return false;
225                 }
226
227                 $width = $this->getWidth();
228                 $height = $this->getHeight();
229
230                 $dest_width = $dest_height = 0;
231
232                 if ((! $width)|| (! $height)) {
233                         return false;
234                 }
235
236                 if ($width > $max && $height > $max) {
237
238                         // very tall image (greater than 16:9)
239                         // constrain the width - let the height float.
240
241                         if ((($height * 9) / 16) > $width) {
242                                 $dest_width = $max;
243                                 $dest_height = intval(($height * $max) / $width);
244                         } elseif ($width > $height) {
245                                 // else constrain both dimensions
246                                 $dest_width = $max;
247                                 $dest_height = intval(($height * $max) / $width);
248                         } else {
249                                 $dest_width = intval(($width * $max) / $height);
250                                 $dest_height = $max;
251                         }
252                 } else {
253                         if ($width > $max) {
254                                 $dest_width = $max;
255                                 $dest_height = intval(($height * $max) / $width);
256                         } else {
257                                 if ($height > $max) {
258
259                                         // very tall image (greater than 16:9)
260                                         // but width is OK - don't do anything
261
262                                         if ((($height * 9) / 16) > $width) {
263                                                 $dest_width = $width;
264                                                 $dest_height = $height;
265                                         } else {
266                                                 $dest_width = intval(($width * $max) / $height);
267                                                 $dest_height = $max;
268                                         }
269                                 } else {
270                                         $dest_width = $width;
271                                         $dest_height = $height;
272                                 }
273                         }
274                 }
275
276
277                 if ($this->is_imagick()) {
278                         /*
279                          * If it is not animated, there will be only one iteration here,
280                          * so don't bother checking
281                          */
282                         // Don't forget to go back to the first frame
283                         $this->image->setFirstIterator();
284                         do {
285
286                                 // FIXME - implement horizantal bias for scaling as in followin GD functions
287                                 // to allow very tall images to be constrained only horizontally.
288
289                                 $this->image->scaleImage($dest_width, $dest_height);
290                         } while ($this->image->nextImage());
291
292                         // These may not be necessary any more
293                         $this->width  = $this->image->getImageWidth();
294                         $this->height = $this->image->getImageHeight();
295
296                         return;
297                 }
298
299
300                 $dest = imagecreatetruecolor($dest_width, $dest_height);
301                 imagealphablending($dest, false);
302                 imagesavealpha($dest, true);
303                 if ($this->type=='image/png') {
304                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
305                 }
306                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
307                 if ($this->image) {
308                         imagedestroy($this->image);
309                 }
310                 $this->image = $dest;
311                 $this->width  = imagesx($this->image);
312                 $this->height = imagesy($this->image);
313         }
314
315         public function rotate($degrees) {
316                 if (!$this->is_valid()) {
317                         return false;
318                 }
319
320                 if ($this->is_imagick()) {
321                         $this->image->setFirstIterator();
322                         do {
323                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
324                         } while ($this->image->nextImage());
325                         return;
326                 }
327
328                 // if script dies at this point check memory_limit setting in php.ini
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 = '', $desc = '') {
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                                 `desc` = '%s'
664                                 WHERE `id` = %d",
665
666                                 intval($uid),
667                                 intval($cid),
668                                 dbesc($guid),
669                                 dbesc($rid),
670                                 dbesc(datetime_convert()),
671                                 dbesc(datetime_convert()),
672                                 dbesc(basename($filename)),
673                                 dbesc($this->getType()),
674                                 dbesc($album),
675                                 intval($this->getHeight()),
676                                 intval($this->getWidth()),
677                                 dbesc(strlen($this->imageString())),
678                                 dbesc($this->imageString()),
679                                 intval($scale),
680                                 intval($profile),
681                                 dbesc($allow_cid),
682                                 dbesc($allow_gid),
683                                 dbesc($deny_cid),
684                                 dbesc($deny_gid),
685                                 dbesc($desc),
686                                 intval($x[0]['id'])
687                         );
688                 } else {
689                         $r = q("INSERT INTO `photo`
690                                 (`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`, `desc`)
691                                 VALUES (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s', '%s')",
692                                 intval($uid),
693                                 intval($cid),
694                                 dbesc($guid),
695                                 dbesc($rid),
696                                 dbesc(datetime_convert()),
697                                 dbesc(datetime_convert()),
698                                 dbesc(basename($filename)),
699                                 dbesc($this->getType()),
700                                 dbesc($album),
701                                 intval($this->getHeight()),
702                                 intval($this->getWidth()),
703                                 dbesc(strlen($this->imageString())),
704                                 dbesc($this->imageString()),
705                                 intval($scale),
706                                 intval($profile),
707                                 dbesc($allow_cid),
708                                 dbesc($allow_gid),
709                                 dbesc($deny_cid),
710                                 dbesc($deny_gid),
711                                 dbesc($desc)
712                         );
713                 }
714
715                 return $r;
716         }
717 }
718
719
720 /**
721  * Guess image mimetype from filename or from Content-Type header
722  *
723  * @arg $filename string Image filename
724  * @arg $fromcurl boolean Check Content-Type header from curl request
725  */
726 function guess_image_type($filename, $fromcurl=false) {
727         logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
728         $type = null;
729         if ($fromcurl) {
730                 $a = get_app();
731                 $headers=array();
732                 $h = explode("\n",$a->get_curl_headers());
733                 foreach ($h as $l) {
734                         list($k,$v) = array_map("trim", explode(":", trim($l), 2));
735                         $headers[$k] = $v;
736                 }
737                 if (array_key_exists('Content-Type', $headers))
738                         $type = $headers['Content-Type'];
739         }
740         if (is_null($type)){
741                 // Guessing from extension? Isn't that... dangerous?
742                 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
743                         /**
744                          * Well, this not much better,
745                          * but at least it comes from the data inside the image,
746                          * we won't be tricked by a manipulated extension
747                          */
748                         $image = new Imagick($filename);
749                         $type = $image->getImageMimeType();
750                         $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
751                 } else {
752                         $ext = pathinfo($filename, PATHINFO_EXTENSION);
753                         $types = Photo::supportedTypes();
754                         $type = "image/jpeg";
755                         foreach ($types as $m => $e){
756                                 if ($ext == $e) {
757                                         $type = $m;
758                                 }
759                         }
760                 }
761         }
762         logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
763         return $type;
764
765 }
766
767 /**
768  * @brief Updates the avatar links in a contact only if needed
769  *
770  * @param string $avatar Link to avatar picture
771  * @param int $uid User id of contact owner
772  * @param int $cid Contact id
773  * @param bool $force force picture update
774  *
775  * @return array Returns array of the different avatar sizes
776  */
777 function update_contact_avatar($avatar, $uid, $cid, $force = false) {
778
779         $r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
780         if (!dbm::is_result($r)) {
781                 return false;
782         } else {
783                 $data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
784         }
785
786         if (($r[0]["avatar"] != $avatar) OR $force) {
787                 $photos = import_profile_photo($avatar, $uid, $cid, true);
788
789                 if ($photos) {
790                         q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
791                                 dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
792                                 dbesc(datetime_convert()), intval($cid));
793                         return $photos;
794                 }
795         }
796
797         return $data;
798 }
799
800 function import_profile_photo($photo, $uid, $cid, $quit_on_error = false) {
801
802         $r = q("SELECT `resource-id` FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `scale` = 4 AND `album` = 'Contact Photos' LIMIT 1",
803                 intval($uid),
804                 intval($cid)
805         );
806         if (dbm::is_result($r) && strlen($r[0]['resource-id'])) {
807                 $hash = $r[0]['resource-id'];
808         } else {
809                 $hash = photo_new_resource();
810         }
811
812         $photo_failure = false;
813
814         $filename = basename($photo);
815         $img_str = fetch_url($photo, true);
816
817         if ($quit_on_error AND ($img_str == "")) {
818                 return false;
819         }
820
821         $type = guess_image_type($photo, true);
822         $img = new Photo($img_str, $type);
823         if ($img->is_valid()) {
824
825                 $img->scaleImageSquare(175);
826
827                 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4);
828
829                 if ($r === false)
830                         $photo_failure = true;
831
832                 $img->scaleImage(80);
833
834                 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5);
835
836                 if ($r === false)
837                         $photo_failure = true;
838
839                 $img->scaleImage(48);
840
841                 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6);
842
843                 if ($r === false) {
844                         $photo_failure = true;
845                 }
846
847                 $photo = App::get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
848                 $thumb = App::get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
849                 $micro = App::get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
850         } else {
851                 $photo_failure = true;
852         }
853
854         if ($photo_failure AND $quit_on_error) {
855                 return false;
856         }
857
858         if ($photo_failure) {
859                 $photo = App::get_baseurl() . '/images/person-175.jpg';
860                 $thumb = App::get_baseurl() . '/images/person-80.jpg';
861                 $micro = App::get_baseurl() . '/images/person-48.jpg';
862         }
863
864         return(array($photo,$thumb,$micro));
865
866 }
867
868 function get_photo_info($url) {
869         $data = array();
870
871         $data = Cache::get($url);
872
873         if (is_null($data) OR !$data OR !is_array($data)) {
874                 $img_str = fetch_url($url, true, $redirects, 4);
875                 $filesize = strlen($img_str);
876
877                 if (function_exists("getimagesizefromstring")) {
878                         $data = getimagesizefromstring($img_str);
879                 } else {
880                         $tempfile = tempnam(get_temppath(), "cache");
881
882                         $a = get_app();
883                         $stamp1 = microtime(true);
884                         file_put_contents($tempfile, $img_str);
885                         $a->save_timestamp($stamp1, "file");
886
887                         $data = getimagesize($tempfile);
888                         unlink($tempfile);
889                 }
890
891                 if ($data) {
892                         $data["size"] = $filesize;
893                 }
894
895                 Cache::set($url, $data);
896         }
897
898         return $data;
899 }
900
901 function scale_image($width, $height, $max) {
902
903         $dest_width = $dest_height = 0;
904
905         if ((!$width) || (!$height)) {
906                 return false;
907         }
908
909         if ($width > $max && $height > $max) {
910
911                 // very tall image (greater than 16:9)
912                 // constrain the width - let the height float.
913
914                 if ((($height * 9) / 16) > $width) {
915                         $dest_width = $max;
916                         $dest_height = intval(($height * $max) / $width);
917                 } elseif ($width > $height) {
918                         // else constrain both dimensions
919                         $dest_width = $max;
920                         $dest_height = intval(($height * $max) / $width);
921                 } else {
922                         $dest_width = intval(($width * $max) / $height);
923                         $dest_height = $max;
924                 }
925         } else {
926                 if ($width > $max) {
927                         $dest_width = $max;
928                         $dest_height = intval(($height * $max) / $width);
929                 } else {
930                         if ($height > $max) {
931
932                                 // very tall image (greater than 16:9)
933                                 // but width is OK - don't do anything
934
935                                 if ((($height * 9) / 16) > $width) {
936                                         $dest_width = $width;
937                                         $dest_height = $height;
938                                 } else {
939                                         $dest_width = intval(($width * $max) / $height);
940                                         $dest_height = $max;
941                                 }
942                         } else {
943                                 $dest_width = $width;
944                                 $dest_height = $height;
945                         }
946                 }
947         }
948         return array("width" => $dest_width, "height" => $dest_height);
949 }
950
951 function store_photo(App $a, $uid, $imagedata = "", $url = "") {
952         $r = q("SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
953                 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
954                 intval($uid));
955
956         if (!dbm::is_result($r)) {
957                 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
958                 return(array());
959         }
960
961         $page_owner_nick  = $r[0]['nickname'];
962
963         /// @TODO
964         /// $default_cid      = $r[0]['id'];
965         /// $community_page   = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
966
967         if ((strlen($imagedata) == 0) AND ($url == "")) {
968                 logger("No image data and no url provided", LOGGER_DEBUG);
969                 return(array());
970         } elseif (strlen($imagedata) == 0) {
971                 logger("Uploading picture from ".$url, LOGGER_DEBUG);
972
973                 $stamp1 = microtime(true);
974                 $imagedata = @file_get_contents($url);
975                 $a->save_timestamp($stamp1, "file");
976         }
977
978         $maximagesize = get_config('system', 'maximagesize');
979
980         if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
981                 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
982                 return(array());
983         }
984
985 /*
986         $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
987                 intval($uid)
988         );
989
990         $limit = service_class_fetch($uid,'photo_upload_limit');
991
992         if (($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
993                 logger("Image exceeds personal limit of uid ".$uid, LOGGER_DEBUG);
994                 return(array());
995         }
996 */
997
998         $tempfile = tempnam(get_temppath(), "cache");
999
1000         $stamp1 = microtime(true);
1001         file_put_contents($tempfile, $imagedata);
1002         $a->save_timestamp($stamp1, "file");
1003
1004         $data = getimagesize($tempfile);
1005
1006         if (!isset($data["mime"])) {
1007                 unlink($tempfile);
1008                 logger("File is no picture", LOGGER_DEBUG);
1009                 return(array());
1010         }
1011
1012         $ph = new Photo($imagedata, $data["mime"]);
1013
1014         if (!$ph->is_valid()) {
1015                 unlink($tempfile);
1016                 logger("Picture is no valid picture", LOGGER_DEBUG);
1017                 return(array());
1018         }
1019
1020         $ph->orient($tempfile);
1021         unlink($tempfile);
1022
1023         $max_length = get_config('system', 'max_image_length');
1024         if (! $max_length) {
1025                 $max_length = MAX_IMAGE_LENGTH;
1026         }
1027         if ($max_length > 0) {
1028                 $ph->scaleImage($max_length);
1029         }
1030
1031         $width = $ph->getWidth();
1032         $height = $ph->getHeight();
1033
1034         $hash = photo_new_resource();
1035
1036         $smallest = 0;
1037
1038         // Pictures are always public by now
1039         //$defperm = '<'.$default_cid.'>';
1040         $defperm = "";
1041         $visitor = 0;
1042
1043         $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
1044
1045         if (!$r) {
1046                 logger("Picture couldn't be stored", LOGGER_DEBUG);
1047                 return(array());
1048         }
1049
1050         $image = array("page" => App::get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
1051                         "full" => App::get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
1052
1053         if ($width > 800 || $height > 800) {
1054                 $image["large"] = App::get_baseurl()."/photo/{$hash}-0.".$ph->getExt();
1055         }
1056
1057         if ($width > 640 || $height > 640) {
1058                 $ph->scaleImage(640);
1059                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
1060                 if ($r) {
1061                         $image["medium"] = App::get_baseurl()."/photo/{$hash}-1.".$ph->getExt();
1062                 }
1063         }
1064
1065         if ($width > 320 || $height > 320) {
1066                 $ph->scaleImage(320);
1067                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
1068                 if ($r) {
1069                         $image["small"] = App::get_baseurl()."/photo/{$hash}-2.".$ph->getExt();
1070                 }
1071         }
1072
1073         if ($width > 160 AND $height > 160) {
1074                 $x = 0;
1075                 $y = 0;
1076
1077                 $min = $ph->getWidth();
1078                 if ($min > 160) {
1079                         $x = ($min - 160) / 2;
1080                 }
1081
1082                 if ($ph->getHeight() < $min) {
1083                         $min = $ph->getHeight();
1084                         if ($min > 160) {
1085                                 $y = ($min - 160) / 2;
1086                         }
1087                 }
1088
1089                 $min = 160;
1090                 $ph->cropImage(160, $x, $y, $min, $min);
1091
1092                 $r = $ph->store($uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
1093                 if ($r) {
1094                         $image["thumb"] = App::get_baseurl()."/photo/{$hash}-3.".$ph->getExt();
1095                 }
1096         }
1097
1098         // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1099         $image["preview"] = $image["full"];
1100
1101         // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1102         //if (isset($image["thumb"]))
1103         //      $image["preview"] = $image["thumb"];
1104
1105         // Unsure, if this should be activated or deactivated
1106         //if (isset($image["small"]))
1107         //      $image["preview"] = $image["small"];
1108
1109         if (isset($image["medium"])) {
1110                 $image["preview"] = $image["medium"];
1111         }
1112
1113         return($image);
1114 }