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