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\HttpClient;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 use Friendica\Object\Image;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Images;
40 use Friendica\Security\Security;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\Strings;
45 * Class to handle photo dabatase table
49 const CONTACT_PHOTOS = 'Contact Photos';
50 const PROFILE_PHOTOS = 'Profile Photos';
51 const BANNER_PHOTOS = 'Banner Photos';
54 const USER_AVATAR = 10;
55 const USER_BANNER = 11;
56 const CONTACT_AVATAR = 20;
57 const CONTACT_BANNER = 21;
60 * Select rows from the photo table and returns them as array
62 * @param array $fields Array of selected fields, empty for all
63 * @param array $conditions Array of fields for conditions
64 * @param array $params Array of several parameters
66 * @return boolean|array
69 * @see \Friendica\Database\DBA::selectToArray
71 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
74 $fields = self::getFields();
77 return DBA::selectToArray('photo', $fields, $conditions, $params);
81 * Retrieve a single record from the photo table
83 * @param array $fields Array of selected fields, empty for all
84 * @param array $conditions Array of fields for conditions
85 * @param array $params Array of several parameters
90 * @see \Friendica\Database\DBA::select
92 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
95 $fields = self::getFields();
98 return DBA::selectFirst("photo", $fields, $conditions, $params);
102 * Get photos for user id
104 * @param integer $uid User id
105 * @param string $resourceid Rescource ID of the photo
106 * @param array $conditions Array of fields for conditions
107 * @param array $params Array of several parameters
112 * @see \Friendica\Database\DBA::select
114 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
116 $conditions["resource-id"] = $resourceid;
117 $conditions["uid"] = $uid;
119 return self::selectToArray([], $conditions, $params);
123 * Get a photo for user id
125 * @param integer $uid User id
126 * @param string $resourceid Rescource ID of the photo
127 * @param integer $scale Scale of the photo. Defaults to 0
128 * @param array $conditions Array of fields for conditions
129 * @param array $params Array of several parameters
134 * @see \Friendica\Database\DBA::select
136 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
138 $conditions["resource-id"] = $resourceid;
139 $conditions["uid"] = $uid;
140 $conditions["scale"] = $scale;
142 return self::selectFirst([], $conditions, $params);
146 * Get a single photo given resource id and scale
148 * This method checks for permissions. Returns associative array
149 * on success, "no sign" image info, if user has no permission,
150 * false if photo does not exists
152 * @param string $resourceid Rescource ID of the photo
153 * @param integer $scale Scale of the photo. Defaults to 0
155 * @return boolean|array
158 public static function getPhoto(string $resourceid, int $scale = 0)
160 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
161 if (!DBA::isResult($r)) {
167 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
169 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
171 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
172 $params = ["order" => ["scale" => true]];
173 $photo = self::selectFirst([], $conditions, $params);
179 * Check if photo with given conditions exists
181 * @param array $conditions Array of extra conditions
186 public static function exists(array $conditions)
188 return DBA::exists("photo", $conditions);
193 * Get Image data for given row id. null if row id does not exist
195 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
197 * @return \Friendica\Object\Image
199 public static function getImageDataForPhoto(array $photo)
201 if (!empty($photo['data'])) {
202 return $photo['data'];
206 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
207 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
208 return $backendClass->get($photo['backend-ref'] ?? '');
209 } catch (InvalidClassStorageException $storageException) {
211 // legacy data storage in "data" column
212 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
216 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
218 } catch (\Exception $exception) {
219 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
221 } catch (ReferenceStorageException $referenceStorageException) {
222 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
223 } catch (StorageException $storageException) {
224 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
225 } catch (\ImagickException $imagickException) {
226 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
233 * Get Image object for given row id. null if row id does not exist
235 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
237 * @return \Friendica\Object\Image
238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239 * @throws \ImagickException
241 public static function getImageForPhoto(array $photo): Image
243 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
247 * Return a list of fields that are associated with the photo table
249 * @return array field list
252 private static function getFields()
254 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
255 $fields = array_keys($allfields["photo"]["fields"]);
256 array_splice($fields, array_search("data", $fields), 1);
261 * Construct a photo array for a system resource image
263 * @param string $filename Image file name relative to code root
264 * @param string $mimetype Image mime type. Is guessed by file name when empty.
269 public static function createPhotoForSystemResource($filename, $mimetype = '')
271 if (empty($mimetype)) {
272 $mimetype = Images::guessTypeByExtension($filename);
275 $fields = self::getFields();
276 $values = array_fill(0, count($fields), "");
278 $photo = array_combine($fields, $values);
279 $photo['backend-class'] = SystemResource::NAME;
280 $photo['backend-ref'] = $filename;
281 $photo['type'] = $mimetype;
282 $photo['cacheable'] = false;
288 * Construct a photo array for an external resource image
290 * @param string $url Image URL
291 * @param int $uid User ID of the requesting person
292 * @param string $mimetype Image mime type. Is guessed by file name when empty.
297 public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = '')
299 if (empty($mimetype)) {
300 $mimetype = Images::guessTypeByExtension($url);
303 $fields = self::getFields();
304 $values = array_fill(0, count($fields), "");
306 $photo = array_combine($fields, $values);
307 $photo['backend-class'] = ExternalResource::NAME;
308 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
309 $photo['type'] = $mimetype;
310 $photo['cacheable'] = true;
316 * store photo metadata in db and binary in default backend
318 * @param Image $Image Image object with data
319 * @param integer $uid User ID
320 * @param integer $cid Contact ID
321 * @param integer $rid Resource ID
322 * @param string $filename Filename
323 * @param string $album Album name
324 * @param integer $scale Scale
325 * @param integer $profile Is a profile image? optional, default = 0
326 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
327 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
328 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
329 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
330 * @param string $desc Photo caption. optional, default = ""
332 * @return boolean True on success
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
335 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $type = self::DEFAULT, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
337 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
338 if (DBA::isResult($photo)) {
339 $guid = $photo["guid"];
341 $guid = System::createGUID();
344 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
345 $created = DateTimeFormat::utcNow();
346 if (DBA::isResult($existing_photo)) {
347 $created = $existing_photo["created"];
350 // Get defined storage backend.
351 // if no storage backend, we use old "data" column in photo table.
352 // if is an existing photo, reuse same backend
358 if (DBA::isResult($existing_photo)) {
359 $backend_ref = (string)$existing_photo["backend-ref"];
360 $storage = DI::storageManager()->getWritableStorageByName($existing_photo["backend-class"] ?? '');
362 $storage = DI::storage();
364 $backend_ref = $storage->put($Image->asString(), $backend_ref);
365 } catch (InvalidClassStorageException $storageException) {
366 $data = $Image->asString();
371 "contact-id" => $cid,
373 "resource-id" => $rid,
374 "hash" => md5($Image->asString()),
375 "created" => $created,
376 "edited" => DateTimeFormat::utcNow(),
377 "filename" => basename($filename),
378 "type" => $Image->getType(),
380 "height" => $Image->getHeight(),
381 "width" => $Image->getWidth(),
382 "datasize" => strlen($Image->asString()),
385 "photo-type" => $type,
387 "allow_cid" => $allow_cid,
388 "allow_gid" => $allow_gid,
389 "deny_cid" => $deny_cid,
390 "deny_gid" => $deny_gid,
392 "backend-class" => (string)$storage,
393 "backend-ref" => $backend_ref
396 if (DBA::isResult($existing_photo)) {
397 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
399 $r = DBA::insert("photo", $fields);
407 * Delete info from table and data from storage
409 * @param array $conditions Field condition(s)
410 * @param array $options Options array, Optional
415 * @see \Friendica\Database\DBA::delete
417 public static function delete(array $conditions, array $options = [])
419 // get photo to delete data info
420 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
422 while ($photo = DBA::fetch($photos)) {
424 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
425 $backend_class->delete($photo['backend-ref'] ?? '');
426 // Delete the photos after they had been deleted successfully
427 DBA::delete("photo", ['id' => $photo['id']]);
428 } catch (InvalidClassStorageException $storageException) {
429 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
430 } catch (ReferenceStorageException $referenceStorageException) {
431 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
437 return DBA::delete("photo", $conditions, $options);
443 * @param array $fields Contains the fields that are updated
444 * @param array $conditions Condition array with the key values
445 * @param Image $img Image to update. Optional, default null.
446 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
448 * @return boolean Was the update successfull?
450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
451 * @see \Friendica\Database\DBA::update
453 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
455 if (!is_null($img)) {
456 // get photo to update
457 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
459 foreach($photos as $photo) {
461 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
462 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
463 } catch (InvalidClassStorageException $storageException) {
464 $fields["data"] = $img->asString();
467 $fields['updated'] = DateTimeFormat::utcNow();
470 $fields['edited'] = DateTimeFormat::utcNow();
472 return DBA::update("photo", $fields, $conditions, $old_fields);
476 * @param string $image_url Remote URL
477 * @param integer $uid user id
478 * @param integer $cid contact id
479 * @param boolean $quit_on_error optional, default false
481 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482 * @throws \ImagickException
484 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
489 $photo = DBA::selectFirst(
490 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "photo-type" => self::CONTACT_AVATAR]
492 if (!empty($photo['resource-id'])) {
493 $resource_id = $photo["resource-id"];
495 $resource_id = self::newResource();
498 $photo_failure = false;
500 $filename = basename($image_url);
501 if (!empty($image_url)) {
502 $ret = DI::httpClient()->get($image_url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_IMAGE]);
503 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
504 $img_str = $ret->getBody();
505 $type = $ret->getContentType();
511 if ($quit_on_error && ($img_str == "")) {
515 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
517 $Image = new Image($img_str, $type);
518 if ($Image->isValid()) {
519 $Image->scaleToSquare(300);
521 $filesize = strlen($Image->asString());
522 $maximagesize = DI::config()->get('system', 'maximagesize');
523 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
524 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
525 if ($Image->getType() == 'image/gif') {
527 $Image = new Image($Image->asString(), 'image/png');
529 $filesize = strlen($Image->asString());
530 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
532 if ($filesize > $maximagesize) {
533 foreach ([160, 80] as $pixels) {
534 if ($filesize > $maximagesize) {
535 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
536 $Image->scaleDown($pixels);
537 $filesize = strlen($Image->asString());
541 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
544 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
547 $photo_failure = true;
550 $Image->scaleDown(80);
552 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
555 $photo_failure = true;
558 $Image->scaleDown(48);
560 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
563 $photo_failure = true;
566 $suffix = "?ts=" . time();
568 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
569 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
570 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
572 $photo_failure = true;
575 if ($photo_failure && $quit_on_error) {
579 if ($photo_failure) {
580 $contact = Contact::getById($cid) ?: [];
581 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
582 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
583 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
586 return [$image_url, $thumb, $micro];
590 * @param array $exifCoord coordinate
591 * @param string $hemi hemi
594 public static function getGps($exifCoord, $hemi)
596 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
597 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
598 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
600 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
602 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
606 * @param string $coordPart coordPart
609 private static function gps2Num($coordPart)
611 $parts = explode("/", $coordPart);
613 if (count($parts) <= 0) {
617 if (count($parts) == 1) {
621 return floatval($parts[0]) / floatval($parts[1]);
625 * Fetch the photo albums that are available for a viewer
627 * The query in this function is cost intensive, so it is cached.
629 * @param int $uid User id of the photos
630 * @param bool $update Update the cache
632 * @return array Returns array of the photo albums
633 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 public static function getAlbums($uid, $update = false)
637 $sql_extra = Security::getPermissionsSQLByUserId($uid);
639 $avatar_type = (local_user() && (local_user() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
640 $banner_type = (local_user() && (local_user() == $uid)) ? self::USER_BANNER : self::DEFAULT;
642 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
643 $albums = DI::cache()->get($key);
644 if (is_null($albums) || $update) {
645 if (!DI::config()->get("system", "no_count", false)) {
646 /// @todo This query needs to be renewed. It is really slow
647 // At this time we just store the data in the cache
648 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
650 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra
651 GROUP BY `album` ORDER BY `created` DESC",
658 // This query doesn't do the count and is much faster
659 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
660 FROM `photo` USE INDEX (`uid_album_scale_created`)
661 WHERE `uid` = ? AND `photo-type` IN (?, ?, ?) $sql_extra",
668 DI::cache()->set($key, $albums, Duration::DAY);
674 * @param int $uid User id of the photos
678 public static function clearAlbumCache($uid)
680 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
681 DI::cache()->set($key, null, Duration::DAY);
685 * Generate a unique photo ID.
690 public static function newResource()
692 return System::createGUID(32, false);
696 * Extracts the rid from a local photo URI
698 * @param string $image_uri The URI of the photo
699 * @return string The rid of the photo, or an empty string if the URI is not local
701 public static function ridFromURI(string $image_uri)
703 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
706 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
707 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
708 if (!strlen($image_uri)) {
715 * Changes photo permissions that had been embedded in a post
717 * @todo This function currently does have some flaws:
718 * - Sharing a post with a forum will create a photo that only the forum can see.
719 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
724 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
726 // Simplify image codes
727 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
728 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
731 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
735 if (empty($images)) {
739 foreach ($images as $image) {
740 $image_rid = self::ridFromURI($image);
741 if (empty($image_rid)) {
745 // Ensure to only modify photos that you own
746 $srch = '<' . intval($original_contact_id) . '>';
749 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
750 'resource-id' => $image_rid, 'uid' => $uid
752 if (!self::exists($condition)) {
753 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
754 if (!DBA::isResult($photo)) {
755 Logger::info('Image not found', ['resource-id' => $image_rid]);
757 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
763 * @todo Existing permissions need to be mixed with the new ones.
764 * Otherwise this creates problems with sharing the same picture multiple times
765 * Also check if $str_contact_allow does contain a public forum.
766 * Then set the permissions to public.
769 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
776 * Add permissions to photo ressource
777 * @todo mix with previous photo permissions
779 * @param string $image_rid
780 * @param integer $uid
781 * @param string $str_contact_allow
782 * @param string $str_group_allow
783 * @param string $str_contact_deny
784 * @param string $str_group_deny
787 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)
789 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
790 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
791 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
793 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
794 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
795 self::update($fields, $condition);
799 * Fetch the guid and scale from picture links
801 * @param string $name Picture link
804 public static function getResourceData(string $name):array
806 $base = DI::baseUrl()->get();
808 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
810 if (parse_url($guid, PHP_URL_SCHEME)) {
814 $guid = pathinfo($guid, PATHINFO_FILENAME);
815 if (substr($guid, -2, 1) != "-") {
819 $scale = intval(substr($guid, -1, 1));
820 if (!is_numeric($scale)) {
824 $guid = substr($guid, 0, -2);
825 return ['guid' => $guid, 'scale' => $scale];
829 * Tests if the picture link points to a locally stored picture
831 * @param string $name Picture link
835 public static function isLocal($name)
837 return (bool)self::getIdForName($name);
841 * Return the id of a local photo
843 * @param string $name Picture link
846 public static function getIdForName($name)
848 $data = self::getResourceData($name);
853 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
854 if (!empty($photo['id'])) {
861 * Tests if the link points to a locally stored picture page
863 * @param string $name Page link
867 public static function isLocalPage($name)
869 $base = DI::baseUrl()->get();
871 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
872 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
877 return DBA::exists('photo', ['resource-id' => $guid]);
880 private static function fitImageSize($Image)
882 $max_length = DI::config()->get('system', 'max_image_length');
883 if ($max_length > 0) {
884 $Image->scaleDown($max_length);
885 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
888 $filesize = strlen($Image->asString());
889 $width = $Image->getWidth();
890 $height = $Image->getHeight();
892 $maximagesize = DI::config()->get('system', 'maximagesize');
894 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
895 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
896 foreach ([5120, 2560, 1280, 640] as $pixels) {
897 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
898 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
899 $Image->scaleDown($pixels);
900 $filesize = strlen($Image->asString());
901 $width = $Image->getWidth();
902 $height = $Image->getHeight();
905 if ($filesize > $maximagesize) {
906 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
914 private static function loadImageFromURL(string $image_url)
916 $filename = basename($image_url);
917 if (!empty($image_url)) {
918 $ret = DI::httpClient()->get($image_url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_IMAGE]);
919 Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
920 $img_str = $ret->getBody();
921 $type = $ret->getContentType();
927 if (empty($img_str)) {
928 Logger::notice('Empty content');
932 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
934 $Image = new Image($img_str, $type);
936 $Image = self::fitImageSize($Image);
941 return ['image' => $Image, 'filename' => $filename];
944 private static function uploadImage(array $files)
946 Logger::info('starting new upload');
949 Logger::notice('Empty upload file');
953 if (!empty($files['tmp_name'])) {
954 if (is_array($files['tmp_name'])) {
955 $src = $files['tmp_name'][0];
957 $src = $files['tmp_name'];
963 if (!empty($files['name'])) {
964 if (is_array($files['name'])) {
965 $filename = basename($files['name'][0]);
967 $filename = basename($files['name']);
973 if (!empty($files['size'])) {
974 if (is_array($files['size'])) {
975 $filesize = intval($files['size'][0]);
977 $filesize = intval($files['size']);
983 if (!empty($files['type'])) {
984 if (is_array($files['type'])) {
985 $filetype = $files['type'][0];
987 $filetype = $files['type'];
994 Logger::notice('No source file name', ['files' => $files]);
998 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
1000 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
1002 $imagedata = @file_get_contents($src);
1003 $Image = new Image($imagedata, $filetype);
1004 if (!$Image->isValid()) {
1005 Logger::notice('Image is unvalid', ['files' => $files]);
1009 $Image->orient($src);
1012 $Image = self::fitImageSize($Image);
1013 if (empty($Image)) {
1017 return ['image' => $Image, 'filename' => $filename];
1021 * @param int $uid User ID
1022 * @param array $files uploaded file array
1023 * @param string $album
1024 * @param string|null $allow_cid
1025 * @param string|null $allow_gid
1026 * @param string $deny_cid
1027 * @param string $deny_gid
1028 * @param string $desc
1029 * @param string $resource_id
1030 * @return array photo record
1031 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1033 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
1035 $user = User::getOwnerDataById($uid);
1037 Logger::notice('User not found', ['uid' => $uid]);
1041 $data = self::uploadImage($files);
1043 Logger::info('upload failed');
1047 $Image = $data['image'];
1048 $filename = $data['filename'];
1049 $width = $Image->getWidth();
1050 $height = $Image->getHeight();
1052 $resource_id = $resource_id ?: self::newResource();
1053 $album = $album ?: DI::l10n()->t('Wall Photos');
1055 if (is_null($allow_cid) && is_null($allow_gid)) {
1056 $allow_cid = '<' . $user['id'] . '>';
1062 $r = self::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1064 Logger::notice('Photo could not be stored');
1068 if ($width > 640 || $height > 640) {
1069 $Image->scaleDown(640);
1070 $r = self::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1076 if ($width > 320 || $height > 320) {
1077 $Image->scaleDown(320);
1078 $r = self::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
1079 if ($r && ($smallest == 0)) {
1084 $condition = ['resource-id' => $resource_id];
1085 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1086 if (empty($photo)) {
1087 Logger::notice('Photo not found', ['condition' => $condition]);
1093 $picture['id'] = $photo['id'];
1094 $picture['resource_id'] = $resource_id;
1095 $picture['size'] = $photo['datasize'];
1096 $picture['width'] = $photo['width'];
1097 $picture['height'] = $photo['height'];
1098 $picture['type'] = $photo['type'];
1099 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1100 $picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
1101 $picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
1103 Logger::info('upload done', ['picture' => $picture]);
1108 * Upload a user avatar
1110 * @param int $uid User ID
1111 * @param array $files uploaded file array
1112 * @param string $url External image url
1113 * @return string avatar resource
1115 public static function uploadAvatar(int $uid, array $files, string $url = ''): string
1117 if (!empty($files)) {
1118 $data = self::uploadImage($files);
1120 Logger::info('upload failed');
1123 } elseif (!empty($url)) {
1124 $data = self::loadImageFromURL($url);
1126 Logger::info('loading from external url failed');
1130 Logger::info('Neither files nor url provided');
1134 $Image = $data['image'];
1135 $filename = $data['filename'];
1136 $width = $Image->getWidth();
1137 $height = $Image->getHeight();
1139 $resource_id = self::newResource();
1140 $album = DI::l10n()->t(self::PROFILE_PHOTOS);
1142 // upload profile image (scales 4, 5, 6)
1143 logger::info('starting new profile image upload');
1145 if ($width > 300 || $height > 300) {
1146 $Image->scaleDown(300);
1149 $r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
1151 logger::notice('profile image upload with scale 4 (300) failed');
1154 if ($width > 80 || $height > 80) {
1155 $Image->scaleDown(80);
1158 $r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
1160 logger::notice('profile image upload with scale 5 (80) failed');
1163 if ($width > 48 || $height > 48) {
1164 $Image->scaleDown(48);
1167 $r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
1169 logger::notice('profile image upload with scale 6 (48) failed');
1172 logger::info('new profile image upload ended');
1174 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
1175 self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
1177 Contact::updateSelfFromUserID($uid, true);
1179 // Update global directory in background
1180 Profile::publishUpdate($uid);
1182 return $resource_id;
1186 * Upload a user banner
1188 * @param int $uid User ID
1189 * @param array $files uploaded file array
1190 * @param string $url External image url
1191 * @return string avatar resource
1193 public static function uploadBanner(int $uid, array $files = [], string $url = ''): string
1195 if (!empty($files)) {
1196 $data = self::uploadImage($files);
1198 Logger::info('upload failed');
1201 } elseif (!empty($url)) {
1202 $data = self::loadImageFromURL($url);
1204 Logger::info('loading from external url failed');
1208 Logger::info('Neither files nor url provided');
1212 $Image = $data['image'];
1213 $filename = $data['filename'];
1214 $width = $Image->getWidth();
1215 $height = $Image->getHeight();
1217 $resource_id = self::newResource();
1218 $album = DI::l10n()->t(self::BANNER_PHOTOS);
1221 $Image->scaleDown(960);
1224 $r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
1226 logger::notice('profile banner upload with scale 3 (960) failed');
1229 logger::info('new profile banner upload ended');
1231 $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
1232 self::update(['photo-type' => self::DEFAULT], $condition);
1234 Contact::updateSelfFromUserID($uid, true);
1236 // Update global directory in background
1237 Profile::publishUpdate($uid);
1239 return $resource_id;