]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Photo.php
spelling: activity
[friendica.git] / src / Model / Photo.php
index b2a815c839b8c516f1792afcef1279a886fdfc15..96c82b0c17d84c0cc095e8872b919cafee805be3 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2022, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -25,7 +25,6 @@ use Friendica\Core\Cache\Enum\Duration;
 use Friendica\Core\Logger;
 use Friendica\Core\System;
 use Friendica\Database\DBA;
-use Friendica\Database\DBStructure;
 use Friendica\DI;
 use Friendica\Core\Storage\Type\ExternalResource;
 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
@@ -37,6 +36,7 @@ use Friendica\Object\Image;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Images;
 use Friendica\Security\Security;
+use Friendica\Util\Network;
 use Friendica\Util\Proxy;
 use Friendica\Util\Strings;
 
@@ -148,13 +148,14 @@ class Photo
         * on success, "no sign" image info, if user has no permission,
         * false if photo does not exists
         *
-        * @param string  $resourceid Rescource ID of the photo
-        * @param integer $scale      Scale of the photo. Defaults to 0
+        * @param string  $resourceid  Rescource ID of the photo
+        * @param integer $scale       Scale of the photo. Defaults to 0
+        * @param integer $visitor_uid UID of the visitor
         *
         * @return boolean|array
         * @throws \Exception
         */
-       public static function getPhoto(string $resourceid, int $scale = 0)
+       public static function getPhoto(string $resourceid, int $scale = 0, int $visitor_uid = 0)
        {
                $r = self::selectFirst(['uid'], ['resource-id' => $resourceid]);
                if (!DBA::isResult($r)) {
@@ -165,15 +166,77 @@ class Photo
 
                $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
 
-               $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
+               if (!empty($visitor_uid) && ($uid == $visitor_uid)) {
+                       $sql_acl = '';
+               } else {
+                       $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
+               }
 
-               $conditions = ['`resource-id` = ? AND `scale` <= ? ' . $sql_acl, $resourceid, $scale];
+               $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
                $params = ['order' => ['scale' => true]];
                $photo = self::selectFirst([], $conditions, $params);
 
                return $photo;
        }
 
+       /**
+        * Returns all browsable albums for a given user
+        *
+        * @param int $uid The given user
+        *
+        * @return array An array of albums
+        * @throws \Exception
+        */
+       public static function getBrowsableAlbumsForUser(int $uid): array
+       {
+               $photos = DBA::toArray(
+                       DBA::p(
+                               "SELECT DISTINCT(`album`) AS `album` FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?)",
+                               $uid,
+                               static::CONTACT_AVATAR,
+                               static::CONTACT_BANNER
+                       )
+               );
+
+               return array_column($photos, 'album');
+       }
+
+       /**
+        * Returns browsable photos for a given user (optional and a given album)
+        *
+        * @param int         $uid   The given user id
+        * @param string|null $album (optional) The given album
+        *
+        * @return array All photos of the user/album
+        * @throws \Exception
+        */
+       public static function getBrowsablePhotosForUser(int $uid, string $album = null): array
+       {
+               $values = [
+                       $uid,
+                       Photo::CONTACT_AVATAR,
+                       Photo::CONTACT_BANNER
+               ];
+
+               if (!empty($album)) {
+                       $sqlExtra  = "AND `album` = ? ";
+                       $values[] = $album;
+                       $sqlExtra2 = "";
+               } else {
+                       $sqlExtra  = '';
+                       $sqlExtra2 = ' ORDER BY created DESC LIMIT 0, 10';
+               }
+
+               return DBA::toArray(
+                       DBA::p(
+                               "SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
+                                       min(`scale`) AS `hiq`, max(`scale`) AS `loq`, ANY_VALUE(`desc`) AS `desc`, ANY_VALUE(`created`) AS `created`
+                                       FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) $sqlExtra
+                                       GROUP BY `resource-id` $sqlExtra2",
+                               $values
+                       ));
+       }
+
        /**
         * Check if photo with given conditions exists
         *
@@ -250,12 +313,34 @@ class Photo
         */
        private static function getFields(): array
        {
-               $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
+               $allfields = DI::dbaDefinition()->getAll();
                $fields = array_keys($allfields['photo']['fields']);
                array_splice($fields, array_search('data', $fields), 1);
                return $fields;
        }
 
