4 * @file src/Model/Photo.php
5 * @brief This file contains the Photo class for database interface
7 namespace Friendica\Model;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Database\DBStructure;
17 use Friendica\Model\Storage\SystemResource;
18 use Friendica\Object\Image;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Images;
21 use Friendica\Util\Network;
22 use Friendica\Util\Security;
23 use Friendica\Util\Strings;
25 require_once "include/dba.php";
28 * Class to handle photo dabatase table
33 * @brief Select rows from the photo table and returns them as array
35 * @param array $fields Array of selected fields, empty for all
36 * @param array $conditions Array of fields for conditions
37 * @param array $params Array of several parameters
39 * @return boolean|array
42 * @see \Friendica\Database\DBA::selectToArray
44 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
47 $fields = self::getFields();
50 return DBA::selectToArray('photo', $fields, $conditions, $params);
54 * @brief Retrieve a single record from the photo table
56 * @param array $fields Array of selected fields, empty for all
57 * @param array $conditions Array of fields for conditions
58 * @param array $params Array of several parameters
63 * @see \Friendica\Database\DBA::select
65 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
68 $fields = self::getFields();
71 return DBA::selectFirst("photo", $fields, $conditions, $params);
75 * @brief Get photos for user id
77 * @param integer $uid User id
78 * @param string $resourceid Rescource ID of the photo
79 * @param array $conditions Array of fields for conditions
80 * @param array $params Array of several parameters
85 * @see \Friendica\Database\DBA::select
87 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
89 $conditions["resource-id"] = $resourceid;
90 $conditions["uid"] = $uid;
92 return self::selectToArray([], $conditions, $params);
96 * @brief Get a photo for user id
98 * @param integer $uid User id
99 * @param string $resourceid Rescource ID of the photo
100 * @param integer $scale Scale of the photo. Defaults to 0
101 * @param array $conditions Array of fields for conditions
102 * @param array $params Array of several parameters
107 * @see \Friendica\Database\DBA::select
109 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
111 $conditions["resource-id"] = $resourceid;
112 $conditions["uid"] = $uid;
113 $conditions["scale"] = $scale;
115 return self::selectFirst([], $conditions, $params);
119 * @brief Get a single photo given resource id and scale
121 * This method checks for permissions. Returns associative array
122 * on success, "no sign" image info, if user has no permission,
123 * false if photo does not exists
125 * @param string $resourceid Rescource ID of the photo
126 * @param integer $scale Scale of the photo. Defaults to 0
128 * @return boolean|array
131 public static function getPhoto($resourceid, $scale = 0)
133 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
134 if (!DBA::isResult($r)) {
140 $sql_acl = Security::getPermissionsSQLByUserId($uid);
142 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
143 $params = ["order" => ["scale" => true]];
144 $photo = self::selectFirst([], $conditions, $params);
150 * @brief Check if photo with given conditions exists
152 * @param array $conditions Array of extra conditions
157 public static function exists(array $conditions)
159 return DBA::exists("photo", $conditions);
164 * @brief Get Image object for given row id. null if row id does not exist
166 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
168 * @return \Friendica\Object\Image
169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 * @throws \ImagickException
172 public static function getImageForPhoto(array $photo)
174 if (empty($photo['backend-class'])) {
175 // legacy data storage in "data" column
176 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
182 $backendClass = DI::facStorage()->getByName($photo['backend-class'] ?? '');
183 $backendRef = $photo['backend-ref'] ?? '';
184 $data = $backendClass->get($backendRef);
191 return new Image($data, $photo['type']);
195 * @brief Return a list of fields that are associated with the photo table
197 * @return array field list
200 private static function getFields()
202 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
203 $fields = array_keys($allfields["photo"]["fields"]);
204 array_splice($fields, array_search("data", $fields), 1);
209 * @brief Construct a photo array for a system resource image
211 * @param string $filename Image file name relative to code root
212 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
217 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
219 $fields = self::getFields();
220 $values = array_fill(0, count($fields), "");
222 $photo = array_combine($fields, $values);
223 $photo['backend-class'] = SystemResource::NAME;
224 $photo['backend-ref'] = $filename;
225 $photo['type'] = $mimetype;
226 $photo['cacheable'] = false;
233 * @brief store photo metadata in db and binary in default backend
235 * @param Image $Image Image object with data
236 * @param integer $uid User ID
237 * @param integer $cid Contact ID
238 * @param integer $rid Resource ID
239 * @param string $filename Filename
240 * @param string $album Album name
241 * @param integer $scale Scale
242 * @param integer $profile Is a profile image? optional, default = 0
243 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
244 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
245 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
246 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
247 * @param string $desc Photo caption. optional, default = ""
249 * @return boolean True on success
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
254 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
255 if (DBA::isResult($photo)) {
256 $guid = $photo["guid"];
258 $guid = System::createGUID();
261 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
262 $created = DateTimeFormat::utcNow();
263 if (DBA::isResult($existing_photo)) {
264 $created = $existing_photo["created"];
267 // Get defined storage backend.
268 // if no storage backend, we use old "data" column in photo table.
269 // if is an existing photo, reuse same backend
273 if (DBA::isResult($existing_photo)) {
274 $backend_ref = (string)$existing_photo["backend-ref"];
275 $storage = DI::facStorage()->getByName($existing_photo["backend-class"] ?? '');
277 $storage = DI::storage();
280 if ($storage === null) {
281 $data = $Image->asString();
283 $backend_ref = $storage->put($Image->asString(), $backend_ref);
289 "contact-id" => $cid,
291 "resource-id" => $rid,
292 "created" => $created,
293 "edited" => DateTimeFormat::utcNow(),
294 "filename" => basename($filename),
295 "type" => $Image->getType(),
297 "height" => $Image->getHeight(),
298 "width" => $Image->getWidth(),
299 "datasize" => strlen($Image->asString()),
302 "profile" => $profile,
303 "allow_cid" => $allow_cid,
304 "allow_gid" => $allow_gid,
305 "deny_cid" => $deny_cid,
306 "deny_gid" => $deny_gid,
308 "backend-class" => (string)$storage,
309 "backend-ref" => $backend_ref
312 if (DBA::isResult($existing_photo)) {
313 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
315 $r = DBA::insert("photo", $fields);
323 * @brief Delete info from table and data from storage
325 * @param array $conditions Field condition(s)
326 * @param array $options Options array, Optional
331 * @see \Friendica\Database\DBA::delete
333 public static function delete(array $conditions, array $options = [])
335 // get photo to delete data info
336 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
338 foreach($photos as $photo) {
339 $backend_class = DI::facStorage()->getByName($photo['backend-class'] ?? '');
340 if ($backend_class !== null) {
341 $backend_class->delete($photo["backend-ref"] ?? '');
345 return DBA::delete("photo", $conditions, $options);
349 * @brief Update a photo
351 * @param array $fields Contains the fields that are updated
352 * @param array $conditions Condition array with the key values
353 * @param Image $img Image to update. Optional, default null.
354 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
356 * @return boolean Was the update successfull?
358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
359 * @see \Friendica\Database\DBA::update
361 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
363 if (!is_null($img)) {
364 // get photo to update
365 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
367 foreach($photos as $photo) {
368 $backend_class = DI::facStorage()->getByName($photo['backend-class'] ?? '');
369 if ($backend_class !== null) {
370 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
372 $fields["data"] = $img->asString();
375 $fields['updated'] = DateTimeFormat::utcNow();
378 $fields['edited'] = DateTimeFormat::utcNow();
380 return DBA::update("photo", $fields, $conditions, $old_fields);
384 * @param string $image_url Remote URL
385 * @param integer $uid user id
386 * @param integer $cid contact id
387 * @param boolean $quit_on_error optional, default false
389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
390 * @throws \ImagickException
392 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
397 $photo = DBA::selectFirst(
398 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
400 if (!empty($photo['resource-id'])) {
401 $resource_id = $photo["resource-id"];
403 $resource_id = self::newResource();
406 $photo_failure = false;
408 $filename = basename($image_url);
409 if (!empty($image_url)) {
410 $ret = Network::curl($image_url, true);
411 $img_str = $ret->getBody();
412 $type = $ret->getContentType();
417 if ($quit_on_error && ($img_str == "")) {
422 $type = Images::guessType($image_url, true);
425 $Image = new Image($img_str, $type);
426 if ($Image->isValid()) {
427 $Image->scaleToSquare(300);
429 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
432 $photo_failure = true;
435 $Image->scaleDown(80);
437 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
440 $photo_failure = true;
443 $Image->scaleDown(48);
445 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
448 $photo_failure = true;
451 $suffix = "?ts=" . time();
453 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
454 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
455 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
457 // Remove the cached photo
459 $basepath = $a->getBasePath();
461 if (is_dir($basepath . "/photo")) {
462 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
463 if (file_exists($filename)) {
466 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
467 if (file_exists($filename)) {
470 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
471 if (file_exists($filename)) {
476 $photo_failure = true;
479 if ($photo_failure && $quit_on_error) {
483 if ($photo_failure) {
484 $image_url = DI::baseUrl() . "/images/person-300.jpg";
485 $thumb = DI::baseUrl() . "/images/person-80.jpg";
486 $micro = DI::baseUrl() . "/images/person-48.jpg";
489 return [$image_url, $thumb, $micro];
493 * @param array $exifCoord coordinate
494 * @param string $hemi hemi
497 public static function getGps($exifCoord, $hemi)
499 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
500 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
501 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
503 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
505 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
509 * @param string $coordPart coordPart
512 private static function gps2Num($coordPart)
514 $parts = explode("/", $coordPart);
516 if (count($parts) <= 0) {
520 if (count($parts) == 1) {
524 return floatval($parts[0]) / floatval($parts[1]);
528 * @brief Fetch the photo albums that are available for a viewer
530 * The query in this function is cost intensive, so it is cached.
532 * @param int $uid User id of the photos
533 * @param bool $update Update the cache
535 * @return array Returns array of the photo albums
536 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
538 public static function getAlbums($uid, $update = false)
540 $sql_extra = Security::getPermissionsSQLByUserId($uid);
542 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
543 $albums = Cache::get($key);
544 if (is_null($albums) || $update) {
545 if (!Config::get("system", "no_count", false)) {
546 /// @todo This query needs to be renewed. It is really slow
547 // At this time we just store the data in the cache
548 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
550 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
551 GROUP BY `album` ORDER BY `created` DESC",
553 DBA::escape("Contact Photos"),
554 DBA::escape(L10n::t("Contact Photos"))
557 // This query doesn't do the count and is much faster
558 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
559 FROM `photo` USE INDEX (`uid_album_scale_created`)
560 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
562 DBA::escape("Contact Photos"),
563 DBA::escape(L10n::t("Contact Photos"))
566 Cache::set($key, $albums, Cache::DAY);
572 * @param int $uid User id of the photos
576 public static function clearAlbumCache($uid)
578 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
579 Cache::set($key, null, Cache::DAY);
583 * Generate a unique photo ID.
588 public static function newResource()
590 return System::createGUID(32, false);
594 * Changes photo permissions that had been embedded in a post
596 * @todo This function currently does have some flaws:
597 * - Sharing a post with a forum will create a photo that only the forum can see.
598 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
603 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
605 // Simplify image codes
606 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
607 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
610 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
614 if (empty($images)) {
618 foreach ($images as $image) {
619 if (!stristr($image, DI::baseUrl() . '/photo/')) {
622 $image_uri = substr($image,strrpos($image,'/') + 1);
623 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
624 if (!strlen($image_uri)) {
628 // Ensure to only modify photos that you own
629 $srch = '<' . intval($original_contact_id) . '>';
632 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
633 'resource-id' => $image_uri, 'uid' => $uid
635 if (!Photo::exists($condition)) {
639 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
641 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
642 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
643 $condition = ['resource-id' => $image_uri, 'uid' => $uid];
644 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
645 Photo::update($fields, $condition);
652 * Strips known picture extensions from picture links
654 * @param string $name Picture link
655 * @return string stripped picture link
658 public static function stripExtension($name)
660 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
661 foreach (Images::supportedTypes() as $m => $e) {
662 $name = str_replace("." . $e, "", $name);
668 * Returns the GUID from picture links
670 * @param string $name Picture link
671 * @return string GUID
674 public static function getGUID($name)
676 $base = DI::baseUrl()->get();
678 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
680 $guid = self::stripExtension($guid);
681 if (substr($guid, -2, 1) != "-") {
685 $scale = intval(substr($guid, -1, 1));
686 if (!is_numeric($scale)) {
690 $guid = substr($guid, 0, -2);
695 * Tests if the picture link points to a locally stored picture
697 * @param string $name Picture link
701 public static function isLocal($name)
703 $guid = self::getGUID($name);
709 return DBA::exists('photo', ['resource-id' => $guid]);
713 * Tests if the link points to a locally stored picture page
715 * @param string $name Page link
719 public static function isLocalPage($name)
721 $base = DI::baseUrl()->get();
723 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
724 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
729 return DBA::exists('photo', ['resource-id' => $guid]);