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;
28 use Friendica\Database\DBStructure;
30 use Friendica\Core\Storage\Type\ExternalResource;
31 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
32 use Friendica\Core\Storage\Exception\ReferenceStorageException;
33 use Friendica\Core\Storage\Exception\StorageException;
34 use Friendica\Core\Storage\Type\SystemResource;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Object\Image;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Images;
39 use Friendica\Security\Security;
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
154 * @return boolean|array
157 public static function getPhoto(string $resourceid, int $scale = 0)
159 $r = self::selectFirst(['uid'], ['resource-id' => $resourceid]);
160 if (!DBA::isResult($r)) {
166 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
168 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
170 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
171 $params = ['order' => ['scale' => true]];
172 $photo = self::selectFirst([], $conditions, $params);
178 * Check if photo with given conditions exists
180 * @param array $conditions Array of extra conditions
185 public static function exists(array $conditions): bool
187 return DBA::exists('photo', $conditions);
192 * Get Image data for given row id. null if row id does not exist
194 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
196 * @return \Friendica\Object\Image|null Image object or null on error
198 public static function getImageDataForPhoto(array $photo)
200 if (!empty($photo['data'])) {
201 return $photo['data'];
205 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
206 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
207 return $backendClass->get($photo['backend-ref'] ?? '');
208 } catch (InvalidClassStorageException $storageException) {
210 // legacy data storage in "data" column
211 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
215 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
217 } catch (\Exception $exception) {
218 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
220 } catch (ReferenceStorageException $referenceStorageException) {
221 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
222 } catch (StorageException $storageException) {
223 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
224 } catch (\ImagickException $imagickException) {
225 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
232 * Get Image object for given row id. null if row id does not exist
234 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
236 * @return \Friendica\Object\Image
237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238 * @throws \ImagickException
240 public static function getImageForPhoto(array $photo): Image
242 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
246 * Return a list of fields that are associated with the photo table
248 * @return array field list
251 private static function getFields(): array
253 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
254 $fields = array_keys($allfields['photo']['fields']);
255 array_splice($fields, array_search('data', $fields), 1);
260 * Construct a photo array for a system resource image
262 * @param string $filename Image file name relative to code root
263 * @param string $mimetype Image mime type. Is guessed by file name when empty.
268 public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
270 if (empty($mimetype)) {
271 $mimetype = Images::guessTypeByExtension($filename);
274 $fields = self::getFields();
275 $values = array_fill(0, count($fields), '');
277 $photo = array_combine($fields, $values);
278 $photo['backend-class'] = SystemResource::NAME;
279 $photo['backend-ref'] = $filename;
280 $photo['type'] = $mimetype;
281 $photo['cacheable'] = false;
287 * Construct a photo array for an external resource image
289 * @param string $url Image URL
290 * @param int $uid User ID of the requesting person
291 * @param string $mimetype Image mime type. Is guessed by file name when empty.
296 public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = ''): array
298 if (empty($mimetype)) {
299 $mimetype = Images::guessTypeByExtension($url);
302 $fields = self::getFields();
303 $values = array_fill(0, count($fields), '');
305 $photo = array_combine($fields, $values);
306 $photo['backend-class'] = ExternalResource::NAME;
307 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
308 $photo['type'] = $mimetype;
309 $photo['cacheable'] = true;
315 * store photo metadata in db and binary in default backend
317 * @param Image $image Image object with data
318 * @param integer $uid User ID
319 * @param integer $cid Contact ID
320 * @param string $rid Resource ID
321 * @param string $filename Filename
322 * @param string $album Album name
323 * @param integer $scale Scale
324 * @param integer $type Photo type, optional, default: Photo::DEFAULT
325 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
326 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
327 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
328 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
329 * @param string $desc Photo caption. optional, default = ""
331 * @return boolean True on success
332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
334 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
336 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
337 if (DBA::isResult($photo)) {
338 $guid = $photo['guid'];
340 $guid = System::createGUID();
343 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
344 $created = DateTimeFormat::utcNow();
345 if (DBA::isResult($existing_photo)) {
346 $created = $existing_photo['created'];
349 // Get defined storage backend.
350 // if no storage backend, we use old "data" column in photo table.
351 // if is an existing photo, reuse same backend
357 if (DBA::isResult($existing_photo)) {
358 $backend_ref = (string)$existing_photo['backend-ref'];
359 $storage = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
361 $storage = DI::storage();
363 $backend_ref = $storage->put($image->asString(), $backend_ref);
364 } catch (InvalidClassStorageException $storageException) {
365 $data = $image->asString();
370 'contact-id' => $cid,
372 'resource-id' => $rid,
373 'hash' => md5($image->asString()),
374 'created' => $created,
375 'edited' => DateTimeFormat::utcNow(),
376 'filename' => basename($filename),
377 'type' => $image->getType(),
379 'height' => $image->getHeight(),
380 'width' => $image->getWidth(),
381 'datasize' => strlen($image->asString()),
384 'photo-type' => $type,
386 'allow_cid' => $allow_cid,
387 'allow_gid' => $allow_gid,
388 'deny_cid' => $deny_cid,
389 'deny_gid' => $deny_gid,
391 'backend-class' => (string)$storage,
392 'backend-ref' => $backend_ref
395 if (DBA::isResult($existing_photo)) {
396 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
398 $r = DBA::insert('photo', $fields);
406 * Delete info from table and data from storage
408 * @param array $conditions Field condition(s)
409 * @param array $options Options array, Optional
414 * @see \Friendica\Database\DBA::delete
416 public static function delete(array $conditions, array $options = []): bool
418 // get photo to delete data info
419 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
421 while ($photo = DBA::fetch($photos)) {
423 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
424 $backend_class->delete($photo['backend-ref'] ?? '');
425 // Delete the photos after they had been deleted successfully
426 DBA::delete('photo', ['id' => $photo['id']]);
427 } catch (InvalidClassStorageException $storageException) {
428 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
429 } catch (ReferenceStorageException $referenceStorageException) {
430 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
436 return DBA::delete('photo', $conditions, $options);
442 * @param array $fields Contains the fields that are updated
443 * @param array $conditions Condition array with the key values
444 * @param Image $image Image to update. Optional, default null.
445 * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
447 * @return boolean Was the update successfull?
449 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
450 * @see \Friendica\Database\DBA::update
452 public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
454 if (!is_null($image)) {
455 // get photo to update
456 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
458 foreach($photos as $photo) {
460 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
461 $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
462 } catch (InvalidClassStorageException $storageException) {
463 $fields['data'] = $image->asString();
466 $fields['updated'] = DateTimeFormat::utcNow();
469 $fields['edited'] = DateTimeFormat::utcNow();
471 return DBA::update('photo', $fields, $conditions, $old_fields);
475 * @param string $image_url Remote URL
476 * @param integer $uid user id
477 * @param integer $cid contact id
478 * @param boolean $quit_on_error optional, default false
479 * @return array|bool Array on success, false on error
480 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
481 * @throws \ImagickException
483 public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
488 $photo = DBA::selectFirst(
489 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
491 if (!empty($photo['resource-id'])) {
492 $resource_id = $photo['resource-id'];
494 $resource_id = self::newResource();
497 $photo_failure = false;
499 $filename = basename($image_url);
500 if (!empty($image_url)) {
501 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
502 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
503 $img_str = $ret->getBody();
504 $type = $ret->getContentType();
510 if ($quit_on_error && ($img_str == '')) {
514 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
516 $image = new Image($img_str, $type);
517 if ($image->isValid()) {
518 $image->scaleToSquare(300);
520 $filesize = strlen($image->asString());
521 $maximagesize = DI::config()->get('system', 'maximagesize');
522 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
523 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
524 if ($image->getType() == 'image/gif') {
526 $image = new Image($image->asString(), 'image/png');
528 $filesize = strlen($image->asString());
529 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
531 if ($filesize > $maximagesize) {
532 foreach ([160, 80] as $pixels) {
533 if ($filesize > $maximagesize) {
534 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
535 $image->scaleDown($pixels);
536 $filesize = strlen($image->asString());
540 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
543 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
546 $photo_failure = true;
549 $image->scaleDown(80);
551 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
554 $photo_failure = true;
557 $image->scaleDown(48);
559 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
562 $photo_failure = true;
565 $suffix = '?ts=' . time();
567 $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
568 $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
569 $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
571 $photo_failure = true;
574 if ($photo_failure && $quit_on_error) {
578 if ($photo_failure) {
579 $contact = Contact::getById($cid) ?: [];
580 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
581 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
582 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
585 return [$image_url, $thumb, $micro];
589 * @param array $exifCoord coordinate
590 * @param string $hemi hemi
593 public static function getGps(array $exifCoord, string $hemi): float
595 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
596 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
597 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
599 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
601 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
605 * Change GPS to float number
607 * @param string $coordPart coordPart
610 private static function gps2Num(string $coordPart): float
612 $parts = explode('/', $coordPart);
614 if (count($parts) <= 0) {
618 if (count($parts) == 1) {
619 return (float)$parts[0];
622 return floatval($parts[0]) / floatval($parts[1]);
626 * Fetch the photo albums that are available for a viewer
628 * The query in this function is cost intensive, so it is cached.
630 * @param int $uid User id of the photos
631 * @param bool $update Update the cache
633 * @return array Returns array of the photo albums
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
636 public static function getAlbums(int $uid, bool $update = false): array
638 $sql_extra = Security::getPermissionsSQLByUserId($uid);
640 $avatar_type = (local_user() && (local_user() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
641 $banner_type = (local_user() && (local_user() == $uid)) ? self::USER_BANNER : self::DEFAULT;
643 $key = 'photo_albums:' . $uid . ':' . local_user() . ':' . remote_user();
644 $albums = DI::cache()->get($key);
646 if (is_null($albums) || $update) {
647 if (!DI::config()->get('system', 'no_count', false)) {
648 /// @todo This query needs to be renewed. It is really slow
649 // At this time we just store the data in the cache
650 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
652 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
653 GROUP BY `album` ORDER BY `created` DESC",
660 // This query doesn't do the count and is much faster
661 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
662 FROM `photo` USE INDEX (`uid_album_scale_created`)
663 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
670 DI::cache()->set($key, $albums, Duration::DAY);
676 * @param int $uid User id of the photos
680 public static function clearAlbumCache(int $uid)
682 $key = 'photo_albums:' . $uid . ':' . local_user() . ':' . remote_user();
683 DI::cache()->set($key, null, Duration::DAY);
687 * Generate a unique photo ID.
689 * @return string Resource GUID
692 public static function newResource(): string
694 return System::createGUID(32, false);
698 * Extracts the rid from a local photo URI
700 * @param string $image_uri The URI of the photo
701 * @return string The rid of the photo, or an empty string if the URI is not local
703 public static function ridFromURI(string $image_uri): string
705 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
708 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
709 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
710 return trim($image_uri);
714 * Checks if the given URL is a local photo.
715 * Since it is meant for time critical occasions, the check is done without any database requests.
720 public static function isPhotoURI(string $url): bool
722 return !empty(self::ridFromURI($url));
726 * Changes photo permissions that had been embedded in a post
728 * @todo This function currently does have some flaws:
729 * - Sharing a post with a forum will create a photo that only the forum can see.
730 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
735 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
737 // Simplify image codes
738 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
739 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
742 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
746 if (empty($images)) {
750 foreach ($images as $image) {
751 $image_rid = self::ridFromURI($image);
752 if (empty($image_rid)) {
756 // Ensure to only modify photos that you own
757 $srch = '<' . intval($original_contact_id) . '>';
760 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
761 'resource-id' => $image_rid, 'uid' => $uid
763 if (!self::exists($condition)) {
764 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
765 if (!DBA::isResult($photo)) {
766 Logger::info('Image not found', ['resource-id' => $image_rid]);
768 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
774 * @todo Existing permissions need to be mixed with the new ones.
775 * Otherwise this creates problems with sharing the same picture multiple times
776 * Also check if $str_contact_allow does contain a public forum.
777 * Then set the permissions to public.
780 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
787 * Add permissions to photo ressource
788 * @todo mix with previous photo permissions
790 * @param string $image_rid
791 * @param integer $uid
792 * @param string $str_contact_allow
793 * @param string $str_group_allow
794 * @param string $str_contact_deny
795 * @param string $str_group_deny
798 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)
800 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
801 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
802 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
804 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
805 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
806 self::update($fields, $condition);
810 * Fetch the guid and scale from picture links
812 * @param string $name Picture link
815 public static function getResourceData(string $name): array
817 $base = DI::baseUrl()->get();
819 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
821 if (parse_url($guid, PHP_URL_SCHEME)) {
825 $guid = pathinfo($guid, PATHINFO_FILENAME);
826 if (substr($guid, -2, 1) != "-") {
830 $scale = intval(substr($guid, -1, 1));
831 if (!is_numeric($scale)) {
835 $guid = substr($guid, 0, -2);
836 return ['guid' => $guid, 'scale' => $scale];
840 * Tests if the picture link points to a locally stored picture
842 * @param string $name Picture link
846 public static function isLocal(string $name): bool
848 // @TODO Maybe a proper check here on true condition?
849 return (bool)self::getIdForName($name);
853 * Return the id of a local photo
855 * @param string $name Picture link
858 public static function getIdForName(string $name): int
860 $data = self::getResourceData($name);
865 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
866 if (!empty($photo['id'])) {
873 * Tests if the link points to a locally stored picture page
875 * @param string $name Page link
879 public static function isLocalPage(string $name): bool
881 $base = DI::baseUrl()->get();
883 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
884 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
889 return DBA::exists('photo', ['resource-id' => $guid]);
893 * Tries to resize image to wanted maximum size
895 * @param Image $image Image instance
896 * @return Image|null Image instance on success, null on error
898 private static function fitImageSize(Image $image)
900 $max_length = DI::config()->get('system', 'max_image_length');
901 if ($max_length > 0) {
902 $image->scaleDown($max_length);
903 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
906 $filesize = strlen($image->asString());
907 $width = $image->getWidth();
908 $height = $image->getHeight();
910 $maximagesize = DI::config()->get('system', 'maximagesize');
912 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
913 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
914 foreach ([5120, 2560, 1280, 640] as $pixels) {
915 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
916 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
917 $image->scaleDown($pixels);
918 $filesize = strlen($image->asString());
919 $width = $image->getWidth();
920 $height = $image->getHeight();
923 if ($filesize > $maximagesize) {
924 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
933 * Fetches image from URL and returns an array with instance and local file name
935 * @param string $image_url URL to image
936 * @return array With: 'image' and 'filename' fields or empty array on error
938 private static function loadImageFromURL(string $image_url): array
940 $filename = basename($image_url);
941 if (!empty($image_url)) {
942 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
943 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
944 $img_str = $ret->getBody();
945 $type = $ret->getContentType();
951 if (empty($img_str)) {
952 Logger::notice('Empty content');
956 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
958 $image = new Image($img_str, $type);
960 $image = self::fitImageSize($image);
965 return ['image' => $image, 'filename' => $filename];
969 * Inserts uploaded image into database and removes local temporary file
971 * @param array $files File array
972 * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
974 private static function uploadImage(array $files): array
976 Logger::info('starting new upload');
979 Logger::notice('Empty upload file');
983 if (!empty($files['tmp_name'])) {
984 if (is_array($files['tmp_name'])) {
985 $src = $files['tmp_name'][0];
987 $src = $files['tmp_name'];
993 if (!empty($files['name'])) {
994 if (is_array($files['name'])) {
995 $filename = basename($files['name'][0]);
997 $filename = basename($files['name']);
1003 if (!empty($files['size'])) {
1004 if (is_array($files['size'])) {
1005 $filesize = intval($files['size'][0]);
1007 $filesize = intval($files['size']);
1013 if (!empty($files['type'])) {
1014 if (is_array($files['type'])) {
1015 $filetype = $files['type'][0];
1017 $filetype = $files['type'];
1024 Logger::notice('No source file name', ['files' => $files]);
1028 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1030 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1032 $imagedata = @file_get_contents($src);
1033 $image = new Image($imagedata, $filetype);
1034 if (!$image->isValid()) {
1035 Logger::notice('Image is unvalid', ['files' => $files]);
1039 $image->orient($src);
1042 $image = self::fitImageSize($image);
1043 if (empty($image)) {
1047 return ['image' => $image, 'filename' => $filename];
1051 * Handles uploaded image and assigns it to given user id
1053 * @param int $uid User ID
1054 * @param array $files uploaded file array
1055 * @param string $album Album name (optional)
1056 * @param string|null $allow_cid
1057 * @param string|null $allow_gid
1058 * @param string $deny_cid
1059 * @param string $deny_gid
1060 * @param string $desc Description (optional)
1061 * @param string $resource_id GUID (optional)
1062 * @return array photo record or empty array on error
1063 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1065 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
1067 $user = User::getOwnerDataById($uid);
1069 Logger::notice('User not found', ['uid' => $uid]);
1073 $data = self::uploadImage($files);
1075 Logger::info('upload failed');
1079 $image = $data['image'];
1080 $filename = $data['filename'];
1081 $width = $image->getWidth();
1082 $height = $image->getHeight();
1084 $resource_id = $resource_id ?: self::newResource();
1085 $album = $album ?: DI::l10n()->t('Wall Photos');
1087 if (is_null($allow_cid) && is_null($allow_gid)) {
1088 $allow_cid = '<' . $user['id'] . '>';
1094 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1096 Logger::notice('Photo could not be stored');
1100 if ($width > 640 || $height > 640) {
1101 $image->scaleDown(640);
1102 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1108 if ($width > 320 || $height > 320) {
1109 $image->scaleDown(320);
1110 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1111 if ($r && ($smallest == 0)) {
1116 $condition = ['resource-id' => $resource_id];
1117 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1118 if (empty($photo)) {
1119 Logger::notice('Photo not found', ['condition' => $condition]);
1125 $picture['id'] = $photo['id'];
1126 $picture['resource_id'] = $resource_id;
1127 $picture['size'] = $photo['datasize'];
1128 $picture['width'] = $photo['width'];
1129 $picture['height'] = $photo['height'];
1130 $picture['type'] = $photo['type'];
1131 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1132 $picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $image->getExt();
1133 $picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $image->getExt();
1135 Logger::info('upload done', ['picture' => $picture]);
1140 * Upload a user avatar
1142 * @param int $uid User ID
1143 * @param array $files uploaded file array
1144 * @param string $url External image url
1145 * @return string avatar resource
1147 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1149 if (!empty($files)) {
1150 $data = self::uploadImage($files);
1152 Logger::info('upload failed');
1155 } elseif (!empty($url)) {
1156 $data = self::loadImageFromURL($url);
1158 Logger::info('loading from external url failed');
1162 Logger::info('Neither files nor url provided');
1166 $image = $data['image'];
1167 $filename = $data['filename'];
1168 $width = $image->getWidth();
1169 $height = $image->getHeight();
1171 $resource_id = self::newResource();
1172 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1174 // upload profile image (scales 4, 5, 6)
1175 logger::info('starting new profile image upload');
1177 if ($width > 300 || $height > 300) {
1178 $image->scaleDown(300);
1181 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1183 logger::notice('profile image upload with scale 4 (300) failed');
1186 if ($width > 80 || $height > 80) {
1187 $image->scaleDown(80);
1190 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1192 logger::notice('profile image upload with scale 5 (80) failed');
1195 if ($width > 48 || $height > 48) {
1196 $image->scaleDown(48);
1199 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1201 logger::notice('profile image upload with scale 6 (48) failed');
1204 logger::info('new profile image upload ended');
1206 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1207 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1209 Contact::updateSelfFromUserID($uid, true);
1211 // Update global directory in background
1212 Profile::publishUpdate($uid);
1214 return $resource_id;
1218 * Upload a user banner
1220 * @param int $uid User ID
1221 * @param array $files uploaded file array
1222 * @param string $url External image url
1223 * @return string avatar resource
1225 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1227 if (!empty($files)) {
1228 $data = self::uploadImage($files);
1230 Logger::info('upload failed');
1233 } elseif (!empty($url)) {
1234 $data = self::loadImageFromURL($url);
1236 Logger::info('loading from external url failed');
1240 Logger::info('Neither files nor url provided');
1244 $image = $data['image'];
1245 $filename = $data['filename'];
1246 $width = $image->getWidth();
1247 $height = $image->getHeight();
1249 $resource_id = self::newResource();
1250 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1253 $image->scaleDown(960);
1256 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1258 logger::notice('profile banner upload with scale 3 (960) failed');
1261 logger::info('new profile banner upload ended');
1263 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1264 self::update(['photo-type' => self::DEFAULT], $condition);
1266 Contact::updateSelfFromUserID($uid, true);
1268 // Update global directory in background
1269 Profile::publishUpdate($uid);
1271 return $resource_id;