]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
Merge pull request #2899 from tobiasd/20161109-stats
[friendica.git] / include / Photo.php
1 <?php
2 /**
3  * @file include/Photo.php
4  * @brief This file contains the Photo class for image processing
5  */
6
7 require_once("include/photos.php");
8
9 class Photo {
10
11         private $image;
12
13         /*
14          * Put back gd stuff, not everybody have Imagick
15          */
16         private $imagick;
17         private $width;
18         private $height;
19         private $valid;
20         private $type;
21         private $types;
22
23         /**
24          * @brief supported mimetypes and corresponding file extensions
25          */
26         static function supportedTypes() {
27                 if (class_exists('Imagick')) {
28
29                         // Imagick::queryFormats won't help us a lot there...
30                         // At least, not yet, other parts of friendica uses this array
31                         $t = array(
32                                 'image/jpeg' => 'jpg',
33                                 'image/png' => 'png',
34                                 'image/gif' => 'gif'
35                         );
36                 } else {
37                         $t = array();
38                         $t['image/jpeg'] ='jpg';
39                         if (imagetypes() & IMG_PNG) {
40                                 $t['image/png'] = 'png';
41                         }
42                 }
43
44                 return $t;
45         }
46
47         public function __construct($data, $type=null) {
48                 $this->imagick = class_exists('Imagick');
49                 $this->types = $this->supportedTypes();
50                 if (!array_key_exists($type, $this->types)){
51                         $type='image/jpeg';
52                 }
53                 $this->type = $type;
54
55                 if ($this->is_imagick() && $this->load_data($data)) {
56                         return true;
57                 } else {
58                         // Failed to load with Imagick, fallback
59                         $this->imagick = false;
60                 }
61                 return $this->load_data($data);
62         }
63
64         public function __destruct() {
65                 if ($this->image) {
66                         if ($this->is_imagick()) {
67                                 $this->image->clear();
68                                 $this->image->destroy();
69                                 return;
70                         }
71                         imagedestroy($this->image);
72                 }
73         }
74
75         public function is_imagick() {
76                 return $this->imagick;
77         }
78
79         /**
80          * @brief Maps Mime types to Imagick formats
81          * @return arr With with image formats (mime type as key)
82          */
83         public function get_FormatsMap() {
84                 $m = array(
85                         'image/jpeg' => 'JPG',
86                         'image/png' => 'PNG',
87                         'image/gif' => 'GIF'
88                 );
89                 return $m;
90         }
91
92         private function load_data($data) {
93                 if ($this->is_imagick()) {
94                         $this->image = new Imagick();
95                         try {
96                                 $this->image->readImageBlob($data);
97                         } catch (Exception $e) {
98                                 // Imagick couldn't use the data
99                                 return false;
100                         }
101
102                         /*
103                          * Setup the image to the format it will be saved to
104                          */
105                         $map = $this->get_FormatsMap();
106                         $format = $map[$type];
107                         $this->image->setFormat($format);
108
109                         // Always coalesce, if it is not a multi-frame image it won't hurt anyway
110                         $this->image = $this->image->coalesceImages();
111
112                         /*
113                          * setup the compression here, so we'll do it only once
114                          */
115                         switch($this->getType()){
116                                 case "image/png":
117                                         $quality = get_config('system', 'png_quality');
118                                         if ((! $quality) || ($quality > 9)) {
119                                                 $quality = PNG_QUALITY;
120                                         }
121                                         /*
122                                          * From http://www.imagemagick.org/script/command-line-options.php#quality:
123                                          *
124                                          * 'For the MNG and PNG image formats, the quality value sets
125                                          * the zlib compression level (quality / 10) and filter-type (quality % 10).
126                                          * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
127                                          * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
128                                          */
129                                         $quality = $quality * 10;
130                                         $this->image->setCompressionQuality($quality);
131                                         break;
132                                 case "image/jpeg":
133                                         $quality = get_config('system', 'jpeg_quality');
134                                         if ((! $quality) || ($quality > 100)) {
135                                                 $quality = JPEG_QUALITY;
136                                         }
137                                         $this->image->setCompressionQuality($quality);
138                         }
139
140                         // The 'width' and 'height' properties are only used by non-Imagick routines.
141                         $this->width  = $this->image->getImageWidth();
142                         $this->height = $this->image->getImageHeight();
143                         $this->valid  = true;
144
145                         return true;
146                 }
147
148                 $this->valid = false;
149                 $this->image = @imagecreatefromstring($data);
150                 if ($this->image !== false) {
151                         $this->width  = imagesx($this->image);
152                         $this->height = imagesy($this->image);
153                         $this->valid  = true;
154                         imagealphablending($this->image, false);
155                         imagesavealpha($this->image, true);
156
157                         return true;
158                 }
159
160                 return false;
161         }
162
163         public function is_valid() {
164                 if ($this->is_imagick()) {
165                         return ($this->image !== false);
166                 }
167                 return $this->valid;
168         }
169
170         public function getWidth() {
171                 if (!$this->is_valid()) {
172                         return false;
173                 }
174
175                 if ($this->is_imagick()) {
176                         return $this->image->getImageWidth();
177                 }
178                 return $this->width;
179         }
180
181         public function getHeight() {
182                 if (!$this->is_valid()) {
183                         return false;
184                 }
185
186                 if ($this->is_imagick()) {
187                         return $this->image->getImageHeight();
188                 }
189                 return $this->height;
190         }
191
192         public function getImage() {
193                 if (!$this->is_valid()) {
194                         return false;
195                 }
196
197                 if ($this->is_imagick()) {
198                         /* Clean it */
199                         $this->image = $this->image->deconstructImages();
200                         return $this->image;
201                 }
202                 return $this->image;
203         }
204
205         public function getType() {
206                 if (!$this->is_valid()) {
207                         return false;
208                 }
209
210                 return $this->type;
211         }
212
213         public function getExt() {
214                 if (!$this->is_valid()) {
215                         return false;
216                 }
217
218                 return $this->types[$this->getType()];
219         }
220
221         public function scaleImage($max) {
222                 if (!$this->is_valid()) {
223                         return false;
224                 }
225
226                 $width = $this->getWidth();
227                 $height = $this->getHeight();
228
229                 $dest_width = $dest_height = 0;
230
231                 if ((! $width)|| (! $height)) {
232                         return false;
233                 }
234
235                 if ($width > $max && $height > $max) {
236
237                         // very tall image (greater than 16:9)
238                         // constrain the width - let the height float.
239
240                         if ((($height * 9) / 16) > $width) {
241                                 $dest_width = $max;
242                                 $dest_height = intval(($height * $max) / $width);
243                         } elseif ($width > $height) {
244                                 // else constrain both dimensions
245                                 $dest_width = $max;
246                                 $dest_height = intval(($height * $max) / $width);
247                         } else {
248                                 $dest_width = intval(($width * $max) / $height);
249                                 $dest_height = $max;
250                         }
251                 } else {
252                         if ($width > $max) {
253                                 $dest_width = $max;
254                                 $dest_height = intval(($height * $max) / $width);
255                         } else {
256                                 if ($height > $max) {
257
258                                         // very tall image (greater than 16:9)
259                                         // but width is OK - don't do anything
260
261                                         if ((($height * 9) / 16) > $width) {
262                                                 $dest_width = $width;
263                                                 $dest_height = $height;
264                                         } else {
265                                                 $dest_width = intval(($width * $max) / $height);
266                                                 $dest_height = $max;
267                                         }
268                                 } else {
269                                         $dest_width = $width;
270                                         $dest_height = $height;
271                                 }
272                         }
273                 }
274
275
276                 if ($this->is_imagick()) {
277                         /*
278                          * If it is not animated, there will be only one iteration here,
279                          * so don't bother checking
280                          */
281                         // Don't forget to go back to the first frame
282                         $this->image->setFirstIterator();
283                         do {
284
285                                 // FIXME - implement horizantal bias for scaling as in followin GD functions
286                                 // to allow very tall images to be constrained only horizontally. 
287
288                                 $this->image->scaleImage($dest_width, $dest_height);
289                         } while ($this->image->nextImage());
290
291                         // These may not be necessary any more
292                         $this->width  = $this->image->getImageWidth();
293                         $this->height = $this->image->getImageHeight();
294
295                         return;
296                 }
297
298
299                 $dest = imagecreatetruecolor($dest_width, $dest_height);
300                 imagealphablending($dest, false);
301                 imagesavealpha($dest, true);
302                 if ($this->type=='image/png') {
303                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
304                 }
305                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
306                 if ($this->image) {
307                         imagedestroy($this->image);
308                 }
309                 $this->image = $dest;
310                 $this->width  = imagesx($this->image);
311                 $this->height = imagesy($this->image);
312         }
313
314         public function rotate($degrees) {
315                 if (!$this->is_valid()) {
316                         return false;
317                 }
318
319                 if ($this->is_imagick()) {
320                         $this->image->setFirstIterator();
321                         do {
322                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
323                         } while ($this->image->nextImage());
324                         return;
325                 }
326
327                 $this->image  = imagerotate($this->image,$degrees,0);
328                 $this->width  = imagesx($this->image);
329                 $this->height = imagesy($this->image);
330         }
331
332         public function flip($horiz = true, $vert = false) {
333                 if (!$this->is_valid()) {
334                         return false;
335                 }
336
337                 if ($this->is_imagick()) {
338                         $this->image->setFirstIterator();
339                         do {
340                                 if ($horiz) {
341                                         $this->image->flipImage();
342                                 }
343                                 if ($vert) {
344                                         $this->image->flopImage();
345                                 }
346                         } while ($this->image->nextImage());
347                         return;
348                 }
349
350                 $w = imagesx($this->image);
351                 $h = imagesy($this->image);
352                 $flipped = imagecreate($w, $h);
353                 if ($horiz) {
354                         for ($x = 0; $x < $w; $x++) {
355                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
356                         }
357                 }
358                 if ($vert) {
359                         for ($y = 0; $y < $h; $y++) {
360                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
361                         }
362                 }
363                 $this->image = $flipped;
364         }
365
366         public function orient($filename) {
367                 if ($this->is_imagick()) {
368                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
369                         $orientation = $this->image->getImageOrientation();
370                         switch ($orientation) {
371                         case imagick::ORIENTATION_BOTTOMRIGHT:
372                                 $this->image->rotateimage("#000", 180);
373                                 break;
374                         case imagick::ORIENTATION_RIGHTTOP:
375                                 $this->image->rotateimage("#000", 90);
376                                 break;
377                         case imagick::ORIENTATION_LEFTBOTTOM:
378                                 $this->image->rotateimage("#000", -90);
379                                 break;
380                         }
381
382                         $this->image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
383                         return true;
384                 }
385                 // based off comment on http://php.net/manual/en/function.imagerotate.php
386
387                 if (!$this->is_valid()) {
388                         return false;
389                 }
390
391                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
392                         return;
393                 }
394
395                 $exif = @exif_read_data($filename,null,true);
396                 if (!$exif) {
397                         return;
398                 }
399
400                 $ort = $exif['IFD0']['Orientation'];
401
402                 switch($ort)
403                 {
404                         case 1: // nothing
405                                 break;
406
407                         case 2: // horizontal flip
408                                 $this->flip();
409                                 break;
410
411                         case 3: // 180 rotate left
412                                 $this->rotate(180);
413                                 break;
414
415                         case 4: // vertical flip
416                                 $this->flip(false, true);
417                                 break;
418
419                         case 5: // vertical flip + 90 rotate right
420                                 $this->flip(false, true);
421                                 $this->rotate(-90);
422                                 break;
423
424                         case 6: // 90 rotate right
425                                 $this->rotate(-90);
426                                 break;
427
428                         case 7: // horizontal flip + 90 rotate right
429                                 $this->flip();
430                                 $this->rotate(-90);
431                                 break;
432
433                         case 8: // 90 rotate left
434                                 $this->rotate(90);
435                                 break;
436                 }
437
438                 //      logger('exif: ' . print_r($exif,true));
439                 return $exif;
440
441         }
442
443
444
445         public function scaleImageUp($min) {
446                 if (!$this->is_valid()) {
447                         return false;
448                 }
449
450
451                 $width = $this->getWidth();
452                 $height = $this->getHeight();
453
454                 $dest_width = $dest_height = 0;
455
456                 if ((!$width)|| (!$height)) {
457                         return false;
458                 }
459
460                 if ($width < $min && $height < $min) {
461                         if ($width > $height) {
462                                 $dest_width = $min;
463                                 $dest_height = intval(($height * $min) / $width);
464                         } else {
465                                 $dest_width = intval(($width * $min) / $height);
466                                 $dest_height = $min;
467                         }
468                 } else {
469                         if ($width < $min) {
470                                 $dest_width = $min;
471                                 $dest_height = intval(($height * $min) / $width);
472                         } else {
473                                 if ($height < $min) {
474                                         $dest_width = intval(($width * $min) / $height);
475                                         $dest_height = $min;
476                                 } else {
477                                         $dest_width = $width;
478                                         $dest_height = $height;
479                                 }
480                         }
481                 }
482
483                 if ($this->is_imagick()) {
484                         return $this->scaleImage($dest_width, $dest_height);
485                 }
486
487                 $dest = imagecreatetruecolor($dest_width, $dest_height);
488                 imagealphablending($dest, false);
489                 imagesavealpha($dest, true);
490                 if ($this->type=='image/png') {
491                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
492                 }
493                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
494                 if ($this->image) {
495                         imagedestroy($this->image);
496                 }
497                 $this->image = $dest;
498                 $this->width  = imagesx($this->image);
499                 $this->height = imagesy($this->image);
500         }
501
502
503
504         public function scaleImageSquare($dim) {
505                 if (!$this->is_valid()) {
506                         return false;
507                 }
508
509                 if ($this->is_imagick()) {
510                         $this->image->setFirstIterator();
511                         do {
512                                 $this->image->scaleImage($dim, $dim);
513                         } while ($this->image->nextImage());
514                         return;
515                 }
516
517                 $dest = imagecreatetruecolor($dim, $dim);
518                 imagealphablending($dest, false);
519                 imagesavealpha($dest, true);
520                 if ($this->type=='image/png') {
521                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
522                 }
523                 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
524                 if ($this->image) {
525                         imagedestroy($this->image);
526                 }
527                 $this->image = $dest;
528                 $this->width  = imagesx($this->image);
529                 $this->height = imagesy($this->image);
530         }
531
532
533         public function cropImage($max, $x, $y, $w, $h) {
534                 if (!$this->is_valid()) {
535                         return false;
536                 }
537
538                 if ($this->is_imagick()) {
539                         $this->image->setFirstIterator();
540                         do {
541                                 $this->image->cropImage($w, $h, $x, $y);
542                                 /*
543                                  * We need to remove the canva,
544                                  * or the image is not resized to the crop:
545                                  * http://php.net/manual/en/imagick.cropimage.php#97232
546                                  */
547                                 $this->image->setImagePage(0, 0, 0, 0);
548                         } while ($this->image->nextImage());
549                         return $this->scaleImage($max);
550                 }
551
552                 $dest = imagecreatetruecolor($max, $max);
553                 imagealphablending($dest, false);
554                 imagesavealpha($dest, true);
555                 if ($this->type=='image/png') {
556                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
557                 }
558                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
559                 if ($this->image) {
560                         imagedestroy($this->image);
561                 }
562                 $this->image = $dest;
563                 $this->width  = imagesx($this->image);
564                 $this->height = imagesy($this->image);
565         }
566
567         public function saveImage($path) {
568                 if (!$this->is_valid()) {
569                         return false;
570                 }
571
572                 $string = $this->imageString();
573
574                 $a = get_app();
575
576                 $stamp1 = microtime(true);
577                 file_put_contents($path, $string);
578                 $a->save_timestamp($stamp1, "file");
579         }
580
581         public function imageString() {
582                 if (!$this->is_valid()) {
583                         return false;
584                 }
585
586                 if ($this->is_imagick()) {
587                         /* Clean it */
588                         $this->image = $this->image->deconstructImages();
589                         $string = $this->image->getImagesBlob();
590                         return $string;
591                 }
592
593                 $quality = false;
594
595                 ob_start();
596
597                 // Enable interlacing
598                 imageinterlace($this->image, true);
599
600                 switch($this->getType()){
601                         case "image/png":
602                                 $quality = get_config('system', 'png_quality');
603                                 if ((!$quality) || ($quality > 9)) {
604                                         $quality = PNG_QUALITY;
605                                 }
606                                 imagepng($this->image, null, $quality);
607                                 break;
608                         case "image/jpeg":
609                                 $quality = get_config('system', 'jpeg_quality');
610                                 if ((!$quality) || ($quality > 100)) {
611                                         $quality = JPEG_QUALITY;
612                                 }
613                                 imagejpeg($this->image, null, $quality);
614                 }
615                 $string = ob_get_contents();
616                 ob_end_clean();
617
618                 return $string;
619         }
620
621
622
623         public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
624
625                 $r = q("SELECT `guid` FROM `photo` WHERE `resource-id` = '%s' AND `guid` != '' LIMIT 1",
626                         dbesc($rid)
627                 );
628                 if (dbm::is_result($r)) {
629                         $guid = $r[0]['guid'];
630                 } else {
631                         $guid = get_guid();
632                 }
633
634                 $x = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d AND `contact-id` = %d AND `scale` = %d LIMIT 1",
635                         dbesc($rid),
636                         intval($uid),
637                         intval($cid),
638                         intval($scale)
639                 );
640                 if (dbm::is_result($x)) {
641                         $r = q("UPDATE `photo`
642                                 SET `uid` = %d,
643                                 `contact-id` = %d,
644                                 `guid` = '%s',
645                                 `resource-id` = '%s',
646                                 `created` = '%s',
647                                 `edited` = '%s',
648                                 `filename` = '%s',
649                                 `type` = '%s',
650                                 `album` = '%s',
651                                 `height` = %d,
652                                 `width` = %d,
653                                 `datasize` = %d,
654                                 `data` = '%s',
655                                 `scale` = %d,
656                                 `profile` = %d,
657                                 `allow_cid` = '%s',
658                                 `allow_gid` = '%s',
659                                 `deny_cid` = '%s',
660                                 `deny_gid` = '%s'
661                                 WHERE `id` = %d",
662
663                                 intval($uid),
664                                 intval($cid),
665                                 dbesc($guid),
666                                 dbesc($rid),
667                                 dbesc(datetime_convert()),
668                                 dbesc(datetime_convert()),
669                                 dbesc(basename($filename)),
670                                 dbesc($this->getType()),
671                                 dbesc($album),
672                                 intval($this->getHeight()),
673                                 intval($this->getWidth()),
674                                 dbesc(strlen($this->imageString())),
675                                 dbesc($this->imageString()),
676                                 intval($scale),
677                                 intval($profile),
678                                 dbesc($allow_cid),
679                                 dbesc($allow_gid),
680                                 dbesc($deny_cid),
681                                 dbesc($deny_gid),
682                                 intval($x[0]['id'])
683                         );
684                 } else {
685                         $r = q("INSERT INTO `photo`
686                                 (`uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `datasize`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`)
687                                 VALUES (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s')",
688                                 intval($uid),
689                                 intval($cid),
690                                 dbesc($guid),
691                                 dbesc($rid),
692                                 dbesc(datetime_convert()),
693                                 dbesc(datetime_convert()),
694                                 dbesc(basename($filename)),
695                                 dbesc($this->getType()),
696                                 dbesc($album),
697                                 intval($this->getHeight()),
698                                 intval($this->getWidth()),
699                                 dbesc(strlen($this->imageString())),
700                                 dbesc($this->imageString()),
701                                 intval($scale),
702                                 intval($profile),
703                                 dbesc($allow_cid),
704                                 dbesc($allow_gid),
705                                 dbesc($deny_cid),
706                                 dbesc($deny_gid)
707                         );
708                 }
709
710                 return $r;
711         }
712 }
713
714
715 /**
716  * Guess image mimetype from filename or from Content-Type header
717  *
718  * @arg $filename string Image filename
719  * @arg $fromcurl boolean Check Content-Type header from curl request
720  */
721 function guess_image_type($filename, $fromcurl=false) {
722         logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
723         $type = null;
724         if ($fromcurl) {
725                 $a = get_app();
726                 $headers=array();
727                 $h = explode("\n",$a->get_curl_headers());
728                 foreach ($h as $l) {
729                         list($k,$v) = array_map("trim", explode(":", trim($l), 2));
730                         $headers[$k] = $v;
731                 }
732                 if (array_key_exists('Content-Type', $headers))
733                         $type = $headers['Content-Type'];
734         }
735         if (is_null($type)){
736                 // Guessing from extension? Isn't that... dangerous?
737                 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
738                         /**
739                          * Well, this not much better,
740                          * but at least it comes from the data inside the image,
741                          * we won't be tricked by a manipulated extension
742                          */
743                         $image = new Imagick($filename);
744                         $type = $image->getImageMimeType();
745                         $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
746                 } else {
747                         $ext = pathinfo($filename, PATHINFO_EXTENSION);
748                         $types = Photo::supportedTypes();
749                         $type = "image/jpeg";
750                         foreach ($types as $m => $e){
751                                 if ($ext == $e) {
752                                         $type = $m;
753                                 }
754                         }
755                 }
756         }
757         logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
758         return $type;
759
760 }
761
762 /**
763  * @brief Updates the avatar links in a contact only if needed
764  *
765  * @param string $avatar Link to avatar picture
766  * @param int $uid User id of contact owner
767  * @param int $cid Contact id
768  * @param bool $force force picture update
769  *
770  * @return array Returns array of the different avatar sizes
771  */
772 function update_contact_avatar($avatar, $uid, $cid, $force = false) {
773
774         $r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
775         if (!dbm::is_result($r)) {
776                 return false;
777         } else {
778                 $data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
779         }
780
781         if (($r[0]["avatar"] != $avatar) OR $force) {
782                 $photos = import_profile_photo($avatar, $uid, $cid, true);
783
784                 if ($photos) {
785                         q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
786                                 dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
787                                 dbesc(datetime_convert()), intval($cid));
788                         return $photos;
789                 }
790         }
791
792         return $data;
793 }
794
795 function import_profile_photo($photo, $uid, $cid, $quit_on_error = false) {
796
797         $a = get_app();
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 = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
845                 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
846                 $micro = $a->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 = $a->get_baseurl() . '/images/person-175.jpg';
857                 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
858                 $micro = $a->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($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" => $a->get_baseurl().'/photos/'.$page_owner_nick.'/image/'.$hash,
1048                         "full" => $a->get_baseurl()."/photo/{$hash}-0.".$ph->getExt());
1049
1050         if ($width > 800 || $height > 800) {
1051                 $image["large"] = $a->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"] = $a->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"] = $a->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"] = $a->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 }