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