]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
4c49bdf43af5f7f35ac94a4e67f5b6ec1760acf5
[friendica.git] / src / Model / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Duration;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\Database\DBStructure;
29 use Friendica\DI;
30 use Friendica\Model\Storage\SystemResource;
31 use Friendica\Object\Image;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Images;
34 use Friendica\Security\Security;
35 use Friendica\Util\Proxy;
36 use Friendica\Util\Strings;
37
38 require_once "include/dba.php";
39
40 /**
41  * Class to handle photo dabatase table
42  */
43 class Photo
44 {
45         const CONTACT_PHOTOS = 'Contact Photos';
46
47         /**
48          * Select rows from the photo table and returns them as array
49          *
50          * @param array $fields     Array of selected fields, empty for all
51          * @param array $conditions Array of fields for conditions
52          * @param array $params     Array of several parameters
53          *
54          * @return boolean|array
55          *
56          * @throws \Exception
57          * @see   \Friendica\Database\DBA::selectToArray
58          */
59         public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
60         {
61                 if (empty($fields)) {
62                         $fields = self::getFields();
63                 }
64
65                 return DBA::selectToArray('photo', $fields, $conditions, $params);
66         }
67
68         /**
69          * Retrieve a single record from the photo table
70          *
71          * @param array $fields     Array of selected fields, empty for all
72          * @param array $conditions Array of fields for conditions
73          * @param array $params     Array of several parameters
74          *
75          * @return bool|array
76          *
77          * @throws \Exception
78          * @see   \Friendica\Database\DBA::select
79          */
80         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
81         {
82                 if (empty($fields)) {
83                         $fields = self::getFields();
84                 }
85
86                 return DBA::selectFirst("photo", $fields, $conditions, $params);
87         }
88
89         /**
90          * Get photos for user id
91          *
92          * @param integer $uid        User id
93          * @param string  $resourceid Rescource ID of the photo
94          * @param array   $conditions Array of fields for conditions
95          * @param array   $params     Array of several parameters
96          *
97          * @return bool|array
98          *
99          * @throws \Exception
100          * @see   \Friendica\Database\DBA::select
101          */
102         public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
103         {
104                 $conditions["resource-id"] = $resourceid;
105                 $conditions["uid"] = $uid;
106
107                 return self::selectToArray([], $conditions, $params);
108         }
109
110         /**
111          * Get a photo for user id
112          *
113          * @param integer $uid        User id
114          * @param string  $resourceid Rescource ID of the photo
115          * @param integer $scale      Scale of the photo. Defaults to 0
116          * @param array   $conditions Array of fields for conditions
117          * @param array   $params     Array of several parameters
118          *
119          * @return bool|array
120          *
121          * @throws \Exception
122          * @see   \Friendica\Database\DBA::select
123          */
124         public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
125         {
126                 $conditions["resource-id"] = $resourceid;
127                 $conditions["uid"] = $uid;
128                 $conditions["scale"] = $scale;
129
130                 return self::selectFirst([], $conditions, $params);
131         }
132
133         /**
134          * Get a single photo given resource id and scale
135          *
136          * This method checks for permissions. Returns associative array
137          * on success, "no sign" image info, if user has no permission,
138          * false if photo does not exists
139          *
140          * @param string  $resourceid Rescource ID of the photo
141          * @param integer $scale      Scale of the photo. Defaults to 0
142          *
143          * @return boolean|array
144          * @throws \Exception
145          */
146         public static function getPhoto(string $resourceid, int $scale = 0)
147         {
148                 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
149                 if (!DBA::isResult($r)) {
150                         return false;
151                 }
152
153                 $uid = $r["uid"];
154
155                 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
156
157                 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
158
159                 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
160                 $params = ["order" => ["scale" => true]];
161                 $photo = self::selectFirst([], $conditions, $params);
162
163                 return $photo;
164         }
165
166         /**
167          * Check if photo with given conditions exists
168          *
169          * @param array $conditions Array of extra conditions
170          *
171          * @return boolean
172          * @throws \Exception
173          */
174         public static function exists(array $conditions)
175         {
176                 return DBA::exists("photo", $conditions);
177         }
178
179
180         /**
181          * Get Image data for given row id. null if row id does not exist
182          *
183          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
184          *
185          * @return \Friendica\Object\Image
186          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
187          * @throws \ImagickException
188          */
189         public static function getImageDataForPhoto(array $photo)
190         {
191                 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
192                 if ($backendClass === null) {
193                         // legacy data storage in "data" column
194                         $i = self::selectFirst(['data'], ['id' => $photo['id']]);
195                         if ($i === false) {
196                                 return null;
197                         }
198                         $data = $i['data'];
199                 } else {
200                         $backendRef = $photo['backend-ref'] ?? '';
201                         $data = $backendClass->get($backendRef);
202                 }
203                 return $data;
204         }
205
206         /**
207          * Get Image object for given row id. null if row id does not exist
208          *
209          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
210          *
211          * @return \Friendica\Object\Image
212          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213          * @throws \ImagickException
214          */
215         public static function getImageForPhoto(array $photo)
216         {
217                 $data = self::getImageDataForPhoto($photo);
218                 if (empty($data)) {
219                         return null;
220                 }
221
222                 return new Image($data, $photo['type']);
223         }
224
225         /**
226          * Return a list of fields that are associated with the photo table
227          *
228          * @return array field list
229          * @throws \Exception
230          */
231         private static function getFields()
232         {
233                 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
234                 $fields = array_keys($allfields["photo"]["fields"]);
235                 array_splice($fields, array_search("data", $fields), 1);
236                 return $fields;
237         }
238
239         /**
240          * Construct a photo array for a system resource image
241          *
242          * @param string $filename Image file name relative to code root
243          * @param string $mimetype Image mime type. Defaults to "image/jpeg"
244          *
245          * @return array
246          * @throws \Exception
247          */
248         public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
249         {
250                 $fields = self::getFields();
251                 $values = array_fill(0, count($fields), "");
252
253                 $photo                  = array_combine($fields, $values);
254                 $photo['backend-class'] = SystemResource::NAME;
255                 $photo['backend-ref']   = $filename;
256                 $photo['type']          = $mimetype;
257                 $photo['cacheable']     = false;
258
259                 return $photo;
260         }
261
262
263         /**
264          * store photo metadata in db and binary in default backend
265          *
266          * @param Image   $Image     Image object with data
267          * @param integer $uid       User ID
268          * @param integer $cid       Contact ID
269          * @param integer $rid       Resource ID
270          * @param string  $filename  Filename
271          * @param string  $album     Album name
272          * @param integer $scale     Scale
273          * @param integer $profile   Is a profile image? optional, default = 0
274          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
275          * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
276          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
277          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ""
278          * @param string  $desc      Photo caption. optional, default = ""
279          *
280          * @return boolean True on success
281          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
282          */
283         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
284         {
285                 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
286                 if (DBA::isResult($photo)) {
287                         $guid = $photo["guid"];
288                 } else {
289                         $guid = System::createGUID();
290                 }
291
292                 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
293                 $created = DateTimeFormat::utcNow();
294                 if (DBA::isResult($existing_photo)) {
295                         $created = $existing_photo["created"];
296                 }
297
298                 // Get defined storage backend.
299                 // if no storage backend, we use old "data" column in photo table.
300                 // if is an existing photo, reuse same backend
301                 $data = "";
302                 $backend_ref = "";
303
304                 if (DBA::isResult($existing_photo)) {
305                         $backend_ref = (string)$existing_photo["backend-ref"];
306                         $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
307                 } else {
308                         $storage = DI::storage();
309                 }
310
311                 if ($storage === null) {
312                         $data = $Image->asString();
313                 } else {
314                         $backend_ref = $storage->put($Image->asString(), $backend_ref);
315                 }
316
317                 $fields = [
318                         "uid" => $uid,
319                         "contact-id" => $cid,
320                         "guid" => $guid,
321                         "resource-id" => $rid,
322                         "hash" => md5($Image->asString()),
323                         "created" => $created,
324                         "edited" => DateTimeFormat::utcNow(),
325                         "filename" => basename($filename),
326                         "type" => $Image->getType(),
327                         "album" => $album,
328                         "height" => $Image->getHeight(),
329                         "width" => $Image->getWidth(),
330                         "datasize" => strlen($Image->asString()),
331                         "data" => $data,
332                         "scale" => $scale,
333                         "profile" => $profile,
334                         "allow_cid" => $allow_cid,
335                         "allow_gid" => $allow_gid,
336                         "deny_cid" => $deny_cid,
337                         "deny_gid" => $deny_gid,
338                         "desc" => $desc,
339                         "backend-class" => (string)$storage,
340                         "backend-ref" => $backend_ref
341                 ];
342
343                 if (DBA::isResult($existing_photo)) {
344                         $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
345                 } else {
346                         $r = DBA::insert("photo", $fields);
347                 }
348
349                 return $r;
350         }
351
352
353         /**
354          * Delete info from table and data from storage
355          *
356          * @param array $conditions Field condition(s)
357          * @param array $options    Options array, Optional
358          *
359          * @return boolean
360          *
361          * @throws \Exception
362          * @see   \Friendica\Database\DBA::delete
363          */
364         public static function delete(array $conditions, array $options = [])
365         {
366                 // get photo to delete data info
367                 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
368
369                 while ($photo = DBA::fetch($photos)) {
370                         $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
371                         if ($backend_class !== null) {
372                                 if ($backend_class->delete($photo["backend-ref"] ?? '')) {
373                                         // Delete the photos after they had been deleted successfully
374                                         DBA::delete("photo", ['id' => $photo['id']]);
375                                 }
376                         }
377                 }
378
379                 DBA::close($photos);
380
381                 return DBA::delete("photo", $conditions, $options);
382         }
383
384         /**
385          * Update a photo
386          *
387          * @param array         $fields     Contains the fields that are updated
388          * @param array         $conditions Condition array with the key values
389          * @param Image         $img        Image to update. Optional, default null.
390          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
391          *
392          * @return boolean  Was the update successfull?
393          *
394          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
395          * @see   \Friendica\Database\DBA::update
396          */
397         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
398         {
399                 if (!is_null($img)) {
400                         // get photo to update
401                         $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
402
403                         foreach($photos as $photo) {
404                                 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
405                                 if ($backend_class !== null) {
406                                         $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
407                                 } else {
408                                         $fields["data"] = $img->asString();
409                                 }
410                         }
411                         $fields['updated'] = DateTimeFormat::utcNow();
412                 }
413
414                 $fields['edited'] = DateTimeFormat::utcNow();
415
416                 return DBA::update("photo", $fields, $conditions, $old_fields);
417         }
418
419         /**
420          * @param string  $image_url     Remote URL
421          * @param integer $uid           user id
422          * @param integer $cid           contact id
423          * @param boolean $quit_on_error optional, default false
424          * @return array
425          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426          * @throws \ImagickException
427          */
428         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
429         {
430                 $thumb = "";
431                 $micro = "";
432
433                 $photo = DBA::selectFirst(
434                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => self::CONTACT_PHOTOS]
435                 );
436                 if (!empty($photo['resource-id'])) {
437                         $resource_id = $photo["resource-id"];
438                 } else {
439                         $resource_id = self::newResource();
440                 }
441
442                 $photo_failure = false;
443
444                 $filename = basename($image_url);
445                 if (!empty($image_url)) {
446                         $ret = DI::httpRequest()->get($image_url);
447                         $img_str = $ret->getBody();
448                         $type = $ret->getContentType();
449                 } else {
450                         $img_str = '';
451                 }
452
453                 if ($quit_on_error && ($img_str == "")) {
454                         return false;
455                 }
456
457                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
458
459                 $Image = new Image($img_str, $type);
460                 if ($Image->isValid()) {
461                         $Image->scaleToSquare(300);
462
463                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4);
464
465                         if ($r === false) {
466                                 $photo_failure = true;
467                         }
468
469                         $Image->scaleDown(80);
470
471                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5);
472
473                         if ($r === false) {
474                                 $photo_failure = true;
475                         }
476
477                         $Image->scaleDown(48);
478
479                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6);
480
481                         if ($r === false) {
482                                 $photo_failure = true;
483                         }
484
485                         $suffix = "?ts=" . time();
486
487                         $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
488                         $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
489                         $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
490
491                         // Remove the cached photo
492                         $a = DI::app();
493                         $basepath = $a->getBasePath();
494
495                         if (is_dir($basepath . "/photo")) {
496                                 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
497                                 if (file_exists($filename)) {
498                                         unlink($filename);
499                                 }
500                                 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
501                                 if (file_exists($filename)) {
502                                         unlink($filename);
503                                 }
504                                 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
505                                 if (file_exists($filename)) {
506                                         unlink($filename);
507                                 }
508                         }
509                 } else {
510                         $photo_failure = true;
511                 }
512
513                 if ($photo_failure && $quit_on_error) {
514                         return false;
515                 }
516
517                 if ($photo_failure) {
518                         $contact = Contact::getById($cid) ?: [];
519                         $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
520                         $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
521                         $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
522                 }
523
524                 return [$image_url, $thumb, $micro];
525         }
526
527         /**
528          * @param array $exifCoord coordinate
529          * @param string $hemi      hemi
530          * @return float
531          */
532         public static function getGps($exifCoord, $hemi)
533         {
534                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
535                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
536                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
537
538                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
539
540                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
541         }
542
543         /**
544          * @param string $coordPart coordPart
545          * @return float
546          */
547         private static function gps2Num($coordPart)
548         {
549                 $parts = explode("/", $coordPart);
550
551                 if (count($parts) <= 0) {
552                         return 0;
553                 }
554
555                 if (count($parts) == 1) {
556                         return $parts[0];
557                 }
558
559                 return floatval($parts[0]) / floatval($parts[1]);
560         }
561
562         /**
563          * Fetch the photo albums that are available for a viewer
564          *
565          * The query in this function is cost intensive, so it is cached.
566          *
567          * @param int  $uid    User id of the photos
568          * @param bool $update Update the cache
569          *
570          * @return array Returns array of the photo albums
571          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
572          */
573         public static function getAlbums($uid, $update = false)
574         {
575                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
576
577                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
578                 $albums = DI::cache()->get($key);
579                 if (is_null($albums) || $update) {
580                         if (!DI::config()->get("system", "no_count", false)) {
581                                 /// @todo This query needs to be renewed. It is really slow
582                                 // At this time we just store the data in the cache
583                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
584                                         FROM `photo`
585                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
586                                         GROUP BY `album` ORDER BY `created` DESC",
587                                         intval($uid),
588                                         DBA::escape(self::CONTACT_PHOTOS),
589                                         DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
590                                 );
591                         } else {
592                                 // This query doesn't do the count and is much faster
593                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
594                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
595                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
596                                         intval($uid),
597                                         DBA::escape(self::CONTACT_PHOTOS),
598                                         DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
599                                 );
600                         }
601                         DI::cache()->set($key, $albums, Duration::DAY);
602                 }
603                 return $albums;
604         }
605
606         /**
607          * @param int $uid User id of the photos
608          * @return void
609          * @throws \Exception
610          */
611         public static function clearAlbumCache($uid)
612         {
613                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
614                 DI::cache()->set($key, null, Duration::DAY);
615         }
616
617         /**
618          * Generate a unique photo ID.
619          *
620          * @return string
621          * @throws \Exception
622          */
623         public static function newResource()
624         {
625                 return System::createGUID(32, false);
626         }
627
628         /**
629          * Extracts the rid from a local photo URI
630          *
631          * @param string $image_uri The URI of the photo
632          * @return string The rid of the photo, or an empty string if the URI is not local
633          */
634         public static function ridFromURI(string $image_uri)
635         {
636                 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
637                         return '';
638                 }
639                 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
640                 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
641                 if (!strlen($image_uri)) {
642                         return '';
643                 }
644                 return $image_uri;
645         }
646
647         /**
648          * Changes photo permissions that had been embedded in a post
649          *
650          * @todo This function currently does have some flaws:
651          * - Sharing a post with a forum will create a photo that only the forum can see.
652          * - Sharing a photo again that been shared non public before doesn't alter the permissions.
653          *
654          * @return string
655          * @throws \Exception
656          */
657         public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
658         {
659                 // Simplify image codes
660                 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
661                 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
662
663                 // Search for images
664                 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
665                         return false;
666                 }
667                 $images = $match[1];
668                 if (empty($images)) {
669                         return false;
670                 }
671
672                 foreach ($images as $image) {
673                         $image_rid = self::ridFromURI($image);
674                         if (empty($image_rid)) {
675                                 continue;
676                         }
677
678                         // Ensure to only modify photos that you own
679                         $srch = '<' . intval($original_contact_id) . '>';
680
681                         $condition = [
682                                 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
683                                 'resource-id' => $image_rid, 'uid' => $uid
684                         ];
685                         if (!Photo::exists($condition)) {
686                                 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
687                                 if (!DBA::isResult($photo)) {
688                                         Logger::info('Image not found', ['resource-id' => $image_rid]);
689                                 } else {
690                                         Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
691                                 }
692                                 continue;
693                         }
694
695                         /**
696                          * @todo Existing permissions need to be mixed with the new ones.
697                          * Otherwise this creates problems with sharing the same picture multiple times
698                          * Also check if $str_contact_allow does contain a public forum.
699                          * Then set the permissions to public.
700                          */
701
702                         $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
703                                         'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
704                                         'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
705
706                         $condition = ['resource-id' => $image_rid, 'uid' => $uid];
707                         Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
708                         Photo::update($fields, $condition);
709                 }
710
711                 return true;
712         }
713
714         /**
715          * Strips known picture extensions from picture links
716          *
717          * @param string $name Picture link
718          * @return string stripped picture link
719          * @throws \Exception
720          */
721         public static function stripExtension($name)
722         {
723                 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
724                 foreach (Images::supportedTypes() as $m => $e) {
725                         $name = str_replace("." . $e, "", $name);
726                 }
727                 return $name;
728         }
729
730         /**
731          * Returns the GUID from picture links
732          *
733          * @param string $name Picture link
734          * @return string GUID
735          * @throws \Exception
736          */
737         public static function getGUID($name)
738         {
739                 $base = DI::baseUrl()->get();
740
741                 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
742
743                 $guid = self::stripExtension($guid);
744                 if (substr($guid, -2, 1) != "-") {
745                         return '';
746                 }
747
748                 $scale = intval(substr($guid, -1, 1));
749                 if (!is_numeric($scale)) {
750                         return '';
751                 }
752
753                 $guid = substr($guid, 0, -2);
754                 return $guid;
755         }
756
757         /**
758          * Tests if the picture link points to a locally stored picture
759          *
760          * @param string $name Picture link
761          * @return boolean
762          * @throws \Exception
763          */
764         public static function isLocal($name)
765         {
766                 $guid = self::getGUID($name);
767
768                 if (empty($guid)) {
769                         return false;
770                 }
771
772                 return DBA::exists('photo', ['resource-id' => $guid]);
773         }
774
775         /**
776          * Tests if the link points to a locally stored picture page
777          *
778          * @param string $name Page link
779          * @return boolean
780          * @throws \Exception
781          */
782         public static function isLocalPage($name)
783         {
784                 $base = DI::baseUrl()->get();
785
786                 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
787                 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
788                 if (empty($guid)) {
789                         return false;
790                 }
791
792                 return DBA::exists('photo', ['resource-id' => $guid]);
793         }
794 }