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