3 * @copyright Copyright (C) 2010-2022, 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\Proxy;
40 use Friendica\Util\Strings;
43 * Class to handle photo dabatase table
47 const CONTACT_PHOTOS = 'Contact Photos';
48 const PROFILE_PHOTOS = 'Profile Photos';
49 const BANNER_PHOTOS = 'Banner Photos';
52 const USER_AVATAR = 10;
53 const USER_BANNER = 11;
54 const CONTACT_AVATAR = 20;
55 const CONTACT_BANNER = 21;
58 * Select rows from the photo table and returns them as array
60 * @param array $fields Array of selected fields, empty for all
61 * @param array $conditions Array of fields for conditions
62 * @param array $params Array of several parameters
64 * @return boolean|array
67 * @see \Friendica\Database\DBA::selectToArray
69 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
72 $fields = self::getFields();
75 return DBA::selectToArray('photo', $fields, $conditions, $params);
79 * Retrieve a single record from the photo table
81 * @param array $fields Array of selected fields, empty for all
82 * @param array $conditions Array of fields for conditions
83 * @param array $params Array of several parameters
88 * @see \Friendica\Database\DBA::select
90 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
93 $fields = self::getFields();
96 return DBA::selectFirst('photo', $fields, $conditions, $params);
100 * Get photos for user id
102 * @param integer $uid User id
103 * @param string $resourceid Rescource ID of the photo
104 * @param array $conditions Array of fields for conditions
105 * @param array $params Array of several parameters
110 * @see \Friendica\Database\DBA::select
112 public static function getPhotosForUser(int $uid, string $resourceid, array $conditions = [], array $params = [])
114 $conditions['resource-id'] = $resourceid;
115 $conditions['uid'] = $uid;
117 return self::selectToArray([], $conditions, $params);
121 * Get a photo for user id
123 * @param integer $uid User id
124 * @param string $resourceid Rescource ID of the photo
125 * @param integer $scale Scale of the photo. Defaults to 0
126 * @param array $conditions Array of fields for conditions
127 * @param array $params Array of several parameters
132 * @see \Friendica\Database\DBA::select
134 public static function getPhotoForUser(int $uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
136 $conditions['resource-id'] = $resourceid;
137 $conditions['uid'] = $uid;
138 $conditions['scale'] = $scale;
140 return self::selectFirst([], $conditions, $params);
144 * Get a single photo given resource id and scale
146 * This method checks for permissions. Returns associative array
147 * on success, "no sign" image info, if user has no permission,
148 * false if photo does not exists
150 * @param string $resourceid Rescource ID of the photo
151 * @param integer $scale Scale of the photo. Defaults to 0
153 * @return boolean|array
156 public static function getPhoto(string $resourceid, int $scale = 0)
158 $r = self::selectFirst(['uid'], ['resource-id' => $resourceid]);
159 if (!DBA::isResult($r)) {
165 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
167 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
169 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
170 $params = ['order' => ['scale' => true]];
171 $photo = self::selectFirst([], $conditions, $params);
177 * Returns all browsable albums for a given user
179 * @param int $uid The given user
181 * @return array An array of albums
184 public static function getBrowsableAlbumsForUser(int $uid): array
186 $photos = DBA::toArray(
188 "SELECT DISTINCT(`album`) AS `album` FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?)",
190 static::CONTACT_AVATAR,
191 static::CONTACT_BANNER
195 return array_column($photos, 'album');
199 * Returns browsable photos for a given user (optional and a given album)
201 * @param int $uid The given user id
202 * @param string|null $album (optional) The given album
204 * @return array All photos of the user/album
207 public static function getBrowsablePhotosForUser(int $uid, string $album = null): array
211 Photo::CONTACT_AVATAR,
212 Photo::CONTACT_BANNER
215 if (!empty($album)) {
216 $sqlExtra = "AND `album` = ? ";
221 $sqlExtra2 = ' ORDER BY created DESC LIMIT 0, 10';
226 "SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
227 min(`scale`) AS `hiq`, max(`scale`) AS `loq`, ANY_VALUE(`desc`) AS `desc`, ANY_VALUE(`created`) AS `created`
228 FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) $sqlExtra
229 GROUP BY `resource-id` $sqlExtra2",
235 * Check if photo with given conditions exists
237 * @param array $conditions Array of extra conditions
242 public static function exists(array $conditions): bool
244 return DBA::exists('photo', $conditions);
249 * Get Image data for given row id. null if row id does not exist
251 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
253 * @return \Friendica\Object\Image|null Image object or null on error
255 public static function getImageDataForPhoto(array $photo)
257 if (!empty($photo['data'])) {
258 return $photo['data'];
262 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
263 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
264 return $backendClass->get($photo['backend-ref'] ?? '');
265 } catch (InvalidClassStorageException $storageException) {
267 // legacy data storage in "data" column
268 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
272 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
274 } catch (\Exception $exception) {
275 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
277 } catch (ReferenceStorageException $referenceStorageException) {
278 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
279 } catch (StorageException $storageException) {
280 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
281 } catch (\ImagickException $imagickException) {
282 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
289 * Get Image object for given row id. null if row id does not exist
291 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
293 * @return \Friendica\Object\Image
294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295 * @throws \ImagickException
297 public static function getImageForPhoto(array $photo): Image
299 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
303 * Return a list of fields that are associated with the photo table
305 * @return array field list
308 private static function getFields(): array
310 $allfields = DI::dbaDefinition()->getAll();
311 $fields = array_keys($allfields['photo']['fields']);
312 array_splice($fields, array_search('data', $fields), 1);
317 * Construct a photo array for a system resource image
319 * @param string $filename Image file name relative to code root
320 * @param string $mimetype Image mime type. Is guessed by file name when empty.
325 public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
327 if (empty($mimetype)) {
328 $mimetype = Images::guessTypeByExtension($filename);
331 $fields = self::getFields();
332 $values = array_fill(0, count($fields), '');
334 $photo = array_combine($fields, $values);
335 $photo['backend-class'] = SystemResource::NAME;
336 $photo['backend-ref'] = $filename;
337 $photo['type'] = $mimetype;
338 $photo['cacheable'] = false;
344 * Construct a photo array for an external resource image
346 * @param string $url Image URL
347 * @param int $uid User ID of the requesting person
348 * @param string $mimetype Image mime type. Is guessed by file name when empty.
353 public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = ''): array
355 if (empty($mimetype)) {
356 $mimetype = Images::guessTypeByExtension($url);
359 $fields = self::getFields();
360 $values = array_fill(0, count($fields), '');
362 $photo = array_combine($fields, $values);
363 $photo['backend-class'] = ExternalResource::NAME;
364 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
365 $photo['type'] = $mimetype;
366 $photo['cacheable'] = true;
372 * store photo metadata in db and binary in default backend
374 * @param Image $image Image object with data
375 * @param integer $uid User ID
376 * @param integer $cid Contact ID
377 * @param string $rid Resource ID
378 * @param string $filename Filename
379 * @param string $album Album name
380 * @param integer $scale Scale
381 * @param integer $type Photo type, optional, default: Photo::DEFAULT
382 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
383 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
384 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
385 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
386 * @param string $desc Photo caption. optional, default = ""
388 * @return boolean True on success
389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
391 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
393 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
394 if (DBA::isResult($photo)) {
395 $guid = $photo['guid'];
397 $guid = System::createGUID();
400 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
401 $created = DateTimeFormat::utcNow();
402 if (DBA::isResult($existing_photo)) {
403 $created = $existing_photo['created'];
406 // Get defined storage backend.
407 // if no storage backend, we use old "data" column in photo table.
408 // if is an existing photo, reuse same backend
414 if (DBA::isResult($existing_photo)) {
415 $backend_ref = (string)$existing_photo['backend-ref'];
416 $storage = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
418 $storage = DI::storage();
420 $backend_ref = $storage->put($image->asString(), $backend_ref);
421 } catch (InvalidClassStorageException $storageException) {
422 $data = $image->asString();
427 'contact-id' => $cid,
429 'resource-id' => $rid,
430 'hash' => md5($image->asString()),
431 'created' => $created,
432 'edited' => DateTimeFormat::utcNow(),
433 'filename' => basename($filename),
434 'type' => $image->getType(),
436 'height' => $image->getHeight(),
437 'width' => $image->getWidth(),
438 'datasize' => strlen($image->asString()),
439 'blurhash' => $image->getBlurHash(),
442 'photo-type' => $type,
444 'allow_cid' => $allow_cid,
445 'allow_gid' => $allow_gid,
446 'deny_cid' => $deny_cid,
447 'deny_gid' => $deny_gid,
449 'backend-class' => (string)$storage,
450 'backend-ref' => $backend_ref
453 if (DBA::isResult($existing_photo)) {
454 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
456 $r = DBA::insert('photo', $fields);
464 * Delete info from table and data from storage
466 * @param array $conditions Field condition(s)
467 * @param array $options Options array, Optional
472 * @see \Friendica\Database\DBA::delete
474 public static function delete(array $conditions, array $options = []): bool
476 // get photo to delete data info
477 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
479 while ($photo = DBA::fetch($photos)) {
481 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
482 $backend_class->delete($photo['backend-ref'] ?? '');
483 // Delete the photos after they had been deleted successfully
484 DBA::delete('photo', ['id' => $photo['id']]);
485 } catch (InvalidClassStorageException $storageException) {
486 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
487 } catch (ReferenceStorageException $referenceStorageException) {
488 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
494 return DBA::delete('photo', $conditions, $options);
500 * @param array $fields Contains the fields that are updated
501 * @param array $conditions Condition array with the key values
502 * @param Image $image Image to update. Optional, default null.
503 * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
505 * @return boolean Was the update successfull?
507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508 * @see \Friendica\Database\DBA::update
510 public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
512 if (!is_null($image)) {
513 // get photo to update
514 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
516 foreach($photos as $photo) {
518 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
519 $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
520 } catch (InvalidClassStorageException $storageException) {
521 $fields['data'] = $image->asString();
524 $fields['updated'] = DateTimeFormat::utcNow();
527 $fields['edited'] = DateTimeFormat::utcNow();
529 return DBA::update('photo', $fields, $conditions, $old_fields);
533 * @param string $image_url Remote URL
534 * @param integer $uid user id
535 * @param integer $cid contact id
536 * @param boolean $quit_on_error optional, default false
537 * @return array|bool Array on success, false on error
538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
539 * @throws \ImagickException
541 public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
546 $photo = DBA::selectFirst(
547 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
549 if (!empty($photo['resource-id'])) {
550 $resource_id = $photo['resource-id'];
552 $resource_id = self::newResource();
555 $photo_failure = false;
557 $filename = basename($image_url);
558 if (!empty($image_url)) {
559 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
560 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
561 $img_str = $ret->getBody();
562 $type = $ret->getContentType();
568 if ($quit_on_error && ($img_str == '')) {
572 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
574 $image = new Image($img_str, $type);
575 if ($image->isValid()) {
576 $image->scaleToSquare(300);
578 $filesize = strlen($image->asString());
579 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
581 if ($maximagesize && ($filesize > $maximagesize)) {
582 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
583 if ($image->getType() == 'image/gif') {
585 $image = new Image($image->asString(), 'image/png');
587 $filesize = strlen($image->asString());
588 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
590 if ($filesize > $maximagesize) {
591 foreach ([160, 80] as $pixels) {
592 if ($filesize > $maximagesize) {
593 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
594 $image->scaleDown($pixels);
595 $filesize = strlen($image->asString());
599 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
602 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
605 $photo_failure = true;
608 $image->scaleDown(80);
610 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
613 $photo_failure = true;
616 $image->scaleDown(48);
618 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
621 $photo_failure = true;
624 $suffix = '?ts=' . time();
626 $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
627 $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
628 $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
630 $photo_failure = true;
633 if ($photo_failure && $quit_on_error) {
637 if ($photo_failure) {
638 $contact = Contact::getById($cid) ?: [];
639 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
640 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
641 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
644 return [$image_url, $thumb, $micro];
648 * Returns a float that represents the GPS coordinate from EXIF data
650 * @param array $exifCoord coordinate
651 * @param string $hemi hemi
654 public static function getGps(array $exifCoord, string $hemi): float
656 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
657 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
658 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
660 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
662 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
666 * Change GPS to float number
668 * @param string $coordPart coordPart
671 private static function gps2Num(string $coordPart): float
673 $parts = explode('/', $coordPart);
675 if (count($parts) <= 0) {
679 if (count($parts) == 1) {
680 return (float)$parts[0];
683 return floatval($parts[0]) / floatval($parts[1]);
687 * Fetch the photo albums that are available for a viewer
689 * The query in this function is cost intensive, so it is cached.
691 * @param int $uid User id of the photos
692 * @param bool $update Update the cache
694 * @return array Returns array of the photo albums
695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
697 public static function getAlbums(int $uid, bool $update = false): array
699 $sql_extra = Security::getPermissionsSQLByUserId($uid);
701 $avatar_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
702 $banner_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_BANNER : self::DEFAULT;
704 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
705 $albums = DI::cache()->get($key);
707 if (is_null($albums) || $update) {
708 if (!DI::config()->get('system', 'no_count', false)) {
709 /// @todo This query needs to be renewed. It is really slow
710 // At this time we just store the data in the cache
711 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
713 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
714 GROUP BY `album` ORDER BY `created` DESC",
721 // This query doesn't do the count and is much faster
722 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
723 FROM `photo` USE INDEX (`uid_album_scale_created`)
724 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
731 DI::cache()->set($key, $albums, Duration::DAY);
737 * @param int $uid User id of the photos
741 public static function clearAlbumCache(int $uid)
743 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
744 DI::cache()->set($key, null, Duration::DAY);
748 * Generate a unique photo ID.
750 * @return string Resource GUID
753 public static function newResource(): string
755 return System::createGUID(32, false);
759 * Extracts the rid from a local photo URI
761 * @param string $image_uri The URI of the photo
762 * @return string The rid of the photo, or an empty string if the URI is not local
764 public static function ridFromURI(string $image_uri): string
766 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
769 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
770 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
771 return trim($image_uri);
775 * Checks if the given URL is a local photo.
776 * Since it is meant for time critical occasions, the check is done without any database requests.
781 public static function isPhotoURI(string $url): bool
783 return !empty(self::ridFromURI($url));
787 * Changes photo permissions that had been embedded in a post
789 * @todo This function currently does have some flaws:
790 * - Sharing a post with a forum will create a photo that only the forum can see.
791 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
796 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
798 // Simplify image codes
799 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
800 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
803 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
807 if (empty($images)) {
811 foreach ($images as $image) {
812 $image_rid = self::ridFromURI($image);
813 if (empty($image_rid)) {
817 // Ensure to only modify photos that you own
818 $srch = '<' . intval($original_contact_id) . '>';
821 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
822 'resource-id' => $image_rid, 'uid' => $uid
824 if (!self::exists($condition)) {
825 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
826 if (!DBA::isResult($photo)) {
827 Logger::info('Image not found', ['resource-id' => $image_rid]);
829 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
835 * @todo Existing permissions need to be mixed with the new ones.
836 * Otherwise this creates problems with sharing the same picture multiple times
837 * Also check if $str_contact_allow does contain a public forum.
838 * Then set the permissions to public.
841 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
848 * Add permissions to photo ressource
849 * @todo mix with previous photo permissions
851 * @param string $image_rid
852 * @param integer $uid
853 * @param string $str_contact_allow
854 * @param string $str_group_allow
855 * @param string $str_contact_deny
856 * @param string $str_group_deny
859 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)
861 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
862 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
863 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
865 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
866 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
867 self::update($fields, $condition);
871 * Fetch the guid and scale from picture links
873 * @param string $name Picture link
876 public static function getResourceData(string $name): array
878 $base = DI::baseUrl()->get();
880 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
882 if (parse_url($guid, PHP_URL_SCHEME)) {
886 $guid = pathinfo($guid, PATHINFO_FILENAME);
887 if (substr($guid, -2, 1) != "-") {
891 $scale = intval(substr($guid, -1, 1));
892 if (!is_numeric($scale)) {
896 $guid = substr($guid, 0, -2);
897 return ['guid' => $guid, 'scale' => $scale];
901 * Tests if the picture link points to a locally stored picture
903 * @param string $name Picture link
907 public static function isLocal(string $name): bool
909 // @TODO Maybe a proper check here on true condition?
910 return (bool)self::getIdForName($name);
914 * Return the id of a local photo
916 * @param string $name Picture link
919 public static function getIdForName(string $name): int
921 $data = self::getResourceData($name);
926 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
927 if (!empty($photo['id'])) {
934 * Tests if the link points to a locally stored picture page
936 * @param string $name Page link
940 public static function isLocalPage(string $name): bool
942 $base = DI::baseUrl()->get();
944 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
945 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
950 return DBA::exists('photo', ['resource-id' => $guid]);
954 * Tries to resize image to wanted maximum size
956 * @param Image $image Image instance
957 * @return Image|null Image instance on success, null on error
959 private static function fitImageSize(Image $image)
961 $max_length = DI::config()->get('system', 'max_image_length');
962 if ($max_length > 0) {
963 $image->scaleDown($max_length);
964 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
967 $filesize = strlen($image->asString());
968 $width = $image->getWidth();
969 $height = $image->getHeight();
971 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
973 if ($maximagesize && ($filesize > $maximagesize)) {
974 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
975 foreach ([5120, 2560, 1280, 640] as $pixels) {
976 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
977 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
978 $image->scaleDown($pixels);
979 $filesize = strlen($image->asString());
980 $width = $image->getWidth();
981 $height = $image->getHeight();
984 if ($filesize > $maximagesize) {
985 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
994 * Fetches image from URL and returns an array with instance and local file name
996 * @param string $image_url URL to image
997 * @return array With: 'image' and 'filename' fields or empty array on error
999 private static function loadImageFromURL(string $image_url): array
1001 $filename = basename($image_url);
1002 if (!empty($image_url)) {
1003 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
1004 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
1005 $img_str = $ret->getBody();
1006 $type = $ret->getContentType();
1012 if (empty($img_str)) {
1013 Logger::notice('Empty content');
1017 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1019 $image = new Image($img_str, $type);
1021 $image = self::fitImageSize($image);
1022 if (empty($image)) {
1026 return ['image' => $image, 'filename' => $filename];
1030 * Inserts uploaded image into database and removes local temporary file
1032 * @param array $files File array
1033 * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1035 private static function uploadImage(array $files): array
1037 Logger::info('starting new upload');
1039 if (empty($files)) {
1040 Logger::notice('Empty upload file');
1044 if (!empty($files['tmp_name'])) {
1045 if (is_array($files['tmp_name'])) {
1046 $src = $files['tmp_name'][0];
1048 $src = $files['tmp_name'];
1054 if (!empty($files['name'])) {
1055 if (is_array($files['name'])) {
1056 $filename = basename($files['name'][0]);
1058 $filename = basename($files['name']);
1064 if (!empty($files['size'])) {
1065 if (is_array($files['size'])) {
1066 $filesize = intval($files['size'][0]);
1068 $filesize = intval($files['size']);
1074 if (!empty($files['type'])) {
1075 if (is_array($files['type'])) {
1076 $filetype = $files['type'][0];
1078 $filetype = $files['type'];
1085 Logger::notice('No source file name', ['files' => $files]);
1089 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1091 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1093 $imagedata = @file_get_contents($src);
1094 $image = new Image($imagedata, $filetype);
1095 if (!$image->isValid()) {
1096 Logger::notice('Image is unvalid', ['files' => $files]);
1100 $image->orient($src);
1103 $image = self::fitImageSize($image);
1104 if (empty($image)) {
1108 return ['image' => $image, 'filename' => $filename];
1112 * Handles uploaded image and assigns it to given user id
1114 * @param int $uid User ID
1115 * @param array $files uploaded file array
1116 * @param string $album Album name (optional)
1117 * @param string|null $allow_cid
1118 * @param string|null $allow_gid
1119 * @param string $deny_cid
1120 * @param string $deny_gid
1121 * @param string $desc Description (optional)
1122 * @param string $resource_id GUID (optional)
1123 * @return array photo record or empty array on error
1124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1126 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
1128 $user = User::getOwnerDataById($uid);
1130 Logger::notice('User not found', ['uid' => $uid]);
1134 $data = self::uploadImage($files);
1136 Logger::info('upload failed');
1140 $image = $data['image'];
1141 $filename = $data['filename'];
1142 $width = $image->getWidth();
1143 $height = $image->getHeight();
1145 $resource_id = $resource_id ?: self::newResource();
1146 $album = $album ?: DI::l10n()->t('Wall Photos');
1148 if (is_null($allow_cid) && is_null($allow_gid)) {
1149 $allow_cid = '<' . $user['id'] . '>';
1155 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1157 Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1161 if ($width > 640 || $height > 640) {
1162 $image->scaleDown(640);
1163 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1169 if ($width > 320 || $height > 320) {
1170 $image->scaleDown(320);
1171 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1172 if ($r && ($smallest == 0)) {
1177 $condition = ['resource-id' => $resource_id];
1178 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1179 if (empty($photo)) {
1180 Logger::notice('Photo not found', ['condition' => $condition]);
1186 $picture['id'] = $photo['id'];
1187 $picture['resource_id'] = $resource_id;
1188 $picture['size'] = $photo['datasize'];
1189 $picture['width'] = $photo['width'];
1190 $picture['height'] = $photo['height'];
1191 $picture['type'] = $photo['type'];
1192 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1193 $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1194 $picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $smallest . '.' . $image->getExt();
1196 Logger::info('upload done', ['picture' => $picture]);
1201 * Upload a user avatar
1203 * @param int $uid User ID
1204 * @param array $files uploaded file array
1205 * @param string $url External image url
1206 * @return string avatar resource
1208 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1210 if (!empty($files)) {
1211 $data = self::uploadImage($files);
1213 Logger::info('upload failed');
1216 } elseif (!empty($url)) {
1217 $data = self::loadImageFromURL($url);
1219 Logger::info('loading from external url failed');
1223 Logger::info('Neither files nor url provided');
1227 $image = $data['image'];
1228 $filename = $data['filename'];
1229 $width = $image->getWidth();
1230 $height = $image->getHeight();
1232 $resource_id = self::newResource();
1233 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1235 // upload profile image (scales 4, 5, 6)
1236 logger::info('starting new profile image upload');
1238 if ($width > 300 || $height > 300) {
1239 $image->scaleDown(300);
1242 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1244 logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1247 if ($width > 80 || $height > 80) {
1248 $image->scaleDown(80);
1251 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1253 logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1256 if ($width > 48 || $height > 48) {
1257 $image->scaleDown(48);
1260 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1262 logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1265 logger::info('new profile image upload ended');
1267 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1268 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1270 Contact::updateSelfFromUserID($uid, true);
1272 // Update global directory in background
1273 Profile::publishUpdate($uid);
1275 return $resource_id;
1279 * Upload a user banner
1281 * @param int $uid User ID
1282 * @param array $files uploaded file array
1283 * @param string $url External image url
1284 * @return string avatar resource
1286 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1288 if (!empty($files)) {
1289 $data = self::uploadImage($files);
1291 Logger::info('upload failed');
1294 } elseif (!empty($url)) {
1295 $data = self::loadImageFromURL($url);
1297 Logger::info('loading from external url failed');
1301 Logger::info('Neither files nor url provided');
1305 $image = $data['image'];
1306 $filename = $data['filename'];
1307 $width = $image->getWidth();
1308 $height = $image->getHeight();
1310 $resource_id = self::newResource();
1311 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1314 $image->scaleDown(960);
1317 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1319 logger::warning('profile banner upload with scale 3 (960) failed');
1322 logger::info('new profile banner upload ended');
1324 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1325 self::update(['photo-type' => self::DEFAULT], $condition);
1327 Contact::updateSelfFromUserID($uid, true);
1329 // Update global directory in background
1330 Profile::publishUpdate($uid);
1332 return $resource_id;