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