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