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