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