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