3 * @copyright Copyright (C) 2020, Friendica
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\SystemResource;
31 use Friendica\Object\Image;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Images;
34 use Friendica\Util\Security;
35 use Friendica\Util\Strings;
37 require_once "include/dba.php";
40 * Class to handle photo dabatase table
45 * Select rows from the photo table and returns them as array
47 * @param array $fields Array of selected fields, empty for all
48 * @param array $conditions Array of fields for conditions
49 * @param array $params Array of several parameters
51 * @return boolean|array
54 * @see \Friendica\Database\DBA::selectToArray
56 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
59 $fields = self::getFields();
62 return DBA::selectToArray('photo', $fields, $conditions, $params);
66 * Retrieve a single record from the photo table
68 * @param array $fields Array of selected fields, empty for all
69 * @param array $conditions Array of fields for conditions
70 * @param array $params Array of several parameters
75 * @see \Friendica\Database\DBA::select
77 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
80 $fields = self::getFields();
83 return DBA::selectFirst("photo", $fields, $conditions, $params);
87 * Get photos for user id
89 * @param integer $uid User id
90 * @param string $resourceid Rescource ID of the photo
91 * @param array $conditions Array of fields for conditions
92 * @param array $params Array of several parameters
97 * @see \Friendica\Database\DBA::select
99 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
101 $conditions["resource-id"] = $resourceid;
102 $conditions["uid"] = $uid;
104 return self::selectToArray([], $conditions, $params);
108 * Get a photo for user id
110 * @param integer $uid User id
111 * @param string $resourceid Rescource ID of the photo
112 * @param integer $scale Scale of the photo. Defaults to 0
113 * @param array $conditions Array of fields for conditions
114 * @param array $params Array of several parameters
119 * @see \Friendica\Database\DBA::select
121 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
123 $conditions["resource-id"] = $resourceid;
124 $conditions["uid"] = $uid;
125 $conditions["scale"] = $scale;
127 return self::selectFirst([], $conditions, $params);
131 * Get a single photo given resource id and scale
133 * This method checks for permissions. Returns associative array
134 * on success, "no sign" image info, if user has no permission,
135 * false if photo does not exists
137 * @param string $resourceid Rescource ID of the photo
138 * @param integer $scale Scale of the photo. Defaults to 0
140 * @return boolean|array
143 public static function getPhoto(string $resourceid, int $scale = 0)
145 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
146 if (!DBA::isResult($r)) {
152 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
154 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
156 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
157 $params = ["order" => ["scale" => true]];
158 $photo = self::selectFirst([], $conditions, $params);
164 * Check if photo with given conditions exists
166 * @param array $conditions Array of extra conditions
171 public static function exists(array $conditions)
173 return DBA::exists("photo", $conditions);
178 * Get Image object for given row id. null if row id does not exist
180 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
182 * @return \Friendica\Object\Image
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function getImageForPhoto(array $photo)
188 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
189 if ($backendClass === null) {
190 // legacy data storage in "data" column
191 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
197 $backendRef = $photo['backend-ref'] ?? '';
198 $data = $backendClass->get($backendRef);
205 return new Image($data, $photo['type']);
209 * Return a list of fields that are associated with the photo table
211 * @return array field list
214 private static function getFields()
216 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
217 $fields = array_keys($allfields["photo"]["fields"]);
218 array_splice($fields, array_search("data", $fields), 1);
223 * Construct a photo array for a system resource image
225 * @param string $filename Image file name relative to code root
226 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
231 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
233 $fields = self::getFields();
234 $values = array_fill(0, count($fields), "");
236 $photo = array_combine($fields, $values);
237 $photo['backend-class'] = SystemResource::NAME;
238 $photo['backend-ref'] = $filename;
239 $photo['type'] = $mimetype;
240 $photo['cacheable'] = false;
247 * store photo metadata in db and binary in default backend
249 * @param Image $Image Image object with data
250 * @param integer $uid User ID
251 * @param integer $cid Contact ID
252 * @param integer $rid Resource ID
253 * @param string $filename Filename
254 * @param string $album Album name
255 * @param integer $scale Scale
256 * @param integer $profile Is a profile image? optional, default = 0
257 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
258 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
259 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
260 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
261 * @param string $desc Photo caption. optional, default = ""
263 * @return boolean True on success
264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
268 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
269 if (DBA::isResult($photo)) {
270 $guid = $photo["guid"];
272 $guid = System::createGUID();
275 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
276 $created = DateTimeFormat::utcNow();
277 if (DBA::isResult($existing_photo)) {
278 $created = $existing_photo["created"];
281 // Get defined storage backend.
282 // if no storage backend, we use old "data" column in photo table.
283 // if is an existing photo, reuse same backend
287 if (DBA::isResult($existing_photo)) {
288 $backend_ref = (string)$existing_photo["backend-ref"];
289 $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
291 $storage = DI::storage();
294 if ($storage === null) {
295 $data = $Image->asString();
297 $backend_ref = $storage->put($Image->asString(), $backend_ref);
302 "contact-id" => $cid,
304 "resource-id" => $rid,
305 "created" => $created,
306 "edited" => DateTimeFormat::utcNow(),
307 "filename" => basename($filename),
308 "type" => $Image->getType(),
310 "height" => $Image->getHeight(),
311 "width" => $Image->getWidth(),
312 "datasize" => strlen($Image->asString()),
315 "profile" => $profile,
316 "allow_cid" => $allow_cid,
317 "allow_gid" => $allow_gid,
318 "deny_cid" => $deny_cid,
319 "deny_gid" => $deny_gid,
321 "backend-class" => (string)$storage,
322 "backend-ref" => $backend_ref
325 if (DBA::isResult($existing_photo)) {
326 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
328 $r = DBA::insert("photo", $fields);
336 * Delete info from table and data from storage
338 * @param array $conditions Field condition(s)
339 * @param array $options Options array, Optional
344 * @see \Friendica\Database\DBA::delete
346 public static function delete(array $conditions, array $options = [])
348 // get photo to delete data info
349 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
351 foreach($photos as $photo) {
352 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
353 if ($backend_class !== null) {
354 $backend_class->delete($photo["backend-ref"] ?? '');
358 return DBA::delete("photo", $conditions, $options);
364 * @param array $fields Contains the fields that are updated
365 * @param array $conditions Condition array with the key values
366 * @param Image $img Image to update. Optional, default null.
367 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
369 * @return boolean Was the update successfull?
371 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
372 * @see \Friendica\Database\DBA::update
374 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
376 if (!is_null($img)) {
377 // get photo to update
378 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
380 foreach($photos as $photo) {
381 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
382 if ($backend_class !== null) {
383 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
385 $fields["data"] = $img->asString();
388 $fields['updated'] = DateTimeFormat::utcNow();
391 $fields['edited'] = DateTimeFormat::utcNow();
393 return DBA::update("photo", $fields, $conditions, $old_fields);
397 * @param string $image_url Remote URL
398 * @param integer $uid user id
399 * @param integer $cid contact id
400 * @param boolean $quit_on_error optional, default false
402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
403 * @throws \ImagickException
405 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
410 $photo = DBA::selectFirst(
411 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
413 if (!empty($photo['resource-id'])) {
414 $resource_id = $photo["resource-id"];
416 $resource_id = self::newResource();
419 $photo_failure = false;
421 $filename = basename($image_url);
422 if (!empty($image_url)) {
423 $ret = DI::httpRequest()->get($image_url, true);
424 $img_str = $ret->getBody();
425 $type = $ret->getContentType();
430 if ($quit_on_error && ($img_str == "")) {
434 $type = Images::getMimeTypeByData($img_str, $image_url, $type);
436 $Image = new Image($img_str, $type);
437 if ($Image->isValid()) {
438 $Image->scaleToSquare(300);
440 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
443 $photo_failure = true;
446 $Image->scaleDown(80);
448 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
451 $photo_failure = true;
454 $Image->scaleDown(48);
456 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
459 $photo_failure = true;
462 $suffix = "?ts=" . time();
464 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
465 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
466 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
468 // Remove the cached photo
470 $basepath = $a->getBasePath();
472 if (is_dir($basepath . "/photo")) {
473 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
474 if (file_exists($filename)) {
477 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
478 if (file_exists($filename)) {
481 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
482 if (file_exists($filename)) {
487 $photo_failure = true;
490 if ($photo_failure && $quit_on_error) {
494 if ($photo_failure) {
495 $image_url = DI::baseUrl() . "/images/person-300.jpg";
496 $thumb = DI::baseUrl() . "/images/person-80.jpg";
497 $micro = DI::baseUrl() . "/images/person-48.jpg";
500 return [$image_url, $thumb, $micro];
504 * @param array $exifCoord coordinate
505 * @param string $hemi hemi
508 public static function getGps($exifCoord, $hemi)
510 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
511 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
512 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
514 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
516 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
520 * @param string $coordPart coordPart
523 private static function gps2Num($coordPart)
525 $parts = explode("/", $coordPart);
527 if (count($parts) <= 0) {
531 if (count($parts) == 1) {
535 return floatval($parts[0]) / floatval($parts[1]);
539 * Fetch the photo albums that are available for a viewer
541 * The query in this function is cost intensive, so it is cached.
543 * @param int $uid User id of the photos
544 * @param bool $update Update the cache
546 * @return array Returns array of the photo albums
547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
549 public static function getAlbums($uid, $update = false)
551 $sql_extra = Security::getPermissionsSQLByUserId($uid);
553 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
554 $albums = DI::cache()->get($key);
555 if (is_null($albums) || $update) {
556 if (!DI::config()->get("system", "no_count", false)) {
557 /// @todo This query needs to be renewed. It is really slow
558 // At this time we just store the data in the cache
559 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
561 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
562 GROUP BY `album` ORDER BY `created` DESC",
564 DBA::escape("Contact Photos"),
565 DBA::escape(DI::l10n()->t("Contact Photos"))
568 // This query doesn't do the count and is much faster
569 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
570 FROM `photo` USE INDEX (`uid_album_scale_created`)
571 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
573 DBA::escape("Contact Photos"),
574 DBA::escape(DI::l10n()->t("Contact Photos"))
577 DI::cache()->set($key, $albums, Duration::DAY);
583 * @param int $uid User id of the photos
587 public static function clearAlbumCache($uid)
589 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
590 DI::cache()->set($key, null, Duration::DAY);
594 * Generate a unique photo ID.
599 public static function newResource()
601 return System::createGUID(32, false);
605 * Extracts the rid from a local photo URI
607 * @param string $image_uri The URI of the photo
608 * @return string The rid of the photo, or an empty string if the URI is not local
610 public static function ridFromURI(string $image_uri)
612 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
615 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
616 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
617 if (!strlen($image_uri)) {
624 * Changes photo permissions that had been embedded in a post
626 * @todo This function currently does have some flaws:
627 * - Sharing a post with a forum will create a photo that only the forum can see.
628 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
633 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
635 // Simplify image codes
636 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
637 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
640 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
644 if (empty($images)) {
648 foreach ($images as $image) {
649 $image_rid = self::ridFromURI($image);
650 if (empty($image_rid)) {
654 // Ensure to only modify photos that you own
655 $srch = '<' . intval($original_contact_id) . '>';
658 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
659 'resource-id' => $image_rid, 'uid' => $uid
661 if (!Photo::exists($condition)) {
662 $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
663 if (!DBA::isResult($photo)) {
664 Logger::info('Image not found', ['resource-id' => $image_rid]);
666 Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
672 * @todo Existing permissions need to be mixed with the new ones.
673 * Otherwise this creates problems with sharing the same picture multiple times
674 * Also check if $str_contact_allow does contain a public forum.
675 * Then set the permissions to public.
678 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
679 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny,
680 'accessible' => DI::pConfig()->get($uid, 'system', 'accessible-photos', false)];
682 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
683 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
684 Photo::update($fields, $condition);
691 * Strips known picture extensions from picture links
693 * @param string $name Picture link
694 * @return string stripped picture link
697 public static function stripExtension($name)
699 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
700 foreach (Images::supportedTypes() as $m => $e) {
701 $name = str_replace("." . $e, "", $name);
707 * Returns the GUID from picture links
709 * @param string $name Picture link
710 * @return string GUID
713 public static function getGUID($name)
715 $base = DI::baseUrl()->get();
717 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
719 $guid = self::stripExtension($guid);
720 if (substr($guid, -2, 1) != "-") {
724 $scale = intval(substr($guid, -1, 1));
725 if (!is_numeric($scale)) {
729 $guid = substr($guid, 0, -2);
734 * Tests if the picture link points to a locally stored picture
736 * @param string $name Picture link
740 public static function isLocal($name)
742 $guid = self::getGUID($name);
748 return DBA::exists('photo', ['resource-id' => $guid]);
752 * Tests if the link points to a locally stored picture page
754 * @param string $name Page link
758 public static function isLocalPage($name)
760 $base = DI::baseUrl()->get();
762 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
763 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
768 return DBA::exists('photo', ['resource-id' => $guid]);