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