]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Merge pull request #12589 from MrPetovan/bug/warnings
[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\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 given image data string
318          *
319          * @param string $image_data Image data
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 createPhotoForImageData(string $image_data, string $mimetype = ''): array
326         {
327                 $fields = self::getFields();
328                 $values = array_fill(0, count($fields), '');
329
330                 $photo                  = array_combine($fields, $values);
331                 $photo['data']          = $image_data;
332                 $photo['type']          = $mimetype ?: Images::getMimeTypeByData($image_data);
333                 $photo['cacheable']     = false;
334
335                 return $photo;
336         }
337
338         /**
339          * Construct a photo array for a system resource image
340          *
341          * @param string $filename Image file name relative to code root
342          * @param string $mimetype Image mime type. Is guessed by file name when empty.
343          *
344          * @return array
345          * @throws \Exception
346          */
347         public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
348         {
349                 if (empty($mimetype)) {
350                         $mimetype = Images::guessTypeByExtension($filename);
351                 }
352
353                 $fields = self::getFields();
354                 $values = array_fill(0, count($fields), '');
355
356                 $photo                  = array_combine($fields, $values);
357                 $photo['backend-class'] = SystemResource::NAME;
358                 $photo['backend-ref']   = $filename;
359                 $photo['type']          = $mimetype;
360                 $photo['cacheable']     = false;
361
362                 return $photo;
363         }
364
365         /**
366          * Construct a photo array for an external resource image
367          *
368          * @param string $url      Image URL
369          * @param int    $uid      User ID of the requesting person
370          * @param string $mimetype Image mime type. Is guessed by file name when empty.
371          * @param string $blurhash The blurhash that will be used to generate a picture when the original picture can't be fetched
372          * @param int    $width    Image width
373          * @param int    $height   Image height
374          *
375          * @return array
376          * @throws \Exception
377          */
378         public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = '', string $blurhash = null, int $width = null, int $height = null): array
379         {
380                 if (empty($mimetype)) {
381                         $mimetype = Images::guessTypeByExtension($url);
382                 }
383
384                 $fields = self::getFields();
385                 $values = array_fill(0, count($fields), '');
386
387                 $photo                  = array_combine($fields, $values);
388                 $photo['backend-class'] = ExternalResource::NAME;
389                 $photo['backend-ref']   = json_encode(['url' => $url, 'uid' => $uid]);
390                 $photo['type']          = $mimetype;
391                 $photo['cacheable']     = true;
392                 $photo['blurhash']      = $blurhash;
393                 $photo['width']         = $width;
394                 $photo['height']        = $height;
395
396                 return $photo;
397         }
398
399         /**
400          * store photo metadata in db and binary in default backend
401          *
402          * @param Image   $image     Image object with data
403          * @param integer $uid       User ID
404          * @param integer $cid       Contact ID
405          * @param string  $rid       Resource ID
406          * @param string  $filename  Filename
407          * @param string  $album     Album name
408          * @param integer $scale     Scale
409          * @param integer $type      Photo type, optional, default: Photo::DEFAULT
410          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
411          * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
412          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
413          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ""
414          * @param string  $desc      Photo caption. optional, default = ""
415          *
416          * @return boolean True on success
417          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418          */
419         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
420         {
421                 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
422                 if (DBA::isResult($photo)) {
423                         $guid = $photo['guid'];
424                 } else {
425                         $guid = System::createGUID();
426                 }
427
428                 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
429                 $created = DateTimeFormat::utcNow();
430                 if (DBA::isResult($existing_photo)) {
431                         $created = $existing_photo['created'];
432                 }
433
434                 // Get defined storage backend.
435                 // if no storage backend, we use old "data" column in photo table.
436                 // if is an existing photo, reuse same backend
437                 $data        = '';
438                 $backend_ref = '';
439                 $storage     = '';
440
441                 try {
442                         if (DBA::isResult($existing_photo)) {
443                                 $backend_ref = (string)$existing_photo['backend-ref'];
444                                 $storage     = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
445                         } else {
446                                 $storage = DI::storage();
447                         }
448                         $backend_ref = $storage->put($image->asString(), $backend_ref);
449                 } catch (InvalidClassStorageException $storageException) {
450                         $data = $image->asString();
451                 }
452
453                 $fields = [
454                         'uid' => $uid,
455                         'contact-id' => $cid,
456                         'guid' => $guid,
457                         'resource-id' => $rid,
458                         'hash' => md5($image->asString()),
459                         'created' => $created,
460                         'edited' => DateTimeFormat::utcNow(),
461                         'filename' => basename($filename),
462                         'type' => $image->getType(),
463                         'album' => $album,
464                         'height' => $image->getHeight(),
465                         'width' => $image->getWidth(),
466                         'datasize' => strlen($image->asString()),
467                         'blurhash' => $image->getBlurHash(),
468                         'data' => $data,
469                         'scale' => $scale,
470                         'photo-type' => $type,
471                         'profile' => false,
472                         'allow_cid' => $allow_cid,
473                         'allow_gid' => $allow_gid,
474                         'deny_cid' => $deny_cid,
475                         'deny_gid' => $deny_gid,
476                         'desc' => $desc,
477                         'backend-class' => (string)$storage,
478                         'backend-ref' => $backend_ref
479                 ];
480
481                 if (DBA::isResult($existing_photo)) {
482                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
483                 } else {
484                         $r = DBA::insert('photo', $fields);
485                 }
486
487                 return $r;
488         }
489
490
491         /**
492          * Delete info from table and data from storage
493          *
494          * @param array $conditions Field condition(s)
495          * @param array $options    Options array, Optional
496          *
497          * @return boolean
498          *
499          * @throws \Exception
500          * @see   \Friendica\Database\DBA::delete
501          */
502         public static function delete(array $conditions, array $options = []): bool
503         {
504                 // get photo to delete data info
505                 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
506
507                 while ($photo = DBA::fetch($photos)) {
508                         try {
509                                 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
510                                 $backend_class->delete($photo['backend-ref'] ?? '');
511                                 // Delete the photos after they had been deleted successfully
512                                 DBA::delete('photo', ['id' => $photo['id']]);
513                         } catch (InvalidClassStorageException $storageException) {
514                                 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
515                         } catch (ReferenceStorageException $referenceStorageException) {
516                                 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
517                         }
518                 }
519
520                 DBA::close($photos);
521
522                 return DBA::delete('photo', $conditions, $options);
523         }
524
525         /**
526          * Update a photo
527          *
528          * @param array $fields     Contains the fields that are updated
529          * @param array $conditions Condition array with the key values
530          * @param Image $image      Image to update. Optional, default null.
531          * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
532          *
533          * @return boolean  Was the update successfull?
534          *
535          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
536          * @see   \Friendica\Database\DBA::update
537          */
538         public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
539         {
540                 if (!is_null($image)) {
541                         // get photo to update
542                         $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
543
544                         foreach($photos as $photo) {
545                                 try {
546                                         $backend_class         = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
547                                         $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
548                                 } catch (InvalidClassStorageException $storageException) {
549                                         $fields['data'] = $image->asString();
550                                 }
551                         }
552                         $fields['updated'] = DateTimeFormat::utcNow();
553                 }
554
555                 $fields['edited'] = DateTimeFormat::utcNow();
556
557                 return DBA::update('photo', $fields, $conditions, $old_fields);
558         }
559
560         /**
561          * @param string  $image_url     Remote URL
562          * @param integer $uid           user id
563          * @param integer $cid           contact id
564          * @param boolean $quit_on_error optional, default false
565          * @return array|bool Array on success, false on error
566          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
567          * @throws \ImagickException
568          */
569         public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
570         {
571                 $thumb = '';
572                 $micro = '';
573
574                 $photo = DBA::selectFirst(
575                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
576                 );
577                 if (!empty($photo['resource-id'])) {
578                         $resource_id = $photo['resource-id'];
579                 } else {
580                         $resource_id = self::newResource();
581                 }
582
583                 $photo_failure = false;
584
585                 $filename = basename($image_url);
586                 if (!empty($image_url)) {
587                         $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
588                         Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
589                         $img_str = $ret->getBody();
590                         $type = $ret->getContentType();
591                 } else {
592                         $img_str = '';
593                         $type = '';
594                 }
595
596                 if ($quit_on_error && ($img_str == '')) {
597                         return false;
598                 }
599
600                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
601
602                 $image = new Image($img_str, $type);
603                 if ($image->isValid()) {
604                         $image->scaleToSquare(300);
605
606                         $filesize = strlen($image->asString());
607                         $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
608
609                         if ($maximagesize && ($filesize > $maximagesize)) {
610                                 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
611                                 if ($image->getType() == 'image/gif') {
612                                         $image->toStatic();
613                                         $image = new Image($image->asString(), 'image/png');
614
615                                         $filesize = strlen($image->asString());
616                                         Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
617                                 }
618                                 if ($filesize > $maximagesize) {
619                                         foreach ([160, 80] as $pixels) {
620                                                 if ($filesize > $maximagesize) {
621                                                         Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
622                                                         $image->scaleDown($pixels);
623                                                         $filesize = strlen($image->asString());
624                                                 }
625                                         }
626                                 }
627                                 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
628                         }
629
630                         $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
631
632                         if ($r === false) {
633                                 $photo_failure = true;
634                         }
635
636                         $image->scaleDown(80);
637
638                         $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
639
640                         if ($r === false) {
641                                 $photo_failure = true;
642                         }
643
644                         $image->scaleDown(48);
645
646                         $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
647
648                         if ($r === false) {
649                                 $photo_failure = true;
650                         }
651
652                         $suffix = '?ts=' . time();
653
654                         $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
655                         $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
656                         $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
657                 } else {
658                         $photo_failure = true;
659                 }
660
661                 if ($photo_failure && $quit_on_error) {
662                         return false;
663                 }
664
665                 if ($photo_failure) {
666                         $contact = Contact::getById($cid) ?: [];
667                         $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
668                         $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
669                         $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
670                 }
671
672                 $photo = DBA::selectFirst(
673                         'photo', ['blurhash'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
674                 );
675
676                 return [$image_url, $thumb, $micro, $photo['blurhash']];
677         }
678
679         /**
680          * Returns a float that represents the GPS coordinate from EXIF data
681          *
682          * @param array $exifCoord coordinate
683          * @param string $hemi      hemi
684          * @return float
685          */
686         public static function getGps(array $exifCoord, string $hemi): float
687         {
688                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
689                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
690                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
691
692                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
693
694                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
695         }
696
697         /**
698          * Change GPS to float number
699          *
700          * @param string $coordPart coordPart
701          * @return float
702          */
703         private static function gps2Num(string $coordPart): float
704         {
705                 $parts = explode('/', $coordPart);
706
707                 if (count($parts) <= 0) {
708                         return 0;
709                 }
710
711                 if (count($parts) == 1) {
712                         return (float)$parts[0];
713                 }
714
715                 return floatval($parts[0]) / floatval($parts[1]);
716         }
717
718         /**
719          * Fetch the photo albums that are available for a viewer
720          *
721          * The query in this function is cost intensive, so it is cached.
722          *
723          * @param int  $uid    User id of the photos
724          * @param bool $update Update the cache
725          *
726          * @return array Returns array of the photo albums
727          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
728          */
729         public static function getAlbums(int $uid, bool $update = false): array
730         {
731                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
732
733                 $avatar_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
734                 $banner_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_BANNER : self::DEFAULT;
735
736                 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
737                 $albums = DI::cache()->get($key);
738
739                 if (is_null($albums) || $update) {
740                         if (!DI::config()->get('system', 'no_count', false)) {
741                                 /// @todo This query needs to be renewed. It is really slow
742                                 // At this time we just store the data in the cache
743                                 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
744                                         FROM `photo`
745                                         WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
746                                         GROUP BY `album` ORDER BY `created` DESC",
747                                         $uid,
748                                         self::DEFAULT,
749                                         $banner_type,
750                                         $avatar_type
751                                 ));
752                         } else {
753                                 // This query doesn't do the count and is much faster
754                                 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
755                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
756                                         WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
757                                         $uid,
758                                         self::DEFAULT,
759                                         $banner_type,
760                                         $avatar_type
761                                 ));
762                         }
763                         DI::cache()->set($key, $albums, Duration::DAY);
764                 }
765                 return $albums;
766         }
767
768         /**
769          * @param int $uid User id of the photos
770          * @return void
771          * @throws \Exception
772          */
773         public static function clearAlbumCache(int $uid)
774         {
775                 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
776                 DI::cache()->set($key, null, Duration::DAY);
777         }
778
779         /**
780          * Generate a unique photo ID.
781          *
782          * @return string Resource GUID
783          * @throws \Exception
784          */
785         public static function newResource(): string
786         {
787                 return System::createGUID(32, false);
788         }
789
790         /**
791          * Extracts the rid from a local photo URI
792          *
793          * @param string $image_uri The URI of the photo
794          * @return string The rid of the photo, or an empty string if the URI is not local
795          */
796         public static function ridFromURI(string $image_uri): string
797         {
798                 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
799                         return '';
800                 }
801                 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
802                 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
803                 return trim($image_uri);
804         }
805
806         /**
807          * Checks if the given URL is a local photo.
808          * Since it is meant for time critical occasions, the check is done without any database requests.
809          *
810          * @param string $url
811          * @return boolean
812          */
813         public static function isPhotoURI(string $url): bool
814         {
815                 return !empty(self::ridFromURI($url));
816         }
817
818         /**
819          * Changes photo permissions that had been embedded in a post
820          *
821          * @todo This function currently does have some flaws:
822          * - Sharing a post with a forum will create a photo that only the forum can see.
823          * - Sharing a photo again that been shared non public before doesn't alter the permissions.
824          *
825          * @return string
826          * @throws \Exception
827          */
828         public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
829         {
830                 // Simplify image codes
831                 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
832                 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
833
834                 // Search for images
835                 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
836                         return false;
837                 }
838                 $images = $match[1];
839                 if (empty($images)) {
840                         return false;
841                 }
842
843                 foreach ($images as $image) {
844                         $image_rid = self::ridFromURI($image);
845                         if (empty($image_rid)) {
846                                 continue;
847                         }
848
849                         // Ensure to only modify photos that you own
850                         $srch = '<' . intval($original_contact_id) . '>';
851
852                         $condition = [
853                                 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
854                                 'resource-id' => $image_rid, 'uid' => $uid
855                         ];
856                         if (!self::exists($condition)) {
857                                 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
858                                 if (!DBA::isResult($photo)) {
859                                         Logger::info('Image not found', ['resource-id' => $image_rid]);
860                                 } else {
861                                         Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
862                                 }
863                                 continue;
864                         }
865
866                         /**
867                          * @todo Existing permissions need to be mixed with the new ones.
868                          * Otherwise this creates problems with sharing the same picture multiple times
869                          * Also check if $str_contact_allow does contain a public forum.
870                          * Then set the permissions to public.
871                          */
872
873                         self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
874                 }
875
876                 return true;
877         }
878
879         /**
880          * Add permissions to photo ressource
881          * @todo mix with previous photo permissions
882          *
883          * @param string $image_rid
884          * @param integer $uid
885          * @param string $str_contact_allow
886          * @param string $str_group_allow
887          * @param string $str_contact_deny
888          * @param string $str_group_deny
889          * @return void
890          */
891         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)
892         {
893                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
894                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
895                 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
896
897                 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
898                 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
899                 self::update($fields, $condition);
900         }
901
902         /**
903          * Fetch the guid and scale from picture links
904          *
905          * @param string $name Picture link
906          * @return array
907          */
908         public static function getResourceData(string $name): array
909         {
910                 $base = DI::baseUrl()->get();
911
912                 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
913
914                 if (parse_url($guid, PHP_URL_SCHEME)) {
915                         return [];
916                 }
917
918                 $guid = pathinfo($guid, PATHINFO_FILENAME);
919                 if (substr($guid, -2, 1) != "-") {
920                         return [];
921                 }
922
923                 $scale = intval(substr($guid, -1, 1));
924                 if (!is_numeric($scale)) {
925                         return [];
926                 }
927
928                 $guid = substr($guid, 0, -2);
929                 return ['guid' => $guid, 'scale' => $scale];
930         }
931
932         /**
933          * Tests if the picture link points to a locally stored picture
934          *
935          * @param string $name Picture link
936          * @return boolean
937          * @throws \Exception
938          */
939         public static function isLocal(string $name): bool
940         {
941                 // @TODO Maybe a proper check here on true condition?
942                 return (bool)self::getIdForName($name);
943         }
944
945         /**
946          * Return the id of a local photo
947          *
948          * @param string $name Picture link
949          * @return int
950          */
951         public static function getIdForName(string $name): int
952         {
953                 $data = self::getResourceData($name);
954                 if (empty($data)) {
955                         return 0;
956                 }
957
958                 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
959                 if (!empty($photo['id'])) {
960                         return $photo['id'];
961                 }
962                 return 0;
963         }
964
965         /**
966          * Tests if the link points to a locally stored picture page
967          *
968          * @param string $name Page link
969          * @return boolean
970          * @throws \Exception
971          */
972         public static function isLocalPage(string $name): bool
973         {
974                 $base = DI::baseUrl()->get();
975
976                 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
977                 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
978                 if (empty($guid)) {
979                         return false;
980                 }
981
982                 return DBA::exists('photo', ['resource-id' => $guid]);
983         }
984
985         /**
986          * Tries to resize image to wanted maximum size
987          *
988          * @param Image $image Image instance
989          * @return Image|null Image instance on success, null on error
990          */
991         private static function fitImageSize(Image $image)
992         {
993                 $max_length = DI::config()->get('system', 'max_image_length');
994                 if ($max_length > 0) {
995                         $image->scaleDown($max_length);
996                         Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
997                 }
998
999                 $filesize = strlen($image->asString());
1000                 $width    = $image->getWidth();
1001                 $height   = $image->getHeight();
1002
1003                 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
1004
1005                 if ($maximagesize && ($filesize > $maximagesize)) {
1006                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
1007                         foreach ([5120, 2560, 1280, 640] as $pixels) {
1008                                 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
1009                                         Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1010                                         $image->scaleDown($pixels);
1011                                         $filesize = strlen($image->asString());
1012                                         $width = $image->getWidth();
1013                                         $height = $image->getHeight();
1014                                 }
1015                         }
1016                         if ($filesize > $maximagesize) {
1017                                 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1018                                 return null;
1019                         }
1020                 }
1021
1022                 return $image;
1023         }
1024
1025         /**
1026          * Fetches image from URL and returns an array with instance and local file name
1027          *
1028          * @param string $image_url URL to image
1029          * @return array With: 'image' and 'filename' fields or empty array on error
1030          */
1031         private static function loadImageFromURL(string $image_url): array
1032         {
1033                 $filename = basename($image_url);
1034                 if (!empty($image_url)) {
1035                         $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
1036                         Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
1037                         $img_str = $ret->getBody();
1038                         $type = $ret->getContentType();
1039                 } else {
1040                         $img_str = '';
1041                         $type = '';
1042                 }
1043
1044                 if (empty($img_str)) {
1045                         Logger::notice('Empty content');
1046                         return [];
1047                 }
1048
1049                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1050
1051                 $image = new Image($img_str, $type);
1052
1053                 $image = self::fitImageSize($image);
1054                 if (empty($image)) {
1055                         return [];
1056                 }
1057
1058                 return ['image' => $image, 'filename' => $filename];
1059         }
1060
1061         /**
1062          * Inserts uploaded image into database and removes local temporary file
1063          *
1064          * @param array $files File array
1065          * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1066          */
1067         private static function uploadImage(array $files): array
1068         {
1069                 Logger::info('starting new upload');
1070
1071                 if (empty($files)) {
1072                         Logger::notice('Empty upload file');
1073                         return [];
1074                 }
1075
1076                 if (!empty($files['tmp_name'])) {
1077                         if (is_array($files['tmp_name'])) {
1078                                 $src = $files['tmp_name'][0];
1079                         } else {
1080                                 $src = $files['tmp_name'];
1081                         }
1082                 } else {
1083                         $src = '';
1084                 }
1085
1086                 if (!empty($files['name'])) {
1087                         if (is_array($files['name'])) {
1088                                 $filename = basename($files['name'][0]);
1089                         } else {
1090                                 $filename = basename($files['name']);
1091                         }
1092                 } else {
1093                         $filename = '';
1094                 }
1095
1096                 if (!empty($files['size'])) {
1097                         if (is_array($files['size'])) {
1098                                 $filesize = intval($files['size'][0]);
1099                         } else {
1100                                 $filesize = intval($files['size']);
1101                         }
1102                 } else {
1103                         $filesize = 0;
1104                 }
1105
1106                 if (!empty($files['type'])) {
1107                         if (is_array($files['type'])) {
1108                                 $filetype = $files['type'][0];
1109                         } else {
1110                                 $filetype = $files['type'];
1111                         }
1112                 } else {
1113                         $filetype = '';
1114                 }
1115
1116                 if (empty($src)) {
1117                         Logger::notice('No source file name', ['files' => $files]);
1118                         return [];
1119                 }
1120
1121                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1122
1123                 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1124
1125                 $imagedata = @file_get_contents($src);
1126                 $image = new Image($imagedata, $filetype);
1127                 if (!$image->isValid()) {
1128                         Logger::notice('Image is unvalid', ['files' => $files]);
1129                         return [];
1130                 }
1131
1132                 $image->orient($src);
1133                 @unlink($src);
1134
1135                 $image = self::fitImageSize($image);
1136                 if (empty($image)) {
1137                         return [];
1138                 }
1139
1140                 return ['image' => $image, 'filename' => $filename];
1141         }
1142
1143         /**
1144          * Handles uploaded image and assigns it to given user id
1145          *
1146          * @param int         $uid   User ID
1147          * @param array       $files uploaded file array
1148          * @param string      $album Album name (optional)
1149          * @param string|null $allow_cid
1150          * @param string|null $allow_gid
1151          * @param string      $deny_cid
1152          * @param string      $deny_gid
1153          * @param string      $desc Description (optional)
1154          * @param string      $resource_id GUID (optional)
1155          * @return array photo record or empty array on error
1156          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1157          */
1158         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
1159         {
1160                 $user = User::getOwnerDataById($uid);
1161                 if (empty($user)) {
1162                         Logger::notice('User not found', ['uid' => $uid]);
1163                         return [];
1164                 }
1165
1166                 $data = self::uploadImage($files);
1167                 if (empty($data)) {
1168                         Logger::info('upload failed');
1169                         return [];
1170                 }
1171
1172                 $image    = $data['image'];
1173                 $filename = $data['filename'];
1174                 $width    = $image->getWidth();
1175                 $height   = $image->getHeight();
1176
1177                 $resource_id = $resource_id ?: self::newResource();
1178                 $album       = $album ?: DI::l10n()->t('Wall Photos');
1179
1180                 if (is_null($allow_cid) && is_null($allow_gid)) {
1181                         $allow_cid = '<' . $user['id'] . '>';
1182                         $allow_gid = '';
1183                 }
1184
1185                 $smallest = 0;
1186
1187                 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1188                 if (!$r) {
1189                         Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1190                         return [];
1191                 }
1192
1193                 if ($width > 640 || $height > 640) {
1194                         $image->scaleDown(640);
1195                         $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1196                         if ($r) {
1197                                 $smallest = 1;
1198                         }
1199                 }
1200
1201                 if ($width > 320 || $height > 320) {
1202                         $image->scaleDown(320);
1203                         $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1204                         if ($r && ($smallest == 0)) {
1205                                 $smallest = 2;
1206                         }
1207                 }
1208
1209                 $condition = ['resource-id' => $resource_id];
1210                 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1211                 if (empty($photo)) {
1212                         Logger::notice('Photo not found', ['condition' => $condition]);
1213                         return [];
1214                 }
1215
1216                 $picture = [];
1217
1218                 $picture['id']          = $photo['id'];
1219                 $picture['resource_id'] = $resource_id;
1220                 $picture['size']        = $photo['datasize'];
1221                 $picture['width']       = $photo['width'];
1222                 $picture['height']      = $photo['height'];
1223                 $picture['type']        = $photo['type'];
1224                 $picture['albumpage']   = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1225                 $picture['picture']     = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1226                 $picture['preview']     = DI::baseUrl() . '/photo/' . $resource_id . '-' . $smallest . '.' . $image->getExt();
1227
1228                 Logger::info('upload done', ['picture' => $picture]);
1229                 return $picture;
1230         }
1231
1232         /**
1233          * Upload a user avatar
1234          *
1235          * @param int    $uid   User ID
1236          * @param array  $files uploaded file array
1237          * @param string $url   External image url
1238          * @return string avatar resource
1239          */
1240         public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1241         {
1242                 if (!empty($files)) {
1243                         $data = self::uploadImage($files);
1244                         if (empty($data)) {
1245                                 Logger::info('upload failed');
1246                                 return '';
1247                         }
1248                 } elseif (!empty($url)) {
1249                         $data = self::loadImageFromURL($url);
1250                         if (empty($data)) {
1251                                 Logger::info('loading from external url failed');
1252                                 return '';
1253                         }
1254                 } else {
1255                         Logger::info('Neither files nor url provided');
1256                         return '';
1257                 }
1258
1259                 $image    = $data['image'];
1260                 $filename = $data['filename'];
1261                 $width    = $image->getWidth();
1262                 $height   = $image->getHeight();
1263
1264                 $resource_id = self::newResource();
1265                 $album       = DI::l10n()->t(self::PROFILE_PHOTOS);
1266
1267                 // upload profile image (scales 4, 5, 6)
1268                 logger::info('starting new profile image upload');
1269
1270                 if ($width > 300 || $height > 300) {
1271                         $image->scaleDown(300);
1272                 }
1273
1274                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1275                 if (!$r) {
1276                         logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1277                 }
1278
1279                 if ($width > 80 || $height > 80) {
1280                         $image->scaleDown(80);
1281                 }
1282
1283                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1284                 if (!$r) {
1285                         logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1286                 }
1287
1288                 if ($width > 48 || $height > 48) {
1289                         $image->scaleDown(48);
1290                 }
1291
1292                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1293                 if (!$r) {
1294                         logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1295                 }
1296
1297                 logger::info('new profile image upload ended');
1298
1299                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1300                 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1301
1302                 Contact::updateSelfFromUserID($uid, true);
1303
1304                 // Update global directory in background
1305                 Profile::publishUpdate($uid);
1306
1307                 return $resource_id;
1308         }
1309
1310         /**
1311          * Upload a user banner
1312          *
1313          * @param int    $uid   User ID
1314          * @param array  $files uploaded file array
1315          * @param string $url   External image url
1316          * @return string avatar resource
1317          */
1318         public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1319         {
1320                 if (!empty($files)) {
1321                         $data = self::uploadImage($files);
1322                         if (empty($data)) {
1323                                 Logger::info('upload failed');
1324                                 return '';
1325                         }
1326                 } elseif (!empty($url)) {
1327                         $data = self::loadImageFromURL($url);
1328                         if (empty($data)) {
1329                                 Logger::info('loading from external url failed');
1330                                 return '';
1331                         }
1332                 } else {
1333                         Logger::info('Neither files nor url provided');
1334                         return '';
1335                 }
1336
1337                 $image    = $data['image'];
1338                 $filename = $data['filename'];
1339                 $width    = $image->getWidth();
1340                 $height   = $image->getHeight();
1341
1342                 $resource_id = self::newResource();
1343                 $album       = DI::l10n()->t(self::BANNER_PHOTOS);
1344
1345                 if ($width > 960) {
1346                         $image->scaleDown(960);
1347                 }
1348
1349                 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1350                 if (!$r) {
1351                         logger::warning('profile banner upload with scale 3 (960) failed');
1352                 }
1353
1354                 logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
1355
1356                 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1357                 self::update(['photo-type' => self::DEFAULT], $condition);
1358
1359                 Contact::updateSelfFromUserID($uid, true);
1360
1361                 // Update global directory in background
1362                 Profile::publishUpdate($uid);
1363
1364                 return $resource_id;
1365         }
1366 }