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\Util\DateTimeFormat;
21 use Friendica\Util\Images;
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"], ["resource-id" => $resourceid]);
135 if (!DBA::isResult($r)) {
141 $sql_acl = Security::getPermissionsSQLByUserId($uid);
143 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
144 $params = ["order" => ["scale" => true]];
145 $photo = self::selectFirst([], $conditions, $params);
151 * @brief Check if photo with given conditions exists
153 * @param array $conditions Array of extra conditions
158 public static function exists(array $conditions)
160 return DBA::exists("photo", $conditions);
165 * @brief Get Image object for given row id. null if row id does not exist
167 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
169 * @return \Friendica\Object\Image
170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171 * @throws \ImagickException
173 public static function getImageForPhoto(array $photo)
177 if ($photo["backend-class"] == "") {
178 // legacy data storage in "data" column
179 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
185 $backendClass = $photo["backend-class"];
186 $backendRef = $photo["backend-ref"];
187 $data = $backendClass::get($backendRef);
194 return new Image($data, $photo["type"]);
198 * @brief Return a list of fields that are associated with the photo table
200 * @return array field list
203 private static function getFields()
205 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
206 $fields = array_keys($allfields["photo"]["fields"]);
207 array_splice($fields, array_search("data", $fields), 1);
212 * @brief Construct a photo array for a system resource image
214 * @param string $filename Image file name relative to code root
215 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
220 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
222 $fields = self::getFields();
223 $values = array_fill(0, count($fields), "");
225 $photo = array_combine($fields, $values);
226 $photo["backend-class"] = Storage\SystemResource::class;
227 $photo["backend-ref"] = $filename;
228 $photo["type"] = $mimetype;
229 $photo["cacheable"] = false;
236 * @brief store photo metadata in db and binary in default backend
238 * @param Image $Image Image object with data
239 * @param integer $uid User ID
240 * @param integer $cid Contact ID
241 * @param integer $rid Resource ID
242 * @param string $filename Filename
243 * @param string $album Album name
244 * @param integer $scale Scale
245 * @param integer $profile Is a profile image? optional, default = 0
246 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
247 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
248 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
249 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
250 * @param string $desc Photo caption. optional, default = ""
252 * @return boolean True on success
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
257 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
258 if (DBA::isResult($photo)) {
259 $guid = $photo["guid"];
261 $guid = System::createGUID();
264 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
265 $created = DateTimeFormat::utcNow();
266 if (DBA::isResult($existing_photo)) {
267 $created = $existing_photo["created"];
270 // Get defined storage backend.
271 // if no storage backend, we use old "data" column in photo table.
272 // if is an existing photo, reuse same backend
276 /** @var IStorage $backend_class */
277 if (DBA::isResult($existing_photo)) {
278 $backend_ref = (string)$existing_photo["backend-ref"];
279 $backend_class = (string)$existing_photo["backend-class"];
281 $backend_class = StorageManager::getBackend();
284 if ($backend_class === "") {
285 $data = $Image->asString();
287 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
293 "contact-id" => $cid,
295 "resource-id" => $rid,
296 "created" => $created,
297 "edited" => DateTimeFormat::utcNow(),
298 "filename" => basename($filename),
299 "type" => $Image->getType(),
301 "height" => $Image->getHeight(),
302 "width" => $Image->getWidth(),
303 "datasize" => strlen($Image->asString()),
306 "profile" => $profile,
307 "allow_cid" => $allow_cid,
308 "allow_gid" => $allow_gid,
309 "deny_cid" => $deny_cid,
310 "deny_gid" => $deny_gid,
312 "backend-class" => $backend_class,
313 "backend-ref" => $backend_ref
316 if (DBA::isResult($existing_photo)) {
317 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
319 $r = DBA::insert("photo", $fields);
327 * @brief Delete info from table and data from storage
329 * @param array $conditions Field condition(s)
330 * @param array $options Options array, Optional
335 * @see \Friendica\Database\DBA::delete
337 public static function delete(array $conditions, array $options = [])
339 // get photo to delete data info
340 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
342 foreach($photos as $photo) {
343 /** @var IStorage $backend_class */
344 $backend_class = (string)$photo["backend-class"];
345 if ($backend_class !== "") {
346 $backend_class::delete($photo["backend-ref"]);
350 return DBA::delete("photo", $conditions, $options);
354 * @brief Update a photo
356 * @param array $fields Contains the fields that are updated
357 * @param array $conditions Condition array with the key values
358 * @param Image $img Image to update. Optional, default null.
359 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
361 * @return boolean Was the update successfull?
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364 * @see \Friendica\Database\DBA::update
366 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
368 if (!is_null($img)) {
369 // get photo to update
370 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
372 foreach($photos as $photo) {
373 /** @var IStorage $backend_class */
374 $backend_class = (string)$photo["backend-class"];
375 if ($backend_class !== "") {
376 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
378 $fields["data"] = $img->asString();
381 $fields['updated'] = DateTimeFormat::utcNow();
384 $fields['edited'] = DateTimeFormat::utcNow();
386 return DBA::update("photo", $fields, $conditions, $old_fields);
390 * @param string $image_url Remote URL
391 * @param integer $uid user id
392 * @param integer $cid contact id
393 * @param boolean $quit_on_error optional, default false
395 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
396 * @throws \ImagickException
398 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
403 $photo = DBA::selectFirst(
404 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
406 if (!empty($photo['resource-id'])) {
407 $resource_id = $photo["resource-id"];
409 $resource_id = self::newResource();
412 $photo_failure = false;
414 $filename = basename($image_url);
415 if (!empty($image_url)) {
416 $ret = Network::curl($image_url, true);
417 $img_str = $ret->getBody();
418 $type = $ret->getContentType();
423 if ($quit_on_error && ($img_str == "")) {
428 $type = Images::guessType($image_url, true);
431 $Image = new Image($img_str, $type);
432 if ($Image->isValid()) {
433 $Image->scaleToSquare(300);
435 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
438 $photo_failure = true;
441 $Image->scaleDown(80);
443 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
446 $photo_failure = true;
449 $Image->scaleDown(48);
451 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
454 $photo_failure = true;
457 $suffix = "?ts=" . time();
459 $image_url = System::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
460 $thumb = System::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
461 $micro = System::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
463 // Remove the cached photo
465 $basepath = $a->getBasePath();
467 if (is_dir($basepath . "/photo")) {
468 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
469 if (file_exists($filename)) {
472 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
473 if (file_exists($filename)) {
476 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
477 if (file_exists($filename)) {
482 $photo_failure = true;
485 if ($photo_failure && $quit_on_error) {
489 if ($photo_failure) {
490 $image_url = System::baseUrl() . "/images/person-300.jpg";
491 $thumb = System::baseUrl() . "/images/person-80.jpg";
492 $micro = System::baseUrl() . "/images/person-48.jpg";
495 return [$image_url, $thumb, $micro];
499 * @param array $exifCoord coordinate
500 * @param string $hemi hemi
503 public static function getGps($exifCoord, $hemi)
505 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
506 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
507 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
509 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
511 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
515 * @param string $coordPart coordPart
518 private static function gps2Num($coordPart)
520 $parts = explode("/", $coordPart);
522 if (count($parts) <= 0) {
526 if (count($parts) == 1) {
530 return floatval($parts[0]) / floatval($parts[1]);
534 * @brief Fetch the photo albums that are available for a viewer
536 * The query in this function is cost intensive, so it is cached.
538 * @param int $uid User id of the photos
539 * @param bool $update Update the cache
541 * @return array Returns array of the photo albums
542 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
544 public static function getAlbums($uid, $update = false)
546 $sql_extra = Security::getPermissionsSQLByUserId($uid);
548 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
549 $albums = Cache::get($key);
550 if (is_null($albums) || $update) {
551 if (!Config::get("system", "no_count", false)) {
552 /// @todo This query needs to be renewed. It is really slow
553 // At this time we just store the data in the cache
554 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
556 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
557 GROUP BY `album` ORDER BY `created` DESC",
559 DBA::escape("Contact Photos"),
560 DBA::escape(L10n::t("Contact Photos"))
563 // This query doesn't do the count and is much faster
564 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
565 FROM `photo` USE INDEX (`uid_album_scale_created`)
566 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
568 DBA::escape("Contact Photos"),
569 DBA::escape(L10n::t("Contact Photos"))
572 Cache::set($key, $albums, Cache::DAY);
578 * @param int $uid User id of the photos
582 public static function clearAlbumCache($uid)
584 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
585 Cache::set($key, null, Cache::DAY);
589 * Generate a unique photo ID.
594 public static function newResource()
596 return System::createGUID(32, false);
600 * Changes photo permissions that had been embedded in a post
602 * @todo This function currently does have some flaws:
603 * - Sharing a post with a forum will create a photo that only the forum can see.
604 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
609 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
611 // Simplify image codes
612 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
613 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
616 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
620 if (empty($images)) {
624 foreach ($images as $image) {
625 if (!stristr($image, System::baseUrl() . '/photo/')) {
628 $image_uri = substr($image,strrpos($image,'/') + 1);
629 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
630 if (!strlen($image_uri)) {
634 // Ensure to only modify photos that you own
635 $srch = '<' . intval($original_contact_id) . '>';
638 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
639 'resource-id' => $image_uri, 'uid' => $uid
641 if (!Photo::exists($condition)) {
645 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
647 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
648 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
649 $condition = ['resource-id' => $image_uri, 'uid' => $uid];
650 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
651 Photo::update($fields, $condition);
658 * Strips known picture extensions from picture links
660 * @param string $name Picture link
661 * @return string stripped picture link
664 public static function stripExtension($name)
666 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
667 foreach (Images::supportedTypes() as $m => $e) {
668 $name = str_replace("." . $e, "", $name);
674 * Returns the GUID from picture links
676 * @param string $name Picture link
677 * @return string GUID
680 public static function getGUID($name)
683 $base = $a->getBaseURL();
685 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
687 $guid = self::stripExtension($guid);
688 if (substr($guid, -2, 1) != "-") {
692 $scale = intval(substr($guid, -1, 1));
693 if (!is_numeric($scale)) {
697 $guid = substr($guid, 0, -2);
702 * Tests if the picture link points to a locally stored picture
704 * @param string $name Picture link
708 public static function isLocal($name)
710 $guid = self::getGUID($name);
716 return DBA::exists('photo', ['resource-id' => $guid]);
720 * Tests if the link points to a locally stored picture page
722 * @param string $name Page link
726 public static function isLocalPage($name)
729 $base = $a->getBaseURL();
731 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
732 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
737 return DBA::exists('photo', ['resource-id' => $guid]);