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\StorageManager;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 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
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(DI::app()->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 if (DBA::isResult($existing_photo)) {
277 $backend_ref = (string)$existing_photo["backend-ref"];
278 $storage = DI::facStorage()->getByName((string)$existing_photo["backend-class"]);
280 $storage = DI::storage();
283 if ($storage === null) {
284 $data = $Image->asString();
286 $backend_ref = $storage->put($Image->asString(), $backend_ref);
292 "contact-id" => $cid,
294 "resource-id" => $rid,
295 "created" => $created,
296 "edited" => DateTimeFormat::utcNow(),
297 "filename" => basename($filename),
298 "type" => $Image->getType(),
300 "height" => $Image->getHeight(),
301 "width" => $Image->getWidth(),
302 "datasize" => strlen($Image->asString()),
305 "profile" => $profile,
306 "allow_cid" => $allow_cid,
307 "allow_gid" => $allow_gid,
308 "deny_cid" => $deny_cid,
309 "deny_gid" => $deny_gid,
311 "backend-class" => (string)$storage,
312 "backend-ref" => $backend_ref
315 if (DBA::isResult($existing_photo)) {
316 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
318 $r = DBA::insert("photo", $fields);
326 * @brief Delete info from table and data from storage
328 * @param array $conditions Field condition(s)
329 * @param array $options Options array, Optional
334 * @see \Friendica\Database\DBA::delete
336 public static function delete(array $conditions, array $options = [])
338 // get photo to delete data info
339 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
341 foreach($photos as $photo) {
342 /** @var IStorage $backend_class */
343 $backend_class = (string)$photo["backend-class"];
344 if ($backend_class !== "") {
345 $backend_class::delete($photo["backend-ref"]);
349 return DBA::delete("photo", $conditions, $options);
353 * @brief Update a photo
355 * @param array $fields Contains the fields that are updated
356 * @param array $conditions Condition array with the key values
357 * @param Image $img Image to update. Optional, default null.
358 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
360 * @return boolean Was the update successfull?
362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
363 * @see \Friendica\Database\DBA::update
365 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
367 if (!is_null($img)) {
368 // get photo to update
369 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
371 foreach($photos as $photo) {
372 /** @var IStorage $backend_class */
373 $backend_class = (string)$photo["backend-class"];
374 if ($backend_class !== "") {
375 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
377 $fields["data"] = $img->asString();
380 $fields['updated'] = DateTimeFormat::utcNow();
383 $fields['edited'] = DateTimeFormat::utcNow();
385 return DBA::update("photo", $fields, $conditions, $old_fields);
389 * @param string $image_url Remote URL
390 * @param integer $uid user id
391 * @param integer $cid contact id
392 * @param boolean $quit_on_error optional, default false
394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
395 * @throws \ImagickException
397 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
402 $photo = DBA::selectFirst(
403 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
405 if (!empty($photo['resource-id'])) {
406 $resource_id = $photo["resource-id"];
408 $resource_id = self::newResource();
411 $photo_failure = false;
413 $filename = basename($image_url);
414 if (!empty($image_url)) {
415 $ret = Network::curl($image_url, true);
416 $img_str = $ret->getBody();
417 $type = $ret->getContentType();
422 if ($quit_on_error && ($img_str == "")) {
427 $type = Images::guessType($image_url, true);
430 $Image = new Image($img_str, $type);
431 if ($Image->isValid()) {
432 $Image->scaleToSquare(300);
434 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
437 $photo_failure = true;
440 $Image->scaleDown(80);
442 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
445 $photo_failure = true;
448 $Image->scaleDown(48);
450 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
453 $photo_failure = true;
456 $suffix = "?ts=" . time();
458 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
459 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
460 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
462 // Remove the cached photo
464 $basepath = $a->getBasePath();
466 if (is_dir($basepath . "/photo")) {
467 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
468 if (file_exists($filename)) {
471 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
472 if (file_exists($filename)) {
475 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
476 if (file_exists($filename)) {
481 $photo_failure = true;
484 if ($photo_failure && $quit_on_error) {
488 if ($photo_failure) {
489 $image_url = DI::baseUrl() . "/images/person-300.jpg";
490 $thumb = DI::baseUrl() . "/images/person-80.jpg";
491 $micro = DI::baseUrl() . "/images/person-48.jpg";
494 return [$image_url, $thumb, $micro];
498 * @param array $exifCoord coordinate
499 * @param string $hemi hemi
502 public static function getGps($exifCoord, $hemi)
504 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
505 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
506 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
508 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
510 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
514 * @param string $coordPart coordPart
517 private static function gps2Num($coordPart)
519 $parts = explode("/", $coordPart);
521 if (count($parts) <= 0) {
525 if (count($parts) == 1) {
529 return floatval($parts[0]) / floatval($parts[1]);
533 * @brief Fetch the photo albums that are available for a viewer
535 * The query in this function is cost intensive, so it is cached.
537 * @param int $uid User id of the photos
538 * @param bool $update Update the cache
540 * @return array Returns array of the photo albums
541 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
543 public static function getAlbums($uid, $update = false)
545 $sql_extra = Security::getPermissionsSQLByUserId($uid);
547 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
548 $albums = Cache::get($key);
549 if (is_null($albums) || $update) {
550 if (!Config::get("system", "no_count", false)) {
551 /// @todo This query needs to be renewed. It is really slow
552 // At this time we just store the data in the cache
553 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
555 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
556 GROUP BY `album` ORDER BY `created` DESC",
558 DBA::escape("Contact Photos"),
559 DBA::escape(L10n::t("Contact Photos"))
562 // This query doesn't do the count and is much faster
563 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
564 FROM `photo` USE INDEX (`uid_album_scale_created`)
565 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
567 DBA::escape("Contact Photos"),
568 DBA::escape(L10n::t("Contact Photos"))
571 Cache::set($key, $albums, Cache::DAY);
577 * @param int $uid User id of the photos
581 public static function clearAlbumCache($uid)
583 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
584 Cache::set($key, null, Cache::DAY);
588 * Generate a unique photo ID.
593 public static function newResource()
595 return System::createGUID(32, false);
599 * Changes photo permissions that had been embedded in a post
601 * @todo This function currently does have some flaws:
602 * - Sharing a post with a forum will create a photo that only the forum can see.
603 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
608 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
610 // Simplify image codes
611 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
612 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
615 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
619 if (empty($images)) {
623 foreach ($images as $image) {
624 if (!stristr($image, DI::baseUrl() . '/photo/')) {
627 $image_uri = substr($image,strrpos($image,'/') + 1);
628 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
629 if (!strlen($image_uri)) {
633 // Ensure to only modify photos that you own
634 $srch = '<' . intval($original_contact_id) . '>';
637 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
638 'resource-id' => $image_uri, 'uid' => $uid
640 if (!Photo::exists($condition)) {
644 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
646 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
647 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
648 $condition = ['resource-id' => $image_uri, 'uid' => $uid];
649 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
650 Photo::update($fields, $condition);
657 * Strips known picture extensions from picture links
659 * @param string $name Picture link
660 * @return string stripped picture link
663 public static function stripExtension($name)
665 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
666 foreach (Images::supportedTypes() as $m => $e) {
667 $name = str_replace("." . $e, "", $name);
673 * Returns the GUID from picture links
675 * @param string $name Picture link
676 * @return string GUID
679 public static function getGUID($name)
681 $base = DI::baseUrl()->get();
683 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
685 $guid = self::stripExtension($guid);
686 if (substr($guid, -2, 1) != "-") {
690 $scale = intval(substr($guid, -1, 1));
691 if (!is_numeric($scale)) {
695 $guid = substr($guid, 0, -2);
700 * Tests if the picture link points to a locally stored picture
702 * @param string $name Picture link
706 public static function isLocal($name)
708 $guid = self::getGUID($name);
714 return DBA::exists('photo', ['resource-id' => $guid]);
718 * Tests if the link points to a locally stored picture page
720 * @param string $name Page link
724 public static function isLocalPage($name)
726 $base = DI::baseUrl()->get();
728 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
729 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
734 return DBA::exists('photo', ['resource-id' => $guid]);