3 * @copyright Copyright (C) 2010-2021, 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\Model\Storage\ExternalResource;
31 use Friendica\Model\Storage\InvalidClassStorageException;
32 use Friendica\Model\Storage\ReferenceStorageException;
33 use Friendica\Model\Storage\StorageException;
34 use Friendica\Model\Storage\SystemResource;
35 use Friendica\Object\Image;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Images;
38 use Friendica\Security\Security;
39 use Friendica\Util\Proxy;
40 use Friendica\Util\Strings;
43 * Class to handle photo dabatase table
47 const CONTACT_PHOTOS = 'Contact Photos';
48 const PROFILE_PHOTOS = 'Profile Photos';
51 const USER_AVATAR = 10;
52 const USER_BANNER = 11;
53 const CONTACT_AVATAR = 20;
54 const CONTACT_BANNER = 21;
57 * Select rows from the photo table and returns them as array
59 * @param array $fields Array of selected fields, empty for all
60 * @param array $conditions Array of fields for conditions
61 * @param array $params Array of several parameters
63 * @return boolean|array
66 * @see \Friendica\Database\DBA::selectToArray
68 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
71 $fields = self::getFields();
74 return DBA::selectToArray('photo', $fields, $conditions, $params);
78 * Retrieve a single record from the photo table
80 * @param array $fields Array of selected fields, empty for all
81 * @param array $conditions Array of fields for conditions
82 * @param array $params Array of several parameters
87 * @see \Friendica\Database\DBA::select
89 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
92 $fields = self::getFields();
95 return DBA::selectFirst("photo", $fields, $conditions, $params);
99 * Get photos for user id
101 * @param integer $uid User id
102 * @param string $resourceid Rescource ID of the photo
103 * @param array $conditions Array of fields for conditions
104 * @param array $params Array of several parameters
109 * @see \Friendica\Database\DBA::select
111 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
113 $conditions["resource-id"] = $resourceid;
114 $conditions["uid"] = $uid;
116 return self::selectToArray([], $conditions, $params);
120 * Get a photo for user id
122 * @param integer $uid User id
123 * @param string $resourceid Rescource ID of the photo
124 * @param integer $scale Scale of the photo. Defaults to 0
125 * @param array $conditions Array of fields for conditions
126 * @param array $params Array of several parameters
131 * @see \Friendica\Database\DBA::select
133 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
135 $conditions["resource-id"] = $resourceid;
136 $conditions["uid"] = $uid;
137 $conditions["scale"] = $scale;
139 return self::selectFirst([], $conditions, $params);
143 * Get a single photo given resource id and scale
145 * This method checks for permissions. Returns associative array
146 * on success, "no sign" image info, if user has no permission,
147 * false if photo does not exists
149 * @param string $resourceid Rescource ID of the photo
150 * @param integer $scale Scale of the photo. Defaults to 0
152 * @return boolean|array
155 public static function getPhoto(string $resourceid, int $scale = 0)
157 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
158 if (!DBA::isResult($r)) {
164 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
166 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
168 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
169 $params = ["order" => ["scale" => true]];
170 $photo = self::selectFirst([], $conditions, $params);
176 * Check if photo with given conditions exists
178 * @param array $conditions Array of extra conditions
183 public static function exists(array $conditions)
185 return DBA::exists("photo", $conditions);
190 * Get Image data for given row id. null if row id does not exist
192 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
194 * @return \Friendica\Object\Image
196 public static function getImageDataForPhoto(array $photo)
198 if (!empty($photo['data'])) {
199 return $photo['data'];
203 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
204 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
205 return $backendClass->get($photo['backend-ref'] ?? '');
206 } catch (InvalidClassStorageException $storageException) {
208 // legacy data storage in "data" column
209 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
213 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
215 } catch (\Exception $exception) {
216 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
218 } catch (ReferenceStorageException $referenceStorageException) {
219 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
220 } catch (StorageException $storageException) {
221 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
222 } catch (\ImagickException $imagickException) {
223 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
230 * Get Image object for given row id. null if row id does not exist
232 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
234 * @return \Friendica\Object\Image
235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
236 * @throws \ImagickException
238 public static function getImageForPhoto(array $photo): Image
240 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
244 * Return a list of fields that are associated with the photo table
246 * @return array field list
249 private static function getFields()
251 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
252 $fields = array_keys($allfields["photo"]["fields"]);
253 array_splice($fields, array_search("data", $fields), 1);
258 * Construct a photo array for a system resource image
260 * @param string $filename Image file name relative to code root
261 * @param string $mimetype Image mime type. Is guessed by file name when empty.
266 public static function createPhotoForSystemResource($filename, $mimetype = '')
268 if (empty($mimetype)) {
269 $mimetype = Images::guessTypeByExtension($filename);
272 $fields = self::getFields();
273 $values = array_fill(0, count($fields), "");
275 $photo = array_combine($fields, $values);
276 $photo['backend-class'] = SystemResource::NAME;
277 $photo['backend-ref'] = $filename;
278 $photo['type'] = $mimetype;
279 $photo['cacheable'] = false;
285 * Construct a photo array for an external resource image
287 * @param string $url Image URL
288 * @param int $uid User ID of the requesting person
289 * @param string $mimetype Image mime type. Is guessed by file name when empty.
294 public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = '')
296 if (empty($mimetype)) {
297 $mimetype = Images::guessTypeByExtension($url);
300 $fields = self::getFields();
301 $values = array_fill(0, count($fields), "");
303 $photo = array_combine($fields, $values);
304 $photo['backend-class'] = ExternalResource::NAME;
305 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
306 $photo['type'] = $mimetype;
307 $photo['cacheable'] = true;
313 * store photo metadata in db and binary in default backend
315 * @param Image $Image Image object with data
316 * @param integer $uid User ID
317 * @param integer $cid Contact ID
318 * @param integer $rid Resource ID
319 * @param string $filename Filename
320 * @param string $album Album name
321 * @param integer $scale Scale
322 * @param integer $profile Is a profile image? optional, default = 0
323 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
324 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
325 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
326 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
327 * @param string $desc Photo caption. optional, default = ""
329 * @return boolean True on success
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
332 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $type = self::DEFAULT, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
334 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
335 if (DBA::isResult($photo)) {
336 $guid = $photo["guid"];
338 $guid = System::createGUID();
341 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
342 $created = DateTimeFormat::utcNow();
343 if (DBA::isResult($existing_photo)) {
344 $created = $existing_photo["created"];
347 // Get defined storage backend.
348 // if no storage backend, we use old "data" column in photo table.
349 // if is an existing photo, reuse same backend
355 if (DBA::isResult($existing_photo)) {
356 $backend_ref = (string)$existing_photo["backend-ref"];
357 $storage = DI::storageManager()->getWritableStorageByName($existing_photo["backend-class"] ?? '');
359 $storage = DI::storage();
361 $backend_ref = $storage->put($Image->asString(), $backend_ref);
362 } catch (InvalidClassStorageException $storageException) {
363 $data = $Image->asString();
368 "contact-id" => $cid,
370 "resource-id" => $rid,
371 "hash" => md5($Image->asString()),
372 "created" => $created,
373 "edited" => DateTimeFormat::utcNow(),
374 "filename" => basename($filename),
375 "type" => $Image->getType(),
377 "height" => $Image->getHeight(),
378 "width" => $Image->getWidth(),
379 "datasize" => strlen($Image->asString()),
382 "photo-type" => $type,
384 "allow_cid" => $allow_cid,
385 "allow_gid" => $allow_gid,
386 "deny_cid" => $deny_cid,
387 "deny_gid" => $deny_gid,
389 "backend-class" => (string)$storage,
390 "backend-ref" => $backend_ref
393 if (DBA::isResult($existing_photo)) {
394 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
396 $r = DBA::insert("photo", $fields);
404 * Delete info from table and data from storage
406 * @param array $conditions Field condition(s)
407 * @param array $options Options array, Optional
412 * @see \Friendica\Database\DBA::delete
414 public static function delete(array $conditions, array $options = [])
416 // get photo to delete data info
417 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
419 while ($photo = DBA::fetch($photos)) {
421 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
422 $backend_class->delete($photo['backend-ref'] ?? '');
423 // Delete the photos after they had been deleted successfully
424 DBA::delete("photo", ['id' => $photo['id']]);
425 } catch (InvalidClassStorageException $storageException) {
426 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
427 } catch (ReferenceStorageException $referenceStorageException) {
428 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
434 return DBA::delete("photo", $conditions, $options);
440 * @param array $fields Contains the fields that are updated
441 * @param array $conditions Condition array with the key values
442 * @param Image $img Image to update. Optional, default null.
443 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
445 * @return boolean Was the update successfull?
447 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
448 * @see \Friendica\Database\DBA::update
450 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
452 if (!is_null($img)) {
453 // get photo to update
454 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
456 foreach($photos as $photo) {
458 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
459 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
460 } catch (InvalidClassStorageException $storageException) {
461 $fields["data"] = $img->asString();
464 $fields['updated'] = DateTimeFormat::utcNow();
467 $fields['edited'] = DateTimeFormat::utcNow();
469 return DBA::update("photo", $fields, $conditions, $old_fields);
473 * @param string $image_url Remote URL
474 * @param integer $uid user id
475 * @param integer $cid contact id
476 * @param boolean $quit_on_error optional, default false
478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
479 * @throws \ImagickException
481 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
486 $photo = DBA::selectFirst(
487 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "photo-type" => self::CONTACT_AVATAR]
489 if (!empty($photo['resource-id'])) {
490 $resource_id = $photo["resource-id"];
492 $resource_id = self::newResource();
495 $photo_failure = false;
497 $filename = basename($image_url);
498 if (!empty($image_url)) {
499 $ret = DI::httpClient()->get($image_url);
500 $img_str = $ret->getBody();
501 $type = $ret->getContentType();
507 if ($quit_on_error && ($img_str == "")) {
511 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
513 $Image = new Image($img_str, $type);
514 if ($Image->isValid()) {
515 $Image->scaleToSquare(300);
517 $filesize = strlen($Image->asString());
518 $maximagesize = DI::config()->get('system', 'maximagesize');
519 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
520 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
521 if ($Image->getType() == 'image/gif') {
523 $Image = new Image($Image->asString(), 'image/png');
525 $filesize = strlen($Image->asString());
526 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
528 if ($filesize > $maximagesize) {
529 foreach ([160, 80] as $pixels) {
530 if ($filesize > $maximagesize) {
531 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
532 $Image->scaleDown($pixels);
533 $filesize = strlen($Image->asString());
537 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
540 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
543 $photo_failure = true;
546 $Image->scaleDown(80);
548 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
551 $photo_failure = true;
554 $Image->scaleDown(48);
556 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
559 $photo_failure = true;
562 $suffix = "?ts=" . time();
564 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
565 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
566 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
568 $photo_failure = true;
571 if ($photo_failure && $quit_on_error) {
575 if ($photo_failure) {
576 $contact = Contact::getById($cid) ?: [];
577 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
578 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
579 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
582 return [$image_url, $thumb, $micro];
586 * @param array $exifCoord coordinate
587 * @param string $hemi hemi
590 public static function getGps($exifCoord, $hemi)
592 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
593 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
594 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
596 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
598 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
602 * @param string $coordPart coordPart
605 private static function gps2Num($coordPart)
607 $parts = explode("/", $coordPart);
609 if (count($parts) <= 0) {
613 if (count($parts) == 1) {
617 return floatval($parts[0]) / floatval($parts[1]);
621 * Fetch the photo albums that are available for a viewer
623 * The query in this function is cost intensive, so it is cached.
625 * @param int $uid User id of the photos
626 * @param bool $update Update the cache
628 * @return array Returns array of the photo albums
629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 public static function getAlbums($uid, $update = false)
633 $sql_extra = Security::getPermissionsSQLByUserId($uid);
635 $avatar_type = (local_user() && (local_user() == $uid)) ? Photo::USER_AVATAR : Photo::DEFAULT;
637 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
638 $albums = DI::cache()->get($key);
639 if (is_null($albums) || $update) {
640 if (!DI::config()->get("system", "no_count", false)) {
641 /// @todo This query needs to be renewed. It is really slow
642 // At this time we just store the data in the cache
643 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
645 WHERE `uid` = ? AND `photo-type` IN (?, ?) $sql_extra
646 GROUP BY `album` ORDER BY `created` DESC",
652 // This query doesn't do the count and is much faster
653 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
654 FROM `photo` USE INDEX (`uid_album_scale_created`)
655 WHERE `uid` = ? AND `photo-type` IN (?, ?) $sql_extra",
661 DI::cache()->set($key, $albums, Duration::DAY);
667 * @param int $uid User id of the photos
671 public static function clearAlbumCache($uid)
673 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
674 DI::cache()->set($key, null, Duration::DAY);
678 * Generate a unique photo ID.
683 public static function newResource()
685 return System::createGUID(32, false);
689 * Extracts the rid from a local photo URI
691 * @param string $image_uri The URI of the photo
692 * @return string The rid of the photo, or an empty string if the URI is not local
694 public static function ridFromURI(string $image_uri)
696 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
699 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
700 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
701 if (!strlen($image_uri)) {
708 * Changes photo permissions that had been embedded in a post
710 * @todo This function currently does have some flaws:
711 * - Sharing a post with a forum will create a photo that only the forum can see.
712 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
717 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
719 // Simplify image codes
720 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
721 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
724 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
728 if (empty($images)) {
732 foreach ($images as $image) {
733 $image_rid = self::ridFromURI($image);
734 if (empty($image_rid)) {
738 // Ensure to only modify photos that you own
739 $srch = '<' . intval($original_contact_id) . '>';
742 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
743 'resource-id' => $image_rid, 'uid' => $uid
745 if (!Photo::exists($condition)) {
746 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
747 if (!DBA::isResult($photo)) {
748 Logger::info('Image not found', ['resource-id' => $image_rid]);
750 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
756 * @todo Existing permissions need to be mixed with the new ones.
757 * Otherwise this creates problems with sharing the same picture multiple times
758 * Also check if $str_contact_allow does contain a public forum.
759 * Then set the permissions to public.
762 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
769 * Add permissions to photo ressource
770 * @todo mix with previous photo permissions
772 * @param string $image_rid
773 * @param integer $uid
774 * @param string $str_contact_allow
775 * @param string $str_group_allow
776 * @param string $str_contact_deny
777 * @param string $str_group_deny
780 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)
782 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
783 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
784 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
786 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
787 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
788 Photo::update($fields, $condition);
792 * Fetch the guid and scale from picture links
794 * @param string $name Picture link
797 public static function getResourceData(string $name):array
799 $base = DI::baseUrl()->get();
801 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
803 if (parse_url($guid, PHP_URL_SCHEME)) {
807 $guid = pathinfo($guid, PATHINFO_FILENAME);
808 if (substr($guid, -2, 1) != "-") {
812 $scale = intval(substr($guid, -1, 1));
813 if (!is_numeric($scale)) {
817 $guid = substr($guid, 0, -2);
818 return ['guid' => $guid, 'scale' => $scale];
822 * Tests if the picture link points to a locally stored picture
824 * @param string $name Picture link
828 public static function isLocal($name)
830 return (bool)self::getIdForName($name);
834 * Return the id of a local photo
836 * @param string $name Picture link
839 public static function getIdForName($name)
841 $data = self::getResourceData($name);
846 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
847 if (!empty($photo['id'])) {
854 * Tests if the link points to a locally stored picture page
856 * @param string $name Page link
860 public static function isLocalPage($name)
862 $base = DI::baseUrl()->get();
864 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
865 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
870 return DBA::exists('photo', ['resource-id' => $guid]);
875 * @param int $uid User ID
876 * @param array $files uploaded file array
877 * @return array photo record
879 public static function upload(int $uid, array $files)
881 Logger::info('starting new upload');
883 $user = User::getOwnerDataById($uid);
885 Logger::notice('User not found', ['uid' => $uid]);
890 Logger::notice('Empty upload file');
894 if (!empty($files['tmp_name'])) {
895 if (is_array($files['tmp_name'])) {
896 $src = $files['tmp_name'][0];
898 $src = $files['tmp_name'];
904 if (!empty($files['name'])) {
905 if (is_array($files['name'])) {
906 $filename = basename($files['name'][0]);
908 $filename = basename($files['name']);
914 if (!empty($files['size'])) {
915 if (is_array($files['size'])) {
916 $filesize = intval($files['size'][0]);
918 $filesize = intval($files['size']);
924 if (!empty($files['type'])) {
925 if (is_array($files['type'])) {
926 $filetype = $files['type'][0];
928 $filetype = $files['type'];
935 Logger::notice('No source file name', ['uid' => $uid, 'files' => $files]);
939 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
941 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
943 $imagedata = @file_get_contents($src);
944 $Image = new Image($imagedata, $filetype);
945 if (!$Image->isValid()) {
946 Logger::notice('Image is unvalid', ['uid' => $uid, 'files' => $files]);
950 $Image->orient($src);
953 $max_length = DI::config()->get('system', 'max_image_length');
955 $max_length = MAX_IMAGE_LENGTH;
957 if ($max_length > 0) {
958 $Image->scaleDown($max_length);
959 $filesize = strlen($Image->asString());
960 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
963 $width = $Image->getWidth();
964 $height = $Image->getHeight();
966 $maximagesize = DI::config()->get('system', 'maximagesize');
968 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
969 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
970 foreach ([5120, 2560, 1280, 640] as $pixels) {
971 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
972 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
973 $Image->scaleDown($pixels);
974 $filesize = strlen($Image->asString());
975 $width = $Image->getWidth();
976 $height = $Image->getHeight();
979 if ($filesize > $maximagesize) {
981 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
986 $resource_id = Photo::newResource();
987 $album = DI::l10n()->t('Wall Photos');
988 $defperm = '<' . $user['id'] . '>';
992 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $defperm);
994 Logger::notice('Photo could not be stored');
998 if ($width > 640 || $height > 640) {
999 $Image->scaleDown(640);
1000 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $defperm);
1006 if ($width > 320 || $height > 320) {
1007 $Image->scaleDown(320);
1008 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $defperm);
1009 if ($r && ($smallest == 0)) {
1014 $condition = ['resource-id' => $resource_id];
1015 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1016 if (empty($photo)) {
1017 Logger::notice('Photo not found', ['condition' => $condition]);
1023 $picture['id'] = $photo['id'];
1024 $picture['size'] = $photo['datasize'];
1025 $picture['width'] = $photo['width'];
1026 $picture['height'] = $photo['height'];
1027 $picture['type'] = $photo['type'];
1028 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1029 $picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
1030 $picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
1032 Logger::info('upload done', ['picture' => $picture]);