+       /**
+        * Construct a photo array for a given image data string
+        *
+        * @param string $image_data Image data
+        * @param string $mimetype   Image mime type. Is guessed by file name when empty.
+        *
+        * @return array
+        * @throws \Exception
+        */
+       public static function createPhotoForImageData(string $image_data, string $mimetype = ''): array
+       {
+               $fields = self::getFields();
+               $values = array_fill(0, count($fields), '');
+
+               $photo                  = array_combine($fields, $values);
+               $photo['data']          = $image_data;
+               $photo['type']          = $mimetype ?: Images::getMimeTypeByData($image_data);
+               $photo['cacheable']     = false;
+
+               return $photo;
+       }
+
        /**
         * Construct a photo array for a system resource image
         *
@@ -289,11 +374,14 @@ class Photo
         * @param string $url      Image URL
         * @param int    $uid      User ID of the requesting person
         * @param string $mimetype Image mime type. Is guessed by file name when empty.
+        * @param string $blurhash The blurhash that will be used to generate a picture when the original picture can't be fetched
+        * @param int    $width    Image width
+        * @param int    $height   Image height
         *
         * @return array
         * @throws \Exception
         */
-       public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = ''): array
+       public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = '', string $blurhash = null, int $width = null, int $height = null): array
        {
                if (empty($mimetype)) {
                        $mimetype = Images::guessTypeByExtension($url);
@@ -307,6 +395,9 @@ class Photo
                $photo['backend-ref']   = json_encode(['url' => $url, 'uid' => $uid]);
                $photo['type']          = $mimetype;
                $photo['cacheable']     = true;
+               $photo['blurhash']      = $blurhash;
+               $photo['width']         = $width;
+               $photo['height']        = $height;
 
                return $photo;
        }
@@ -317,11 +408,11 @@ class Photo
         * @param Image   $image     Image object with data
         * @param integer $uid       User ID
         * @param integer $cid       Contact ID
-        * @param integer $rid       Resource ID
+        * @param string  $rid       Resource ID
         * @param string  $filename  Filename
         * @param string  $album     Album name
         * @param integer $scale     Scale
-        * @param integer $type      Photo type
+        * @param integer $type      Photo type, optional, default: Photo::DEFAULT
         * @param string  $allow_cid Permissions, allowed contacts. optional, default = ""
         * @param string  $allow_gid Permissions, allowed groups. optional, default = ""
         * @param string  $deny_cid  Permissions, denied contacts.optional, default = ""
@@ -331,9 +422,9 @@ class Photo
         * @return boolean True on success
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       public static function store(Image $image, int $uid, int $cid, int $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
+       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
        {
-               $photo = self::selectFirst(['guid'], ['`resource-id` = ? AND `guid` != ?', $rid, '']);
+               $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
                if (DBA::isResult($photo)) {
                        $guid = $photo['guid'];
                } else {
@@ -379,6 +470,7 @@ class Photo
                        'height' => $image->getHeight(),
                        'width' => $image->getWidth(),
                        'datasize' => strlen($image->asString()),
+                       'blurhash' => $image->getBlurHash(),
                        'data' => $data,
                        'scale' => $scale,
                        'photo-type' => $type,
@@ -476,7 +568,7 @@ class Photo
         * @param integer $uid           user id
         * @param integer $cid           contact id
         * @param boolean $quit_on_error optional, default false
-        * @return array
+        * @return array|bool Array on success, false on error
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         * @throws \ImagickException
         */
@@ -496,6 +588,11 @@ class Photo
 
                $photo_failure = false;
 
+               if (!Network::isValidHttpUrl($image_url)) {
+                       Logger::warning('Invalid image url', ['image_url' => $image_url, 'uid' => $uid, 'cid' => $cid, 'callstack' => System::callstack(20)]);
+                       return false;
+               }
+
                $filename = basename($image_url);
                if (!empty($image_url)) {
                        $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
@@ -518,8 +615,9 @@ class Photo
                        $image->scaleToSquare(300);
 
                        $filesize = strlen($image->asString());
-                       $maximagesize = DI::config()->get('system', 'maximagesize');
-                       if (!empty($maximagesize) && ($filesize > $maximagesize)) {
+                       $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
+
+                       if ($maximagesize && ($filesize > $maximagesize)) {
                                Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
                                if ($image->getType() == 'image/gif') {
                                        $image->toStatic();
@@ -582,15 +680,21 @@ class Photo
                        $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
                }
 
-               return [$image_url, $thumb, $micro];
+               $photo = DBA::selectFirst(
+                       'photo', ['blurhash'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
+               );
+
+               return [$image_url, $thumb, $micro, $photo['blurhash']];
        }
 
        /**
+        * Returns a float that represents the GPS coordinate from EXIF data
+        *
         * @param array $exifCoord coordinate
         * @param string $hemi      hemi
         * @return float
         */
-       public static function getGps(array $exifCoord, strinf $hemi): float
+       public static function getGps(array $exifCoord, string $hemi): float
        {
                $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
                $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
@@ -637,10 +741,10 @@ class Photo
        {
                $sql_extra = Security::getPermissionsSQLByUserId($uid);
 
-               $avatar_type = (local_user() && (local_user() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
-               $banner_type = (local_user() && (local_user() == $uid)) ? self::USER_BANNER : self::DEFAULT;
+               $avatar_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
+               $banner_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_BANNER : self::DEFAULT;
 
-               $key = 'photo_albums:' . $uid . ':' . local_user() . ':' . remote_user();
+               $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
                $albums = DI::cache()->get($key);
 
                if (is_null($albums) || $update) {
@@ -679,7 +783,7 @@ class Photo
         */
        public static function clearAlbumCache(int $uid)
        {
-               $key = 'photo_albums:' . $uid . ':' . local_user() . ':' . remote_user();
+               $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
                DI::cache()->set($key, null, Duration::DAY);
        }
 
@@ -814,7 +918,7 @@ class Photo
         */
        public static function getResourceData(string $name): array
        {
-               $base = DI::baseUrl()->get();
+               $base = DI::baseUrl();
 
                $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
 
@@ -878,7 +982,7 @@ class Photo
         */
        public static function isLocalPage(string $name): bool
        {
-               $base = DI::baseUrl()->get();
+               $base = DI::baseUrl();
 
                $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
                $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
@@ -907,9 +1011,9 @@ class Photo
                $width    = $image->getWidth();
                $height   = $image->getHeight();
 
-               $maximagesize = DI::config()->get('system', 'maximagesize');
+               $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
 
-               if (!empty($maximagesize) && ($filesize > $maximagesize)) {
+               if ($maximagesize && ($filesize > $maximagesize)) {
                        // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
                        foreach ([5120, 2560, 1280, 640] as $pixels) {
                                if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
@@ -1093,7 +1197,7 @@ class Photo
 
                $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                if (!$r) {
-                       Logger::notice('Photo could not be stored');
+                       Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
                        return [];
                }
 
@@ -1129,8 +1233,8 @@ class Photo
                $picture['height']      = $photo['height'];
                $picture['type']        = $photo['type'];
                $picture['albumpage']   = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
-               $picture['picture']     = DI::baseUrl() . '/photo/{$resource_id}-0.' . $image->getExt();
-               $picture['preview']     = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $image->getExt();
+               $picture['picture']     = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
+               $picture['preview']     = DI::baseUrl() . '/photo/' . $resource_id . '-' . $smallest . '.' . $image->getExt();
 
                Logger::info('upload done', ['picture' => $picture]);
                return $picture;
@@ -1180,7 +1284,7 @@ class Photo
 
                $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
                if (!$r) {
-                       logger::notice('profile image upload with scale 4 (300) failed');
+                       logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
                }
 
                if ($width > 80 || $height > 80) {
@@ -1189,7 +1293,7 @@ class Photo
 
                $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
                if (!$r) {
-                       logger::notice('profile image upload with scale 5 (80) failed');
+                       logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
                }
 
                if ($width > 48 || $height > 48) {
@@ -1198,7 +1302,7 @@ class Photo
 
                $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
                if (!$r) {
-                       logger::notice('profile image upload with scale 6 (48) failed');
+                       logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
                }
 
                logger::info('new profile image upload ended');
@@ -1255,10 +1359,10 @@ class Photo
 
                $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
                if (!$r) {
-                       logger::notice('profile banner upload with scale 3 (960) failed');
+                       logger::warning('profile banner upload with scale 3 (960) failed');
                }
 
-               logger::info('new profile banner upload ended');
+               logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
 
                $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
                self::update(['photo-type' => self::DEFAULT], $condition);
@@ -1271,4 +1375,3 @@ class Photo
                return $resource_id;
        }
 }
-