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