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
209 if (!empty($album)) {
210 $sqlExtra = sprintf("AND `album` = '%s' ", DBA::escape($album));
214 $sqlExtra2 = ' ORDER BY created DESC LIMIT 0, 10';
219 "SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
220 min(`scale`) AS `hiq`, max(`scale`) AS `loq`, ANY_VALUE(`desc`) AS `desc`, ANY_VALUE(`created`) AS `created`
221 FROM `photo` WHERE `uid` = ? $sqlExtra AND NOT `photo-type` IN (?, ?)
222 GROUP BY `resource-id` $sqlExtra2",
224 Photo::CONTACT_AVATAR,
225 Photo::CONTACT_BANNER
230 * Check if photo with given conditions exists
232 * @param array $conditions Array of extra conditions
237 public static function exists(array $conditions): bool
239 return DBA::exists('photo', $conditions);
244 * Get Image data for given row id. null if row id does not exist
246 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
248 * @return \Friendica\Object\Image|null Image object or null on error
250 public static function getImageDataForPhoto(array $photo)
252 if (!empty($photo['data'])) {
253 return $photo['data'];
257 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
258 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
259 return $backendClass->get($photo['backend-ref'] ?? '');
260 } catch (InvalidClassStorageException $storageException) {
262 // legacy data storage in "data" column
263 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
267 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
269 } catch (\Exception $exception) {
270 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
272 } catch (ReferenceStorageException $referenceStorageException) {
273 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
274 } catch (StorageException $storageException) {
275 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
276 } catch (\ImagickException $imagickException) {
277 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
284 * Get Image object for given row id. null if row id does not exist
286 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
288 * @return \Friendica\Object\Image
289 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 * @throws \ImagickException
292 public static function getImageForPhoto(array $photo): Image
294 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
298 * Return a list of fields that are associated with the photo table
300 * @return array field list
303 private static function getFields(): array
305 $allfields = DI::dbaDefinition()->getAll();
306 $fields = array_keys($allfields['photo']['fields']);
307 array_splice($fields, array_search('data', $fields), 1);
312 * Construct a photo array for a system resource image
314 * @param string $filename Image file name relative to code root
315 * @param string $mimetype Image mime type. Is guessed by file name when empty.
320 public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
322 if (empty($mimetype)) {
323 $mimetype = Images::guessTypeByExtension($filename);
326 $fields = self::getFields();
327 $values = array_fill(0, count($fields), '');
329 $photo = array_combine($fields, $values);
330 $photo['backend-class'] = SystemResource::NAME;
331 $photo['backend-ref'] = $filename;
332 $photo['type'] = $mimetype;
333 $photo['cacheable'] = false;
339 * Construct a photo array for an external resource image
341 * @param string $url Image URL
342 * @param int $uid User ID of the requesting person
343 * @param string $mimetype Image mime type. Is guessed by file name when empty.
348 public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = ''): array
350 if (empty($mimetype)) {
351 $mimetype = Images::guessTypeByExtension($url);
354 $fields = self::getFields();
355 $values = array_fill(0, count($fields), '');
357 $photo = array_combine($fields, $values);
358 $photo['backend-class'] = ExternalResource::NAME;
359 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
360 $photo['type'] = $mimetype;
361 $photo['cacheable'] = true;
367 * store photo metadata in db and binary in default backend
369 * @param Image $image Image object with data
370 * @param integer $uid User ID
371 * @param integer $cid Contact ID
372 * @param string $rid Resource ID
373 * @param string $filename Filename
374 * @param string $album Album name
375 * @param integer $scale Scale
376 * @param integer $type Photo type, optional, default: Photo::DEFAULT
377 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
378 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
379 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
380 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
381 * @param string $desc Photo caption. optional, default = ""
383 * @return boolean True on success
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
386 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
388 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
389 if (DBA::isResult($photo)) {
390 $guid = $photo['guid'];
392 $guid = System::createGUID();
395 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
396 $created = DateTimeFormat::utcNow();
397 if (DBA::isResult($existing_photo)) {
398 $created = $existing_photo['created'];
401 // Get defined storage backend.
402 // if no storage backend, we use old "data" column in photo table.
403 // if is an existing photo, reuse same backend
409 if (DBA::isResult($existing_photo)) {
410 $backend_ref = (string)$existing_photo['backend-ref'];
411 $storage = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
413 $storage = DI::storage();
415 $backend_ref = $storage->put($image->asString(), $backend_ref);
416 } catch (InvalidClassStorageException $storageException) {
417 $data = $image->asString();
422 'contact-id' => $cid,
424 'resource-id' => $rid,
425 'hash' => md5($image->asString()),
426 'created' => $created,
427 'edited' => DateTimeFormat::utcNow(),
428 'filename' => basename($filename),
429 'type' => $image->getType(),
431 'height' => $image->getHeight(),
432 'width' => $image->getWidth(),
433 'datasize' => strlen($image->asString()),
436 'photo-type' => $type,
438 'allow_cid' => $allow_cid,
439 'allow_gid' => $allow_gid,
440 'deny_cid' => $deny_cid,
441 'deny_gid' => $deny_gid,
443 'backend-class' => (string)$storage,
444 'backend-ref' => $backend_ref
447 if (DBA::isResult($existing_photo)) {
448 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
450 $r = DBA::insert('photo', $fields);
458 * Delete info from table and data from storage
460 * @param array $conditions Field condition(s)
461 * @param array $options Options array, Optional
466 * @see \Friendica\Database\DBA::delete
468 public static function delete(array $conditions, array $options = []): bool
470 // get photo to delete data info
471 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
473 while ($photo = DBA::fetch($photos)) {
475 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
476 $backend_class->delete($photo['backend-ref'] ?? '');
477 // Delete the photos after they had been deleted successfully
478 DBA::delete('photo', ['id' => $photo['id']]);
479 } catch (InvalidClassStorageException $storageException) {
480 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
481 } catch (ReferenceStorageException $referenceStorageException) {
482 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
488 return DBA::delete('photo', $conditions, $options);
494 * @param array $fields Contains the fields that are updated
495 * @param array $conditions Condition array with the key values
496 * @param Image $image Image to update. Optional, default null.
497 * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
499 * @return boolean Was the update successfull?
501 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
502 * @see \Friendica\Database\DBA::update
504 public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
506 if (!is_null($image)) {
507 // get photo to update
508 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
510 foreach($photos as $photo) {
512 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
513 $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
514 } catch (InvalidClassStorageException $storageException) {
515 $fields['data'] = $image->asString();
518 $fields['updated'] = DateTimeFormat::utcNow();
521 $fields['edited'] = DateTimeFormat::utcNow();
523 return DBA::update('photo', $fields, $conditions, $old_fields);
527 * @param string $image_url Remote URL
528 * @param integer $uid user id
529 * @param integer $cid contact id
530 * @param boolean $quit_on_error optional, default false
531 * @return array|bool Array on success, false on error
532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
533 * @throws \ImagickException
535 public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
540 $photo = DBA::selectFirst(
541 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
543 if (!empty($photo['resource-id'])) {
544 $resource_id = $photo['resource-id'];
546 $resource_id = self::newResource();
549 $photo_failure = false;
551 $filename = basename($image_url);
552 if (!empty($image_url)) {
553 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
554 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
555 $img_str = $ret->getBody();
556 $type = $ret->getContentType();
562 if ($quit_on_error && ($img_str == '')) {
566 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
568 $image = new Image($img_str, $type);
569 if ($image->isValid()) {
570 $image->scaleToSquare(300);
572 $filesize = strlen($image->asString());
573 $maximagesize = DI::config()->get('system', 'maximagesize');
574 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
575 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
576 if ($image->getType() == 'image/gif') {
578 $image = new Image($image->asString(), 'image/png');
580 $filesize = strlen($image->asString());
581 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
583 if ($filesize > $maximagesize) {
584 foreach ([160, 80] as $pixels) {
585 if ($filesize > $maximagesize) {
586 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
587 $image->scaleDown($pixels);
588 $filesize = strlen($image->asString());
592 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
595 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
598 $photo_failure = true;
601 $image->scaleDown(80);
603 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
606 $photo_failure = true;
609 $image->scaleDown(48);
611 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
614 $photo_failure = true;
617 $suffix = '?ts=' . time();
619 $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
620 $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
621 $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
623 $photo_failure = true;
626 if ($photo_failure && $quit_on_error) {
630 if ($photo_failure) {
631 $contact = Contact::getById($cid) ?: [];
632 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
633 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
634 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
637 return [$image_url, $thumb, $micro];
641 * Returns a float that represents the GPS coordinate from EXIF data
643 * @param array $exifCoord coordinate
644 * @param string $hemi hemi
647 public static function getGps(array $exifCoord, string $hemi): float
649 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
650 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
651 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
653 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
655 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
659 * Change GPS to float number
661 * @param string $coordPart coordPart
664 private static function gps2Num(string $coordPart): float
666 $parts = explode('/', $coordPart);
668 if (count($parts) <= 0) {
672 if (count($parts) == 1) {
673 return (float)$parts[0];
676 return floatval($parts[0]) / floatval($parts[1]);
680 * Fetch the photo albums that are available for a viewer
682 * The query in this function is cost intensive, so it is cached.
684 * @param int $uid User id of the photos
685 * @param bool $update Update the cache
687 * @return array Returns array of the photo albums
688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
690 public static function getAlbums(int $uid, bool $update = false): array
692 $sql_extra = Security::getPermissionsSQLByUserId($uid);
694 $avatar_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
695 $banner_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_BANNER : self::DEFAULT;
697 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
698 $albums = DI::cache()->get($key);
700 if (is_null($albums) || $update) {
701 if (!DI::config()->get('system', 'no_count', false)) {
702 /// @todo This query needs to be renewed. It is really slow
703 // At this time we just store the data in the cache
704 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
706 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
707 GROUP BY `album` ORDER BY `created` DESC",
714 // This query doesn't do the count and is much faster
715 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
716 FROM `photo` USE INDEX (`uid_album_scale_created`)
717 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
724 DI::cache()->set($key, $albums, Duration::DAY);
730 * @param int $uid User id of the photos
734 public static function clearAlbumCache(int $uid)
736 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
737 DI::cache()->set($key, null, Duration::DAY);
741 * Generate a unique photo ID.
743 * @return string Resource GUID
746 public static function newResource(): string
748 return System::createGUID(32, false);
752 * Extracts the rid from a local photo URI
754 * @param string $image_uri The URI of the photo
755 * @return string The rid of the photo, or an empty string if the URI is not local
757 public static function ridFromURI(string $image_uri): string
759 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
762 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
763 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
764 return trim($image_uri);
768 * Checks if the given URL is a local photo.
769 * Since it is meant for time critical occasions, the check is done without any database requests.
774 public static function isPhotoURI(string $url): bool
776 return !empty(self::ridFromURI($url));
780 * Changes photo permissions that had been embedded in a post
782 * @todo This function currently does have some flaws:
783 * - Sharing a post with a forum will create a photo that only the forum can see.
784 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
789 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
791 // Simplify image codes
792 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
793 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
796 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
800 if (empty($images)) {
804 foreach ($images as $image) {
805 $image_rid = self::ridFromURI($image);
806 if (empty($image_rid)) {
810 // Ensure to only modify photos that you own
811 $srch = '<' . intval($original_contact_id) . '>';
814 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
815 'resource-id' => $image_rid, 'uid' => $uid
817 if (!self::exists($condition)) {
818 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
819 if (!DBA::isResult($photo)) {
820 Logger::info('Image not found', ['resource-id' => $image_rid]);
822 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
828 * @todo Existing permissions need to be mixed with the new ones.
829 * Otherwise this creates problems with sharing the same picture multiple times
830 * Also check if $str_contact_allow does contain a public forum.
831 * Then set the permissions to public.
834 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
841 * Add permissions to photo ressource
842 * @todo mix with previous photo permissions
844 * @param string $image_rid
845 * @param integer $uid
846 * @param string $str_contact_allow
847 * @param string $str_group_allow
848 * @param string $str_contact_deny
849 * @param string $str_group_deny
852 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)
854 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
855 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
856 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
858 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
859 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
860 self::update($fields, $condition);
864 * Fetch the guid and scale from picture links
866 * @param string $name Picture link
869 public static function getResourceData(string $name): array
871 $base = DI::baseUrl()->get();
873 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
875 if (parse_url($guid, PHP_URL_SCHEME)) {
879 $guid = pathinfo($guid, PATHINFO_FILENAME);
880 if (substr($guid, -2, 1) != "-") {
884 $scale = intval(substr($guid, -1, 1));
885 if (!is_numeric($scale)) {
889 $guid = substr($guid, 0, -2);
890 return ['guid' => $guid, 'scale' => $scale];
894 * Tests if the picture link points to a locally stored picture
896 * @param string $name Picture link
900 public static function isLocal(string $name): bool
902 // @TODO Maybe a proper check here on true condition?
903 return (bool)self::getIdForName($name);
907 * Return the id of a local photo
909 * @param string $name Picture link
912 public static function getIdForName(string $name): int
914 $data = self::getResourceData($name);
919 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
920 if (!empty($photo['id'])) {
927 * Tests if the link points to a locally stored picture page
929 * @param string $name Page link
933 public static function isLocalPage(string $name): bool
935 $base = DI::baseUrl()->get();
937 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
938 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
943 return DBA::exists('photo', ['resource-id' => $guid]);
947 * Tries to resize image to wanted maximum size
949 * @param Image $image Image instance
950 * @return Image|null Image instance on success, null on error
952 private static function fitImageSize(Image $image)
954 $max_length = DI::config()->get('system', 'max_image_length');
955 if ($max_length > 0) {
956 $image->scaleDown($max_length);
957 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
960 $filesize = strlen($image->asString());
961 $width = $image->getWidth();
962 $height = $image->getHeight();
964 $maximagesize = DI::config()->get('system', 'maximagesize');
966 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
967 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
968 foreach ([5120, 2560, 1280, 640] as $pixels) {
969 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
970 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
971 $image->scaleDown($pixels);
972 $filesize = strlen($image->asString());
973 $width = $image->getWidth();
974 $height = $image->getHeight();
977 if ($filesize > $maximagesize) {
978 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
987 * Fetches image from URL and returns an array with instance and local file name
989 * @param string $image_url URL to image
990 * @return array With: 'image' and 'filename' fields or empty array on error
992 private static function loadImageFromURL(string $image_url): array
994 $filename = basename($image_url);
995 if (!empty($image_url)) {
996 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
997 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
998 $img_str = $ret->getBody();
999 $type = $ret->getContentType();
1005 if (empty($img_str)) {
1006 Logger::notice('Empty content');
1010 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1012 $image = new Image($img_str, $type);
1014 $image = self::fitImageSize($image);
1015 if (empty($image)) {
1019 return ['image' => $image, 'filename' => $filename];
1023 * Inserts uploaded image into database and removes local temporary file
1025 * @param array $files File array
1026 * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1028 private static function uploadImage(array $files): array
1030 Logger::info('starting new upload');
1032 if (empty($files)) {
1033 Logger::notice('Empty upload file');
1037 if (!empty($files['tmp_name'])) {
1038 if (is_array($files['tmp_name'])) {
1039 $src = $files['tmp_name'][0];
1041 $src = $files['tmp_name'];
1047 if (!empty($files['name'])) {
1048 if (is_array($files['name'])) {
1049 $filename = basename($files['name'][0]);
1051 $filename = basename($files['name']);
1057 if (!empty($files['size'])) {
1058 if (is_array($files['size'])) {
1059 $filesize = intval($files['size'][0]);
1061 $filesize = intval($files['size']);
1067 if (!empty($files['type'])) {
1068 if (is_array($files['type'])) {
1069 $filetype = $files['type'][0];
1071 $filetype = $files['type'];
1078 Logger::notice('No source file name', ['files' => $files]);
1082 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1084 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1086 $imagedata = @file_get_contents($src);
1087 $image = new Image($imagedata, $filetype);
1088 if (!$image->isValid()) {
1089 Logger::notice('Image is unvalid', ['files' => $files]);
1093 $image->orient($src);
1096 $image = self::fitImageSize($image);
1097 if (empty($image)) {
1101 return ['image' => $image, 'filename' => $filename];
1105 * Handles uploaded image and assigns it to given user id
1107 * @param int $uid User ID
1108 * @param array $files uploaded file array
1109 * @param string $album Album name (optional)
1110 * @param string|null $allow_cid
1111 * @param string|null $allow_gid
1112 * @param string $deny_cid
1113 * @param string $deny_gid
1114 * @param string $desc Description (optional)
1115 * @param string $resource_id GUID (optional)
1116 * @return array photo record or empty array on error
1117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1119 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
1121 $user = User::getOwnerDataById($uid);
1123 Logger::notice('User not found', ['uid' => $uid]);
1127 $data = self::uploadImage($files);
1129 Logger::info('upload failed');
1133 $image = $data['image'];
1134 $filename = $data['filename'];
1135 $width = $image->getWidth();
1136 $height = $image->getHeight();
1138 $resource_id = $resource_id ?: self::newResource();
1139 $album = $album ?: DI::l10n()->t('Wall Photos');
1141 if (is_null($allow_cid) && is_null($allow_gid)) {
1142 $allow_cid = '<' . $user['id'] . '>';
1148 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1150 Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1154 if ($width > 640 || $height > 640) {
1155 $image->scaleDown(640);
1156 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1162 if ($width > 320 || $height > 320) {
1163 $image->scaleDown(320);
1164 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1165 if ($r && ($smallest == 0)) {
1170 $condition = ['resource-id' => $resource_id];
1171 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1172 if (empty($photo)) {
1173 Logger::notice('Photo not found', ['condition' => $condition]);
1179 $picture['id'] = $photo['id'];
1180 $picture['resource_id'] = $resource_id;
1181 $picture['size'] = $photo['datasize'];
1182 $picture['width'] = $photo['width'];
1183 $picture['height'] = $photo['height'];
1184 $picture['type'] = $photo['type'];
1185 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1186 $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1187 $picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $smallest . '.' . $image->getExt();
1189 Logger::info('upload done', ['picture' => $picture]);
1194 * Upload a user avatar
1196 * @param int $uid User ID
1197 * @param array $files uploaded file array
1198 * @param string $url External image url
1199 * @return string avatar resource
1201 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1203 if (!empty($files)) {
1204 $data = self::uploadImage($files);
1206 Logger::info('upload failed');
1209 } elseif (!empty($url)) {
1210 $data = self::loadImageFromURL($url);
1212 Logger::info('loading from external url failed');
1216 Logger::info('Neither files nor url provided');
1220 $image = $data['image'];
1221 $filename = $data['filename'];
1222 $width = $image->getWidth();
1223 $height = $image->getHeight();
1225 $resource_id = self::newResource();
1226 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1228 // upload profile image (scales 4, 5, 6)
1229 logger::info('starting new profile image upload');
1231 if ($width > 300 || $height > 300) {
1232 $image->scaleDown(300);
1235 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1237 logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1240 if ($width > 80 || $height > 80) {
1241 $image->scaleDown(80);
1244 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1246 logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1249 if ($width > 48 || $height > 48) {
1250 $image->scaleDown(48);
1253 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1255 logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1258 logger::info('new profile image upload ended');
1260 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1261 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1263 Contact::updateSelfFromUserID($uid, true);
1265 // Update global directory in background
1266 Profile::publishUpdate($uid);
1268 return $resource_id;
1272 * Upload a user banner
1274 * @param int $uid User ID
1275 * @param array $files uploaded file array
1276 * @param string $url External image url
1277 * @return string avatar resource
1279 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1281 if (!empty($files)) {
1282 $data = self::uploadImage($files);
1284 Logger::info('upload failed');
1287 } elseif (!empty($url)) {
1288 $data = self::loadImageFromURL($url);
1290 Logger::info('loading from external url failed');
1294 Logger::info('Neither files nor url provided');
1298 $image = $data['image'];
1299 $filename = $data['filename'];
1300 $width = $image->getWidth();
1301 $height = $image->getHeight();
1303 $resource_id = self::newResource();
1304 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1307 $image->scaleDown(960);
1310 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1312 logger::warning('profile banner upload with scale 3 (960) failed');
1315 logger::info('new profile banner upload ended');
1317 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1318 self::update(['photo-type' => self::DEFAULT], $condition);
1320 Contact::updateSelfFromUserID($uid, true);
1322 // Update global directory in background
1323 Profile::publishUpdate($uid);
1325 return $resource_id;