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