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\SystemResource;
32 use Friendica\Object\Image;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Images;
35 use Friendica\Security\Security;
36 use Friendica\Util\Proxy;
37 use Friendica\Util\Strings;
39 require_once "include/dba.php";
42 * Class to handle photo dabatase table
46 const CONTACT_PHOTOS = 'Contact Photos';
49 * Select rows from the photo table and returns them as array
51 * @param array $fields Array of selected fields, empty for all
52 * @param array $conditions Array of fields for conditions
53 * @param array $params Array of several parameters
55 * @return boolean|array
58 * @see \Friendica\Database\DBA::selectToArray
60 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
63 $fields = self::getFields();
66 return DBA::selectToArray('photo', $fields, $conditions, $params);
70 * Retrieve a single record from the photo table
72 * @param array $fields Array of selected fields, empty for all
73 * @param array $conditions Array of fields for conditions
74 * @param array $params Array of several parameters
79 * @see \Friendica\Database\DBA::select
81 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
84 $fields = self::getFields();
87 return DBA::selectFirst("photo", $fields, $conditions, $params);
91 * Get photos for user id
93 * @param integer $uid User id
94 * @param string $resourceid Rescource ID of the photo
95 * @param array $conditions Array of fields for conditions
96 * @param array $params Array of several parameters
101 * @see \Friendica\Database\DBA::select
103 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
105 $conditions["resource-id"] = $resourceid;
106 $conditions["uid"] = $uid;
108 return self::selectToArray([], $conditions, $params);
112 * Get a photo for user id
114 * @param integer $uid User id
115 * @param string $resourceid Rescource ID of the photo
116 * @param integer $scale Scale of the photo. Defaults to 0
117 * @param array $conditions Array of fields for conditions
118 * @param array $params Array of several parameters
123 * @see \Friendica\Database\DBA::select
125 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
127 $conditions["resource-id"] = $resourceid;
128 $conditions["uid"] = $uid;
129 $conditions["scale"] = $scale;
131 return self::selectFirst([], $conditions, $params);
135 * Get a single photo given resource id and scale
137 * This method checks for permissions. Returns associative array
138 * on success, "no sign" image info, if user has no permission,
139 * false if photo does not exists
141 * @param string $resourceid Rescource ID of the photo
142 * @param integer $scale Scale of the photo. Defaults to 0
144 * @return boolean|array
147 public static function getPhoto(string $resourceid, int $scale = 0)
149 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
150 if (!DBA::isResult($r)) {
156 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
158 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
160 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
161 $params = ["order" => ["scale" => true]];
162 $photo = self::selectFirst([], $conditions, $params);
168 * Check if photo with given conditions exists
170 * @param array $conditions Array of extra conditions
175 public static function exists(array $conditions)
177 return DBA::exists("photo", $conditions);
182 * Get Image data for given row id. null if row id does not exist
184 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
186 * @return \Friendica\Object\Image
187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
188 * @throws \ImagickException
190 public static function getImageDataForPhoto(array $photo)
192 if (!empty($photo['data'])) {
193 return $photo['data'];
196 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
197 if (empty($backendClass)) {
198 // legacy data storage in "data" column
199 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
205 $backendRef = $photo['backend-ref'] ?? '';
206 $data = $backendClass->get($backendRef);
212 * Get Image object for given row id. null if row id does not exist
214 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
216 * @return \Friendica\Object\Image
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 * @throws \ImagickException
220 public static function getImageForPhoto(array $photo)
222 $data = self::getImageDataForPhoto($photo);
227 return new Image($data, $photo['type']);
231 * Return a list of fields that are associated with the photo table
233 * @return array field list
236 private static function getFields()
238 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
239 $fields = array_keys($allfields["photo"]["fields"]);
240 array_splice($fields, array_search("data", $fields), 1);
245 * Construct a photo array for a system resource image
247 * @param string $filename Image file name relative to code root
248 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
253 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
255 $fields = self::getFields();
256 $values = array_fill(0, count($fields), "");
258 $photo = array_combine($fields, $values);
259 $photo['backend-class'] = SystemResource::NAME;
260 $photo['backend-ref'] = $filename;
261 $photo['type'] = $mimetype;
262 $photo['cacheable'] = false;
268 * Construct a photo array for an external resource image
270 * @param string $url Image URL
271 * @param int $uid User ID of the requesting person
272 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
277 public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = "image/jpeg")
279 $fields = self::getFields();
280 $values = array_fill(0, count($fields), "");
282 $photo = array_combine($fields, $values);
283 $photo['backend-class'] = ExternalResource::NAME;
284 $photo['backend-ref'] = json_encode(['url' => $url, 'uid' => $uid]);
285 $photo['type'] = $mimetype;
286 $photo['cacheable'] = true;
292 * store photo metadata in db and binary in default backend
294 * @param Image $Image Image object with data
295 * @param integer $uid User ID
296 * @param integer $cid Contact ID
297 * @param integer $rid Resource ID
298 * @param string $filename Filename
299 * @param string $album Album name
300 * @param integer $scale Scale
301 * @param integer $profile Is a profile image? optional, default = 0
302 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
303 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
304 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
305 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
306 * @param string $desc Photo caption. optional, default = ""
308 * @return boolean True on success
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
311 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
313 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
314 if (DBA::isResult($photo)) {
315 $guid = $photo["guid"];
317 $guid = System::createGUID();
320 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
321 $created = DateTimeFormat::utcNow();
322 if (DBA::isResult($existing_photo)) {
323 $created = $existing_photo["created"];
326 // Get defined storage backend.
327 // if no storage backend, we use old "data" column in photo table.
328 // if is an existing photo, reuse same backend
332 if (DBA::isResult($existing_photo)) {
333 $backend_ref = (string)$existing_photo["backend-ref"];
334 $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
336 $storage = DI::storage();
339 if (empty($storage)) {
340 $data = $Image->asString();
342 $backend_ref = $storage->put($Image->asString(), $backend_ref);
347 "contact-id" => $cid,
349 "resource-id" => $rid,
350 "hash" => md5($Image->asString()),
351 "created" => $created,
352 "edited" => DateTimeFormat::utcNow(),
353 "filename" => basename($filename),
354 "type" => $Image->getType(),
356 "height" => $Image->getHeight(),
357 "width" => $Image->getWidth(),
358 "datasize" => strlen($Image->asString()),
361 "profile" => $profile,
362 "allow_cid" => $allow_cid,
363 "allow_gid" => $allow_gid,
364 "deny_cid" => $deny_cid,
365 "deny_gid" => $deny_gid,
367 "backend-class" => (string)$storage,
368 "backend-ref" => $backend_ref
371 if (DBA::isResult($existing_photo)) {
372 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
374 $r = DBA::insert("photo", $fields);
382 * Delete info from table and data from storage
384 * @param array $conditions Field condition(s)
385 * @param array $options Options array, Optional
390 * @see \Friendica\Database\DBA::delete
392 public static function delete(array $conditions, array $options = [])
394 // get photo to delete data info
395 $photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
397 while ($photo = DBA::fetch($photos)) {
398 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
399 if (!empty($backend_class)) {
400 if ($backend_class->delete($photo["backend-ref"] ?? '')) {
401 // Delete the photos after they had been deleted successfully
402 DBA::delete("photo", ['id' => $photo['id']]);
409 return DBA::delete("photo", $conditions, $options);
415 * @param array $fields Contains the fields that are updated
416 * @param array $conditions Condition array with the key values
417 * @param Image $img Image to update. Optional, default null.
418 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
420 * @return boolean Was the update successfull?
422 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
423 * @see \Friendica\Database\DBA::update
425 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
427 if (!is_null($img)) {
428 // get photo to update
429 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
431 foreach($photos as $photo) {
432 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
433 if (!empty($backend_class)) {
434 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
436 $fields["data"] = $img->asString();
439 $fields['updated'] = DateTimeFormat::utcNow();
442 $fields['edited'] = DateTimeFormat::utcNow();
444 return DBA::update("photo", $fields, $conditions, $old_fields);
448 * @param string $image_url Remote URL
449 * @param integer $uid user id
450 * @param integer $cid contact id
451 * @param boolean $quit_on_error optional, default false
453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454 * @throws \ImagickException
456 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
461 $photo = DBA::selectFirst(
462 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => self::CONTACT_PHOTOS]
464 if (!empty($photo['resource-id'])) {
465 $resource_id = $photo["resource-id"];
467 $resource_id = self::newResource();
470 $photo_failure = false;
472 $filename = basename($image_url);
473 if (!empty($image_url)) {
474 $ret = DI::httpRequest()->get($image_url);
475 $img_str = $ret->getBody();
476 $type = $ret->getContentType();
481 if ($quit_on_error && ($img_str == "")) {
485 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
487 $Image = new Image($img_str, $type);
488 if ($Image->isValid()) {
489 $Image->scaleToSquare(300);
491 $filesize = strlen($Image->asString());
492 $maximagesize = DI::config()->get('system', 'maximagesize');
493 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
494 Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
495 if ($Image->getType() == 'image/gif') {
497 $Image = new Image($Image->asString(), 'image/png');
499 $filesize = strlen($Image->asString());
500 Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
502 if ($filesize > $maximagesize) {
503 foreach ([160, 80] as $pixels) {
504 if ($filesize > $maximagesize) {
505 Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
506 $Image->scaleDown($pixels);
507 $filesize = strlen($Image->asString());
511 Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
514 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4);
517 $photo_failure = true;
520 $Image->scaleDown(80);
522 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5);
525 $photo_failure = true;
528 $Image->scaleDown(48);
530 $r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6);
533 $photo_failure = true;
536 $suffix = "?ts=" . time();
538 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
539 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
540 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
542 // Remove the cached photo
544 $basepath = $a->getBasePath();
546 if (is_dir($basepath . "/photo")) {
547 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
548 if (file_exists($filename)) {
551 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
552 if (file_exists($filename)) {
555 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
556 if (file_exists($filename)) {
561 $photo_failure = true;
564 if ($photo_failure && $quit_on_error) {
568 if ($photo_failure) {
569 $contact = Contact::getById($cid) ?: [];
570 $image_url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
571 $thumb = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
572 $micro = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
575 return [$image_url, $thumb, $micro];
579 * @param array $exifCoord coordinate
580 * @param string $hemi hemi
583 public static function getGps($exifCoord, $hemi)
585 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
586 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
587 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
589 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
591 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
595 * @param string $coordPart coordPart
598 private static function gps2Num($coordPart)
600 $parts = explode("/", $coordPart);
602 if (count($parts) <= 0) {
606 if (count($parts) == 1) {
610 return floatval($parts[0]) / floatval($parts[1]);
614 * Fetch the photo albums that are available for a viewer
616 * The query in this function is cost intensive, so it is cached.
618 * @param int $uid User id of the photos
619 * @param bool $update Update the cache
621 * @return array Returns array of the photo albums
622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
624 public static function getAlbums($uid, $update = false)
626 $sql_extra = Security::getPermissionsSQLByUserId($uid);
628 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
629 $albums = DI::cache()->get($key);
630 if (is_null($albums) || $update) {
631 if (!DI::config()->get("system", "no_count", false)) {
632 /// @todo This query needs to be renewed. It is really slow
633 // At this time we just store the data in the cache
634 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
636 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
637 GROUP BY `album` ORDER BY `created` DESC",
639 DBA::escape(self::CONTACT_PHOTOS),
640 DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
643 // This query doesn't do the count and is much faster
644 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
645 FROM `photo` USE INDEX (`uid_album_scale_created`)
646 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
648 DBA::escape(self::CONTACT_PHOTOS),
649 DBA::escape(DI::l10n()->t(self::CONTACT_PHOTOS))
652 DI::cache()->set($key, $albums, Duration::DAY);
658 * @param int $uid User id of the photos
662 public static function clearAlbumCache($uid)
664 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
665 DI::cache()->set($key, null, Duration::DAY);
669 * Generate a unique photo ID.
674 public static function newResource()
676 return System::createGUID(32, false);
680 * Extracts the rid from a local photo URI
682 * @param string $image_uri The URI of the photo
683 * @return string The rid of the photo, or an empty string if the URI is not local
685 public static function ridFromURI(string $image_uri)
687 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
690 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
691 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
692 if (!strlen($image_uri)) {
699 * Changes photo permissions that had been embedded in a post
701 * @todo This function currently does have some flaws:
702 * - Sharing a post with a forum will create a photo that only the forum can see.
703 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
708 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
710 // Simplify image codes
711 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
712 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
715 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
719 if (empty($images)) {
723 foreach ($images as $image) {
724 $image_rid = self::ridFromURI($image);
725 if (empty($image_rid)) {
729 // Ensure to only modify photos that you own
730 $srch = '<' . intval($original_contact_id) . '>';
733 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
734 'resource-id' => $image_rid, 'uid' => $uid
736 if (!Photo::exists($condition)) {
737 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
738 if (!DBA::isResult($photo)) {
739 Logger::info('Image not found', ['resource-id' => $image_rid]);
741 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
747 * @todo Existing permissions need to be mixed with the new ones.
748 * Otherwise this creates problems with sharing the same picture multiple times
749 * Also check if $str_contact_allow does contain a public forum.
750 * Then set the permissions to public.
753 self::setPermissionForRessource($image_rid, $uid, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
760 * Add permissions to photo ressource
761 * @todo mix with previous photo permissions
763 * @param string $image_rid
764 * @param integer $uid
765 * @param string $str_contact_allow
766 * @param string $str_group_allow
767 * @param string $str_contact_deny
768 * @param string $str_group_deny
771 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)
773 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
774 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
775 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
777 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
778 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
779 Photo::update($fields, $condition);
783 * Strips known picture extensions from picture links
785 * @param string $name Picture link
786 * @return string stripped picture link
789 public static function stripExtension($name)
791 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
792 foreach (Images::supportedTypes() as $m => $e) {
793 $name = str_replace("." . $e, "", $name);
799 * Returns the GUID from picture links
801 * @param string $name Picture link
802 * @return string GUID
805 public static function getGUID($name)
807 $base = DI::baseUrl()->get();
809 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
811 $guid = self::stripExtension($guid);
812 if (substr($guid, -2, 1) != "-") {
816 $scale = intval(substr($guid, -1, 1));
817 if (!is_numeric($scale)) {
821 $guid = substr($guid, 0, -2);
826 * Tests if the picture link points to a locally stored picture
828 * @param string $name Picture link
832 public static function isLocal($name)
834 $guid = self::getGUID($name);
840 return DBA::exists('photo', ['resource-id' => $guid]);
844 * Tests if the link points to a locally stored picture page
846 * @param string $name Page link
850 public static function isLocalPage($name)
852 $base = DI::baseUrl()->get();
854 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
855 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
860 return DBA::exists('photo', ['resource-id' => $guid]);
865 * @param int $uid User ID
866 * @param array $files uploaded file array
867 * @return array photo record
869 public static function upload(int $uid, array $files)
871 Logger::info('starting new upload');
873 $user = User::getOwnerDataById($uid);
875 Logger::notice('User not found', ['uid' => $uid]);
880 Logger::notice('Empty upload file');
884 if (!empty($files['tmp_name'])) {
885 if (is_array($files['tmp_name'])) {
886 $src = $files['tmp_name'][0];
888 $src = $files['tmp_name'];
894 if (!empty($files['name'])) {
895 if (is_array($files['name'])) {
896 $filename = basename($files['name'][0]);
898 $filename = basename($files['name']);
904 if (!empty($files['size'])) {
905 if (is_array($files['size'])) {
906 $filesize = intval($files['size'][0]);
908 $filesize = intval($files['size']);
914 if (!empty($files['type'])) {
915 if (is_array($files['type'])) {
916 $filetype = $files['type'][0];
918 $filetype = $files['type'];
925 Logger::notice('No source file name', ['uid' => $uid, 'files' => $files]);
929 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
931 Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
933 $imagedata = @file_get_contents($src);
934 $Image = new Image($imagedata, $filetype);
935 if (!$Image->isValid()) {
936 Logger::notice('Image is unvalid', ['uid' => $uid, 'files' => $files]);
940 $Image->orient($src);
943 $max_length = DI::config()->get('system', 'max_image_length');
945 $max_length = MAX_IMAGE_LENGTH;
947 if ($max_length > 0) {
948 $Image->scaleDown($max_length);
949 $filesize = strlen($Image->asString());
950 Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
953 $width = $Image->getWidth();
954 $height = $Image->getHeight();
956 $maximagesize = DI::config()->get('system', 'maximagesize');
958 if (!empty($maximagesize) && ($filesize > $maximagesize)) {
959 // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
960 foreach ([5120, 2560, 1280, 640] as $pixels) {
961 if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
962 Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
963 $Image->scaleDown($pixels);
964 $filesize = strlen($Image->asString());
965 $width = $Image->getWidth();
966 $height = $Image->getHeight();
969 if ($filesize > $maximagesize) {
971 Logger::notice('Image size is too big', ['size' => $filesize, 'max' => $maximagesize]);
976 $resource_id = Photo::newResource();
977 $album = DI::l10n()->t('Wall Photos');
978 $defperm = '<' . $user['id'] . '>';
982 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, 0, $defperm);
984 Logger::notice('Photo could not be stored');
988 if ($width > 640 || $height > 640) {
989 $Image->scaleDown(640);
990 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, 0, $defperm);
996 if ($width > 320 || $height > 320) {
997 $Image->scaleDown(320);
998 $r = Photo::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, 0, $defperm);
999 if ($r && ($smallest == 0)) {
1004 $condition = ['resource-id' => $resource_id];
1005 $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
1006 if (empty($photo)) {
1007 Logger::notice('Photo not found', ['condition' => $condition]);
1013 $picture['id'] = $photo['id'];
1014 $picture['size'] = $photo['datasize'];
1015 $picture['width'] = $photo['width'];
1016 $picture['height'] = $photo['height'];
1017 $picture['type'] = $photo['type'];
1018 $picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
1019 $picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
1020 $picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
1022 Logger::info('upload done', ['picture' => $picture]);