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