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 dabatase 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 Rescource 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 Rescource 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 Rescource 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 groups. optional, default = ""
418 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
419 * @param string $deny_gid Permissions, denied greoup.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 successfull?
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 forum will create a photo that only the forum 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_group_allow, $str_contact_deny, $str_group_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 forum.
881 * Then set the permissions to public.
884 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
891 * Add permissions to photo ressource
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_group_allow
898 * @param string $str_contact_deny
899 * @param string $str_group_deny
902 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)
904 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
905 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_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 $base = DI::baseUrl()->get();
923 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
925 if (parse_url($guid, PHP_URL_SCHEME)) {
929 $guid = pathinfo($guid, PATHINFO_FILENAME);
930 if (substr($guid, -2, 1) != "-") {
934 $scale = intval(substr($guid, -1, 1));
935 if (!is_numeric($scale)) {
939 $guid = substr($guid, 0, -2);
940 return ['guid' => $guid, 'scale' => $scale];
944 * Tests if the picture link points to a locally stored picture
946 * @param string $name Picture link
950 public static function isLocal(string $name): bool
952 // @TODO Maybe a proper check here on true condition?
953 return (bool)self::getIdForName($name);
957 * Return the id of a local photo
959 * @param string $name Picture link
962 public static function getIdForName(string $name): int
964 $data = self::getResourceData($name);
969 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
970 if (!empty($photo['id'])) {
977 * Tests if the link points to a locally stored picture page
979 * @param string $name Page link
983 public static function isLocalPage(string $name): bool
985 $base = DI::baseUrl()->get();
987 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
988 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
993 return DBA::exists('photo', ['resource-id' => $guid]);
997 * Tries to resize image to wanted maximum size
999 * @param Image $image Image instance
1000 * @return Image|null Image instance on success, null on error
1002 private static function fitImageSize(Image $image)
1004 $max_length = DI::config()->get('system', 'max_image_length');
1005 if ($max_length > 0) {
1006 $image->scaleDown($max_length);
1007 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
1010 $filesize = strlen($image->asString());
1011 $width = $image->getWidth();
1012 $height = $image->getHeight();
1014 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
1016 if ($maximagesize && ($filesize > $maximagesize)) {
1017 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
1018 foreach ([5120, 2560, 1280, 640] as $pixels) {
1019 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
1020 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1021 $image->scaleDown($pixels);
1022 $filesize = strlen($image->asString());
1023 $width = $image->getWidth();
1024 $height = $image->getHeight();
1027 if ($filesize > $maximagesize) {
1028 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1037 * Fetches image from URL and returns an array with instance and local file name
1039 * @param string $image_url URL to image
1040 * @return array With: 'image' and 'filename' fields or empty array on error
1042 private static function loadImageFromURL(string $image_url): array
1044 $filename = basename($image_url);
1045 if (!empty($image_url)) {
1046 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
1047 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
1048 $img_str = $ret->getBody();
1049 $type = $ret->getContentType();
1055 if (empty($img_str)) {
1056 Logger::notice('Empty content');
1060 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1062 $image = new Image($img_str, $type);
1064 $image = self::fitImageSize($image);
1065 if (empty($image)) {
1069 return ['image' => $image, 'filename' => $filename];
1073 * Inserts uploaded image into database and removes local temporary file
1075 * @param array $files File array
1076 * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1078 private static function uploadImage(array $files): array
1080 Logger::info('starting new upload');
1082 if (empty($files)) {
1083 Logger::notice('Empty upload file');
1087 if (!empty($files['tmp_name'])) {
1088 if (is_array($files['tmp_name'])) {
1089 $src = $files['tmp_name'][0];
1091 $src = $files['tmp_name'];
1097 if (!empty($files['name'])) {
1098 if (is_array($files['name'])) {
1099 $filename = basename($files['name'][0]);
1101 $filename = basename($files['name']);
1107 if (!empty($files['size'])) {
1108 if (is_array($files['size'])) {
1109 $filesize = intval($files['size'][0]);
1111 $filesize = intval($files['size']);
1117 if (!empty($files['type'])) {
1118 if (is_array($files['type'])) {
1119 $filetype = $files['type'][0];
1121 $filetype = $files['type'];
1128 Logger::notice('No source file name', ['files' => $files]);
1132 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1134 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1136 $imagedata = @file_get_contents($src);
1137 $image = new Image($imagedata, $filetype);
1138 if (!$image->isValid()) {
1139 Logger::notice('Image is unvalid', ['files' => $files]);
1143 $image->orient($src);
1146 $image = self::fitImageSize($image);
1147 if (empty($image)) {
1151 return ['image' => $image, 'filename' => $filename];
1155 * Handles uploaded image and assigns it to given user id
1157 * @param int $uid User ID
1158 * @param array $files uploaded file array
1159 * @param string $album Album name (optional)
1160 * @param string|null $allow_cid
1161 * @param string|null $allow_gid
1162 * @param string $deny_cid
1163 * @param string $deny_gid
1164 * @param string $desc Description (optional)
1165 * @param string $resource_id GUID (optional)
1166 * @return array photo record or empty array on error
1167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1169 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
1171 $user = User::getOwnerDataById($uid);
1173 Logger::notice('User not found', ['uid' => $uid]);
1177 $data = self::uploadImage($files);
1179 Logger::info('upload failed');
1183 $image = $data['image'];
1184 $filename = $data['filename'];
1185 $width = $image->getWidth();
1186 $height = $image->getHeight();
1188 $resource_id = $resource_id ?: self::newResource();
1189 $album = $album ?: DI::l10n()->t('Wall Photos');
1191 if (is_null($allow_cid) && is_null($allow_gid)) {
1192 $allow_cid = '<' . $user['id'] . '>';
1198 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1200 Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1204 if ($width > 640 || $height > 640) {
1205 $image->scaleDown(640);
1206 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1212 if ($width > 320 || $height > 320) {
1213 $image->scaleDown(320);
1214 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1215 if ($r && ($smallest == 0)) {
1220 $condition = ['resource-id' => $resource_id];
1221 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1222 if (empty($photo)) {
1223 Logger::notice('Photo not found', ['condition' => $condition]);
1229 $picture['id'] = $photo['id'];
1230 $picture['resource_id'] = $resource_id;
1231 $picture['size'] = $photo['datasize'];
1232 $picture['width'] = $photo['width'];
1233 $picture['height'] = $photo['height'];
1234 $picture['type'] = $photo['type'];
1235 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1236 $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1237 $picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $smallest . '.' . $image->getExt();
1239 Logger::info('upload done', ['picture' => $picture]);
1244 * Upload a user avatar
1246 * @param int $uid User ID
1247 * @param array $files uploaded file array
1248 * @param string $url External image url
1249 * @return string avatar resource
1251 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1253 if (!empty($files)) {
1254 $data = self::uploadImage($files);
1256 Logger::info('upload failed');
1259 } elseif (!empty($url)) {
1260 $data = self::loadImageFromURL($url);
1262 Logger::info('loading from external url failed');
1266 Logger::info('Neither files nor url provided');
1270 $image = $data['image'];
1271 $filename = $data['filename'];
1272 $width = $image->getWidth();
1273 $height = $image->getHeight();
1275 $resource_id = self::newResource();
1276 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1278 // upload profile image (scales 4, 5, 6)
1279 logger::info('starting new profile image upload');
1281 if ($width > 300 || $height > 300) {
1282 $image->scaleDown(300);
1285 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1287 logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1290 if ($width > 80 || $height > 80) {
1291 $image->scaleDown(80);
1294 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1296 logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1299 if ($width > 48 || $height > 48) {
1300 $image->scaleDown(48);
1303 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1305 logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1308 logger::info('new profile image upload ended');
1310 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1311 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1313 Contact::updateSelfFromUserID($uid, true);
1315 // Update global directory in background
1316 Profile::publishUpdate($uid);
1318 return $resource_id;
1322 * Upload a user banner
1324 * @param int $uid User ID
1325 * @param array $files uploaded file array
1326 * @param string $url External image url
1327 * @return string avatar resource
1329 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1331 if (!empty($files)) {
1332 $data = self::uploadImage($files);
1334 Logger::info('upload failed');
1337 } elseif (!empty($url)) {
1338 $data = self::loadImageFromURL($url);
1340 Logger::info('loading from external url failed');
1344 Logger::info('Neither files nor url provided');
1348 $image = $data['image'];
1349 $filename = $data['filename'];
1350 $width = $image->getWidth();
1351 $height = $image->getHeight();
1353 $resource_id = self::newResource();
1354 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1357 $image->scaleDown(960);
1360 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1362 logger::warning('profile banner upload with scale 3 (960) failed');
1365 logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
1367 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1368 self::update(['photo-type' => self::DEFAULT], $condition);
1370 Contact::updateSelfFromUserID($uid, true);
1372 // Update global directory in background
1373 Profile::publishUpdate($uid);
1375 return $resource_id;