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\Network;
35 use Friendica\Util\Security;
36 use Friendica\Util\Strings;
38 require_once "include/dba.php";
41 * Class to handle photo dabatase table
46 * Select rows from the photo table and returns them as array
48 * @param array $fields Array of selected fields, empty for all
49 * @param array $conditions Array of fields for conditions
50 * @param array $params Array of several parameters
52 * @return boolean|array
55 * @see \Friendica\Database\DBA::selectToArray
57 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
60 $fields = self::getFields();
63 return DBA::selectToArray('photo', $fields, $conditions, $params);
67 * Retrieve a single record from the photo table
69 * @param array $fields Array of selected fields, empty for all
70 * @param array $conditions Array of fields for conditions
71 * @param array $params Array of several parameters
76 * @see \Friendica\Database\DBA::select
78 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
81 $fields = self::getFields();
84 return DBA::selectFirst("photo", $fields, $conditions, $params);
88 * Get photos for user id
90 * @param integer $uid User id
91 * @param string $resourceid Rescource ID of the photo
92 * @param array $conditions Array of fields for conditions
93 * @param array $params Array of several parameters
98 * @see \Friendica\Database\DBA::select
100 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
102 $conditions["resource-id"] = $resourceid;
103 $conditions["uid"] = $uid;
105 return self::selectToArray([], $conditions, $params);
109 * Get a photo for user id
111 * @param integer $uid User id
112 * @param string $resourceid Rescource ID of the photo
113 * @param integer $scale Scale of the photo. Defaults to 0
114 * @param array $conditions Array of fields for conditions
115 * @param array $params Array of several parameters
120 * @see \Friendica\Database\DBA::select
122 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
124 $conditions["resource-id"] = $resourceid;
125 $conditions["uid"] = $uid;
126 $conditions["scale"] = $scale;
128 return self::selectFirst([], $conditions, $params);
132 * Get a single photo given resource id and scale
134 * This method checks for permissions. Returns associative array
135 * on success, "no sign" image info, if user has no permission,
136 * false if photo does not exists
138 * @param string $resourceid Rescource ID of the photo
139 * @param integer $scale Scale of the photo. Defaults to 0
141 * @return boolean|array
144 public static function getPhoto(string $resourceid, int $scale = 0)
146 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
147 if (!DBA::isResult($r)) {
153 $accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
155 $sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
157 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
158 $params = ["order" => ["scale" => true]];
159 $photo = self::selectFirst([], $conditions, $params);
165 * Check if photo with given conditions exists
167 * @param array $conditions Array of extra conditions
172 public static function exists(array $conditions)
174 return DBA::exists("photo", $conditions);
179 * Get Image object for given row id. null if row id does not exist
181 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
183 * @return \Friendica\Object\Image
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 * @throws \ImagickException
187 public static function getImageForPhoto(array $photo)
189 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
190 if ($backendClass === null) {
191 // legacy data storage in "data" column
192 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
198 $backendRef = $photo['backend-ref'] ?? '';
199 $data = $backendClass->get($backendRef);
206 return new Image($data, $photo['type']);
210 * Return a list of fields that are associated with the photo table
212 * @return array field list
215 private static function getFields()
217 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
218 $fields = array_keys($allfields["photo"]["fields"]);
219 array_splice($fields, array_search("data", $fields), 1);
224 * Construct a photo array for a system resource image
226 * @param string $filename Image file name relative to code root
227 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
232 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
234 $fields = self::getFields();
235 $values = array_fill(0, count($fields), "");
237 $photo = array_combine($fields, $values);
238 $photo['backend-class'] = SystemResource::NAME;
239 $photo['backend-ref'] = $filename;
240 $photo['type'] = $mimetype;
241 $photo['cacheable'] = false;
248 * store photo metadata in db and binary in default backend
250 * @param Image $Image Image object with data
251 * @param integer $uid User ID
252 * @param integer $cid Contact ID
253 * @param integer $rid Resource ID
254 * @param string $filename Filename
255 * @param string $album Album name
256 * @param integer $scale Scale
257 * @param integer $profile Is a profile image? optional, default = 0
258 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
259 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
260 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
261 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
262 * @param string $desc Photo caption. optional, default = ""
264 * @return boolean True on success
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
269 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
270 if (DBA::isResult($photo)) {
271 $guid = $photo["guid"];
273 $guid = System::createGUID();
276 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
277 $created = DateTimeFormat::utcNow();
278 if (DBA::isResult($existing_photo)) {
279 $created = $existing_photo["created"];
282 // Get defined storage backend.
283 // if no storage backend, we use old "data" column in photo table.
284 // if is an existing photo, reuse same backend
288 if (DBA::isResult($existing_photo)) {
289 $backend_ref = (string)$existing_photo["backend-ref"];
290 $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
292 $storage = DI::storage();
295 if ($storage === null) {
296 $data = $Image->asString();
298 $backend_ref = $storage->put($Image->asString(), $backend_ref);
301 // Prevent "null" permissions
303 $allow_cid = $allow_cid ?? '<' . $uid . '>';
304 $allow_gid = $allow_gid ?? '';
305 $deny_cid = $deny_cid ?? '';
306 $deny_gid = $deny_gid ?? '';
311 "contact-id" => $cid,
313 "resource-id" => $rid,
314 "created" => $created,
315 "edited" => DateTimeFormat::utcNow(),
316 "filename" => basename($filename),
317 "type" => $Image->getType(),
319 "height" => $Image->getHeight(),
320 "width" => $Image->getWidth(),
321 "datasize" => strlen($Image->asString()),
324 "profile" => $profile,
325 "allow_cid" => $allow_cid,
326 "allow_gid" => $allow_gid,
327 "deny_cid" => $deny_cid,
328 "deny_gid" => $deny_gid,
330 "backend-class" => (string)$storage,
331 "backend-ref" => $backend_ref
334 if (DBA::isResult($existing_photo)) {
335 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
337 $r = DBA::insert("photo", $fields);
345 * Delete info from table and data from storage
347 * @param array $conditions Field condition(s)
348 * @param array $options Options array, Optional
353 * @see \Friendica\Database\DBA::delete
355 public static function delete(array $conditions, array $options = [])
357 // get photo to delete data info
358 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
360 foreach($photos as $photo) {
361 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
362 if ($backend_class !== null) {
363 $backend_class->delete($photo["backend-ref"] ?? '');
367 return DBA::delete("photo", $conditions, $options);
373 * @param array $fields Contains the fields that are updated
374 * @param array $conditions Condition array with the key values
375 * @param Image $img Image to update. Optional, default null.
376 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
378 * @return boolean Was the update successfull?
380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
381 * @see \Friendica\Database\DBA::update
383 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
385 if (!is_null($img)) {
386 // get photo to update
387 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
389 foreach($photos as $photo) {
390 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
391 if ($backend_class !== null) {
392 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
394 $fields["data"] = $img->asString();
397 $fields['updated'] = DateTimeFormat::utcNow();
400 $fields['edited'] = DateTimeFormat::utcNow();
402 return DBA::update("photo", $fields, $conditions, $old_fields);
406 * @param string $image_url Remote URL
407 * @param integer $uid user id
408 * @param integer $cid contact id
409 * @param boolean $quit_on_error optional, default false
411 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
412 * @throws \ImagickException
414 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
419 $photo = DBA::selectFirst(
420 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
422 if (!empty($photo['resource-id'])) {
423 $resource_id = $photo["resource-id"];
425 $resource_id = self::newResource();
428 $photo_failure = false;
430 $filename = basename($image_url);
431 if (!empty($image_url)) {
432 $ret = Network::curl($image_url, true);
433 $img_str = $ret->getBody();
434 $type = $ret->getContentType();
439 if ($quit_on_error && ($img_str == "")) {
444 $type = Images::guessType($image_url, true);
447 $Image = new Image($img_str, $type);
448 if ($Image->isValid()) {
449 $Image->scaleToSquare(300);
451 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
454 $photo_failure = true;
457 $Image->scaleDown(80);
459 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
462 $photo_failure = true;
465 $Image->scaleDown(48);
467 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
470 $photo_failure = true;
473 $suffix = "?ts=" . time();
475 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
476 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
477 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
479 // Remove the cached photo
481 $basepath = $a->getBasePath();
483 if (is_dir($basepath . "/photo")) {
484 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
485 if (file_exists($filename)) {
488 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
489 if (file_exists($filename)) {
492 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
493 if (file_exists($filename)) {
498 $photo_failure = true;
501 if ($photo_failure && $quit_on_error) {
505 if ($photo_failure) {
506 $image_url = DI::baseUrl() . "/images/person-300.jpg";
507 $thumb = DI::baseUrl() . "/images/person-80.jpg";
508 $micro = DI::baseUrl() . "/images/person-48.jpg";
511 return [$image_url, $thumb, $micro];
515 * @param array $exifCoord coordinate
516 * @param string $hemi hemi
519 public static function getGps($exifCoord, $hemi)
521 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
522 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
523 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
525 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
527 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
531 * @param string $coordPart coordPart
534 private static function gps2Num($coordPart)
536 $parts = explode("/", $coordPart);
538 if (count($parts) <= 0) {
542 if (count($parts) == 1) {
546 return floatval($parts[0]) / floatval($parts[1]);
550 * Fetch the photo albums that are available for a viewer
552 * The query in this function is cost intensive, so it is cached.
554 * @param int $uid User id of the photos
555 * @param bool $update Update the cache
557 * @return array Returns array of the photo albums
558 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
560 public static function getAlbums($uid, $update = false)
562 $sql_extra = Security::getPermissionsSQLByUserId($uid);
564 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
565 $albums = DI::cache()->get($key);
566 if (is_null($albums) || $update) {
567 if (!DI::config()->get("system", "no_count", false)) {
568 /// @todo This query needs to be renewed. It is really slow
569 // At this time we just store the data in the cache
570 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
572 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
573 GROUP BY `album` ORDER BY `created` DESC",
575 DBA::escape("Contact Photos"),
576 DBA::escape(DI::l10n()->t("Contact Photos"))
579 // This query doesn't do the count and is much faster
580 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
581 FROM `photo` USE INDEX (`uid_album_scale_created`)
582 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
584 DBA::escape("Contact Photos"),
585 DBA::escape(DI::l10n()->t("Contact Photos"))
588 DI::cache()->set($key, $albums, Duration::DAY);
594 * @param int $uid User id of the photos
598 public static function clearAlbumCache($uid)
600 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
601 DI::cache()->set($key, null, Duration::DAY);
605 * Generate a unique photo ID.
610 public static function newResource()
612 return System::createGUID(32, false);
616 * Extracts the rid from a local photo URI
618 * @param string $image_uri The URI of the photo
619 * @return string The rid of the photo, or an empty string if the URI is not local
621 public static function ridFromURI(string $image_uri)
623 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
626 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
627 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
628 if (!strlen($image_uri)) {
635 * Changes photo permissions that had been embedded in a post
637 * @todo This function currently does have some flaws:
638 * - Sharing a post with a forum will create a photo that only the forum can see.
639 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
644 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
646 // Simplify image codes
647 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
648 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
651 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
655 if (empty($images)) {
659 foreach ($images as $image) {
660 $image_rid = self::ridFromURI($image);
661 if (empty($image_rid)) {
665 if (DI::pConfig()->get($uid, 'system', 'accessible-photos')) {
666 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
667 Logger::info('Set accessibility', ['condition' => $condition]);
668 Photo::update(['accessible' => true], $condition);
671 // Ensure to only modify photos that you own
672 $srch = '<' . intval($original_contact_id) . '>';
674 $condition = ["(`allow_cid` = ? OR `allow_cid` IS NULL) AND
675 (`allow_gid` = ? OR `allow_gid` IS NULL) AND
676 (`deny_cid` = ? OR `deny_cid` IS NULL) AND
677 (`deny_gid` = ? OR `deny_gid` IS NULL) AND
678 `resource-id` = ? AND `uid` =?", $srch, '', '', '', $image_rid, $uid];
679 if (!Photo::exists($condition)) {
684 * @todo Existing permissions need to be mixed with the new ones.
685 * Otherwise this creates problems with sharing the same picture multiple times
686 * Also check if $str_contact_allow does contain a public forum.
687 * Then set the permissions to public.
690 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
691 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
693 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
694 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
695 Photo::update($fields, $condition);
702 * Strips known picture extensions from picture links
704 * @param string $name Picture link
705 * @return string stripped picture link
708 public static function stripExtension($name)
710 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
711 foreach (Images::supportedTypes() as $m => $e) {
712 $name = str_replace("." . $e, "", $name);
718 * Returns the GUID from picture links
720 * @param string $name Picture link
721 * @return string GUID
724 public static function getGUID($name)
726 $base = DI::baseUrl()->get();
728 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
730 $guid = self::stripExtension($guid);
731 if (substr($guid, -2, 1) != "-") {
735 $scale = intval(substr($guid, -1, 1));
736 if (!is_numeric($scale)) {
740 $guid = substr($guid, 0, -2);
745 * Tests if the picture link points to a locally stored picture
747 * @param string $name Picture link
751 public static function isLocal($name)
753 $guid = self::getGUID($name);
759 return DBA::exists('photo', ['resource-id' => $guid]);
763 * Tests if the link points to a locally stored picture page
765 * @param string $name Page link
769 public static function isLocalPage($name)
771 $base = DI::baseUrl()->get();
773 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
774 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
779 return DBA::exists('photo', ['resource-id' => $guid]);