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