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