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