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