]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Issue 13221: Diaspora posts are now stored correctly
[friendica.git] / src / Model / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
233                                         min(`scale`) AS `hiq`, max(`scale`) AS `loq`, ANY_VALUE(`desc`) AS `desc`, ANY_VALUE(`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, 'callstack' => System::callstack(20)]);
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->getBody();
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`, ANY_VALUE(`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 DISTINCT(`album`), '' AS `total`
766                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
767                                         WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
768                                         $uid,
769                                         self::DEFAULT,
770                                         $banner_type,
771                                         $avatar_type
772                                 ));
773                         }
774                         DI::cache()->set($key, $albums, Duration::DAY);
775                 }
776                 return $albums;
777         }
778
779         /**
780          * @param int $uid User id of the photos
781          * @return void
782          * @throws \Exception
783          */
784         public static function clearAlbumCache(int $uid)
785         {
786                 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
787                 DI::cache()->set($key, null, Duration::DAY);
788         }
789
790         /**
791          * Generate a unique photo ID.
792          *
793          * @return string Resource GUID
794          * @throws \Exception
795          */
796         public static function newResource(): string
797         {
798                 return System::createGUID(32, false);
799         }
800
801         /**
802          * Extracts the rid from a local photo URI
803          *
804          * @param string $image_uri The URI of the photo
805          * @return string The rid of the photo, or an empty string if the URI is not local
806          */
807         public static function ridFromURI(string $image_uri): string
808         {
809                 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
810                         return '';
811                 }
812                 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
813                 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
814                 return trim($image_uri);
815         }
816
817         /**
818          * Checks if the given URL is a local photo.
819          * Since it is meant for time critical occasions, the check is done without any database requests.
820          *
821          * @param string $url
822          * @return boolean
823          */
824         public static function isPhotoURI(string $url): bool
825         {
826                 return !empty(self::ridFromURI($url));
827         }
828
829         /**
830          * Changes photo permissions that had been embedded in a post
831          *
832          * @todo This function currently does have some flaws:
833          * - Sharing a post with a group will create a photo that only the group can see.
834          * - Sharing a photo again that been shared non public before doesn't alter the permissions.
835          *
836          * @return string
837          * @throws \Exception
838          */
839         public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_circle_allow, $str_contact_deny, $str_circle_deny)
840         {
841                 // Simplify image codes
842                 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
843                 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
844
845                 // Search for images
846                 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
847                         return false;
848                 }
849                 $images = $match[1];
850                 if (empty($images)) {
851                         return false;
852                 }
853
854                 foreach ($images as $image) {
855                         $image_rid = self::ridFromURI($image);
856                         if (empty($image_rid)) {
857                                 continue;
858                         }
859
860                         // Ensure to only modify photos that you own
861                         $srch = '<' . intval($original_contact_id) . '>';
862
863                         $condition = [
864                                 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
865                                 'resource-id' => $image_rid, 'uid' => $uid
866                         ];
867                         if (!self::exists($condition)) {
868                                 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
869                                 if (!DBA::isResult($photo)) {
870                                         Logger::info('Image not found', ['resource-id' => $image_rid]);
871                                 } else {
872                                         Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
873                                 }
874                                 continue;
875                         }
876
877                         /**
878                          * @todo Existing permissions need to be mixed with the new ones.
879                          * Otherwise this creates problems with sharing the same picture multiple times
880                          * Also check if $str_contact_allow does contain a public group.
881                          * Then set the permissions to public.
882                          */
883
884                         self::setPermissionForResource($image_rid, $uid, $str_contact_allow, $str_circle_allow, $str_contact_deny, $str_circle_deny);
885                 }
886
887                 return true;
888         }
889
890         /**
891          * Add permissions to photo resource
892          * @todo mix with previous photo permissions
893          *
894          * @param string $image_rid
895          * @param integer $uid
896          * @param string $str_contact_allow
897          * @param string $str_circle_allow
898          * @param string $str_contact_deny
899          * @param string $str_circle_deny
900          * @return void
901          */
902         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)
903         {
904                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_circle_allow,
905                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_circle_deny,
906                 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
907
908                 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
909                 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
910                 self::update($fields, $condition);
911         }
912
913         /**
914          * Fetch the guid and scale from picture links
915          *
916          * @param string $name Picture link
917          * @return array
918          */
919         public static function getResourceData(string $name): array
920         {
921                 $guid = str_replace([Strings::normaliseLink((string)DI::baseUrl()), '/photo/'], '', Strings::normaliseLink($name));
922
923                 if (parse_url($guid, PHP_URL_SCHEME)) {
924                         return [];
925                 }
926
927                 $guid = pathinfo($guid, PATHINFO_FILENAME);
928                 if (substr($guid, -2, 1) != "-") {
929                         return [];
930                 }
931
932                 $scale = intval(substr($guid, -1, 1));
933                 if (!is_numeric($scale)) {
934                         return [];
935                 }
936
937                 $guid = substr($guid, 0, -2);
938                 return ['guid' => $guid, 'scale' => $scale];
939         }
940
941         /**
942          * Tests if the picture link points to a locally stored picture
943          *
944          * @param string $name Picture link
945          * @return boolean
946          * @throws \Exception
947          */
948         public static function isLocal(string $name): bool
949         {
950                 // @TODO Maybe a proper check here on true condition?
951                 return (bool)self::getIdForName($name);
952         }
953
954         /**
955          * Return the id of a local photo
956          *
957          * @param string $name Picture link
958          * @return int
959          */
960         public static function getIdForName(string $name): int
961         {
962                 $data = self::getResourceData($name);
963                 if (empty($data)) {
964                         return 0;
965                 }
966
967                 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
968                 if (!empty($photo['id'])) {
969                         return $photo['id'];
970                 }
971                 return 0;
972         }
973
974         /**
975          * Tests if the link points to a locally stored picture page
976          *
977          * @param string $name Page link
978          * @return boolean
979          * @throws \Exception
980          */
981         public static function isLocalPage(string $name): bool
982         {
983                 $guid = str_replace(Strings::normaliseLink((string)DI::baseUrl()), '', Strings::normaliseLink($name));
984                 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
985                 if (empty($guid)) {
986                         return false;
987                 }
988
989                 return DBA::exists('photo', ['resource-id' => $guid]);
990         }
991
992         /**
993          * Tries to resize image to wanted maximum size
994          *
995          * @param Image $image Image instance
996          * @return Image|null Image instance on success, null on error
997          */
998         private static function fitImageSize(Image $image)
999         {
1000                 $max_length = DI::config()->get('system', 'max_image_length');
1001                 if ($max_length > 0) {
1002                         $image->scaleDown($max_length);
1003                         Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
1004                 }
1005
1006                 $filesize = strlen($image->asString());
1007                 $width    = $image->getWidth();
1008                 $height   = $image->getHeight();
1009
1010                 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
1011
1012                 if ($maximagesize && ($filesize > $maximagesize)) {
1013                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
1014                         foreach ([5120, 2560, 1280, 640] as $pixels) {
1015                                 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
1016                                         Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1017                                         $image->scaleDown($pixels);
1018                                         $filesize = strlen($image->asString());
1019                                         $width = $image->getWidth();
1020                                         $height = $image->getHeight();
1021                                 }
1022                         }
1023                         if ($filesize > $maximagesize) {
1024                                 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1025                                 return null;
1026                         }
1027                 }
1028
1029                 return $image;
1030         }
1031
1032         /**
1033          * Fetches image from URL and returns an array with instance and local file name
1034          *
1035          * @param string $image_url URL to image
1036          * @return array With: 'image' and 'filename' fields or empty array on error
1037          */
1038         private static function loadImageFromURL(string $image_url): array
1039         {
1040                 $filename = basename($image_url);
1041                 if (!empty($image_url)) {
1042                         $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
1043                         Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
1044                         $img_str = $ret->getBody();
1045                         $type = $ret->getContentType();
1046                 } else {
1047                         $img_str = '';
1048                         $type = '';
1049                 }
1050
1051                 if (empty($img_str)) {
1052                         Logger::notice('Empty content');
1053                         return [];
1054                 }
1055
1056                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1057
1058                 $image = new Image($img_str, $type);
1059
1060                 $image = self::fitImageSize($image);
1061                 if (empty($image)) {
1062                         return [];
1063                 }
1064
1065                 return ['image' => $image, 'filename' => $filename];
1066         }
1067
1068         /**
1069          * Inserts uploaded image into database and removes local temporary file
1070          *
1071          * @param array $files File array
1072          * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1073          */
1074         private static function uploadImage(array $files): array
1075         {
1076                 Logger::info('starting new upload');
1077
1078                 if (empty($files)) {
1079                         Logger::notice('Empty upload file');
1080                         return [];
1081                 }
1082
1083                 if (!empty($files['tmp_name'])) {
1084                         if (is_array($files['tmp_name'])) {
1085                                 $src = $files['tmp_name'][0];
1086                         } else {
1087                                 $src = $files['tmp_name'];
1088                         }
1089                 } else {
1090                         $src = '';
1091                 }
1092
1093                 if (!empty($files['name'])) {
1094                         if (is_array($files['name'])) {
1095                                 $filename = basename($files['name'][0]);
1096                         } else {
1097                                 $filename = basename($files['name']);
1098                         }
1099                 } else {
1100                         $filename = '';
1101                 }
1102
1103                 if (!empty($files['size'])) {
1104                         if (is_array($files['size'])) {
1105                                 $filesize = intval($files['size'][0]);
1106                         } else {
1107                                 $filesize = intval($files['size']);
1108                         }
1109                 } else {
1110                         $filesize = 0;
1111                 }
1112
1113                 if (!empty($files['type'])) {
1114                         if (is_array($files['type'])) {
1115                                 $filetype = $files['type'][0];
1116                         } else {
1117                                 $filetype = $files['type'];
1118                         }
1119                 } else {
1120                         $filetype = '';
1121                 }
1122
1123                 if (empty($src)) {
1124                         Logger::notice('No source file name', ['files' => $files]);
1125                         return [];
1126                 }
1127
1128                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1129
1130                 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1131
1132                 $imagedata = @file_get_contents($src);
1133                 $image = new Image($imagedata, $filetype);
1134                 if (!$image->isValid()) {
1135                         Logger::notice('Image is unvalid', ['files' => $files]);
1136                         return [];
1137                 }
1138
1139                 $image->orient($src);
1140                 @unlink($src);
1141
1142                 $image = self::fitImageSize($image);
1143                 if (empty($image)) {
1144                         return [];
1145                 }
1146
1147                 return ['image' => $image, 'filename' => $filename, 'size' => $filesize];
1148         }
1149
1150         /**
1151          * Handles uploaded image and assigns it to given user id
1152          *
1153          * @param int         $uid   User ID
1154          * @param array       $files uploaded file array
1155          * @param string      $album Album name (optional)
1156          * @param string|null $allow_cid
1157          * @param string|null $allow_gid
1158          * @param string      $deny_cid
1159          * @param string      $deny_gid
1160          * @param string      $desc Description (optional)
1161          * @param string      $resource_id GUID (optional)
1162          * @return array photo record or empty array on error
1163          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164          */
1165         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
1166         {
1167                 $user = User::getOwnerDataById($uid);
1168                 if (empty($user)) {
1169                         Logger::notice('User not found', ['uid' => $uid]);
1170                         return [];
1171                 }
1172
1173                 $data = self::uploadImage($files);
1174                 if (empty($data)) {
1175                         Logger::info('upload failed');
1176                         return [];
1177                 }
1178
1179                 $image    = $data['image'];
1180                 $filename = $data['filename'];
1181                 $filesize = $data['size'];
1182
1183                 $resource_id = $resource_id ?: self::newResource();
1184                 $album       = $album ?: DI::l10n()->t('Wall Photos');
1185
1186                 if (is_null($allow_cid) && is_null($allow_gid)) {
1187                         $allow_cid = '<' . $user['id'] . '>';
1188                         $allow_gid = '';
1189                 }
1190
1191                 $preview = self::storeWithPreview($image, $user['uid'], $resource_id, $filename, $filesize, $album, $desc, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
1192                 if ($preview < 0) {
1193                         Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1194                         return [];
1195                 }
1196
1197                 $condition = ['resource-id' => $resource_id];
1198                 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1199                 if (empty($photo)) {
1200                         Logger::notice('Photo not found', ['condition' => $condition]);
1201                         return [];
1202                 }
1203
1204                 $picture = [];
1205
1206                 $picture['id']          = $photo['id'];
1207                 $picture['resource_id'] = $resource_id;
1208                 $picture['size']        = $photo['datasize'];
1209                 $picture['width']       = $photo['width'];
1210                 $picture['height']      = $photo['height'];
1211                 $picture['type']        = $photo['type'];
1212                 $picture['albumpage']   = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1213                 $picture['picture']     = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1214                 $picture['preview']     = DI::baseUrl() . '/photo/' . $resource_id . '-' . $preview . '.' . $image->getExt();
1215
1216                 Logger::info('upload done', ['picture' => $picture]);
1217                 return $picture;
1218         }
1219
1220         /**
1221          * store photo metadata in db and binary with preview photos in default backend
1222          *
1223          * @param Image   $image       Image object with data
1224          * @param integer $uid         User ID
1225          * @param string  $resource_id Resource ID
1226          * @param string  $filename    Filename
1227          * @param integer $filesize    Filesize
1228          * @param string  $album       Album name
1229          * @param string  $description Photo caption
1230          * @param string  $allow_cid   Permissions, allowed contacts
1231          * @param string  $allow_gid   Permissions, allowed circles
1232          * @param string  $deny_cid    Permissions, denied contacts
1233          * @param string  $deny_gid    Permissions, denied circles
1234          *
1235          * @return integer preview photo size
1236          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1237          */
1238         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
1239         {
1240                 if ($filesize == 0) {
1241                         $filesize = strlen($image->asString());
1242                 }
1243
1244                 $width  = $image->getWidth();
1245                 $height = $image->getHeight();
1246
1247                 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
1248
1249                 if ($maximagesize && $filesize > $maximagesize) {
1250                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
1251                         foreach ([5120, 2560, 1280, 640, 320] as $pixels) {
1252                                 if ($filesize > $maximagesize && max($width, $height) > $pixels) {
1253                                         DI::logger()->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1254                                         $image->scaleDown($pixels);
1255                                         $filesize = strlen($image->asString());
1256                                         $width    = $image->getWidth();
1257                                         $height   = $image->getHeight();
1258                                 }
1259                         }
1260
1261                         if ($filesize > $maximagesize) {
1262                                 DI::logger()->notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1263                                 return -1;
1264                         }
1265                 }
1266
1267                 $width   = $image->getWidth();
1268                 $height  = $image->getHeight();
1269                 $preview = 0;
1270
1271                 $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
1272                 if (!$result) {
1273                         Logger::warning('Photo could not be stored', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1274                         return -1;
1275                 }
1276
1277                 if ($width > 640 || $height > 640) {
1278                         $image->scaleDown(640);
1279                 }
1280
1281                 if ($width > 320 || $height > 320) {
1282                         $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
1283                         if ($result) {
1284                                 $preview = 1;
1285                         }
1286                         $image->scaleDown(320);
1287                         $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
1288                         if ($result && ($preview == 0)) {
1289                                 $preview = 2;
1290                         }
1291                 }
1292                 return $preview;
1293         }
1294
1295         /**
1296          * Upload a user avatar
1297          *
1298          * @param int    $uid   User ID
1299          * @param array  $files uploaded file array
1300          * @param string $url   External image url
1301          * @return string avatar resource
1302          */
1303         public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1304         {
1305                 if (!empty($files)) {
1306                         $data = self::uploadImage($files);
1307                         if (empty($data)) {
1308                                 Logger::info('upload failed');
1309                                 return '';
1310                         }
1311                 } elseif (!empty($url)) {
1312                         $data = self::loadImageFromURL($url);
1313                         if (empty($data)) {
1314                                 Logger::info('loading from external url failed');
1315                                 return '';
1316                         }
1317                 } else {
1318                         Logger::info('Neither files nor url provided');
1319                         return '';
1320                 }
1321
1322                 $image    = $data['image'];
1323                 $filename = $data['filename'];
1324                 $width    = $image->getWidth();
1325                 $height   = $image->getHeight();
1326
1327                 $resource_id = self::newResource();
1328                 $album       = DI::l10n()->t(self::PROFILE_PHOTOS);
1329
1330                 // upload profile image (scales 4, 5, 6)
1331                 logger::info('starting new profile image upload');
1332
1333                 if ($width > 300 || $height > 300) {
1334                         $image->scaleDown(300);
1335                 }
1336
1337                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1338                 if (!$r) {
1339                         logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1340                 }
1341
1342                 if ($width > 80 || $height > 80) {
1343                         $image->scaleDown(80);
1344                 }
1345
1346                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1347                 if (!$r) {
1348                         logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1349                 }
1350
1351                 if ($width > 48 || $height > 48) {
1352                         $image->scaleDown(48);
1353                 }
1354
1355                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1356                 if (!$r) {
1357                         logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1358                 }
1359
1360                 logger::info('new profile image upload ended');
1361
1362                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1363                 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1364
1365                 Contact::updateSelfFromUserID($uid, true);
1366
1367                 // Update global directory in background
1368                 Profile::publishUpdate($uid);
1369
1370                 return $resource_id;
1371         }
1372
1373         /**
1374          * Upload a user banner
1375          *
1376          * @param int    $uid   User ID
1377          * @param array  $files uploaded file array
1378          * @param string $url   External image url
1379          * @return string avatar resource
1380          */
1381         public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1382         {
1383                 if (!empty($files)) {
1384                         $data = self::uploadImage($files);
1385                         if (empty($data)) {
1386                                 Logger::info('upload failed');
1387                                 return '';
1388                         }
1389                 } elseif (!empty($url)) {
1390                         $data = self::loadImageFromURL($url);
1391                         if (empty($data)) {
1392                                 Logger::info('loading from external url failed');
1393                                 return '';
1394                         }
1395                 } else {
1396                         Logger::info('Neither files nor url provided');
1397                         return '';
1398                 }
1399
1400                 $image    = $data['image'];
1401                 $filename = $data['filename'];
1402                 $width    = $image->getWidth();
1403                 $height   = $image->getHeight();
1404
1405                 $resource_id = self::newResource();
1406                 $album       = DI::l10n()->t(self::BANNER_PHOTOS);
1407
1408                 if ($width > 960) {
1409                         $image->scaleDown(960);
1410                 }
1411
1412                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1413                 if (!$r) {
1414                         logger::warning('profile banner upload with scale 3 (960) failed');
1415                 }
1416
1417                 logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
1418
1419                 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1420                 self::update(['photo-type' => self::DEFAULT], $condition);
1421
1422                 Contact::updateSelfFromUserID($uid, true);
1423
1424                 // Update global directory in background
1425                 Profile::publishUpdate($uid);
1426
1427                 return $resource_id;
1428         }
1429 }