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