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;
42 require_once "include/dba.php";
45 * Class to handle photo dabatase table
49 const CONTACT_PHOTOS = 'Contact Photos';
52 * Select rows from the photo table and returns them as array
54 * @param array $fields Array of selected fields, empty for all
55 * @param array $conditions Array of fields for conditions
56 * @param array $params Array of several parameters
58 * @return boolean|array
61 * @see \Friendica\Database\DBA::selectToArray
63 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
66 $fields = self::getFields();
69 return DBA::selectToArray('photo', $fields, $conditions, $params);
73 * Retrieve a single record from the photo table
75 * @param array $fields Array of selected fields, empty for all
76 * @param array $conditions Array of fields for conditions
77 * @param array $params Array of several parameters
82 * @see \Friendica\Database\DBA::select
84 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
87 $fields = self::getFields();
90 return DBA::selectFirst("photo", $fields, $conditions, $params);
94 * Get photos for user id
96 * @param integer $uid User id
97 * @param string $resourceid Rescource ID of the photo
98 * @param array $conditions Array of fields for conditions
99 * @param array $params Array of several parameters
104 * @see \Friendica\Database\DBA::select
106 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
108 $conditions["resource-id"] = $resourceid;
109 $conditions["uid"] = $uid;
111 return self::selectToArray([], $conditions, $params);
115 * Get a photo for user id
117 * @param integer $uid User id
118 * @param string $resourceid Rescource ID of the photo
119 * @param integer $scale Scale of the photo. Defaults to 0
120 * @param array $conditions Array of fields for conditions
121 * @param array $params Array of several parameters
126 * @see \Friendica\Database\DBA::select
128 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
130 $conditions["resource-id"] = $resourceid;
131 $conditions["uid"] = $uid;
132 $conditions["scale"] = $scale;
134 return self::selectFirst([], $conditions, $params);
138 * Get a single photo given resource id and scale
140 * This method checks for permissions. Returns associative array
141 * on success, "no sign" image info, if user has no permission,
142 * false if photo does not exists
144 * @param string $resourceid Rescource ID of the photo
145 * @param integer $scale Scale of the photo. Defaults to 0
147 * @return boolean|array
150 public static function getPhoto(string $resourceid, int $scale = 0)
152 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
153 if (!DBA::isResult($r)) {
159 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
161 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
163 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
164 $params = ["order" => ["scale" => true]];
165 $photo = self::selectFirst([], $conditions, $params);
171 * Check if photo with given conditions exists
173 * @param array $conditions Array of extra conditions
178 public static function exists(array $conditions)
180 return DBA::exists("photo", $conditions);
185 * Get Image data for given row id. null if row id does not exist
187 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
189 * @return \Friendica\Object\Image
191 public static function getImageDataForPhoto(array $photo)
193 if (!empty($photo['data'])) {
194 return $photo['data'];
198 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
199 /// @todo refactoring this returning, because the storage returns a "string" which is casted in different ways - a check "instanceof Image" will fail!
200 return $backendClass->get($photo['backend-ref'] ?? '');
201 } catch (InvalidClassStorageException $storageException) {
203 // legacy data storage in "data" column
204 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
208 DI::logger()->info('Stored legacy data is empty', ['photo' => $photo]);
210 } catch (\Exception $exception) {
211 DI::logger()->info('Unexpected database exception', ['photo' => $photo, 'exception' => $exception]);
213 } catch (ReferenceStorageException $referenceStorageException) {
214 DI::logger()->debug('Invalid reference for photo', ['photo' => $photo, 'exception' => $referenceStorageException]);
215 } catch (StorageException $storageException) {
216 DI::logger()->info('Unexpected storage exception', ['photo' => $photo, 'exception' => $storageException]);
217 } catch (\ImagickException $imagickException) {
218 DI::logger()->info('Unexpected imagick exception', ['photo' => $photo, 'exception' => $imagickException]);
225 * Get Image object for given row id. null if row id does not exist
227 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
229 * @return \Friendica\Object\Image
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 public static function getImageForPhoto(array $photo): Image
235 return new Image(self::getImageDataForPhoto($photo), $photo['type']);
239 * Return a list of fields that are associated with the photo table
241 * @return array field list
244 private static function getFields()
246 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
247 $fields = array_keys($allfields["photo"]["fields"]);
248 array_splice($fields, array_search("data", $fields), 1);
253 * Construct a photo array for a system resource image
255 * @param string $filename Image file name relative to code root
256 * @param string $mimetype Image mime type. Is guessed by file name when empty.
261 public static function createPhotoForSystemResource($filename, $mimetype = '')
263 if (empty($mimetype)) {
264 $mimetype = Images::guessTypeByExtension($filename);
267 $fields = self::getFields();
268 $values = array_fill(0, count($fields), "");
270 $photo = array_combine($fields, $values);
271 $photo['backend-class'] = SystemResource::NAME;
272 $photo['backend-ref'] = $filename;
273 $photo['type'] = $mimetype;
274 $photo['cacheable'] = false;
280 * Construct a photo array for an external resource image
282 * @param string $url Image URL
283 * @param int $uid User ID of the requesting person
284 * @param string $mimetype Image mime type. Is guessed by file name when empty.
289 public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = '')
291 if (empty($mimetype)) {
292 $mimetype = Images::guessTypeByExtension($url);
295 $fields = self::getFields();
296 $values = array_fill(0, count($fields), "");
298 $photo = array_combine($fields, $values);
299 $photo['backend-class'] = ExternalResource::NAME;
300 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
301 $photo['type'] = $mimetype;
302 $photo['cacheable'] = true;
308 * store photo metadata in db and binary in default backend
310 * @param Image $Image Image object with data
311 * @param integer $uid User ID
312 * @param integer $cid Contact ID
313 * @param integer $rid Resource ID
314 * @param string $filename Filename
315 * @param string $album Album name
316 * @param integer $scale Scale
317 * @param integer $profile Is a profile image? optional, default = 0
318 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
319 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
320 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
321 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
322 * @param string $desc Photo caption. optional, default = ""
324 * @return boolean True on success
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
329 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
330 if (DBA::isResult($photo)) {
331 $guid = $photo["guid"];
333 $guid = System::createGUID();
336 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
337 $created = DateTimeFormat::utcNow();
338 if (DBA::isResult($existing_photo)) {
339 $created = $existing_photo["created"];
342 // Get defined storage backend.
343 // if no storage backend, we use old "data" column in photo table.
344 // if is an existing photo, reuse same backend
350 if (DBA::isResult($existing_photo)) {
351 $backend_ref = (string)$existing_photo["backend-ref"];
352 $storage = DI::storageManager()->getWritableStorageByName($existing_photo["backend-class"] ?? '');
354 $storage = DI::storage();
356 $backend_ref = $storage->put($Image->asString(), $backend_ref);
357 } catch (InvalidClassStorageException $storageException) {
358 $data = $Image->asString();
363 "contact-id" => $cid,
365 "resource-id" => $rid,
366 "hash" => md5($Image->asString()),
367 "created" => $created,
368 "edited" => DateTimeFormat::utcNow(),
369 "filename" => basename($filename),
370 "type" => $Image->getType(),
372 "height" => $Image->getHeight(),
373 "width" => $Image->getWidth(),
374 "datasize" => strlen($Image->asString()),
377 "profile" => $profile,
378 "allow_cid" => $allow_cid,
379 "allow_gid" => $allow_gid,
380 "deny_cid" => $deny_cid,
381 "deny_gid" => $deny_gid,
383 "backend-class" => (string)$storage,
384 "backend-ref" => $backend_ref
387 if (DBA::isResult($existing_photo)) {
388 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
390 $r = DBA::insert("photo", $fields);
398 * Delete info from table and data from storage
400 * @param array $conditions Field condition(s)
401 * @param array $options Options array, Optional
406 * @see \Friendica\Database\DBA::delete
408 public static function delete(array $conditions, array $options = [])
410 // get photo to delete data info
411 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
413 while ($photo = DBA::fetch($photos)) {
415 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
416 $backend_class->delete($photo['backend-ref'] ?? '');
417 // Delete the photos after they had been deleted successfully
418 DBA::delete("photo", ['id' => $photo['id']]);
419 } catch (InvalidClassStorageException $storageException) {
420 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
421 } catch (ReferenceStorageException $referenceStorageException) {
422 DI::logger()->debug('Photo doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
428 return DBA::delete("photo", $conditions, $options);
434 * @param array $fields Contains the fields that are updated
435 * @param array $conditions Condition array with the key values
436 * @param Image $img Image to update. Optional, default null.
437 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
439 * @return boolean Was the update successfull?
441 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442 * @see \Friendica\Database\DBA::update
444 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
446 if (!is_null($img)) {
447 // get photo to update
448 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
450 foreach($photos as $photo) {
452 $backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
453 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
454 } catch (InvalidClassStorageException $storageException) {
455 $fields["data"] = $img->asString();
458 $fields['updated'] = DateTimeFormat::utcNow();
461 $fields['edited'] = DateTimeFormat::utcNow();
463 return DBA::update("photo", $fields, $conditions, $old_fields);
467 * @param string $image_url Remote URL
468 * @param integer $uid user id
469 * @param integer $cid contact id
470 * @param boolean $quit_on_error optional, default false
472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
473 * @throws \ImagickException
475 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
480 $photo = DBA::selectFirst(
481 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => self::CONTACT_PHOTOS]
483 if (!empty($photo['resource-id'])) {
484 $resource_id = $photo["resource-id"];
486 $resource_id = self::newResource();
489 $photo_failure = false;
491 $filename = basename($image_url);
492 if (!empty($image_url)) {
493 $ret = DI::httpClient()->get($image_url);
494 $img_str = $ret->getBody();
495 $type = $ret->getContentType();
501 if ($quit_on_error && ($img_str == "")) {
505 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
507 $Image = new Image($img_str, $type);
508 if ($Image->isValid()) {
509 $Image->scaleToSquare(300);
511 $filesize = strlen($Image->asString());
512 $maximagesize = DI::config()->get('system', 'maximagesize');
513 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
514 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
515 if ($Image->getType() == 'image/gif') {
517 $Image = new Image($Image->asString(), 'image/png');
519 $filesize = strlen($Image->asString());
520 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
522 if ($filesize > $maximagesize) {
523 foreach ([160, 80] as $pixels) {
524 if ($filesize > $maximagesize) {
525 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
526 $Image->scaleDown($pixels);
527 $filesize = strlen($Image->asString());
531 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
534 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4);
537 $photo_failure = true;
540 $Image->scaleDown(80);
542 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5);
545 $photo_failure = true;
548 $Image->scaleDown(48);
550 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6);
553 $photo_failure = true;
556 $suffix = "?ts=" . time();
558 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
559 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
560 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
562 // Remove the cached photo
564 $basepath = $a->getBasePath();
566 if (is_dir($basepath . "/photo")) {
567 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
568 if (file_exists($filename)) {
571 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
572 if (file_exists($filename)) {
575 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
576 if (file_exists($filename)) {
581 $photo_failure = true;
584 if ($photo_failure && $quit_on_error) {
588 if ($photo_failure) {
589 $contact = Contact::getById($cid) ?: [];
590 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
591 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
592 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
595 return [$image_url, $thumb, $micro];
599 * @param array $exifCoord coordinate
600 * @param string $hemi hemi
603 public static function getGps($exifCoord, $hemi)
605 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
606 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
607 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
609 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
611 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
615 * @param string $coordPart coordPart
618 private static function gps2Num($coordPart)
620 $parts = explode("/", $coordPart);
622 if (count($parts) <= 0) {
626 if (count($parts) == 1) {
630 return floatval($parts[0]) / floatval($parts[1]);
634 * Fetch the photo albums that are available for a viewer
636 * The query in this function is cost intensive, so it is cached.
638 * @param int $uid User id of the photos
639 * @param bool $update Update the cache
641 * @return array Returns array of the photo albums
642 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
644 public static function getAlbums($uid, $update = false)
646 $sql_extra = Security::getPermissionsSQLByUserId($uid);
648 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
649 $albums = DI::cache()->get($key);
650 if (is_null($albums) || $update) {
651 if (!DI::config()->get("system", "no_count", false)) {
652 /// @todo This query needs to be renewed. It is really slow
653 // At this time we just store the data in the cache
654 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
656 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
657 GROUP BY `album` ORDER BY `created` DESC",
659 DBA::escape(self::CONTACT_PHOTOS),
660 DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
663 // This query doesn't do the count and is much faster
664 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
665 FROM `photo` USE INDEX (`uid_album_scale_created`)
666 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
668 DBA::escape(self::CONTACT_PHOTOS),
669 DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
672 DI::cache()->set($key, $albums, Duration::DAY);
678 * @param int $uid User id of the photos
682 public static function clearAlbumCache($uid)
684 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
685 DI::cache()->set($key, null, Duration::DAY);
689 * Generate a unique photo ID.
694 public static function newResource()
696 return System::createGUID(32, false);
700 * Extracts the rid from a local photo URI
702 * @param string $image_uri The URI of the photo
703 * @return string The rid of the photo, or an empty string if the URI is not local
705 public static function ridFromURI(string $image_uri)
707 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
710 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
711 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
712 if (!strlen($image_uri)) {
719 * Changes photo permissions that had been embedded in a post
721 * @todo This function currently does have some flaws:
722 * - Sharing a post with a forum will create a photo that only the forum can see.
723 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
728 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
730 // Simplify image codes
731 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
732 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
735 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
739 if (empty($images)) {
743 foreach ($images as $image) {
744 $image_rid = self::ridFromURI($image);
745 if (empty($image_rid)) {
749 // Ensure to only modify photos that you own
750 $srch = '<' . intval($original_contact_id) . '>';
753 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
754 'resource-id' => $image_rid, 'uid' => $uid
756 if (!Photo::exists($condition)) {
757 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
758 if (!DBA::isResult($photo)) {
759 Logger::info('Image not found', ['resource-id' => $image_rid]);
761 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
767 * @todo Existing permissions need to be mixed with the new ones.
768 * Otherwise this creates problems with sharing the same picture multiple times
769 * Also check if $str_contact_allow does contain a public forum.
770 * Then set the permissions to public.
773 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
780 * Add permissions to photo ressource
781 * @todo mix with previous photo permissions
783 * @param string $image_rid
784 * @param integer $uid
785 * @param string $str_contact_allow
786 * @param string $str_group_allow
787 * @param string $str_contact_deny
788 * @param string $str_group_deny
791 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)
793 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
794 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
795 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
797 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
798 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
799 Photo::update($fields, $condition);
803 * Strips known picture extensions from picture links
805 * @param string $name Picture link
806 * @return string stripped picture link
809 public static function stripExtension($name)
811 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
812 foreach (Images::supportedTypes() as $m => $e) {
813 $name = str_replace("." . $e, "", $name);
819 * Fetch the guid and scale from picture links
821 * @param string $name Picture link
824 public static function getResourceData(string $name):array
826 $base = DI::baseUrl()->get();
828 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
830 if (parse_url($guid, PHP_URL_SCHEME)) {
834 $guid = self::stripExtension($guid);
835 if (substr($guid, -2, 1) != "-") {
839 $scale = intval(substr($guid, -1, 1));
840 if (!is_numeric($scale)) {
844 $guid = substr($guid, 0, -2);
845 return ['guid' => $guid, 'scale' => $scale];
849 * Tests if the picture link points to a locally stored picture
851 * @param string $name Picture link
855 public static function isLocal($name)
857 return (bool)self::getIdForName($name);
861 * Return the id of a local photo
863 * @param string $name Picture link
866 public static function getIdForName($name)
868 $data = self::getResourceData($name);
873 $photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
874 if (!empty($photo['id'])) {
881 * Tests if the link points to a locally stored picture page
883 * @param string $name Page link
887 public static function isLocalPage($name)
889 $base = DI::baseUrl()->get();
891 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
892 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
897 return DBA::exists('photo', ['resource-id' => $guid]);
902 * @param int $uid User ID
903 * @param array $files uploaded file array
904 * @return array photo record
906 public static function upload(int $uid, array $files)
908 Logger::info('starting new upload');
910 $user = User::getOwnerDataById($uid);
912 Logger::notice('User not found', ['uid' => $uid]);
917 Logger::notice('Empty upload file');
921 if (!empty($files['tmp_name'])) {
922 if (is_array($files['tmp_name'])) {
923 $src = $files['tmp_name'][0];
925 $src = $files['tmp_name'];
931 if (!empty($files['name'])) {
932 if (is_array($files['name'])) {
933 $filename = basename($files['name'][0]);
935 $filename = basename($files['name']);
941 if (!empty($files['size'])) {
942 if (is_array($files['size'])) {
943 $filesize = intval($files['size'][0]);
945 $filesize = intval($files['size']);
951 if (!empty($files['type'])) {
952 if (is_array($files['type'])) {
953 $filetype = $files['type'][0];
955 $filetype = $files['type'];
962 Logger::notice('No source file name', ['uid' => $uid, 'files' => $files]);
966 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
968 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
970 $imagedata = @file_get_contents($src);
971 $Image = new Image($imagedata, $filetype);
972 if (!$Image->isValid()) {
973 Logger::notice('Image is unvalid', ['uid' => $uid, 'files' => $files]);
977 $Image->orient($src);
980 $max_length = DI::config()->get('system', 'max_image_length');
982 $max_length = MAX_IMAGE_LENGTH;
984 if ($max_length > 0) {
985 $Image->scaleDown($max_length);
986 $filesize = strlen($Image->asString());
987 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
990 $width = $Image->getWidth();
991 $height = $Image->getHeight();
993 $maximagesize = DI::config()->get('system', 'maximagesize');
995 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
996 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
997 foreach ([5120, 2560, 1280, 640] as $pixels) {
998 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
999 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
1000 $Image->scaleDown($pixels);
1001 $filesize = strlen($Image->asString());
1002 $width = $Image->getWidth();
1003 $height = $Image->getHeight();
1006 if ($filesize > $maximagesize) {
1008 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
1013 $resource_id = Photo::newResource();
1014 $album = DI::l10n()->t('Wall Photos');
1015 $defperm = '<' . $user['id'] . '>';
1019 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, 0, $defperm);
1021 Logger::notice('Photo could not be stored');
1025 if ($width > 640 || $height > 640) {
1026 $Image->scaleDown(640);
1027 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, 0, $defperm);
1033 if ($width > 320 || $height > 320) {
1034 $Image->scaleDown(320);
1035 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, 0, $defperm);
1036 if ($r && ($smallest == 0)) {
1041 $condition = ['resource-id' => $resource_id];
1042 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1043 if (empty($photo)) {
1044 Logger::notice('Photo not found', ['condition' => $condition]);
1050 $picture['id'] = $photo['id'];
1051 $picture['size'] = $photo['datasize'];
1052 $picture['width'] = $photo['width'];
1053 $picture['height'] = $photo['height'];
1054 $picture['type'] = $photo['type'];
1055 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1056 $picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
1057 $picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
1059 Logger::info('upload done', ['picture' => $picture]);