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