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\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';
50 const USER_AVATAR = 10;
51 const USER_BANNER = 11;
52 const CONTACT_AVATAR = 20;
53 const CONTACT_BANNER = 21;
56 * Select rows from the photo table and returns them as array
58 * @param array $fields Array of selected fields, empty for all
59 * @param array $conditions Array of fields for conditions
60 * @param array $params Array of several parameters
62 * @return boolean|array
65 * @see \Friendica\Database\DBA::selectToArray
67 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
70 $fields = self::getFields();
73 return DBA::selectToArray('photo', $fields, $conditions, $params);
77 * Retrieve a single record from the photo table
79 * @param array $fields Array of selected fields, empty for all
80 * @param array $conditions Array of fields for conditions
81 * @param array $params Array of several parameters
86 * @see \Friendica\Database\DBA::select
88 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
91 $fields = self::getFields();
94 return DBA::selectFirst("photo", $fields, $conditions, $params);
98 * Get photos for user id
100 * @param integer $uid User id
101 * @param string $resourceid Rescource ID of the photo
102 * @param array $conditions Array of fields for conditions
103 * @param array $params Array of several parameters
108 * @see \Friendica\Database\DBA::select
110 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
112 $conditions["resource-id"] = $resourceid;
113 $conditions["uid"] = $uid;
115 return self::selectToArray([], $conditions, $params);
119 * Get a photo for user id
121 * @param integer $uid User id
122 * @param string $resourceid Rescource ID of the photo
123 * @param integer $scale Scale of the photo. Defaults to 0
124 * @param array $conditions Array of fields for conditions
125 * @param array $params Array of several parameters
130 * @see \Friendica\Database\DBA::select
132 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
134 $conditions["resource-id"] = $resourceid;
135 $conditions["uid"] = $uid;
136 $conditions["scale"] = $scale;
138 return self::selectFirst([], $conditions, $params);
142 * Get a single photo given resource id and scale
144 * This method checks for permissions. Returns associative array
145 * on success, "no sign" image info, if user has no permission,
146 * false if photo does not exists
148 * @param string $resourceid Rescource ID of the photo
149 * @param integer $scale Scale of the photo. Defaults to 0
151 * @return boolean|array
154 public static function getPhoto(string $resourceid, int $scale = 0)
156 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
157 if (!DBA::isResult($r)) {
163 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
165 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
167 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
168 $params = ["order" => ["scale" => true]];
169 $photo = self::selectFirst([], $conditions, $params);
175 * Check if photo with given conditions exists
177 * @param array $conditions Array of extra conditions
182 public static function exists(array $conditions)
184 return DBA::exists("photo", $conditions);
189 * Get Image data for given row id. null if row id does not exist
191 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
193 * @return \Friendica\Object\Image
195 public static function getImageDataForPhoto(array $photo)
197 if (!empty($photo['data'])) {
198 return $photo['data'];
202 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
203 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
204 return $backendClass->get($photo['backend-ref'] ?? '');
205 } catch (InvalidClassStorageException $storageException) {
207 // legacy data storage in "data" column
208 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
212 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
214 } catch (\Exception $exception) {
215 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
217 } catch (ReferenceStorageException $referenceStorageException) {
218 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
219 } catch (StorageException $storageException) {
220 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
221 } catch (\ImagickException $imagickException) {
222 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
229 * Get Image object for given row id. null if row id does not exist
231 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
233 * @return \Friendica\Object\Image
234 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
235 * @throws \ImagickException
237 public static function getImageForPhoto(array $photo): Image
239 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
243 * Return a list of fields that are associated with the photo table
245 * @return array field list
248 private static function getFields()
250 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
251 $fields = array_keys($allfields["photo"]["fields"]);
252 array_splice($fields, array_search("data", $fields), 1);
257 * Construct a photo array for a system resource image
259 * @param string $filename Image file name relative to code root
260 * @param string $mimetype Image mime type. Is guessed by file name when empty.
265 public static function createPhotoForSystemResource($filename, $mimetype = '')
267 if (empty($mimetype)) {
268 $mimetype = Images::guessTypeByExtension($filename);
271 $fields = self::getFields();
272 $values = array_fill(0, count($fields), "");
274 $photo = array_combine($fields, $values);
275 $photo['backend-class'] = SystemResource::NAME;
276 $photo['backend-ref'] = $filename;
277 $photo['type'] = $mimetype;
278 $photo['cacheable'] = false;
284 * Construct a photo array for an external resource image
286 * @param string $url Image URL
287 * @param int $uid User ID of the requesting person
288 * @param string $mimetype Image mime type. Is guessed by file name when empty.
293 public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = '')
295 if (empty($mimetype)) {
296 $mimetype = Images::guessTypeByExtension($url);
299 $fields = self::getFields();
300 $values = array_fill(0, count($fields), "");
302 $photo = array_combine($fields, $values);
303 $photo['backend-class'] = ExternalResource::NAME;
304 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
305 $photo['type'] = $mimetype;
306 $photo['cacheable'] = true;
312 * store photo metadata in db and binary in default backend
314 * @param Image $Image Image object with data
315 * @param integer $uid User ID
316 * @param integer $cid Contact ID
317 * @param integer $rid Resource ID
318 * @param string $filename Filename
319 * @param string $album Album name
320 * @param integer $scale Scale
321 * @param integer $profile Is a profile image? optional, default = 0
322 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
323 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
324 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
325 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
326 * @param string $desc Photo caption. optional, default = ""
328 * @return boolean True on success
329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $type = self::DEFAULT, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
333 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
334 if (DBA::isResult($photo)) {
335 $guid = $photo["guid"];
337 $guid = System::createGUID();
340 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
341 $created = DateTimeFormat::utcNow();
342 if (DBA::isResult($existing_photo)) {
343 $created = $existing_photo["created"];
346 // Get defined storage backend.
347 // if no storage backend, we use old "data" column in photo table.
348 // if is an existing photo, reuse same backend
354 if (DBA::isResult($existing_photo)) {
355 $backend_ref = (string)$existing_photo["backend-ref"];
356 $storage = DI::storageManager()->getWritableStorageByName($existing_photo["backend-class"] ?? '');
358 $storage = DI::storage();
360 $backend_ref = $storage->put($Image->asString(), $backend_ref);
361 } catch (InvalidClassStorageException $storageException) {
362 $data = $Image->asString();
367 "contact-id" => $cid,
369 "resource-id" => $rid,
370 "hash" => md5($Image->asString()),
371 "created" => $created,
372 "edited" => DateTimeFormat::utcNow(),
373 "filename" => basename($filename),
374 "type" => $Image->getType(),
376 "height" => $Image->getHeight(),
377 "width" => $Image->getWidth(),
378 "datasize" => strlen($Image->asString()),
381 "photo-type" => $type,
382 "profile" => $type == self::USER_AVATAR,
383 "allow_cid" => $allow_cid,
384 "allow_gid" => $allow_gid,
385 "deny_cid" => $deny_cid,
386 "deny_gid" => $deny_gid,
388 "backend-class" => (string)$storage,
389 "backend-ref" => $backend_ref
392 if (DBA::isResult($existing_photo)) {
393 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
395 $r = DBA::insert("photo", $fields);
403 * Delete info from table and data from storage
405 * @param array $conditions Field condition(s)
406 * @param array $options Options array, Optional
411 * @see \Friendica\Database\DBA::delete
413 public static function delete(array $conditions, array $options = [])
415 // get photo to delete data info
416 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
418 while ($photo = DBA::fetch($photos)) {
420 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
421 $backend_class->delete($photo['backend-ref'] ?? '');
422 // Delete the photos after they had been deleted successfully
423 DBA::delete("photo", ['id' => $photo['id']]);
424 } catch (InvalidClassStorageException $storageException) {
425 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
426 } catch (ReferenceStorageException $referenceStorageException) {
427 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
433 return DBA::delete("photo", $conditions, $options);
439 * @param array $fields Contains the fields that are updated
440 * @param array $conditions Condition array with the key values
441 * @param Image $img Image to update. Optional, default null.
442 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
444 * @return boolean Was the update successfull?
446 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
447 * @see \Friendica\Database\DBA::update
449 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
451 if (!is_null($img)) {
452 // get photo to update
453 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
455 foreach($photos as $photo) {
457 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
458 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
459 } catch (InvalidClassStorageException $storageException) {
460 $fields["data"] = $img->asString();
463 $fields['updated'] = DateTimeFormat::utcNow();
466 $fields['edited'] = DateTimeFormat::utcNow();
468 return DBA::update("photo", $fields, $conditions, $old_fields);
472 * @param string $image_url Remote URL
473 * @param integer $uid user id
474 * @param integer $cid contact id
475 * @param boolean $quit_on_error optional, default false
477 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
478 * @throws \ImagickException
480 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
485 $photo = DBA::selectFirst(
486 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "photo-type" => self::CONTACT_AVATAR]
488 if (!empty($photo['resource-id'])) {
489 $resource_id = $photo["resource-id"];
491 $resource_id = self::newResource();
494 $photo_failure = false;
496 $filename = basename($image_url);
497 if (!empty($image_url)) {
498 $ret = DI::httpClient()->get($image_url);
499 $img_str = $ret->getBody();
500 $type = $ret->getContentType();
506 if ($quit_on_error && ($img_str == "")) {
510 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
512 $Image = new Image($img_str, $type);
513 if ($Image->isValid()) {
514 $Image->scaleToSquare(300);
516 $filesize = strlen($Image->asString());
517 $maximagesize = DI::config()->get('system', 'maximagesize');
518 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
519 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
520 if ($Image->getType() == 'image/gif') {
522 $Image = new Image($Image->asString(), 'image/png');
524 $filesize = strlen($Image->asString());
525 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
527 if ($filesize > $maximagesize) {
528 foreach ([160, 80] as $pixels) {
529 if ($filesize > $maximagesize) {
530 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
531 $Image->scaleDown($pixels);
532 $filesize = strlen($Image->asString());
536 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
539 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
542 $photo_failure = true;
545 $Image->scaleDown(80);
547 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
550 $photo_failure = true;
553 $Image->scaleDown(48);
555 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
558 $photo_failure = true;
561 $suffix = "?ts=" . time();
563 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
564 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
565 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
567 // Remove the cached photo
569 $basepath = $a->getBasePath();
571 if (is_dir($basepath . "/photo")) {
572 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
573 if (file_exists($filename)) {
576 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
577 if (file_exists($filename)) {
580 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
581 if (file_exists($filename)) {
586 $photo_failure = true;
589 if ($photo_failure && $quit_on_error) {
593 if ($photo_failure) {
594 $contact = Contact::getById($cid) ?: [];
595 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
596 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
597 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
600 return [$image_url, $thumb, $micro];
604 * @param array $exifCoord coordinate
605 * @param string $hemi hemi
608 public static function getGps($exifCoord, $hemi)
610 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
611 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
612 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
614 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
616 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
620 * @param string $coordPart coordPart
623 private static function gps2Num($coordPart)
625 $parts = explode("/", $coordPart);
627 if (count($parts) <= 0) {
631 if (count($parts) == 1) {
635 return floatval($parts[0]) / floatval($parts[1]);
639 * Fetch the photo albums that are available for a viewer
641 * The query in this function is cost intensive, so it is cached.
643 * @param int $uid User id of the photos
644 * @param bool $update Update the cache
646 * @return array Returns array of the photo albums
647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
649 public static function getAlbums($uid, $update = false)
651 $sql_extra = Security::getPermissionsSQLByUserId($uid);
653 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
654 $albums = DI::cache()->get($key);
655 if (is_null($albums) || $update) {
656 if (!DI::config()->get("system", "no_count", false)) {
657 /// @todo This query needs to be renewed. It is really slow
658 // At this time we just store the data in the cache
659 $albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
661 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) $sql_extra
662 GROUP BY `album` ORDER BY `created` DESC",
664 self::CONTACT_AVATAR,
668 // This query doesn't do the count and is much faster
669 $albums = DBA::toArray(DBA::p("SELECT DISTINCT(`album`), '' AS `total`
670 FROM `photo` USE INDEX (`uid_album_scale_created`)
671 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) $sql_extra",
673 self::CONTACT_AVATAR,
677 DI::cache()->set($key, $albums, Duration::DAY);
683 * @param int $uid User id of the photos
687 public static function clearAlbumCache($uid)
689 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
690 DI::cache()->set($key, null, Duration::DAY);
694 * Generate a unique photo ID.
699 public static function newResource()
701 return System::createGUID(32, false);
705 * Extracts the rid from a local photo URI
707 * @param string $image_uri The URI of the photo
708 * @return string The rid of the photo, or an empty string if the URI is not local
710 public static function ridFromURI(string $image_uri)
712 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
715 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
716 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
717 if (!strlen($image_uri)) {
724 * Changes photo permissions that had been embedded in a post
726 * @todo This function currently does have some flaws:
727 * - Sharing a post with a forum will create a photo that only the forum can see.
728 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
733 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
735 // Simplify image codes
736 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
737 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
740 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
744 if (empty($images)) {
748 foreach ($images as $image) {
749 $image_rid = self::ridFromURI($image);
750 if (empty($image_rid)) {
754 // Ensure to only modify photos that you own
755 $srch = '<' . intval($original_contact_id) . '>';
758 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
759 'resource-id' => $image_rid, 'uid' => $uid
761 if (!Photo::exists($condition)) {
762 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
763 if (!DBA::isResult($photo)) {
764 Logger::info('Image not found', ['resource-id' => $image_rid]);
766 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
772 * @todo Existing permissions need to be mixed with the new ones.
773 * Otherwise this creates problems with sharing the same picture multiple times
774 * Also check if $str_contact_allow does contain a public forum.
775 * Then set the permissions to public.
778 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
785 * Add permissions to photo ressource
786 * @todo mix with previous photo permissions
788 * @param string $image_rid
789 * @param integer $uid
790 * @param string $str_contact_allow
791 * @param string $str_group_allow
792 * @param string $str_contact_deny
793 * @param string $str_group_deny
796 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)
798 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
799 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
800 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
802 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
803 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
804 Photo::update($fields, $condition);
808 * Fetch the guid and scale from picture links
810 * @param string $name Picture link
813 public static function getResourceData(string $name):array
815 $base = DI::baseUrl()->get();
817 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
819 if (parse_url($guid, PHP_URL_SCHEME)) {
823 $guid = pathinfo($guid, PATHINFO_FILENAME);
824 if (substr($guid, -2, 1) != "-") {
828 $scale = intval(substr($guid, -1, 1));
829 if (!is_numeric($scale)) {
833 $guid = substr($guid, 0, -2);
834 return ['guid' => $guid, 'scale' => $scale];
838 * Tests if the picture link points to a locally stored picture
840 * @param string $name Picture link
844 public static function isLocal($name)
846 return (bool)self::getIdForName($name);
850 * Return the id of a local photo
852 * @param string $name Picture link
855 public static function getIdForName($name)
857 $data = self::getResourceData($name);
862 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
863 if (!empty($photo['id'])) {
870 * Tests if the link points to a locally stored picture page
872 * @param string $name Page link
876 public static function isLocalPage($name)
878 $base = DI::baseUrl()->get();
880 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
881 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
886 return DBA::exists('photo', ['resource-id' => $guid]);
891 * @param int $uid User ID
892 * @param array $files uploaded file array
893 * @return array photo record
895 public static function upload(int $uid, array $files)
897 Logger::info('starting new upload');
899 $user = User::getOwnerDataById($uid);
901 Logger::notice('User not found', ['uid' => $uid]);
906 Logger::notice('Empty upload file');
910 if (!empty($files['tmp_name'])) {
911 if (is_array($files['tmp_name'])) {
912 $src = $files['tmp_name'][0];
914 $src = $files['tmp_name'];
920 if (!empty($files['name'])) {
921 if (is_array($files['name'])) {
922 $filename = basename($files['name'][0]);
924 $filename = basename($files['name']);
930 if (!empty($files['size'])) {
931 if (is_array($files['size'])) {
932 $filesize = intval($files['size'][0]);
934 $filesize = intval($files['size']);
940 if (!empty($files['type'])) {
941 if (is_array($files['type'])) {
942 $filetype = $files['type'][0];
944 $filetype = $files['type'];
951 Logger::notice('No source file name', ['uid' => $uid, 'files' => $files]);
955 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
957 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
959 $imagedata = @file_get_contents($src);
960 $Image = new Image($imagedata, $filetype);
961 if (!$Image->isValid()) {
962 Logger::notice('Image is unvalid', ['uid' => $uid, 'files' => $files]);
966 $Image->orient($src);
969 $max_length = DI::config()->get('system', 'max_image_length');
971 $max_length = MAX_IMAGE_LENGTH;
973 if ($max_length > 0) {
974 $Image->scaleDown($max_length);
975 $filesize = strlen($Image->asString());
976 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
979 $width = $Image->getWidth();
980 $height = $Image->getHeight();
982 $maximagesize = DI::config()->get('system', 'maximagesize');
984 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
985 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
986 foreach ([5120, 2560, 1280, 640] as $pixels) {
987 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
988 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
989 $Image->scaleDown($pixels);
990 $filesize = strlen($Image->asString());
991 $width = $Image->getWidth();
992 $height = $Image->getHeight();
995 if ($filesize > $maximagesize) {
997 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1002 $resource_id = Photo::newResource();
1003 $album = DI::l10n()->t('Wall Photos');
1004 $defperm = '<' . $user['id'] . '>';
1008 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $defperm);
1010 Logger::notice('Photo could not be stored');
1014 if ($width > 640 || $height > 640) {
1015 $Image->scaleDown(640);
1016 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $defperm);
1022 if ($width > 320 || $height > 320) {
1023 $Image->scaleDown(320);
1024 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $defperm);
1025 if ($r && ($smallest == 0)) {
1030 $condition = ['resource-id' => $resource_id];
1031 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1032 if (empty($photo)) {
1033 Logger::notice('Photo not found', ['condition' => $condition]);
1039 $picture['id'] = $photo['id'];
1040 $picture['size'] = $photo['datasize'];
1041 $picture['width'] = $photo['width'];
1042 $picture['height'] = $photo['height'];
1043 $picture['type'] = $photo['type'];
1044 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1045 $picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
1046 $picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
1048 Logger::info('upload done', ['picture' => $picture]);