4 * @file src/Model/Photo.php
5 * @brief This file contains the Photo class for database interface
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Core\Cache;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\StorageManager;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Database\DBStructure;
18 use Friendica\Model\Storage\IStorage;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\DFRN;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Security;
24 use Friendica\Util\Strings;
26 require_once "include/dba.php";
29 * Class to handle photo dabatase table
31 class Photo extends BaseObject
34 * @brief Select rows from the photo table and returns them as array
36 * @param array $fields Array of selected fields, empty for all
37 * @param array $conditions Array of fields for conditions
38 * @param array $params Array of several parameters
40 * @return boolean|array
43 * @see \Friendica\Database\DBA::selectToArray
45 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
48 $fields = self::getFields();
51 return DBA::selectToArray('photo', $fields, $conditions, $params);
55 * @brief Retrieve a single record from the photo table
57 * @param array $fields Array of selected fields, empty for all
58 * @param array $conditions Array of fields for conditions
59 * @param array $params Array of several parameters
64 * @see \Friendica\Database\DBA::select
66 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
69 $fields = self::getFields();
72 return DBA::selectFirst("photo", $fields, $conditions, $params);
76 * @brief Get photos for user id
78 * @param integer $uid User id
79 * @param string $resourceid Rescource ID of the photo
80 * @param array $conditions Array of fields for conditions
81 * @param array $params Array of several parameters
86 * @see \Friendica\Database\DBA::select
88 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
90 $conditions["resource-id"] = $resourceid;
91 $conditions["uid"] = $uid;
93 return self::selectToArray([], $conditions, $params);
97 * @brief Get a photo for user id
99 * @param integer $uid User id
100 * @param string $resourceid Rescource ID of the photo
101 * @param integer $scale Scale of the photo. Defaults to 0
102 * @param array $conditions Array of fields for conditions
103 * @param array $params Array of several parameters
108 * @see \Friendica\Database\DBA::select
110 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
112 $conditions["resource-id"] = $resourceid;
113 $conditions["uid"] = $uid;
114 $conditions["scale"] = $scale;
116 return self::selectFirst([], $conditions, $params);
120 * @brief Get a single photo given resource id and scale
122 * This method checks for permissions. Returns associative array
123 * on success, "no sign" image info, if user has no permission,
124 * false if photo does not exists
126 * @param string $resourceid Rescource ID of the photo
127 * @param integer $scale Scale of the photo. Defaults to 0
129 * @return boolean|array
132 public static function getPhoto($resourceid, $scale = 0)
134 $r = self::selectFirst(["uid", "allow_cid", "allow_gid", "deny_cid", "deny_gid"], ["resource-id" => $resourceid]);
140 // This is the first place, when retrieving just a photo, that we know who owns the photo.
141 // Check if the photo is public (empty allow and deny means public), if so, skip auth attempt, if not
142 // make sure that the requester's session is appropriately authenticated to that user
143 // otherwise permissions checks done by getPermissionsSQLByUserId() won't work correctly
144 if (!empty($r["allow_cid"]) || !empty($r["allow_gid"]) || !empty($r["deny_cid"]) || !empty($r["deny_gid"])) {
145 $r = DBA::selectFirst("user", ["nickname"], ["uid" => $uid], []);
146 // this will either just return (if auth all ok) or will redirect and exit (starting over)
147 DFRN::autoRedir(self::getApp(), $r["nickname"]);
150 $sql_acl = Security::getPermissionsSQLByUserId($uid);
153 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
157 $params = ["order" => ["scale" => true]];
159 $photo = self::selectFirst([], $conditions, $params);
165 * @brief 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 * @brief 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)
191 if ($photo["backend-class"] == "") {
192 // legacy data storage in "data" column
193 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
199 $backendClass = $photo["backend-class"];
200 $backendRef = $photo["backend-ref"];
201 $data = $backendClass::get($backendRef);
208 return new Image($data, $photo["type"]);
212 * @brief Return a list of fields that are associated with the photo table
214 * @return array field list
217 private static function getFields()
219 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
220 $fields = array_keys($allfields["photo"]["fields"]);
221 array_splice($fields, array_search("data", $fields), 1);
226 * @brief Construct a photo array for a system resource image
228 * @param string $filename Image file name relative to code root
229 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
234 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
236 $fields = self::getFields();
237 $values = array_fill(0, count($fields), "");
239 $photo = array_combine($fields, $values);
240 $photo["backend-class"] = Storage\SystemResource::class;
241 $photo["backend-ref"] = $filename;
242 $photo["type"] = $mimetype;
243 $photo["cacheable"] = false;
250 * @brief store photo metadata in db and binary in default backend
252 * @param Image $Image Image object with data
253 * @param integer $uid User ID
254 * @param integer $cid Contact ID
255 * @param integer $rid Resource ID
256 * @param string $filename Filename
257 * @param string $album Album name
258 * @param integer $scale Scale
259 * @param integer $profile Is a profile image? optional, default = 0
260 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
261 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
262 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
263 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
264 * @param string $desc Photo caption. optional, default = ""
266 * @return boolean True on success
267 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
271 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
272 if (DBA::isResult($photo)) {
273 $guid = $photo["guid"];
275 $guid = System::createGUID();
278 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
279 $created = DateTimeFormat::utcNow();
280 if (DBA::isResult($existing_photo)) {
281 $created = $existing_photo["created"];
284 // Get defined storage backend.
285 // if no storage backend, we use old "data" column in photo table.
286 // if is an existing photo, reuse same backend
290 /** @var IStorage $backend_class */
291 if (DBA::isResult($existing_photo)) {
292 $backend_ref = (string)$existing_photo["backend-ref"];
293 $backend_class = (string)$existing_photo["backend-class"];
295 $backend_class = StorageManager::getBackend();
298 if ($backend_class === "") {
299 $data = $Image->asString();
301 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
307 "contact-id" => $cid,
309 "resource-id" => $rid,
310 "created" => $created,
311 "edited" => DateTimeFormat::utcNow(),
312 "filename" => basename($filename),
313 "type" => $Image->getType(),
315 "height" => $Image->getHeight(),
316 "width" => $Image->getWidth(),
317 "datasize" => strlen($Image->asString()),
320 "profile" => $profile,
321 "allow_cid" => $allow_cid,
322 "allow_gid" => $allow_gid,
323 "deny_cid" => $deny_cid,
324 "deny_gid" => $deny_gid,
326 "backend-class" => $backend_class,
327 "backend-ref" => $backend_ref
330 if (DBA::isResult($existing_photo)) {
331 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
333 $r = DBA::insert("photo", $fields);
341 * @brief Delete info from table and data from storage
343 * @param array $conditions Field condition(s)
344 * @param array $options Options array, Optional
349 * @see \Friendica\Database\DBA::delete
351 public static function delete(array $conditions, array $options = [])
353 // get photo to delete data info
354 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
356 foreach($photos as $photo) {
357 /** @var IStorage $backend_class */
358 $backend_class = (string)$photo["backend-class"];
359 if ($backend_class !== "") {
360 $backend_class::delete($photo["backend-ref"]);
364 return DBA::delete("photo", $conditions, $options);
368 * @brief Update a photo
370 * @param array $fields Contains the fields that are updated
371 * @param array $conditions Condition array with the key values
372 * @param Image $img Image to update. Optional, default null.
373 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
375 * @return boolean Was the update successfull?
377 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
378 * @see \Friendica\Database\DBA::update
380 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
382 if (!is_null($img)) {
383 // get photo to update
384 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
386 foreach($photos as $photo) {
387 /** @var IStorage $backend_class */
388 $backend_class = (string)$photo["backend-class"];
389 if ($backend_class !== "") {
390 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
392 $fields["data"] = $img->asString();
395 $fields['updated'] = DateTimeFormat::utcNow();
398 $fields['edited'] = DateTimeFormat::utcNow();
400 return DBA::update("photo", $fields, $conditions, $old_fields);
404 * @param string $image_url Remote URL
405 * @param integer $uid user id
406 * @param integer $cid contact id
407 * @param boolean $quit_on_error optional, default false
409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410 * @throws \ImagickException
412 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
417 $photo = DBA::selectFirst(
418 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
420 if (!empty($photo['resource-id'])) {
421 $hash = $photo["resource-id"];
423 $hash = self::newResource();
426 $photo_failure = false;
428 $filename = basename($image_url);
429 if (!empty($image_url)) {
430 $ret = Network::curl($image_url, true);
431 $img_str = $ret->getBody();
432 $type = $ret->getContentType();
437 if ($quit_on_error && ($img_str == "")) {
442 $type = Image::guessType($image_url, true);
445 $Image = new Image($img_str, $type);
446 if ($Image->isValid()) {
447 $Image->scaleToSquare(300);
449 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
452 $photo_failure = true;
455 $Image->scaleDown(80);
457 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
460 $photo_failure = true;
463 $Image->scaleDown(48);
465 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
468 $photo_failure = true;
471 $suffix = "?ts=" . time();
473 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
474 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
475 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
477 // Remove the cached photo
479 $basepath = $a->getBasePath();
481 if (is_dir($basepath . "/photo")) {
482 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
483 if (file_exists($filename)) {
486 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
487 if (file_exists($filename)) {
490 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
491 if (file_exists($filename)) {
496 $photo_failure = true;
499 if ($photo_failure && $quit_on_error) {
503 if ($photo_failure) {
504 $image_url = System::baseUrl() . "/images/person-300.jpg";
505 $thumb = System::baseUrl() . "/images/person-80.jpg";
506 $micro = System::baseUrl() . "/images/person-48.jpg";
509 return [$image_url, $thumb, $micro];
513 * @param array $exifCoord coordinate
514 * @param string $hemi hemi
517 public static function getGps($exifCoord, $hemi)
519 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
520 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
521 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
523 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
525 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
529 * @param string $coordPart coordPart
532 private static function gps2Num($coordPart)
534 $parts = explode("/", $coordPart);
536 if (count($parts) <= 0) {
540 if (count($parts) == 1) {
544 return floatval($parts[0]) / floatval($parts[1]);
548 * @brief Fetch the photo albums that are available for a viewer
550 * The query in this function is cost intensive, so it is cached.
552 * @param int $uid User id of the photos
553 * @param bool $update Update the cache
555 * @return array Returns array of the photo albums
556 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
558 public static function getAlbums($uid, $update = false)
560 $sql_extra = Security::getPermissionsSQLByUserId($uid);
562 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
563 $albums = Cache::get($key);
564 if (is_null($albums) || $update) {
565 if (!Config::get("system", "no_count", false)) {
566 /// @todo This query needs to be renewed. It is really slow
567 // At this time we just store the data in the cache
568 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
570 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
571 GROUP BY `album` ORDER BY `created` DESC",
573 DBA::escape("Contact Photos"),
574 DBA::escape(L10n::t("Contact Photos"))
577 // This query doesn't do the count and is much faster
578 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
579 FROM `photo` USE INDEX (`uid_album_scale_created`)
580 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
582 DBA::escape("Contact Photos"),
583 DBA::escape(L10n::t("Contact Photos"))
586 Cache::set($key, $albums, Cache::DAY);
592 * @param int $uid User id of the photos
596 public static function clearAlbumCache($uid)
598 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
599 Cache::set($key, null, Cache::DAY);
603 * Generate a unique photo ID.
608 public static function newResource()
610 return System::createGUID(32, false);
614 * Changes photo permissions that had been embedded in a post
616 * @todo This function currently does have some flaws:
617 * - Sharing a post with a forum will create a photo that only the forum can see.
618 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
623 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
625 // Simplify image codes
626 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
627 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
630 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
634 if (empty($images)) {
638 foreach ($images as $image) {
639 if (!stristr($image, System::baseUrl() . '/photo/')) {
642 $image_uri = substr($image,strrpos($image,'/') + 1);
643 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
644 if (!strlen($image_uri)) {
648 // Ensure to only modify photos that you own
649 $srch = '<' . intval($original_contact_id) . '>';
652 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
653 'resource-id' => $image_uri, 'uid' => $uid
655 if (!Photo::exists($condition)) {
659 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
661 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
662 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
663 $condition = ['resource-id' => $image_uri, 'uid' => $uid];
664 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
665 Photo::update($fields, $condition);
672 * Strips known picture extensions from picture links
674 * @param string $name Picture link
675 * @return string stripped picture link
678 public static function stripExtension($name)
680 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
681 foreach (Image::supportedTypes() as $m => $e) {
682 $name = str_replace("." . $e, "", $name);
688 * Returns the GUID from picture links
690 * @param string $name Picture link
691 * @return string GUID
694 public static function getGUID($name)
697 $base = $a->getBaseURL();
699 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
701 $guid = self::stripExtension($guid);
702 if (substr($guid, -2, 1) != "-") {
706 $scale = intval(substr($guid, -1, 1));
711 $guid = substr($guid, 0, -2);
716 * Tests if the picture link points to a locally stored picture
718 * @param string $name Picture link
722 public static function isLocal($name)
724 $guid = self::getGUID($name);
730 return DBA::exists('photo', ['resource-id' => $guid]);