]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
f74c68da583c770111212e125245be4c23bafaec
[friendica.git] / src / Model / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Core\Cache\Duration;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\Database\DBStructure;
29 use Friendica\DI;
30 use Friendica\Model\Storage\ExternalResource;
31 use Friendica\Model\Storage\ReferenceStorageException;
32 use Friendica\Model\Storage\StorageException;
33 use Friendica\Model\Storage\SystemResource;
34 use Friendica\Object\Image;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Images;
37 use Friendica\Security\Security;
38 use Friendica\Util\Proxy;
39 use Friendica\Util\Strings;
40
41 require_once "include/dba.php";
42
43 /**
44  * Class to handle photo dabatase table
45  */
46 class Photo
47 {
48         const CONTACT_PHOTOS = 'Contact Photos';
49
50         /**
51          * Select rows from the photo table and returns them as array
52          *
53          * @param array $fields     Array of selected fields, empty for all
54          * @param array $conditions Array of fields for conditions
55          * @param array $params     Array of several parameters
56          *
57          * @return boolean|array
58          *
59          * @throws \Exception
60          * @see   \Friendica\Database\DBA::selectToArray
61          */
62         public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
63         {
64                 if (empty($fields)) {
65                         $fields = self::getFields();
66                 }
67
68                 return DBA::selectToArray('photo', $fields, $conditions, $params);
69         }
70
71         /**
72          * Retrieve a single record from the photo table
73          *
74          * @param array $fields     Array of selected fields, empty for all
75          * @param array $conditions Array of fields for conditions
76          * @param array $params     Array of several parameters
77          *
78          * @return bool|array
79          *
80          * @throws \Exception
81          * @see   \Friendica\Database\DBA::select
82          */
83         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
84         {
85                 if (empty($fields)) {
86                         $fields = self::getFields();
87                 }
88
89                 return DBA::selectFirst("photo", $fields, $conditions, $params);
90         }
91
92         /**
93          * Get photos for user id
94          *
95          * @param integer $uid        User id
96          * @param string  $resourceid Rescource ID of the photo
97          * @param array   $conditions Array of fields for conditions
98          * @param array   $params     Array of several parameters
99          *
100          * @return bool|array
101          *
102          * @throws \Exception
103          * @see   \Friendica\Database\DBA::select
104          */
105         public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
106         {
107                 $conditions["resource-id"] = $resourceid;
108                 $conditions["uid"] = $uid;
109
110                 return self::selectToArray([], $conditions, $params);
111         }
112
113         /**
114          * Get a photo for user id
115          *
116          * @param integer $uid        User id
117          * @param string  $resourceid Rescource ID of the photo
118          * @param integer $scale      Scale of the photo. Defaults to 0
119          * @param array   $conditions Array of fields for conditions
120          * @param array   $params     Array of several parameters
121          *
122          * @return bool|array
123          *
124          * @throws \Exception
125          * @see   \Friendica\Database\DBA::select
126          */
127         public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
128         {
129                 $conditions["resource-id"] = $resourceid;
130                 $conditions["uid"] = $uid;
131                 $conditions["scale"] = $scale;
132
133                 return self::selectFirst([], $conditions, $params);
134         }
135
136         /**
137          * Get a single photo given resource id and scale
138          *
139          * This method checks for permissions. Returns associative array
140          * on success, "no sign" image info, if user has no permission,
141          * false if photo does not exists
142          *
143          * @param string  $resourceid Rescource ID of the photo
144          * @param integer $scale      Scale of the photo. Defaults to 0
145          *
146          * @return boolean|array
147          * @throws \Exception
148          */
149         public static function getPhoto(string $resourceid, int $scale = 0)
150         {
151                 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
152                 if (!DBA::isResult($r)) {
153                         return false;
154                 }
155
156                 $uid = $r["uid"];
157
158                 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
159
160                 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
161
162                 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
163                 $params = ["order" => ["scale" => true]];
164                 $photo = self::selectFirst([], $conditions, $params);
165
166                 return $photo;
167         }
168
169         /**
170          * Check if photo with given conditions exists
171          *
172          * @param array $conditions Array of extra conditions
173          *
174          * @return boolean
175          * @throws \Exception
176          */
177         public static function exists(array $conditions)
178         {
179                 return DBA::exists("photo", $conditions);
180         }
181
182
183         /**
184          * Get Image data for given row id. null if row id does not exist
185          *
186          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
187          *
188          * @return \Friendica\Object\Image|string
189          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190          * @throws \ImagickException
191          * @throws StorageException
192          */
193         public static function getImageDataForPhoto(array $photo)
194         {
195                 if (!empty($photo['data'])) {
196                         return $photo['data'];
197                 }
198
199                 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
200                 if (empty($backendClass)) {
201                         // legacy data storage in "data" column
202                         $i = self::selectFirst(['data'], ['id' => $photo['id']]);
203                         if ($i === false) {
204                                 return '';
205                         }
206                         $data = $i['data'];
207                 } else {
208                         $backendRef = $photo['backend-ref'] ?? '';
209                         try {
210                                 $data = $backendClass->get($backendRef);
211                         } catch (ReferenceStorageException $referenceStorageException) {
212                                 DI::logger()->debug('No data found for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
213                                 return '';
214                         }
215                 }
216                 return $data;
217         }
218
219         /**
220          * Get Image object for given row id. null if row id does not exist
221          *
222          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
223          *
224          * @return \Friendica\Object\Image
225          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
226          * @throws \ImagickException
227          */
228         public static function getImageForPhoto(array $photo)
229         {
230                 $data = self::getImageDataForPhoto($photo);
231                 if (empty($data)) {
232                         return null;
233                 }
234
235                 return new Image($data, $photo['type']);
236         }
237
238         /**
239          * Return a list of fields that are associated with the photo table
240          *
241          * @return array field list
242          * @throws \Exception
243          */
244         private static function getFields()
245         {
246                 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
247                 $fields = array_keys($allfields["photo"]["fields"]);
248                 array_splice($fields, array_search("data", $fields), 1);
249                 return $fields;
250         }
251
252         /**
253          * Construct a photo array for a system resource image
254          *
255          * @param string $filename Image file name relative to code root
256          * @param string $mimetype Image mime type. Is guessed by file name when empty.
257          *
258          * @return array
259          * @throws \Exception
260          */
261         public static function createPhotoForSystemResource($filename, $mimetype = '')
262         {
263                 if (empty($mimetype)) {
264                         $mimetype = Images::guessTypeByExtension($filename);
265                 }
266
267                 $fields = self::getFields();
268                 $values = array_fill(0, count($fields), "");
269
270                 $photo                  = array_combine($fields, $values);
271                 $photo['backend-class'] = SystemResource::NAME;
272                 $photo['backend-ref']   = $filename;
273                 $photo['type']          = $mimetype;
274                 $photo['cacheable']     = false;
275
276                 return $photo;
277         }
278
279         /**
280          * Construct a photo array for an external resource image
281          *
282          * @param string $url      Image URL
283          * @param int    $uid      User ID of the requesting person
284          * @param string $mimetype Image mime type. Is guessed by file name when empty.
285          *
286          * @return array
287          * @throws \Exception
288          */
289         public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = '')
290         {
291                 if (empty($mimetype)) {
292                         $mimetype = Images::guessTypeByExtension($url);
293                 }
294
295                 $fields = self::getFields();
296                 $values = array_fill(0, count($fields), "");
297
298                 $photo                  = array_combine($fields, $values);
299                 $photo['backend-class'] = ExternalResource::NAME;
300                 $photo['backend-ref']   = json_encode(['url' => $url, 'uid' => $uid]);
301                 $photo['type']          = $mimetype;
302                 $photo['cacheable']     = true;
303
304                 return $photo;
305         }
306
307         /**
308          * store photo metadata in db and binary in default backend
309          *
310          * @param Image   $Image     Image object with data
311          * @param integer $uid       User ID
312          * @param integer $cid       Contact ID
313          * @param integer $rid       Resource ID
314          * @param string  $filename  Filename
315          * @param string  $album     Album name
316          * @param integer $scale     Scale
317          * @param integer $profile   Is a profile image? optional, default = 0
318          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
319          * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
320          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
321          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ""
322          * @param string  $desc      Photo caption. optional, default = ""
323          *
324          * @return boolean True on success
325          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326          */
327         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
328         {
329                 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
330                 if (DBA::isResult($photo)) {
331                         $guid = $photo["guid"];
332                 } else {
333                         $guid = System::createGUID();
334                 }
335
336                 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
337                 $created = DateTimeFormat::utcNow();
338                 if (DBA::isResult($existing_photo)) {
339                         $created = $existing_photo["created"];
340                 }
341
342                 // Get defined storage backend.
343                 // if no storage backend, we use old "data" column in photo table.
344                 // if is an existing photo, reuse same backend
345                 $data = "";
346                 $backend_ref = "";
347
348                 if (DBA::isResult($existing_photo)) {
349                         $backend_ref = (string)$existing_photo["backend-ref"];
350                         $storage = DI::storageManager()->getSelectableStorageByName($existing_photo["backend-class"] ?? '');
351                 } else {
352                         $storage = DI::storage();
353                 }
354
355                 if (empty($storage)) {
356                         $data = $Image->asString();
357                 } else {
358                         $backend_ref = $storage->put($Image->asString(), $backend_ref);
359                 }
360
361                 $fields = [
362                         "uid" => $uid,
363                         "contact-id" => $cid,
364                         "guid" => $guid,
365                         "resource-id" => $rid,
366                         "hash" => md5($Image->asString()),
367                         "created" => $created,
368                         "edited" => DateTimeFormat::utcNow(),
369                         "filename" => basename($filename),
370                         "type" => $Image->getType(),
371                         "album" => $album,
372                         "height" => $Image->getHeight(),
373                         "width" => $Image->getWidth(),
374                         "datasize" => strlen($Image->asString()),
375                         "data" => $data,
376                         "scale" => $scale,
377                         "profile" => $profile,
378                         "allow_cid" => $allow_cid,
379                         "allow_gid" => $allow_gid,
380                         "deny_cid" => $deny_cid,
381                         "deny_gid" => $deny_gid,
382                         "desc" => $desc,
383                         "backend-class" => (string)$storage,
384                         "backend-ref" => $backend_ref
385                 ];
386
387                 if (DBA::isResult($existing_photo)) {
388                         $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
389                 } else {
390                         $r = DBA::insert("photo", $fields);
391                 }
392
393                 return $r;
394         }
395
396
397         /**
398          * Delete info from table and data from storage
399          *
400          * @param array $conditions Field condition(s)
401          * @param array $options    Options array, Optional
402          *
403          * @return boolean
404          *
405          * @throws \Exception
406          * @see   \Friendica\Database\DBA::delete
407          */
408         public static function delete(array $conditions, array $options = [])
409         {
410                 // get photo to delete data info
411                 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
412
413                 while ($photo = DBA::fetch($photos)) {
414                         $backend_class = DI::storageManager()->getSelectableStorageByName($photo['backend-class'] ?? '');
415                         if (!empty($backend_class)) {
416                                 try {
417                                         $backend_class->delete($item['backend-ref'] ?? '');
418                                         // Delete the photos after they had been deleted successfully
419                                         DBA::delete("photo", ['id' => $photo['id']]);
420                                 } catch (ReferenceStorageException $referenceStorageException) {
421                                         DI::logger()->debug('phot doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
422                                 }
423                         }
424                 }
425
426                 DBA::close($photos);
427
428                 return DBA::delete("photo", $conditions, $options);
429         }
430
431         /**
432          * Update a photo
433          *
434          * @param array         $fields     Contains the fields that are updated
435          * @param array         $conditions Condition array with the key values
436          * @param Image         $img        Image to update. Optional, default null.
437          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
438          *
439          * @return boolean  Was the update successfull?
440          *
441          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442          * @see   \Friendica\Database\DBA::update
443          */
444         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
445         {
446                 if (!is_null($img)) {
447                         // get photo to update
448                         $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
449
450                         foreach($photos as $photo) {
451                                 $backend_class = DI::storageManager()->getSelectableStorageByName($photo['backend-class'] ?? '');
452                                 if (!empty($backend_class)) {
453                                         $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
454                                 } else {
455                                         $fields["data"] = $img->asString();
456                                 }
457                         }
458                         $fields['updated'] = DateTimeFormat::utcNow();
459                 }
460
461                 $fields['edited'] = DateTimeFormat::utcNow();
462
463                 return DBA::update("photo", $fields, $conditions, $old_fields);
464         }
465
466         /**
467          * @param string  $image_url     Remote URL
468          * @param integer $uid           user id
469          * @param integer $cid           contact id
470          * @param boolean $quit_on_error optional, default false
471          * @return array
472          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
473          * @throws \ImagickException
474          */
475         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
476         {
477                 $thumb = "";
478                 $micro = "";
479
480                 $photo = DBA::selectFirst(
481                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => self::CONTACT_PHOTOS]
482                 );
483                 if (!empty($photo['resource-id'])) {
484                         $resource_id = $photo["resource-id"];
485                 } else {
486                         $resource_id = self::newResource();
487                 }
488
489                 $photo_failure = false;
490
491                 $filename = basename($image_url);
492                 if (!empty($image_url)) {
493                         $ret = DI::httpRequest()->get($image_url);
494                         $img_str = $ret->getBody();
495                         $type = $ret->getContentType();
496                 } else {
497                         $img_str = '';
498                 }
499
500                 if ($quit_on_error && ($img_str == "")) {
501                         return false;
502                 }
503
504                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
505
506                 $Image = new Image($img_str, $type);
507                 if ($Image->isValid()) {
508                         $Image->scaleToSquare(300);
509
510                         $filesize = strlen($Image->asString());
511                         $maximagesize = DI::config()->get('system', 'maximagesize');
512                         if (!empty($maximagesize) && ($filesize > $maximagesize)) {
513                                 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
514                                 if ($Image->getType() == 'image/gif') {
515                                         $Image->toStatic();
516                                         $Image = new Image($Image->asString(), 'image/png');
517
518                                         $filesize = strlen($Image->asString());
519                                         Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
520                                 }
521                                 if ($filesize > $maximagesize) {
522                                         foreach ([160, 80] as $pixels) {
523                                                 if ($filesize > $maximagesize) {
524                                                         Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
525                                                         $Image->scaleDown($pixels);
526                                                         $filesize = strlen($Image->asString());
527                                                 }
528                                         }
529                                 }
530                                 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
531                         }
532
533                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4);
534
535                         if ($r === false) {
536                                 $photo_failure = true;
537                         }
538
539                         $Image->scaleDown(80);
540
541                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5);
542
543                         if ($r === false) {
544                                 $photo_failure = true;
545                         }
546
547                         $Image->scaleDown(48);
548
549                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6);
550
551                         if ($r === false) {
552                                 $photo_failure = true;
553                         }
554
555                         $suffix = "?ts=" . time();
556
557                         $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
558                         $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
559                         $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
560
561                         // Remove the cached photo
562                         $a = DI::app();
563                         $basepath = $a->getBasePath();
564
565                         if (is_dir($basepath . "/photo")) {
566                                 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
567                                 if (file_exists($filename)) {
568                                         unlink($filename);
569                                 }
570                                 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
571                                 if (file_exists($filename)) {
572                                         unlink($filename);
573                                 }
574                                 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
575                                 if (file_exists($filename)) {
576                                         unlink($filename);
577                                 }
578                         }
579                 } else {
580                         $photo_failure = true;
581                 }
582
583                 if ($photo_failure && $quit_on_error) {
584                         return false;
585                 }
586
587                 if ($photo_failure) {
588                         $contact = Contact::getById($cid) ?: [];
589                         $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
590                         $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
591                         $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
592                 }
593
594                 return [$image_url, $thumb, $micro];
595         }
596
597         /**
598          * @param array $exifCoord coordinate
599          * @param string $hemi      hemi
600          * @return float
601          */
602         public static function getGps($exifCoord, $hemi)
603         {
604                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
605                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
606                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
607
608                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
609
610                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
611         }
612
613         /**
614          * @param string $coordPart coordPart
615          * @return float
616          */
617         private static function gps2Num($coordPart)
618         {
619                 $parts = explode("/", $coordPart);
620
621                 if (count($parts) <= 0) {
622                         return 0;
623                 }
624
625                 if (count($parts) == 1) {
626                         return $parts[0];
627                 }
628
629                 return floatval($parts[0]) / floatval($parts[1]);
630         }
631
632         /**
633          * Fetch the photo albums that are available for a viewer
634          *
635          * The query in this function is cost intensive, so it is cached.
636          *
637          * @param int  $uid    User id of the photos
638          * @param bool $update Update the cache
639          *
640          * @return array Returns array of the photo albums
641          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
642          */
643         public static function getAlbums($uid, $update = false)
644         {
645                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
646
647                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
648                 $albums = DI::cache()->get($key);
649                 if (is_null($albums) || $update) {
650                         if (!DI::config()->get("system", "no_count", false)) {
651                                 /// @todo This query needs to be renewed. It is really slow
652                                 // At this time we just store the data in the cache
653                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
654                                         FROM `photo`
655                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
656                                         GROUP BY `album` ORDER BY `created` DESC",
657                                         intval($uid),
658                                         DBA::escape(self::CONTACT_PHOTOS),
659                                         DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
660                                 );
661                         } else {
662                                 // This query doesn't do the count and is much faster
663                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
664                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
665                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
666                                         intval($uid),
667                                         DBA::escape(self::CONTACT_PHOTOS),
668                                         DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
669                                 );
670                         }
671                         DI::cache()->set($key, $albums, Duration::DAY);
672                 }
673                 return $albums;
674         }
675
676         /**
677          * @param int $uid User id of the photos
678          * @return void
679          * @throws \Exception
680          */
681         public static function clearAlbumCache($uid)
682         {
683                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
684                 DI::cache()->set($key, null, Duration::DAY);
685         }
686
687         /**
688          * Generate a unique photo ID.
689          *
690          * @return string
691          * @throws \Exception
692          */
693         public static function newResource()
694         {
695                 return System::createGUID(32, false);
696         }
697
698         /**
699          * Extracts the rid from a local photo URI
700          *
701          * @param string $image_uri The URI of the photo
702          * @return string The rid of the photo, or an empty string if the URI is not local
703          */
704         public static function ridFromURI(string $image_uri)
705         {
706                 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
707                         return '';
708                 }
709                 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
710                 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
711                 if (!strlen($image_uri)) {
712                         return '';
713                 }
714                 return $image_uri;
715         }
716
717         /**
718          * Changes photo permissions that had been embedded in a post
719          *
720          * @todo This function currently does have some flaws:
721          * - Sharing a post with a forum will create a photo that only the forum can see.
722          * - Sharing a photo again that been shared non public before doesn't alter the permissions.
723          *
724          * @return string
725          * @throws \Exception
726          */
727         public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
728         {
729                 // Simplify image codes
730                 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
731                 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
732
733                 // Search for images
734                 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
735                         return false;
736                 }
737                 $images = $match[1];
738                 if (empty($images)) {
739                         return false;
740                 }
741
742                 foreach ($images as $image) {
743                         $image_rid = self::ridFromURI($image);
744                         if (empty($image_rid)) {
745                                 continue;
746                         }
747
748                         // Ensure to only modify photos that you own
749                         $srch = '<' . intval($original_contact_id) . '>';
750
751                         $condition = [
752                                 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
753                                 'resource-id' => $image_rid, 'uid' => $uid
754                         ];
755                         if (!Photo::exists($condition)) {
756                                 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
757                                 if (!DBA::isResult($photo)) {
758                                         Logger::info('Image not found', ['resource-id' => $image_rid]);
759                                 } else {
760                                         Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
761                                 }
762                                 continue;
763                         }
764
765                         /**
766                          * @todo Existing permissions need to be mixed with the new ones.
767                          * Otherwise this creates problems with sharing the same picture multiple times
768                          * Also check if $str_contact_allow does contain a public forum.
769                          * Then set the permissions to public.
770                          */
771
772                         self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
773                 }
774
775                 return true;
776         }
777
778         /**
779          * Add permissions to photo ressource
780          * @todo mix with previous photo permissions
781          * 
782          * @param string $image_rid
783          * @param integer $uid
784          * @param string $str_contact_allow
785          * @param string $str_group_allow
786          * @param string $str_contact_deny
787          * @param string $str_group_deny
788          * @return void
789          */
790         public static function setPermissionForRessource(string $image_rid, int $uid, string $str_contact_allow, string $str_group_allow, string $str_contact_deny, string $str_group_deny)
791         {
792                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
793                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
794                 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
795
796                 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
797                 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
798                 Photo::update($fields, $condition);
799         }
800
801         /**
802          * Strips known picture extensions from picture links
803          *
804          * @param string $name Picture link
805          * @return string stripped picture link
806          * @throws \Exception
807          */
808         public static function stripExtension($name)
809         {
810                 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
811                 foreach (Images::supportedTypes() as $m => $e) {
812                         $name = str_replace("." . $e, "", $name);
813                 }
814                 return $name;
815         }
816
817         /**
818          * Fetch the guid and scale from picture links
819          *
820          * @param string $name Picture link
821          * @return array
822          */
823         public static function getResourceData(string $name):array
824         {
825                 $base = DI::baseUrl()->get();
826
827                 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
828
829                 if (parse_url($guid, PHP_URL_SCHEME)) {
830                         return [];
831                 }
832
833                 $guid = self::stripExtension($guid);
834                 if (substr($guid, -2, 1) != "-") {
835                         return [];
836                 }
837
838                 $scale = intval(substr($guid, -1, 1));
839                 if (!is_numeric($scale)) {
840                         return [];
841                 }
842
843                 $guid = substr($guid, 0, -2);
844                 return ['guid' => $guid, 'scale' => $scale];
845         }
846
847         /**
848          * Tests if the picture link points to a locally stored picture
849          *
850          * @param string $name Picture link
851          * @return boolean
852          * @throws \Exception
853          */
854         public static function isLocal($name)
855         {
856                 return (bool)self::getIdForName($name);
857         }
858
859         /**
860          * Return the id of a local photo
861          *
862          * @param string $name Picture link
863          * @return int
864          */
865         public static function getIdForName($name)
866         {
867                 $data = self::getResourceData($name);
868                 if (empty($data)) {
869                         return 0;
870                 }
871
872                 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
873                 if (!empty($photo['id'])) {
874                         return $photo['id'];
875                 }
876                 return 0;
877         }
878
879         /**
880          * Tests if the link points to a locally stored picture page
881          *
882          * @param string $name Page link
883          * @return boolean
884          * @throws \Exception
885          */
886         public static function isLocalPage($name)
887         {
888                 $base = DI::baseUrl()->get();
889
890                 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
891                 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
892                 if (empty($guid)) {
893                         return false;
894                 }
895
896                 return DBA::exists('photo', ['resource-id' => $guid]);
897         }
898
899         /**
900          * 
901          * @param int   $uid   User ID
902          * @param array $files uploaded file array
903          * @return array photo record
904          */
905         public static function upload(int $uid, array $files)
906         {
907                 Logger::info('starting new upload');
908
909                 $user = User::getOwnerDataById($uid);
910                 if (empty($user)) {
911                         Logger::notice('User not found', ['uid' => $uid]);
912                         return [];
913                 }
914
915                 if (empty($files)) {
916                         Logger::notice('Empty upload file');
917                         return [];
918                 }
919
920                 if (!empty($files['tmp_name'])) {
921                         if (is_array($files['tmp_name'])) {
922                                 $src = $files['tmp_name'][0];
923                         } else {
924                                 $src = $files['tmp_name'];
925                         }
926                 } else {
927                         $src = '';
928                 }
929
930                 if (!empty($files['name'])) {
931                         if (is_array($files['name'])) {
932                                 $filename = basename($files['name'][0]);
933                         } else {
934                                 $filename = basename($files['name']);
935                         }
936                 } else {
937                         $filename = '';
938                 }
939
940                 if (!empty($files['size'])) {
941                         if (is_array($files['size'])) {
942                                 $filesize = intval($files['size'][0]);
943                         } else {
944                                 $filesize = intval($files['size']);
945                         }
946                 } else {
947                         $filesize = 0;
948                 }
949
950                 if (!empty($files['type'])) {
951                         if (is_array($files['type'])) {
952                                 $filetype = $files['type'][0];
953                         } else {
954                                 $filetype = $files['type'];
955                         }
956                 } else {
957                         $filetype = '';
958                 }
959
960                 if (empty($src)) {
961                         Logger::notice('No source file name', ['uid' => $uid, 'files' => $files]);
962                         return [];
963                 }
964
965                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
966
967                 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
968
969                 $imagedata = @file_get_contents($src);
970                 $Image = new Image($imagedata, $filetype);
971                 if (!$Image->isValid()) {
972                         Logger::notice('Image is unvalid', ['uid' => $uid, 'files' => $files]);
973                         return [];
974                 }
975
976                 $Image->orient($src);
977                 @unlink($src);
978
979                 $max_length = DI::config()->get('system', 'max_image_length');
980                 if (!$max_length) {
981                         $max_length = MAX_IMAGE_LENGTH;
982                 }
983                 if ($max_length > 0) {
984                         $Image->scaleDown($max_length);
985                         $filesize = strlen($Image->asString());
986                         Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
987                 }
988
989                 $width = $Image->getWidth();
990                 $height = $Image->getHeight();
991
992                 $maximagesize = DI::config()->get('system', 'maximagesize');
993
994                 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
995                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
996                         foreach ([5120, 2560, 1280, 640] as $pixels) {
997                                 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
998                                         Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
999                                         $Image->scaleDown($pixels);
1000                                         $filesize = strlen($Image->asString());
1001                                         $width = $Image->getWidth();
1002                                         $height = $Image->getHeight();
1003                                 }
1004                         }
1005                         if ($filesize > $maximagesize) {
1006                                 @unlink($src);
1007                                 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1008                                 return [];
1009                         }
1010                 }
1011
1012                 $resource_id = Photo::newResource();
1013                 $album       = DI::l10n()->t('Wall Photos');
1014                 $defperm     = '<' . $user['id'] . '>';
1015
1016                 $smallest = 0;
1017
1018                 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, 0, $defperm);
1019                 if (!$r) {
1020                         Logger::notice('Photo could not be stored');
1021                         return [];
1022                 }
1023
1024                 if ($width > 640 || $height > 640) {
1025                         $Image->scaleDown(640);
1026                         $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, 0, $defperm);
1027                         if ($r) {
1028                                 $smallest = 1;
1029                         }
1030                 }
1031
1032                 if ($width > 320 || $height > 320) {
1033                         $Image->scaleDown(320);
1034                         $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, 0, $defperm);
1035                         if ($r && ($smallest == 0)) {
1036                                 $smallest = 2;
1037                         }
1038                 }
1039
1040                 $condition = ['resource-id' => $resource_id];
1041                 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1042                 if (empty($photo)) {
1043                         Logger::notice('Photo not found', ['condition' => $condition]);
1044                         return [];
1045                 }
1046
1047                 $picture = [];
1048
1049                 $picture['id']        = $photo['id'];
1050                 $picture['size']      = $photo['datasize'];
1051                 $picture['width']     = $photo['width'];
1052                 $picture['height']    = $photo['height'];
1053                 $picture['type']      = $photo['type'];
1054                 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1055                 $picture['picture']   = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
1056                 $picture['preview']   = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
1057
1058                 Logger::info('upload done', ['picture' => $picture]);
1059                 return $picture;
1060         }
1061 }