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