3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
29 use Friendica\Core\Storage\Type\ExternalResource;
30 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
31 use Friendica\Core\Storage\Exception\ReferenceStorageException;
32 use Friendica\Core\Storage\Exception\StorageException;
33 use Friendica\Core\Storage\Type\SystemResource;
34 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
35 use Friendica\Object\Image;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Images;
38 use Friendica\Security\Security;
39 use Friendica\Util\Network;
40 use Friendica\Util\Proxy;
41 use Friendica\Util\Strings;
44 * Class to handle photo dabatase table
48 const CONTACT_PHOTOS = 'Contact Photos';
49 const PROFILE_PHOTOS = 'Profile Photos';
50 const BANNER_PHOTOS = 'Banner Photos';
53 const USER_AVATAR = 10;
54 const USER_BANNER = 11;
55 const CONTACT_AVATAR = 20;
56 const CONTACT_BANNER = 21;
59 * Select rows from the photo table and returns them as array
61 * @param array $fields Array of selected fields, empty for all
62 * @param array $conditions Array of fields for conditions
63 * @param array $params Array of several parameters
65 * @return boolean|array
68 * @see \Friendica\Database\DBA::selectToArray
70 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
73 $fields = self::getFields();
76 return DBA::selectToArray('photo', $fields, $conditions, $params);
80 * Retrieve a single record from the photo table
82 * @param array $fields Array of selected fields, empty for all
83 * @param array $conditions Array of fields for conditions
84 * @param array $params Array of several parameters
89 * @see \Friendica\Database\DBA::select
91 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
94 $fields = self::getFields();
97 return DBA::selectFirst('photo', $fields, $conditions, $params);
101 * Get photos for user id
103 * @param integer $uid User id
104 * @param string $resourceid Rescource ID of the photo
105 * @param array $conditions Array of fields for conditions
106 * @param array $params Array of several parameters
111 * @see \Friendica\Database\DBA::select
113 public static function getPhotosForUser(int $uid, string $resourceid, array $conditions = [], array $params = [])
115 $conditions['resource-id'] = $resourceid;
116 $conditions['uid'] = $uid;
118 return self::selectToArray([], $conditions, $params);
122 * Get a photo for user id
124 * @param integer $uid User id
125 * @param string $resourceid Rescource ID of the photo
126 * @param integer $scale Scale of the photo. Defaults to 0
127 * @param array $conditions Array of fields for conditions
128 * @param array $params Array of several parameters
133 * @see \Friendica\Database\DBA::select
135 public static function getPhotoForUser(int $uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
137 $conditions['resource-id'] = $resourceid;
138 $conditions['uid'] = $uid;
139 $conditions['scale'] = $scale;
141 return self::selectFirst([], $conditions, $params);
145 * Get a single photo given resource id and scale
147 * This method checks for permissions. Returns associative array
148 * on success, "no sign" image info, if user has no permission,
149 * false if photo does not exists
151 * @param string $resourceid Rescource ID of the photo
152 * @param integer $scale Scale of the photo. Defaults to 0
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 * Returns all browsable albums for a given user
180 * @param int $uid The given user
182 * @return array An array of albums
185 public static function getBrowsableAlbumsForUser(int $uid): array
187 $photos = DBA::toArray(
189 "SELECT DISTINCT(`album`) AS `album` FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?)",
191 static::CONTACT_AVATAR,
192 static::CONTACT_BANNER
196 return array_column($photos, 'album');
200 * Returns browsable photos for a given user (optional and a given album)
202 * @param int $uid The given user id
203 * @param string|null $album (optional) The given album
205 * @return array All photos of the user/album
208 public static function getBrowsablePhotosForUser(int $uid, string $album = null): array
212 Photo::CONTACT_AVATAR,
213 Photo::CONTACT_BANNER
216 if (!empty($album)) {
217 $sqlExtra = "AND `album` = ? ";
222 $sqlExtra2 = ' ORDER BY created DESC LIMIT 0, 10';
227 "SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
228 min(`scale`) AS `hiq`, max(`scale`) AS `loq`, ANY_VALUE(`desc`) AS `desc`, ANY_VALUE(`created`) AS `created`
229 FROM `photo` WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) $sqlExtra
230 GROUP BY `resource-id` $sqlExtra2",
236 * Check if photo with given conditions exists
238 * @param array $conditions Array of extra conditions
243 public static function exists(array $conditions): bool
245 return DBA::exists('photo', $conditions);
250 * Get Image data for given row id. null if row id does not exist
252 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
254 * @return \Friendica\Object\Image|null Image object or null on error
256 public static function getImageDataForPhoto(array $photo)
258 if (!empty($photo['data'])) {
259 return $photo['data'];
263 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
264 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
265 return $backendClass->get($photo['backend-ref'] ?? '');
266 } catch (InvalidClassStorageException $storageException) {
268 // legacy data storage in "data" column
269 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
273 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
275 } catch (\Exception $exception) {
276 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
278 } catch (ReferenceStorageException $referenceStorageException) {
279 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
280 } catch (StorageException $storageException) {
281 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
282 } catch (\ImagickException $imagickException) {
283 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
290 * Get Image object for given row id. null if row id does not exist
292 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
294 * @return \Friendica\Object\Image
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
296 * @throws \ImagickException
298 public static function getImageForPhoto(array $photo): Image
300 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
304 * Return a list of fields that are associated with the photo table
306 * @return array field list
309 private static function getFields(): array
311 $allfields = DI::dbaDefinition()->getAll();
312 $fields = array_keys($allfields['photo']['fields']);
313 array_splice($fields, array_search('data', $fields), 1);
318 * Construct a photo array for a given image data string
320 * @param string $image_data Image data
321 * @param string $mimetype Image mime type. Is guessed by file name when empty.
326 public static function createPhotoForImageData(string $image_data, string $mimetype = ''): array
328 $fields = self::getFields();
329 $values = array_fill(0, count($fields), '');
331 $photo = array_combine($fields, $values);
332 $photo['data'] = $image_data;
333 $photo['type'] = $mimetype ?: Images::getMimeTypeByData($image_data);
334 $photo['cacheable'] = false;
340 * Construct a photo array for a system resource image
342 * @param string $filename Image file name relative to code root
343 * @param string $mimetype Image mime type. Is guessed by file name when empty.
348 public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
350 if (empty($mimetype)) {
351 $mimetype = Images::guessTypeByExtension($filename);
354 $fields = self::getFields();
355 $values = array_fill(0, count($fields), '');
357 $photo = array_combine($fields, $values);
358 $photo['backend-class'] = SystemResource::NAME;
359 $photo['backend-ref'] = $filename;
360 $photo['type'] = $mimetype;
361 $photo['cacheable'] = false;
367 * Construct a photo array for an external resource image
369 * @param string $url Image URL
370 * @param int $uid User ID of the requesting person
371 * @param string $mimetype Image mime type. Is guessed by file name when empty.
372 * @param string $blurhash The blurhash that will be used to generate a picture when the original picture can't be fetched
373 * @param int $width Image width
374 * @param int $height Image height
379 public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = '', string $blurhash = null, int $width = null, int $height = null): array
381 if (empty($mimetype)) {
382 $mimetype = Images::guessTypeByExtension($url);
385 $fields = self::getFields();
386 $values = array_fill(0, count($fields), '');
388 $photo = array_combine($fields, $values);
389 $photo['backend-class'] = ExternalResource::NAME;
390 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
391 $photo['type'] = $mimetype;
392 $photo['cacheable'] = true;
393 $photo['blurhash'] = $blurhash;
394 $photo['width'] = $width;
395 $photo['height'] = $height;
401 * store photo metadata in db and binary in default backend
403 * @param Image $image Image object with data
404 * @param integer $uid User ID
405 * @param integer $cid Contact ID
406 * @param string $rid Resource ID
407 * @param string $filename Filename
408 * @param string $album Album name
409 * @param integer $scale Scale
410 * @param integer $type Photo type, optional, default: Photo::DEFAULT
411 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
412 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
413 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
414 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
415 * @param string $desc Photo caption. optional, default = ""
417 * @return boolean True on success
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 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
422 $photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
423 if (DBA::isResult($photo)) {
424 $guid = $photo['guid'];
426 $guid = System::createGUID();
429 $existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
430 $created = DateTimeFormat::utcNow();
431 if (DBA::isResult($existing_photo)) {
432 $created = $existing_photo['created'];
435 // Get defined storage backend.
436 // if no storage backend, we use old "data" column in photo table.
437 // if is an existing photo, reuse same backend
443 if (DBA::isResult($existing_photo)) {
444 $backend_ref = (string)$existing_photo['backend-ref'];
445 $storage = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
447 $storage = DI::storage();
449 $backend_ref = $storage->put($image->asString(), $backend_ref);
450 } catch (InvalidClassStorageException $storageException) {
451 $data = $image->asString();
456 'contact-id' => $cid,
458 'resource-id' => $rid,
459 'hash' => md5($image->asString()),
460 'created' => $created,
461 'edited' => DateTimeFormat::utcNow(),
462 'filename' => basename($filename),
463 'type' => $image->getType(),
465 'height' => $image->getHeight(),
466 'width' => $image->getWidth(),
467 'datasize' => strlen($image->asString()),
468 'blurhash' => $image->getBlurHash(),
471 'photo-type' => $type,
473 'allow_cid' => $allow_cid,
474 'allow_gid' => $allow_gid,
475 'deny_cid' => $deny_cid,
476 'deny_gid' => $deny_gid,
478 'backend-class' => (string)$storage,
479 'backend-ref' => $backend_ref
482 if (DBA::isResult($existing_photo)) {
483 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
485 $r = DBA::insert('photo', $fields);
493 * Delete info from table and data from storage
495 * @param array $conditions Field condition(s)
496 * @param array $options Options array, Optional
501 * @see \Friendica\Database\DBA::delete
503 public static function delete(array $conditions, array $options = []): bool
505 // get photo to delete data info
506 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
508 while ($photo = DBA::fetch($photos)) {
510 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
511 $backend_class->delete($photo['backend-ref'] ?? '');
512 // Delete the photos after they had been deleted successfully
513 DBA::delete('photo', ['id' => $photo['id']]);
514 } catch (InvalidClassStorageException $storageException) {
515 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
516 } catch (ReferenceStorageException $referenceStorageException) {
517 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
523 return DBA::delete('photo', $conditions, $options);
529 * @param array $fields Contains the fields that are updated
530 * @param array $conditions Condition array with the key values
531 * @param Image $image Image to update. Optional, default null.
532 * @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
534 * @return boolean Was the update successfull?
536 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537 * @see \Friendica\Database\DBA::update
539 public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
541 if (!is_null($image)) {
542 // get photo to update
543 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
545 foreach($photos as $photo) {
547 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
548 $fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
549 } catch (InvalidClassStorageException $storageException) {
550 $fields['data'] = $image->asString();
553 $fields['updated'] = DateTimeFormat::utcNow();
556 $fields['edited'] = DateTimeFormat::utcNow();
558 return DBA::update('photo', $fields, $conditions, $old_fields);
562 * @param string $image_url Remote URL
563 * @param integer $uid user id
564 * @param integer $cid contact id
565 * @param boolean $quit_on_error optional, default false
566 * @return array|bool Array on success, false on error
567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
568 * @throws \ImagickException
570 public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
575 $photo = DBA::selectFirst(
576 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
578 if (!empty($photo['resource-id'])) {
579 $resource_id = $photo['resource-id'];
581 $resource_id = self::newResource();
584 $photo_failure = false;
586 if (!Network::isValidHttpUrl($image_url)) {
587 Logger::warning('Invalid image url', ['image_url' => $image_url, 'uid' => $uid, 'cid' => $cid, 'callstack' => System::callstack(20)]);
591 $filename = basename($image_url);
592 if (!empty($image_url)) {
593 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
594 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
595 $img_str = $ret->getBody();
596 $type = $ret->getContentType();
602 if ($quit_on_error && ($img_str == '')) {
606 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
608 $image = new Image($img_str, $type);
609 if ($image->isValid()) {
610 $image->scaleToSquare(300);
612 $filesize = strlen($image->asString());
613 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
615 if ($maximagesize && ($filesize > $maximagesize)) {
616 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
617 if ($image->getType() == 'image/gif') {
619 $image = new Image($image->asString(), 'image/png');
621 $filesize = strlen($image->asString());
622 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
624 if ($filesize > $maximagesize) {
625 foreach ([160, 80] as $pixels) {
626 if ($filesize > $maximagesize) {
627 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
628 $image->scaleDown($pixels);
629 $filesize = strlen($image->asString());
633 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
636 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
639 $photo_failure = true;
642 $image->scaleDown(80);
644 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
647 $photo_failure = true;
650 $image->scaleDown(48);
652 $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
655 $photo_failure = true;
658 $suffix = '?ts=' . time();
660 $image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
661 $thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
662 $micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
664 $photo_failure = true;
667 if ($photo_failure && $quit_on_error) {
671 if ($photo_failure) {
672 $contact = Contact::getById($cid) ?: [];
673 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
674 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
675 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
678 $photo = DBA::selectFirst(
679 'photo', ['blurhash'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
682 return [$image_url, $thumb, $micro, $photo['blurhash']];
686 * Returns a float that represents the GPS coordinate from EXIF data
688 * @param array $exifCoord coordinate
689 * @param string $hemi hemi
692 public static function getGps(array $exifCoord, string $hemi): float
694 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
695 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
696 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
698 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
700 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
704 * Change GPS to float number
706 * @param string $coordPart coordPart
709 private static function gps2Num(string $coordPart): float
711 $parts = explode('/', $coordPart);
713 if (count($parts) <= 0) {
717 if (count($parts) == 1) {
718 return (float)$parts[0];
721 return floatval($parts[0]) / floatval($parts[1]);
725 * Fetch the photo albums that are available for a viewer
727 * The query in this function is cost intensive, so it is cached.
729 * @param int $uid User id of the photos
730 * @param bool $update Update the cache
732 * @return array Returns array of the photo albums
733 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
735 public static function getAlbums(int $uid, bool $update = false): array
737 $sql_extra = Security::getPermissionsSQLByUserId($uid);
739 $avatar_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
740 $banner_type = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $uid)) ? self::USER_BANNER : self::DEFAULT;
742 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
743 $albums = DI::cache()->get($key);
745 if (is_null($albums) || $update) {
746 if (!DI::config()->get('system', 'no_count', false)) {
747 /// @todo This query needs to be renewed. It is really slow
748 // At this time we just store the data in the cache
749 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
751 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
752 GROUP BY `album` ORDER BY `created` DESC",
759 // This query doesn't do the count and is much faster
760 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
761 FROM `photo` USE INDEX (`uid_album_scale_created`)
762 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
769 DI::cache()->set($key, $albums, Duration::DAY);
775 * @param int $uid User id of the photos
779 public static function clearAlbumCache(int $uid)
781 $key = 'photo_albums:' . $uid . ':' . DI::userSession()->getLocalUserId() . ':' . DI::userSession()->getRemoteUserId();
782 DI::cache()->set($key, null, Duration::DAY);
786 * Generate a unique photo ID.
788 * @return string Resource GUID
791 public static function newResource(): string
793 return System::createGUID(32, false);
797 * Extracts the rid from a local photo URI
799 * @param string $image_uri The URI of the photo
800 * @return string The rid of the photo, or an empty string if the URI is not local
802 public static function ridFromURI(string $image_uri): string
804 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
807 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
808 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
809 return trim($image_uri);
813 * Checks if the given URL is a local photo.
814 * Since it is meant for time critical occasions, the check is done without any database requests.
819 public static function isPhotoURI(string $url): bool
821 return !empty(self::ridFromURI($url));
825 * Changes photo permissions that had been embedded in a post
827 * @todo This function currently does have some flaws:
828 * - Sharing a post with a forum will create a photo that only the forum can see.
829 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
834 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
836 // Simplify image codes
837 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
838 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
841 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
845 if (empty($images)) {
849 foreach ($images as $image) {
850 $image_rid = self::ridFromURI($image);
851 if (empty($image_rid)) {
855 // Ensure to only modify photos that you own
856 $srch = '<' . intval($original_contact_id) . '>';
859 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
860 'resource-id' => $image_rid, 'uid' => $uid
862 if (!self::exists($condition)) {
863 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
864 if (!DBA::isResult($photo)) {
865 Logger::info('Image not found', ['resource-id' => $image_rid]);
867 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
873 * @todo Existing permissions need to be mixed with the new ones.
874 * Otherwise this creates problems with sharing the same picture multiple times
875 * Also check if $str_contact_allow does contain a public forum.
876 * Then set the permissions to public.
879 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
886 * Add permissions to photo ressource
887 * @todo mix with previous photo permissions
889 * @param string $image_rid
890 * @param integer $uid
891 * @param string $str_contact_allow
892 * @param string $str_group_allow
893 * @param string $str_contact_deny
894 * @param string $str_group_deny
897 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)
899 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
900 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
901 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
903 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
904 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
905 self::update($fields, $condition);
909 * Fetch the guid and scale from picture links
911 * @param string $name Picture link
914 public static function getResourceData(string $name): array
916 $base = DI::baseUrl()->get();
918 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
920 if (parse_url($guid, PHP_URL_SCHEME)) {
924 $guid = pathinfo($guid, PATHINFO_FILENAME);
925 if (substr($guid, -2, 1) != "-") {
929 $scale = intval(substr($guid, -1, 1));
930 if (!is_numeric($scale)) {
934 $guid = substr($guid, 0, -2);
935 return ['guid' => $guid, 'scale' => $scale];
939 * Tests if the picture link points to a locally stored picture
941 * @param string $name Picture link
945 public static function isLocal(string $name): bool
947 // @TODO Maybe a proper check here on true condition?
948 return (bool)self::getIdForName($name);
952 * Return the id of a local photo
954 * @param string $name Picture link
957 public static function getIdForName(string $name): int
959 $data = self::getResourceData($name);
964 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
965 if (!empty($photo['id'])) {
972 * Tests if the link points to a locally stored picture page
974 * @param string $name Page link
978 public static function isLocalPage(string $name): bool
980 $base = DI::baseUrl()->get();
982 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
983 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
988 return DBA::exists('photo', ['resource-id' => $guid]);
992 * Tries to resize image to wanted maximum size
994 * @param Image $image Image instance
995 * @return Image|null Image instance on success, null on error
997 private static function fitImageSize(Image $image)
999 $max_length = DI::config()->get('system', 'max_image_length');
1000 if ($max_length > 0) {
1001 $image->scaleDown($max_length);
1002 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
1005 $filesize = strlen($image->asString());
1006 $width = $image->getWidth();
1007 $height = $image->getHeight();
1009 $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
1011 if ($maximagesize && ($filesize > $maximagesize)) {
1012 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
1013 foreach ([5120, 2560, 1280, 640] as $pixels) {
1014 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
1015 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1016 $image->scaleDown($pixels);
1017 $filesize = strlen($image->asString());
1018 $width = $image->getWidth();
1019 $height = $image->getHeight();
1022 if ($filesize > $maximagesize) {
1023 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1032 * Fetches image from URL and returns an array with instance and local file name
1034 * @param string $image_url URL to image
1035 * @return array With: 'image' and 'filename' fields or empty array on error
1037 private static function loadImageFromURL(string $image_url): array
1039 $filename = basename($image_url);
1040 if (!empty($image_url)) {
1041 $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE);
1042 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
1043 $img_str = $ret->getBody();
1044 $type = $ret->getContentType();
1050 if (empty($img_str)) {
1051 Logger::notice('Empty content');
1055 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
1057 $image = new Image($img_str, $type);
1059 $image = self::fitImageSize($image);
1060 if (empty($image)) {
1064 return ['image' => $image, 'filename' => $filename];
1068 * Inserts uploaded image into database and removes local temporary file
1070 * @param array $files File array
1071 * @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
1073 private static function uploadImage(array $files): array
1075 Logger::info('starting new upload');
1077 if (empty($files)) {
1078 Logger::notice('Empty upload file');
1082 if (!empty($files['tmp_name'])) {
1083 if (is_array($files['tmp_name'])) {
1084 $src = $files['tmp_name'][0];
1086 $src = $files['tmp_name'];
1092 if (!empty($files['name'])) {
1093 if (is_array($files['name'])) {
1094 $filename = basename($files['name'][0]);
1096 $filename = basename($files['name']);
1102 if (!empty($files['size'])) {
1103 if (is_array($files['size'])) {
1104 $filesize = intval($files['size'][0]);
1106 $filesize = intval($files['size']);
1112 if (!empty($files['type'])) {
1113 if (is_array($files['type'])) {
1114 $filetype = $files['type'][0];
1116 $filetype = $files['type'];
1123 Logger::notice('No source file name', ['files' => $files]);
1127 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1129 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1131 $imagedata = @file_get_contents($src);
1132 $image = new Image($imagedata, $filetype);
1133 if (!$image->isValid()) {
1134 Logger::notice('Image is unvalid', ['files' => $files]);
1138 $image->orient($src);
1141 $image = self::fitImageSize($image);
1142 if (empty($image)) {
1146 return ['image' => $image, 'filename' => $filename];
1150 * Handles uploaded image and assigns it to given user id
1152 * @param int $uid User ID
1153 * @param array $files uploaded file array
1154 * @param string $album Album name (optional)
1155 * @param string|null $allow_cid
1156 * @param string|null $allow_gid
1157 * @param string $deny_cid
1158 * @param string $deny_gid
1159 * @param string $desc Description (optional)
1160 * @param string $resource_id GUID (optional)
1161 * @return array photo record or empty array on error
1162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164 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
1166 $user = User::getOwnerDataById($uid);
1168 Logger::notice('User not found', ['uid' => $uid]);
1172 $data = self::uploadImage($files);
1174 Logger::info('upload failed');
1178 $image = $data['image'];
1179 $filename = $data['filename'];
1180 $width = $image->getWidth();
1181 $height = $image->getHeight();
1183 $resource_id = $resource_id ?: self::newResource();
1184 $album = $album ?: DI::l10n()->t('Wall Photos');
1186 if (is_null($allow_cid) && is_null($allow_gid)) {
1187 $allow_cid = '<' . $user['id'] . '>';
1193 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1195 Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1199 if ($width > 640 || $height > 640) {
1200 $image->scaleDown(640);
1201 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1207 if ($width > 320 || $height > 320) {
1208 $image->scaleDown(320);
1209 $r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1210 if ($r && ($smallest == 0)) {
1215 $condition = ['resource-id' => $resource_id];
1216 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1217 if (empty($photo)) {
1218 Logger::notice('Photo not found', ['condition' => $condition]);
1224 $picture['id'] = $photo['id'];
1225 $picture['resource_id'] = $resource_id;
1226 $picture['size'] = $photo['datasize'];
1227 $picture['width'] = $photo['width'];
1228 $picture['height'] = $photo['height'];
1229 $picture['type'] = $photo['type'];
1230 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1231 $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
1232 $picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $smallest . '.' . $image->getExt();
1234 Logger::info('upload done', ['picture' => $picture]);
1239 * Upload a user avatar
1241 * @param int $uid User ID
1242 * @param array $files uploaded file array
1243 * @param string $url External image url
1244 * @return string avatar resource
1246 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1248 if (!empty($files)) {
1249 $data = self::uploadImage($files);
1251 Logger::info('upload failed');
1254 } elseif (!empty($url)) {
1255 $data = self::loadImageFromURL($url);
1257 Logger::info('loading from external url failed');
1261 Logger::info('Neither files nor url provided');
1265 $image = $data['image'];
1266 $filename = $data['filename'];
1267 $width = $image->getWidth();
1268 $height = $image->getHeight();
1270 $resource_id = self::newResource();
1271 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1273 // upload profile image (scales 4, 5, 6)
1274 logger::info('starting new profile image upload');
1276 if ($width > 300 || $height > 300) {
1277 $image->scaleDown(300);
1280 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1282 logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1285 if ($width > 80 || $height > 80) {
1286 $image->scaleDown(80);
1289 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1291 logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1294 if ($width > 48 || $height > 48) {
1295 $image->scaleDown(48);
1298 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1300 logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
1303 logger::info('new profile image upload ended');
1305 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1306 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1308 Contact::updateSelfFromUserID($uid, true);
1310 // Update global directory in background
1311 Profile::publishUpdate($uid);
1313 return $resource_id;
1317 * Upload a user banner
1319 * @param int $uid User ID
1320 * @param array $files uploaded file array
1321 * @param string $url External image url
1322 * @return string avatar resource
1324 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1326 if (!empty($files)) {
1327 $data = self::uploadImage($files);
1329 Logger::info('upload failed');
1332 } elseif (!empty($url)) {
1333 $data = self::loadImageFromURL($url);
1335 Logger::info('loading from external url failed');
1339 Logger::info('Neither files nor url provided');
1343 $image = $data['image'];
1344 $filename = $data['filename'];
1345 $width = $image->getWidth();
1346 $height = $image->getHeight();
1348 $resource_id = self::newResource();
1349 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1352 $image->scaleDown(960);
1355 $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1357 logger::warning('profile banner upload with scale 3 (960) failed');
1360 logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
1362 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1363 self::update(['photo-type' => self::DEFAULT], $condition);
1365 Contact::updateSelfFromUserID($uid, true);
1367 // Update global directory in background
1368 Profile::publishUpdate($uid);
1370 return $resource_id;