3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Model;
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
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\Network;
40 use Friendica\Util\Proxy;
41 use Friendica\Util\Strings;
44 * Class to handle photo database table
48 const CONTACT_PHOTOS = 'Contact Photos';
49 const PROFILE_PHOTOS = 'Profile Photos';
50 const BANNER_PHOTOS = 'Banner Photos';
53 const USER_AVATAR = 10;
54 const USER_BANNER = 11;
55 const CONTACT_AVATAR = 20;
56 const CONTACT_BANNER = 21;
59 * Select rows from the photo table and returns them as array
61 * @param array $fields Array of selected fields, empty for all
62 * @param array $conditions Array of fields for conditions
63 * @param array $params Array of several parameters
65 * @return boolean|array
68 * @see \Friendica\Database\DBA::selectToArray
70 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
73 $fields = self::getFields();
76 return DBA::selectToArray('photo', $fields, $conditions, $params);
80 * Retrieve a single record from the photo table
82 * @param array $fields Array of selected fields, empty for all
83 * @param array $conditions Array of fields for conditions
84 * @param array $params Array of several parameters
89 * @see \Friendica\Database\DBA::select
91 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
94 $fields = self::getFields();
97 return DBA::selectFirst('photo', $fields, $conditions, $params);
101 * Get photos for user id
103 * @param integer $uid User id
104 * @param string $resourceid Resource ID of the photo
105 * @param array $conditions Array of fields for conditions
106 * @param array $params Array of several parameters
111 * @see \Friendica\Database\DBA::select
113 public static function getPhotosForUser(int $uid, string $resourceid, array $conditions = [], array $params = [])
115 $conditions['resource-id'] = $resourceid;
116 $conditions['uid'] = $uid;
118 return self::selectToArray([], $conditions, $params);
122 * Get a photo for user id
124 * @param integer $uid User id
125 * @param string $resourceid Resource ID of the photo
126 * @param integer $scale Scale of the photo. Defaults to 0
127 * @param array $conditions Array of fields for conditions
128 * @param array $params Array of several parameters
133 * @see \Friendica\Database\DBA::select
135 public static function getPhotoForUser(int $uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
137 $conditions['resource-id'] = $resourceid;
138 $conditions['uid'] = $uid;
139 $conditions['scale'] = $scale;
141 return self::selectFirst([], $conditions, $params);
145 * Get a single photo given resource id and scale
147 * This method checks for permissions. Returns associative array
148 * on success, "no sign" image info, if user has no permission,
149 * false if photo does not exists
151 * @param string $resourceid Resource ID of the photo
152 * @param integer $scale Scale of the photo. Defaults to 0
153 * @param integer $visitor_uid UID of the visitor
155 * @return boolean|array
158 public static function getPhoto(string $resourceid, int $scale = 0, int $visitor_uid = 0)
160 $r = self::selectFirst(['uid'], ['resource-id' => $resourceid]);
161 if (!DBA::isResult($r)) {
167 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
169 if (!empty($visitor_uid) && ($uid == $visitor_uid)) {
172 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
175 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
176 $params = ['order' => ['scale' => true]];
177 $photo = self::selectFirst([], $conditions, $params);
183 * Returns all browsable albums for a given user
185 * @param int $uid The given user
187 * @return array An array of albums
190 public static function getBrowsableAlbumsForUser(int $uid): array
192 $photos = DBA::toArray(
194 "SELECT DISTINCT(`album`) AS `album` FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?)",
196 static::CONTACT_AVATAR,
197 static::CONTACT_BANNER
201 return array_column($photos, 'album');
205 * Returns browsable photos for a given user (optional and a given album)
207 * @param int $uid The given user id
208 * @param string|null $album (optional) The given album
210 * @return array All photos of the user/album
213 public static function getBrowsablePhotosForUser(int $uid, string $album = null): array
217 Photo::CONTACT_AVATAR,
218 Photo::CONTACT_BANNER
221 if (!empty($album)) {
222 $sqlExtra = "AND `album` = ? ";
227 $sqlExtra2 = ' ORDER BY created DESC LIMIT 0, 10';
232 "SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
233 min(`scale`) AS `hiq`, max(`scale`) AS `loq`, ANY_VALUE(`desc`) AS `desc`, ANY_VALUE(`created`) AS `created`
234 FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) $sqlExtra
235 GROUP BY `resource-id` $sqlExtra2",
241 * Check if photo with given conditions exists
243 * @param array $conditions Array of extra conditions
248 public static function exists(array $conditions): bool
250 return DBA::exists('photo', $conditions);
255 * Get Image data for given row id. null if row id does not exist
257 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
259 * @return \Friendica\Object\Image|null Image object or null on error
261 public static function getImageDataForPhoto(array $photo)
263 if (!empty($photo['data'])) {
264 return $photo['data'];
268 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
269 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
270 return $backendClass->get($photo['backend-ref'] ?? '');
271 } catch (InvalidClassStorageException $storageException) {
273 // legacy data storage in "data" column
274 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
278 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
280 } catch (\Exception $exception) {
281 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
283 } catch (ReferenceStorageException $referenceStorageException) {
284 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
285 } catch (StorageException $storageException) {
286 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
287 } catch (\ImagickException $imagickException) {
288 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
295 * Get Image object for given row id. null if row id does not exist
297 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
299 * @return \Friendica\Object\Image
300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
301 * @throws \ImagickException
303 public static function getImageForPhoto(array $photo): Image
305 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
309 * Return a list of fields that are associated with the photo table
311 * @return array field list
314 private static function getFields(): array
316 $allfields = DI::dbaDefinition()->getAll();
317 $fields = array_keys($allfields['photo']['fields']);
318 array_splice($fields, array_search('data', $fields), 1);
323 * Construct a photo array for a given image data string
325 * @param string $image_data Image data
326 * @param string $mimetype Image mime type. Is guessed by file name when empty.
331 public static function createPhotoForImageData(string $image_data, string $mimetype = ''): array
333 $fields = self::getFields();
334 $values = array_fill(0, count($fields), '');
336 $photo = array_combine($fields, $values);
337 $photo['data'] = $image_data;
338 $photo['type'] = $mimetype ?: Images::getMimeTypeByData($image_data);
339 $photo['cacheable'] = false;
345 * Construct a photo array for a system resource image
347 * @param string $filename Image file name relative to code root
348 * @param string $mimetype Image mime type. Is guessed by file name when empty.
353 public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
355 if (empty($mimetype)) {
356 $mimetype = Images::guessTypeByExtension($filename);
359 $fields = self::getFields();
360 $values = array_fill(0, count($fields), '');
362 $photo = array_combine($fields, $values);
363 $photo['backend-class'] = SystemResource::NAME;
364 $photo['backend-ref'] = $filename;
365 $photo['type'] = $mimetype;
366 $photo['cacheable'] = false;
372 * Construct a photo array for an external resource image
374 * @param string $url Image URL
375 * @param int $uid User ID of the requesting person
376 * @param string $mimetype Image mime type. Is guessed by file name when empty.
377 * @param string $blurhash The blurhash that will be used to generate a picture when the original picture can't be fetched
378 * @param int $width Image width
379 * @param int $height Image height
384 public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = '', string $blurhash = null, int $width = null, int $height = null): array
386 if (empty($mimetype)) {
387 $mimetype = Images::guessTypeByExtension($url);
390 $fields = self::getFields();
391 $values = array_fill(0, count($fields), '');
393 $photo = array_combine($fields, $values);
394 $photo['backend-class'] = ExternalResource::NAME;
395 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
396 $photo['type'] = $mimetype;
397 $photo['cacheable'] = true;
398 $photo['blurhash'] = $blurhash;
399 $photo['width'] = $width;
400 $photo['height'] = $height;
406 * store photo metadata in db and binary in default backend
408 * @param Image $image Image object with data
409 * @param integer $uid User ID
410 * @param integer $cid Contact ID
411 * @param string $rid Resource ID
412 * @param string $filename Filename
413 * @param string $album Album name
414 * @param integer $scale Scale
415 * @param integer $type Photo type, optional, default: Photo::DEFAULT
416 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
417 * @param string $allow_gid Permissions, allowed circles. optional, default = ""
418 * @param string $deny_cid Permissions, denied contacts. optional, default = ""
419 * @param string $deny_gid Permissions, denied circle. optional, default = ""
420 * @param string $desc Photo caption. optional, default = ""
422 * @return boolean True on success
423 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 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
427 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
428 if (DBA::isResult($photo)) {
429 $guid = $photo['guid'];
431 $guid = System::createGUID();
434 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
435 $created = DateTimeFormat::utcNow();
436 if (DBA::isResult($existing_photo)) {
437 $created = $existing_photo['created'];
440 // Get defined storage backend.
441 // if no storage backend, we use old "data" column in photo table.
442 // if is an existing photo, reuse same backend
448 if (DBA::isResult($existing_photo)) {
449 $backend_ref = (string)$existing_photo['backend-ref'];
450 $storage = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
452 $storage = DI::storage();
454 $backend_ref = $storage->put($image->asString(), $backend_ref);
455 } catch (InvalidClassStorageException $storageException) {
456 $data = $image->asString();
461 'contact-id' => $cid,
463 'resource-id' => $rid,
464 'hash' => md5($image->asString()),
465 'created' => $created,
466 'edited' => DateTimeFormat::utcNow(),
467 'filename' => basename($filename),
468 'type' => $image->getType(),
470 'height' => $image->getHeight(),
471 'width' => $image->getWidth(),
472 'datasize' => strlen($image->asString()),
473 'blurhash' => $image->getBlurHash(),
476 'photo-type' => $type,
478 'allow_cid' => $allow_cid,
479 'allow_gid' => $allow_gid,
480 'deny_cid' => $deny_cid,
481 'deny_gid' => $deny_gid,
483 'backend-class' => (string)$storage,
484 'backend-ref' => $backend_ref
487 if (DBA::isResult($existing_photo)) {
488 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
490 $r = DBA::insert('photo', $fields);
498 * Delete info from table and data from storage
500 * @param array $conditions Field condition(s)
501 * @param array $options Options array, Optional
506 * @see \Friendica\Database\DBA::delete
508 public static function delete(array $conditions, array $options = []): bool
510 // get photo to delete data info
511 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
513 while ($photo = DBA::fetch($photos)) {
515 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
516 $backend_class->delete($photo['backend-ref'] ?? '');
517 // Delete the photos after they had been deleted successfully
518 DBA::delete('photo', ['id' => $photo['id']]);
519 } catch (InvalidClassStorageException $storageException) {
520 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
521 } catch (ReferenceStorageException $referenceStorageException) {
522 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
528 return DBA::delete('photo', $conditions, $options);
534 * @param array $fields Contains the fields that are updated
535 * @param array $conditions Condition array with the key values
536 * @param Image $image Image to update. Optional, default null.
537 * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
539 * @return boolean Was the update successful?
541 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
542 * @see \Friendica\Database\DBA::update
544 public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
546 if (!is_null($image)) {
547 // get photo to update
548 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
550 foreach($photos as $photo) {
552 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
553 $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
554 } catch (InvalidClassStorageException $storageException) {
555 $fields['data'] = $image->asString();
558 $fields['updated'] = DateTimeFormat::utcNow();
561 $fields['edited'] = DateTimeFormat::utcNow();
563 return DBA::update('photo', $fields, $conditions, $old_fields);
567 * @param string $image_url Remote URL
568 * @param integer $uid user id
569 * @param integer $cid contact id
570 * @param boolean $quit_on_error optional, default false
571 * @return array|bool Array on success, false on error
572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
573 * @throws \ImagickException
575 public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
580 $photo = DBA::selectFirst(
581 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
583 if (!empty($photo['resource-id'])) {
584 $resource_id = $photo['resource-id'];
586 $resource_id = self::newResource();
589 $photo_failure = false;
591 if (!Network::isValidHttpUrl($image_url)) {
592 Logger::warning('Invalid image url', ['image_url' => $image_url, 'uid' => $uid, 'cid' => $cid, 'callstack' => System::callstack(20)]);
596 $filename = basename($image_url);
597 if (!empty($image_url)) {
598 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
599 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
600 $img_str = $ret->getBody();
601 $type = $ret->getContentType();
607 if ($quit_on_error && ($img_str == '')) {
611 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
613 $image = new Image($img_str, $type);
614 if ($image->isValid()) {
615 $image->scaleToSquare(300);
617 $filesize = strlen($image->asString());
618 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
620 if ($maximagesize && ($filesize > $maximagesize)) {
621 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
622 if ($image->getType() == 'image/gif') {
624 $image = new Image($image->asString(), 'image/png');
626 $filesize = strlen($image->asString());
627 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
629 if ($filesize > $maximagesize) {
630 foreach ([160, 80] as $pixels) {
631 if ($filesize > $maximagesize) {
632 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
633 $image->scaleDown($pixels);
634 $filesize = strlen($image->asString());
638 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
641 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
644 $photo_failure = true;
647 $image->scaleDown(80);
649 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
652 $photo_failure = true;
655 $image->scaleDown(48);
657 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
660 $photo_failure = true;
663 $suffix = '?ts=' . time();
665 $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
666 $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
667 $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
669 $photo_failure = true;
672 if ($photo_failure && $quit_on_error) {
676 if ($photo_failure) {
677 $contact = Contact::getById($cid) ?: [];
678 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
679 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
680 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
683 $photo = DBA::selectFirst(
684 'photo', ['blurhash'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
687 return [$image_url, $thumb, $micro, $photo['blurhash']];
691 * Returns a float that represents the GPS coordinate from EXIF data
693 * @param array $exifCoord coordinate
694 * @param string $hemi hemi
697 public static function getGps(array $exifCoord, string $hemi): float
699 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
700 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
701 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
703 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
705 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
709 * Change GPS to float number
711 * @param string $coordPart coordPart
714 private static function gps2Num(string $coordPart): float
716 $parts = explode('/', $coordPart);
718 if (count($parts) <= 0) {
722 if (count($parts) == 1) {
723 return (float)$parts[0];
726 return floatval($parts[0]) / floatval($parts[1]);
730 * Fetch the photo albums that are available for a viewer
732 * The query in this function is cost intensive, so it is cached.
734 * @param int $uid User id of the photos
735 * @param bool $update Update the cache
737 * @return array Returns array of the photo albums
738 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
740 public static function getAlbums(int $uid, bool $update = false): array
742 $sql_extra = Security::getPermissionsSQLByUserId($uid);
744 $avatar_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
745 $banner_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_BANNER : self::DEFAULT;
747 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
748 $albums = DI::cache()->get($key);
750 if (is_null($albums) || $update) {
751 if (!DI::config()->get('system', 'no_count', false)) {
752 /// @todo This query needs to be renewed. It is really slow
753 // At this time we just store the data in the cache
754 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
756 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
757 GROUP BY `album` ORDER BY `created` DESC",
764 // This query doesn't do the count and is much faster
765 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
766 FROM `photo` USE INDEX (`uid_album_scale_created`)
767 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
774 DI::cache()->set($key, $albums, Duration::DAY);
780 * @param int $uid User id of the photos
784 public static function clearAlbumCache(int $uid)
786 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
787 DI::cache()->set($key, null, Duration::DAY);
791 * Generate a unique photo ID.
793 * @return string Resource GUID
796 public static function newResource(): string
798 return System::createGUID(32, false);
802 * Extracts the rid from a local photo URI
804 * @param string $image_uri The URI of the photo
805 * @return string The rid of the photo, or an empty string if the URI is not local
807 public static function ridFromURI(string $image_uri): string
809 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
812 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
813 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
814 return trim($image_uri);
818 * Checks if the given URL is a local photo.
819 * Since it is meant for time critical occasions, the check is done without any database requests.
824 public static function isPhotoURI(string $url): bool
826 return !empty(self::ridFromURI($url));
830 * Changes photo permissions that had been embedded in a post
832 * @todo This function currently does have some flaws:
833 * - Sharing a post with a group will create a photo that only the group can see.
834 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
839 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_circle_allow, $str_contact_deny, $str_circle_deny)
841 // Simplify image codes
842 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
843 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
846 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
850 if (empty($images)) {
854 foreach ($images as $image) {
855 $image_rid = self::ridFromURI($image);
856 if (empty($image_rid)) {
860 // Ensure to only modify photos that you own
861 $srch = '<' . intval($original_contact_id) . '>';
864 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
865 'resource-id' => $image_rid, 'uid' => $uid
867 if (!self::exists($condition)) {
868 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
869 if (!DBA::isResult($photo)) {
870 Logger::info('Image not found', ['resource-id' => $image_rid]);
872 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
878 * @todo Existing permissions need to be mixed with the new ones.
879 * Otherwise this creates problems with sharing the same picture multiple times
880 * Also check if $str_contact_allow does contain a public group.
881 * Then set the permissions to public.
884 self::setPermissionForResource($image_rid, $uid, $str_contact_allow, $str_circle_allow, $str_contact_deny, $str_circle_deny);
891 * Add permissions to photo resource
892 * @todo mix with previous photo permissions
894 * @param string $image_rid
895 * @param integer $uid
896 * @param string $str_contact_allow
897 * @param string $str_circle_allow
898 * @param string $str_contact_deny
899 * @param string $str_circle_deny
902 public static function setPermissionForResource(string $image_rid, int $uid, string $str_contact_allow, string $str_circle_allow, string $str_contact_deny, string $str_circle_deny)
904 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_circle_allow,
905 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_circle_deny,
906 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
908 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
909 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
910 self::update($fields, $condition);
914 * Fetch the guid and scale from picture links
916 * @param string $name Picture link
919 public static function getResourceData(string $name): array
921 $guid = str_replace([Strings::normaliseLink((string)DI::baseUrl()), '/photo/'], '', Strings::normaliseLink($name));
923 if (parse_url($guid, PHP_URL_SCHEME)) {
927 $guid = pathinfo($guid, PATHINFO_FILENAME);
928 if (substr($guid, -2, 1) != "-") {
932 $scale = intval(substr($guid, -1, 1));
933 if (!is_numeric($scale)) {
937 $guid = substr($guid, 0, -2);
938 return ['guid' => $guid, 'scale' => $scale];
942 * Tests if the picture link points to a locally stored picture
944 * @param string $name Picture link
948 public static function isLocal(string $name): bool
950 // @TODO Maybe a proper check here on true condition?
951 return (bool)self::getIdForName($name);
955 * Return the id of a local photo
957 * @param string $name Picture link
960 public static function getIdForName(string $name): int
962 $data = self::getResourceData($name);
967 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
968 if (!empty($photo['id'])) {
975 * Tests if the link points to a locally stored picture page
977 * @param string $name Page link
981 public static function isLocalPage(string $name): bool
983 $guid = str_replace(Strings::normaliseLink((string)DI::baseUrl()), '', Strings::normaliseLink($name));
984 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
989 return DBA::exists('photo', ['resource-id' => $guid]);
993 * Resize to a given maximum file size
995 * @param Image $image
996 * @param integer $maximagesize
999 public static function resizeToFileSize(Image $image, int $maximagesize): Image
1001 $filesize = strlen($image->asString());
1002 $width = $image->getWidth();
1003 $height = $image->getHeight();
1005 if ($maximagesize && ($filesize > $maximagesize)) {
1006 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
1007 foreach ([5120, 2560, 1280, 640, 320] as $pixels) {
1008 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
1009 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1010 $image->scaleDown($pixels);
1011 $filesize = strlen($image->asString());
1012 $width = $image->getWidth();
1013 $height = $image->getHeight();
1022 * Tries to resize image to wanted maximum size
1024 * @param Image $image Image instance
1025 * @return Image|null Image instance on success, null on error
1027 private static function fitImageSize(Image $image)
1029 $max_length = DI::config()->get('system', 'max_image_length');
1030 if ($max_length > 0) {
1031 $image->scaleDown($max_length);
1032 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
1035 return self::resizeToFileSize($image, Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize')));
1039 * Fetches image from URL and returns an array with instance and local file name
1041 * @param string $image_url URL to image
1042 * @return array With: 'image' and 'filename' fields or empty array on error
1044 private static function loadImageFromURL(string $image_url): array
1046 $filename = basename($image_url);
1047 if (!empty($image_url)) {
1048 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
1049 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
1050 $img_str = $ret->getBody();
1051 $type = $ret->getContentType();
1057 if (empty($img_str)) {
1058 Logger::notice('Empty content');
1062 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1064 $image = new Image($img_str, $type);
1066 $image = self::fitImageSize($image);
1067 if (empty($image)) {
1071 return ['image' => $image, 'filename' => $filename];
1075 * Inserts uploaded image into database and removes local temporary file
1077 * @param array $files File array
1078 * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1080 private static function uploadImage(array $files): array
1082 Logger::info('starting new upload');
1084 if (empty($files)) {
1085 Logger::notice('Empty upload file');
1089 if (!empty($files['tmp_name'])) {
1090 if (is_array($files['tmp_name'])) {
1091 $src = $files['tmp_name'][0];
1093 $src = $files['tmp_name'];
1099 if (!empty($files['name'])) {
1100 if (is_array($files['name'])) {
1101 $filename = basename($files['name'][0]);
1103 $filename = basename($files['name']);
1109 if (!empty($files['size'])) {
1110 if (is_array($files['size'])) {
1111 $filesize = intval($files['size'][0]);
1113 $filesize = intval($files['size']);
1119 if (!empty($files['type'])) {
1120 if (is_array($files['type'])) {
1121 $filetype = $files['type'][0];
1123 $filetype = $files['type'];
1130 Logger::notice('No source file name', ['files' => $files]);
1134 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1136 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1138 $imagedata = @file_get_contents($src);
1139 $image = new Image($imagedata, $filetype);
1140 if (!$image->isValid()) {
1141 Logger::notice('Image is unvalid', ['files' => $files]);
1145 $image->orient($src);
1148 $image = self::fitImageSize($image);
1149 if (empty($image)) {
1153 return ['image' => $image, 'filename' => $filename, 'size' => $filesize];
1157 * Handles uploaded image and assigns it to given user id
1159 * @param int $uid User ID
1160 * @param array $files uploaded file array
1161 * @param string $album Album name (optional)
1162 * @param string|null $allow_cid
1163 * @param string|null $allow_gid
1164 * @param string $deny_cid
1165 * @param string $deny_gid
1166 * @param string $desc Description (optional)
1167 * @param string $resource_id GUID (optional)
1168 * @return array photo record or empty array on error
1169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1171 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
1173 $user = User::getOwnerDataById($uid);
1175 Logger::notice('User not found', ['uid' => $uid]);
1179 $data = self::uploadImage($files);
1181 Logger::info('upload failed');
1185 $image = $data['image'];
1186 $filename = $data['filename'];
1187 $filesize = $data['size'];
1189 $resource_id = $resource_id ?: self::newResource();
1190 $album = $album ?: DI::l10n()->t('Wall Photos');
1192 if (is_null($allow_cid) && is_null($allow_gid)) {
1193 $allow_cid = '<' . $user['id'] . '>';
1197 $preview = self::storeWithPreview($image, $user['uid'], $resource_id, $filename, $filesize, $album, $desc, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
1199 Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1203 $condition = ['resource-id' => $resource_id];
1204 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1205 if (empty($photo)) {
1206 Logger::notice('Photo not found', ['condition' => $condition]);
1212 $picture['id'] = $photo['id'];
1213 $picture['resource_id'] = $resource_id;
1214 $picture['size'] = $photo['datasize'];
1215 $picture['width'] = $photo['width'];
1216 $picture['height'] = $photo['height'];
1217 $picture['type'] = $photo['type'];
1218 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1219 $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1220 $picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $preview . '.' . $image->getExt();
1222 Logger::info('upload done', ['picture' => $picture]);
1227 * store photo metadata in db and binary with preview photos in default backend
1229 * @param Image $image Image object with data
1230 * @param integer $uid User ID
1231 * @param string $resource_id Resource ID
1232 * @param string $filename Filename
1233 * @param integer $filesize Filesize
1234 * @param string $album Album name
1235 * @param string $description Photo caption
1236 * @param string $allow_cid Permissions, allowed contacts
1237 * @param string $allow_gid Permissions, allowed circles
1238 * @param string $deny_cid Permissions, denied contacts
1239 * @param string $deny_gid Permissions, denied circles
1241 * @return integer preview photo size
1242 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1244 public static function storeWithPreview(Image $image, int $uid, string $resource_id, string $filename, int $filesize, string $album, string $description, string $allow_cid, string $allow_gid, string $deny_cid, string $deny_gid): int
1246 $image = self::resizeToFileSize($image, Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize')));
1248 $width = $image->getWidth();
1249 $height = $image->getHeight();
1252 $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
1254 Logger::warning('Photo could not be stored', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1258 if ($width > 640 || $height > 640) {
1259 $image->scaleDown(640);
1262 if ($width > 320 || $height > 320) {
1263 $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
1267 $image->scaleDown(320);
1268 $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
1269 if ($result && ($preview == 0)) {
1277 * Upload a user avatar
1279 * @param int $uid User ID
1280 * @param array $files uploaded file array
1281 * @param string $url External image url
1282 * @return string avatar resource
1284 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1286 if (!empty($files)) {
1287 $data = self::uploadImage($files);
1289 Logger::info('upload failed');
1292 } elseif (!empty($url)) {
1293 $data = self::loadImageFromURL($url);
1295 Logger::info('loading from external url failed');
1299 Logger::info('Neither files nor url provided');
1303 $image = $data['image'];
1304 $filename = $data['filename'];
1305 $width = $image->getWidth();
1306 $height = $image->getHeight();
1308 $resource_id = self::newResource();
1309 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1311 // upload profile image (scales 4, 5, 6)
1312 logger::info('starting new profile image upload');
1314 if ($width > 300 || $height > 300) {
1315 $image->scaleDown(300);
1318 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1320 logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1323 if ($width > 80 || $height > 80) {
1324 $image->scaleDown(80);
1327 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1329 logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1332 if ($width > 48 || $height > 48) {
1333 $image->scaleDown(48);
1336 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1338 logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1341 logger::info('new profile image upload ended');
1343 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1344 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1346 Contact::updateSelfFromUserID($uid, true);
1348 // Update global directory in background
1349 Profile::publishUpdate($uid);
1351 return $resource_id;
1355 * Upload a user banner
1357 * @param int $uid User ID
1358 * @param array $files uploaded file array
1359 * @param string $url External image url
1360 * @return string avatar resource
1362 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1364 if (!empty($files)) {
1365 $data = self::uploadImage($files);
1367 Logger::info('upload failed');
1370 } elseif (!empty($url)) {
1371 $data = self::loadImageFromURL($url);
1373 Logger::info('loading from external url failed');
1377 Logger::info('Neither files nor url provided');
1381 $image = $data['image'];
1382 $filename = $data['filename'];
1383 $width = $image->getWidth();
1384 $height = $image->getHeight();
1386 $resource_id = self::newResource();
1387 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1390 $image->scaleDown(960);
1393 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1395 logger::warning('profile banner upload with scale 3 (960) failed');
1398 logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
1400 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1401 self::update(['photo-type' => self::DEFAULT], $condition);
1403 Contact::updateSelfFromUserID($uid, true);
1405 // Update global directory in background
1406 Profile::publishUpdate($uid);
1408 return $resource_id;