]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
f79409e3f5c332f1115002d9b265f0388fbd2813
[friendica.git] / src / Model / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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 data 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 getImageDataForPhoto(array $photo)
190         {
191                 if (!empty($photo['data'])) {
192                         return $photo['data'];
193                 }
194
195                 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
196                 if (empty($backendClass)) {
197                         // legacy data storage in "data" column
198                         $i = self::selectFirst(['data'], ['id' => $photo['id']]);
199                         if ($i === false) {
200                                 return null;
201                         }
202                         $data = $i['data'];
203                 } else {
204                         $backendRef = $photo['backend-ref'] ?? '';
205                         $data = $backendClass->get($backendRef);
206                 }
207                 return $data;
208         }
209
210         /**
211          * Get Image object for given row id. null if row id does not exist
212          *
213          * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
214          *
215          * @return \Friendica\Object\Image
216          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217          * @throws \ImagickException
218          */
219         public static function getImageForPhoto(array $photo)
220         {
221                 $data = self::getImageDataForPhoto($photo);
222                 if (empty($data)) {
223                         return null;
224                 }
225
226                 return new Image($data, $photo['type']);
227         }
228
229         /**
230          * Return a list of fields that are associated with the photo table
231          *
232          * @return array field list
233          * @throws \Exception
234          */
235         private static function getFields()
236         {
237                 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
238                 $fields = array_keys($allfields["photo"]["fields"]);
239                 array_splice($fields, array_search("data", $fields), 1);
240                 return $fields;
241         }
242
243         /**
244          * Construct a photo array for a system resource image
245          *
246          * @param string $filename Image file name relative to code root
247          * @param string $mimetype Image mime type. Defaults to "image/jpeg"
248          *
249          * @return array
250          * @throws \Exception
251          */
252         public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
253         {
254                 $fields = self::getFields();
255                 $values = array_fill(0, count($fields), "");
256
257                 $photo                  = array_combine($fields, $values);
258                 $photo['backend-class'] = SystemResource::NAME;
259                 $photo['backend-ref']   = $filename;
260                 $photo['type']          = $mimetype;
261                 $photo['cacheable']     = false;
262
263                 return $photo;
264         }
265
266
267         /**
268          * store photo metadata in db and binary in default backend
269          *
270          * @param Image   $Image     Image object with data
271          * @param integer $uid       User ID
272          * @param integer $cid       Contact ID
273          * @param integer $rid       Resource ID
274          * @param string  $filename  Filename
275          * @param string  $album     Album name
276          * @param integer $scale     Scale
277          * @param integer $profile   Is a profile image? optional, default = 0
278          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
279          * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
280          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
281          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ""
282          * @param string  $desc      Photo caption. optional, default = ""
283          *
284          * @return boolean True on success
285          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286          */
287         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
288         {
289                 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
290                 if (DBA::isResult($photo)) {
291                         $guid = $photo["guid"];
292                 } else {
293                         $guid = System::createGUID();
294                 }
295
296                 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
297                 $created = DateTimeFormat::utcNow();
298                 if (DBA::isResult($existing_photo)) {
299                         $created = $existing_photo["created"];
300                 }
301
302                 // Get defined storage backend.
303                 // if no storage backend, we use old "data" column in photo table.
304                 // if is an existing photo, reuse same backend
305                 $data = "";
306                 $backend_ref = "";
307
308                 if (DBA::isResult($existing_photo)) {
309                         $backend_ref = (string)$existing_photo["backend-ref"];
310                         $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
311                 } else {
312                         $storage = DI::storage();
313                 }
314
315                 if (empty($storage)) {
316                         $data = $Image->asString();
317                 } else {
318                         $backend_ref = $storage->put($Image->asString(), $backend_ref);
319                 }
320
321                 $fields = [
322                         "uid" => $uid,
323                         "contact-id" => $cid,
324                         "guid" => $guid,
325                         "resource-id" => $rid,
326                         "hash" => md5($Image->asString()),
327                         "created" => $created,
328                         "edited" => DateTimeFormat::utcNow(),
329                         "filename" => basename($filename),
330                         "type" => $Image->getType(),
331                         "album" => $album,
332                         "height" => $Image->getHeight(),
333                         "width" => $Image->getWidth(),
334                         "datasize" => strlen($Image->asString()),
335                         "data" => $data,
336                         "scale" => $scale,
337                         "profile" => $profile,
338                         "allow_cid" => $allow_cid,
339                         "allow_gid" => $allow_gid,
340                         "deny_cid" => $deny_cid,
341                         "deny_gid" => $deny_gid,
342                         "desc" => $desc,
343                         "backend-class" => (string)$storage,
344                         "backend-ref" => $backend_ref
345                 ];
346
347                 if (DBA::isResult($existing_photo)) {
348                         $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
349                 } else {
350                         $r = DBA::insert("photo", $fields);
351                 }
352
353                 return $r;
354         }
355
356
357         /**
358          * Delete info from table and data from storage
359          *
360          * @param array $conditions Field condition(s)
361          * @param array $options    Options array, Optional
362          *
363          * @return boolean
364          *
365          * @throws \Exception
366          * @see   \Friendica\Database\DBA::delete
367          */
368         public static function delete(array $conditions, array $options = [])
369         {
370                 // get photo to delete data info
371                 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
372
373                 while ($photo = DBA::fetch($photos)) {
374                         $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
375                         if (!empty($backend_class)) {
376                                 if ($backend_class->delete($photo["backend-ref"] ?? '')) {
377                                         // Delete the photos after they had been deleted successfully
378                                         DBA::delete("photo", ['id' => $photo['id']]);
379                                 }
380                         }
381                 }
382
383                 DBA::close($photos);
384
385                 return DBA::delete("photo", $conditions, $options);
386         }
387
388         /**
389          * Update a photo
390          *
391          * @param array         $fields     Contains the fields that are updated
392          * @param array         $conditions Condition array with the key values
393          * @param Image         $img        Image to update. Optional, default null.
394          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
395          *
396          * @return boolean  Was the update successfull?
397          *
398          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
399          * @see   \Friendica\Database\DBA::update
400          */
401         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
402         {
403                 if (!is_null($img)) {
404                         // get photo to update
405                         $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
406
407                         foreach($photos as $photo) {
408                                 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
409                                 if (!empty($backend_class)) {
410                                         $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
411                                 } else {
412                                         $fields["data"] = $img->asString();
413                                 }
414                         }
415                         $fields['updated'] = DateTimeFormat::utcNow();
416                 }
417
418                 $fields['edited'] = DateTimeFormat::utcNow();
419
420                 return DBA::update("photo", $fields, $conditions, $old_fields);
421         }
422
423         /**
424          * @param string  $image_url     Remote URL
425          * @param integer $uid           user id
426          * @param integer $cid           contact id
427          * @param boolean $quit_on_error optional, default false
428          * @return array
429          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
430          * @throws \ImagickException
431          */
432         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
433         {
434                 $thumb = "";
435                 $micro = "";
436
437                 $photo = DBA::selectFirst(
438                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => self::CONTACT_PHOTOS]
439                 );
440                 if (!empty($photo['resource-id'])) {
441                         $resource_id = $photo["resource-id"];
442                 } else {
443                         $resource_id = self::newResource();
444                 }
445
446                 $photo_failure = false;
447
448                 $filename = basename($image_url);
449                 if (!empty($image_url)) {
450                         $ret = DI::httpRequest()->get($image_url);
451                         $img_str = $ret->getBody();
452                         $type = $ret->getContentType();
453                 } else {
454                         $img_str = '';
455                 }
456
457                 if ($quit_on_error && ($img_str == "")) {
458                         return false;
459                 }
460
461                 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
462
463                 $Image = new Image($img_str, $type);
464                 if ($Image->isValid()) {
465                         $Image->scaleToSquare(300);
466
467                         $filesize = strlen($Image->asString());
468                         $maximagesize = DI::config()->get('system', 'maximagesize');
469                         if (!empty($maximagesize) && ($filesize > $maximagesize)) {
470                                 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
471                                 if ($Image->getType() == 'image/gif') {
472                                         $Image->toStatic();
473                                         $Image = new Image($Image->asString(), 'image/png');
474
475                                         $filesize = strlen($Image->asString());
476                                         Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
477                                 }
478                                 if ($filesize > $maximagesize) {
479                                         foreach ([160, 80] as $pixels) {
480                                                 if ($filesize > $maximagesize) {
481                                                         Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
482                                                         $Image->scaleDown($pixels);
483                                                         $filesize = strlen($Image->asString());
484                                                 }
485                                         }
486                                 }
487                                 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
488                         }
489
490                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4);
491
492                         if ($r === false) {
493                                 $photo_failure = true;
494                         }
495
496                         $Image->scaleDown(80);
497
498                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5);
499
500                         if ($r === false) {
501                                 $photo_failure = true;
502                         }
503
504                         $Image->scaleDown(48);
505
506                         $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6);
507
508                         if ($r === false) {
509                                 $photo_failure = true;
510                         }
511
512                         $suffix = "?ts=" . time();
513
514                         $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
515                         $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
516                         $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
517
518                         // Remove the cached photo
519                         $a = DI::app();
520                         $basepath = $a->getBasePath();
521
522                         if (is_dir($basepath . "/photo")) {
523                                 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
524                                 if (file_exists($filename)) {
525                                         unlink($filename);
526                                 }
527                                 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
528                                 if (file_exists($filename)) {
529                                         unlink($filename);
530                                 }
531                                 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
532                                 if (file_exists($filename)) {
533                                         unlink($filename);
534                                 }
535                         }
536                 } else {
537                         $photo_failure = true;
538                 }
539
540                 if ($photo_failure && $quit_on_error) {
541                         return false;
542                 }
543
544                 if ($photo_failure) {
545                         $contact = Contact::getById($cid) ?: [];
546                         $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
547                         $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
548                         $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
549                 }
550
551                 return [$image_url, $thumb, $micro];
552         }
553
554         /**
555          * @param array $exifCoord coordinate
556          * @param string $hemi      hemi
557          * @return float
558          */
559         public static function getGps($exifCoord, $hemi)
560         {
561                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
562                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
563                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
564
565                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
566
567                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
568         }
569
570         /**
571          * @param string $coordPart coordPart
572          * @return float
573          */
574         private static function gps2Num($coordPart)
575         {
576                 $parts = explode("/", $coordPart);
577
578                 if (count($parts) <= 0) {
579                         return 0;
580                 }
581
582                 if (count($parts) == 1) {
583                         return $parts[0];
584                 }
585
586                 return floatval($parts[0]) / floatval($parts[1]);
587         }
588
589         /**
590          * Fetch the photo albums that are available for a viewer
591          *
592          * The query in this function is cost intensive, so it is cached.
593          *
594          * @param int  $uid    User id of the photos
595          * @param bool $update Update the cache
596          *
597          * @return array Returns array of the photo albums
598          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
599          */
600         public static function getAlbums($uid, $update = false)
601         {
602                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
603
604                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
605                 $albums = DI::cache()->get($key);
606                 if (is_null($albums) || $update) {
607                         if (!DI::config()->get("system", "no_count", false)) {
608                                 /// @todo This query needs to be renewed. It is really slow
609                                 // At this time we just store the data in the cache
610                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
611                                         FROM `photo`
612                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
613                                         GROUP BY `album` ORDER BY `created` DESC",
614                                         intval($uid),
615                                         DBA::escape(self::CONTACT_PHOTOS),
616                                         DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
617                                 );
618                         } else {
619                                 // This query doesn't do the count and is much faster
620                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
621                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
622                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
623                                         intval($uid),
624                                         DBA::escape(self::CONTACT_PHOTOS),
625                                         DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
626                                 );
627                         }
628                         DI::cache()->set($key, $albums, Duration::DAY);
629                 }
630                 return $albums;
631         }
632
633         /**
634          * @param int $uid User id of the photos
635          * @return void
636          * @throws \Exception
637          */
638         public static function clearAlbumCache($uid)
639         {
640                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
641                 DI::cache()->set($key, null, Duration::DAY);
642         }
643
644         /**
645          * Generate a unique photo ID.
646          *
647          * @return string
648          * @throws \Exception
649          */
650         public static function newResource()
651         {
652                 return System::createGUID(32, false);
653         }
654
655         /**
656          * Extracts the rid from a local photo URI
657          *
658          * @param string $image_uri The URI of the photo
659          * @return string The rid of the photo, or an empty string if the URI is not local
660          */
661         public static function ridFromURI(string $image_uri)
662         {
663                 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
664                         return '';
665                 }
666                 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
667                 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
668                 if (!strlen($image_uri)) {
669                         return '';
670                 }
671                 return $image_uri;
672         }
673
674         /**
675          * Changes photo permissions that had been embedded in a post
676          *
677          * @todo This function currently does have some flaws:
678          * - Sharing a post with a forum will create a photo that only the forum can see.
679          * - Sharing a photo again that been shared non public before doesn't alter the permissions.
680          *
681          * @return string
682          * @throws \Exception
683          */
684         public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
685         {
686                 // Simplify image codes
687                 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
688                 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
689
690                 // Search for images
691                 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
692                         return false;
693                 }
694                 $images = $match[1];
695                 if (empty($images)) {
696                         return false;
697                 }
698
699                 foreach ($images as $image) {
700                         $image_rid = self::ridFromURI($image);
701                         if (empty($image_rid)) {
702                                 continue;
703                         }
704
705                         // Ensure to only modify photos that you own
706                         $srch = '<' . intval($original_contact_id) . '>';
707
708                         $condition = [
709                                 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
710                                 'resource-id' => $image_rid, 'uid' => $uid
711                         ];
712                         if (!Photo::exists($condition)) {
713                                 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
714                                 if (!DBA::isResult($photo)) {
715                                         Logger::info('Image not found', ['resource-id' => $image_rid]);
716                                 } else {
717                                         Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
718                                 }
719                                 continue;
720                         }
721
722                         /**
723                          * @todo Existing permissions need to be mixed with the new ones.
724                          * Otherwise this creates problems with sharing the same picture multiple times
725                          * Also check if $str_contact_allow does contain a public forum.
726                          * Then set the permissions to public.
727                          */
728
729                         self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
730                 }
731
732                 return true;
733         }
734
735         /**
736          * Add permissions to photo ressource
737          * @todo mix with previous photo permissions
738          * 
739          * @param string $image_rid
740          * @param integer $uid
741          * @param string $str_contact_allow
742          * @param string $str_group_allow
743          * @param string $str_contact_deny
744          * @param string $str_group_deny
745          * @return void
746          */
747         public static function setPermissionForRessource(string $image_rid, int $uid, string $str_contact_allow, string $str_group_allow, string $str_contact_deny, string $str_group_deny)
748         {
749                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
750                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
751                 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
752
753                 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
754                 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
755                 Photo::update($fields, $condition);
756         }
757
758         /**
759          * Strips known picture extensions from picture links
760          *
761          * @param string $name Picture link
762          * @return string stripped picture link
763          * @throws \Exception
764          */
765         public static function stripExtension($name)
766         {
767                 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
768                 foreach (Images::supportedTypes() as $m => $e) {
769                         $name = str_replace("." . $e, "", $name);
770                 }
771                 return $name;
772         }
773
774         /**
775          * Returns the GUID from picture links
776          *
777          * @param string $name Picture link
778          * @return string GUID
779          * @throws \Exception
780          */
781         public static function getGUID($name)
782         {
783                 $base = DI::baseUrl()->get();
784
785                 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
786
787                 $guid = self::stripExtension($guid);
788                 if (substr($guid, -2, 1) != "-") {
789                         return '';
790                 }
791
792                 $scale = intval(substr($guid, -1, 1));
793                 if (!is_numeric($scale)) {
794                         return '';
795                 }
796
797                 $guid = substr($guid, 0, -2);
798                 return $guid;
799         }
800
801         /**
802          * Tests if the picture link points to a locally stored picture
803          *
804          * @param string $name Picture link
805          * @return boolean
806          * @throws \Exception
807          */
808         public static function isLocal($name)
809         {
810                 $guid = self::getGUID($name);
811
812                 if (empty($guid)) {
813                         return false;
814                 }
815
816                 return DBA::exists('photo', ['resource-id' => $guid]);
817         }
818
819         /**
820          * Tests if the link points to a locally stored picture page
821          *
822          * @param string $name Page link
823          * @return boolean
824          * @throws \Exception
825          */
826         public static function isLocalPage($name)
827         {
828                 $base = DI::baseUrl()->get();
829
830                 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
831                 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
832                 if (empty($guid)) {
833                         return false;
834                 }
835
836                 return DBA::exists('photo', ['resource-id' => $guid]);
837         }
838
839         /**
840          * 
841          * @param int   $uid   User ID
842          * @param array $files uploaded file array
843          * @return array photo record
844          */
845         public static function upload(int $uid, array $files)
846         {
847                 Logger::info('starting new upload');
848
849                 $user = User::getOwnerDataById($uid);
850                 if (empty($user)) {
851                         Logger::notice('User not found', ['uid' => $uid]);
852                         return [];
853                 }
854
855                 if (empty($files)) {
856                         Logger::notice('Empty upload file');
857                         return [];
858                 }
859
860                 if (!empty($files['tmp_name'])) {
861                         if (is_array($files['tmp_name'])) {
862                                 $src = $files['tmp_name'][0];
863                         } else {
864                                 $src = $files['tmp_name'];
865                         }
866                 } else {
867                         $src = '';
868                 }
869
870                 if (!empty($files['name'])) {
871                         if (is_array($files['name'])) {
872                                 $filename = basename($files['name'][0]);
873                         } else {
874                                 $filename = basename($files['name']);
875                         }
876                 } else {
877                         $filename = '';
878                 }
879
880                 if (!empty($files['size'])) {
881                         if (is_array($files['size'])) {
882                                 $filesize = intval($files['size'][0]);
883                         } else {
884                                 $filesize = intval($files['size']);
885                         }
886                 } else {
887                         $filesize = 0;
888                 }
889
890                 if (!empty($files['type'])) {
891                         if (is_array($files['type'])) {
892                                 $filetype = $files['type'][0];
893                         } else {
894                                 $filetype = $files['type'];
895                         }
896                 } else {
897                         $filetype = '';
898                 }
899
900                 if (empty($src)) {
901                         Logger::notice('No source file name', ['uid' => $uid, 'files' => $files]);
902                         return [];
903                 }
904
905                 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
906
907                 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
908
909                 $imagedata = @file_get_contents($src);
910                 $Image = new Image($imagedata, $filetype);
911                 if (!$Image->isValid()) {
912                         Logger::notice('Image is unvalid', ['uid' => $uid, 'files' => $files]);
913                         return [];
914                 }
915
916                 $Image->orient($src);
917                 @unlink($src);
918
919                 $max_length = DI::config()->get('system', 'max_image_length');
920                 if (!$max_length) {
921                         $max_length = MAX_IMAGE_LENGTH;
922                 }
923                 if ($max_length > 0) {
924                         $Image->scaleDown($max_length);
925                         $filesize = strlen($Image->asString());
926                         Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
927                 }
928
929                 $width = $Image->getWidth();
930                 $height = $Image->getHeight();
931
932                 $maximagesize = DI::config()->get('system', 'maximagesize');
933
934                 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
935                         // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
936                         foreach ([5120, 2560, 1280, 640] as $pixels) {
937                                 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
938                                         Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
939                                         $Image->scaleDown($pixels);
940                                         $filesize = strlen($Image->asString());
941                                         $width = $Image->getWidth();
942                                         $height = $Image->getHeight();
943                                 }
944                         }
945                         if ($filesize > $maximagesize) {
946                                 @unlink($src);
947                                 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
948                                 return [];
949                         }
950                 }
951
952                 $resource_id = Photo::newResource();
953                 $album       = DI::l10n()->t('Wall Photos');
954                 $defperm     = '<' . $user['id'] . '>';
955
956                 $smallest = 0;
957
958                 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, 0, $defperm);
959                 if (!$r) {
960                         Logger::notice('Photo could not be stored');
961                         return [];
962                 }
963
964                 if ($width > 640 || $height > 640) {
965                         $Image->scaleDown(640);
966                         $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, 0, $defperm);
967                         if ($r) {
968                                 $smallest = 1;
969                         }
970                 }
971
972                 if ($width > 320 || $height > 320) {
973                         $Image->scaleDown(320);
974                         $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, 0, $defperm);
975                         if ($r && ($smallest == 0)) {
976                                 $smallest = 2;
977                         }
978                 }
979
980                 $condition = ['resource-id' => $resource_id];
981                 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
982                 if (empty($photo)) {
983                         Logger::notice('Photo not found', ['condition' => $condition]);
984                         return [];
985                 }
986
987                 $picture = [];
988
989                 $picture['id']        = $photo['id'];
990                 $picture['size']      = $photo['datasize'];
991                 $picture['width']     = $photo['width'];
992                 $picture['height']    = $photo['height'];
993                 $picture['type']      = $photo['type'];
994                 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
995                 $picture['picture']   = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
996                 $picture['preview']   = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
997
998                 Logger::info('upload done', ['picture' => $picture]);
999                 return $picture;
1000         }
1001 }