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\Model\Storage\SystemResource;
20 use Friendica\Object\Image;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Images;
23 use Friendica\Util\Network;
24 use Friendica\Util\Security;
25 use Friendica\Util\Strings;
27 require_once "include/dba.php";
30 * Class to handle photo dabatase table
35 * @brief Select rows from the photo table and returns them as array
37 * @param array $fields Array of selected fields, empty for all
38 * @param array $conditions Array of fields for conditions
39 * @param array $params Array of several parameters
41 * @return boolean|array
44 * @see \Friendica\Database\DBA::selectToArray
46 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
49 $fields = self::getFields();
52 return DBA::selectToArray('photo', $fields, $conditions, $params);
56 * @brief Retrieve a single record from the photo table
58 * @param array $fields Array of selected fields, empty for all
59 * @param array $conditions Array of fields for conditions
60 * @param array $params Array of several parameters
65 * @see \Friendica\Database\DBA::select
67 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
70 $fields = self::getFields();
73 return DBA::selectFirst("photo", $fields, $conditions, $params);
77 * @brief Get photos for user id
79 * @param integer $uid User id
80 * @param string $resourceid Rescource ID of the photo
81 * @param array $conditions Array of fields for conditions
82 * @param array $params Array of several parameters
87 * @see \Friendica\Database\DBA::select
89 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
91 $conditions["resource-id"] = $resourceid;
92 $conditions["uid"] = $uid;
94 return self::selectToArray([], $conditions, $params);
98 * @brief Get a photo for user id
100 * @param integer $uid User id
101 * @param string $resourceid Rescource ID of the photo
102 * @param integer $scale Scale of the photo. Defaults to 0
103 * @param array $conditions Array of fields for conditions
104 * @param array $params Array of several parameters
109 * @see \Friendica\Database\DBA::select
111 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
113 $conditions["resource-id"] = $resourceid;
114 $conditions["uid"] = $uid;
115 $conditions["scale"] = $scale;
117 return self::selectFirst([], $conditions, $params);
121 * @brief Get a single photo given resource id and scale
123 * This method checks for permissions. Returns associative array
124 * on success, "no sign" image info, if user has no permission,
125 * false if photo does not exists
127 * @param string $resourceid Rescource ID of the photo
128 * @param integer $scale Scale of the photo. Defaults to 0
130 * @return boolean|array
133 public static function getPhoto($resourceid, $scale = 0)
135 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
136 if (!DBA::isResult($r)) {
142 $sql_acl = Security::getPermissionsSQLByUserId($uid);
144 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
145 $params = ["order" => ["scale" => true]];
146 $photo = self::selectFirst([], $conditions, $params);
152 * @brief Check if photo with given conditions exists
154 * @param array $conditions Array of extra conditions
159 public static function exists(array $conditions)
161 return DBA::exists("photo", $conditions);
166 * @brief Get Image object for given row id. null if row id does not exist
168 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
170 * @return \Friendica\Object\Image
171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
172 * @throws \ImagickException
174 public static function getImageForPhoto(array $photo)
176 if (empty($photo['backend-class'])) {
177 // legacy data storage in "data" column
178 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
184 $backendClass = DI::facStorage()->getByName($photo['backend-class'] ?? '');
185 $backendRef = $photo['backend-ref'] ?? '';
186 $data = $backendClass->get($backendRef);
193 return new Image($data, $photo['type']);
197 * @brief Return a list of fields that are associated with the photo table
199 * @return array field list
202 private static function getFields()
204 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
205 $fields = array_keys($allfields["photo"]["fields"]);
206 array_splice($fields, array_search("data", $fields), 1);
211 * @brief Construct a photo array for a system resource image
213 * @param string $filename Image file name relative to code root
214 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
219 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
221 $fields = self::getFields();
222 $values = array_fill(0, count($fields), "");
224 $photo = array_combine($fields, $values);
225 $photo['backend-class'] = SystemResource::NAME;
226 $photo['backend-ref'] = $filename;
227 $photo['type'] = $mimetype;
228 $photo['cacheable'] = false;
235 * @brief store photo metadata in db and binary in default backend
237 * @param Image $Image Image object with data
238 * @param integer $uid User ID
239 * @param integer $cid Contact ID
240 * @param integer $rid Resource ID
241 * @param string $filename Filename
242 * @param string $album Album name
243 * @param integer $scale Scale
244 * @param integer $profile Is a profile image? optional, default = 0
245 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
246 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
247 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
248 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
249 * @param string $desc Photo caption. optional, default = ""
251 * @return boolean True on success
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
256 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
257 if (DBA::isResult($photo)) {
258 $guid = $photo["guid"];
260 $guid = System::createGUID();
263 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
264 $created = DateTimeFormat::utcNow();
265 if (DBA::isResult($existing_photo)) {
266 $created = $existing_photo["created"];
269 // Get defined storage backend.
270 // if no storage backend, we use old "data" column in photo table.
271 // if is an existing photo, reuse same backend
275 if (DBA::isResult($existing_photo)) {
276 $backend_ref = (string)$existing_photo["backend-ref"];
277 $storage = DI::facStorage()->getByName($existing_photo["backend-class"] ?? '');
279 $storage = DI::storage();
282 if ($storage === null) {
283 $data = $Image->asString();
285 $backend_ref = $storage->put($Image->asString(), $backend_ref);
291 "contact-id" => $cid,
293 "resource-id" => $rid,
294 "created" => $created,
295 "edited" => DateTimeFormat::utcNow(),
296 "filename" => basename($filename),
297 "type" => $Image->getType(),
299 "height" => $Image->getHeight(),
300 "width" => $Image->getWidth(),
301 "datasize" => strlen($Image->asString()),
304 "profile" => $profile,
305 "allow_cid" => $allow_cid,
306 "allow_gid" => $allow_gid,
307 "deny_cid" => $deny_cid,
308 "deny_gid" => $deny_gid,
310 "backend-class" => (string)$storage,
311 "backend-ref" => $backend_ref
314 if (DBA::isResult($existing_photo)) {
315 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
317 $r = DBA::insert("photo", $fields);
325 * @brief Delete info from table and data from storage
327 * @param array $conditions Field condition(s)
328 * @param array $options Options array, Optional
333 * @see \Friendica\Database\DBA::delete
335 public static function delete(array $conditions, array $options = [])
337 // get photo to delete data info
338 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
340 foreach($photos as $photo) {
341 $backend_class = DI::facStorage()->getByName($photo['backend-class'] ?? '');
342 if ($backend_class !== null) {
343 $backend_class->delete($photo["backend-ref"] ?? '');
347 return DBA::delete("photo", $conditions, $options);
351 * @brief Update a photo
353 * @param array $fields Contains the fields that are updated
354 * @param array $conditions Condition array with the key values
355 * @param Image $img Image to update. Optional, default null.
356 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
358 * @return boolean Was the update successfull?
360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
361 * @see \Friendica\Database\DBA::update
363 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
365 if (!is_null($img)) {
366 // get photo to update
367 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
369 foreach($photos as $photo) {
370 $backend_class = DI::facStorage()->getByName($photo['backend-class'] ?? '');
371 if ($backend_class !== null) {
372 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
374 $fields["data"] = $img->asString();
377 $fields['updated'] = DateTimeFormat::utcNow();
380 $fields['edited'] = DateTimeFormat::utcNow();
382 return DBA::update("photo", $fields, $conditions, $old_fields);
386 * @param string $image_url Remote URL
387 * @param integer $uid user id
388 * @param integer $cid contact id
389 * @param boolean $quit_on_error optional, default false
391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
392 * @throws \ImagickException
394 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
399 $photo = DBA::selectFirst(
400 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
402 if (!empty($photo['resource-id'])) {
403 $resource_id = $photo["resource-id"];
405 $resource_id = self::newResource();
408 $photo_failure = false;
410 $filename = basename($image_url);
411 if (!empty($image_url)) {
412 $ret = Network::curl($image_url, true);
413 $img_str = $ret->getBody();
414 $type = $ret->getContentType();
419 if ($quit_on_error && ($img_str == "")) {
424 $type = Images::guessType($image_url, true);
427 $Image = new Image($img_str, $type);
428 if ($Image->isValid()) {
429 $Image->scaleToSquare(300);
431 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
434 $photo_failure = true;
437 $Image->scaleDown(80);
439 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
442 $photo_failure = true;
445 $Image->scaleDown(48);
447 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
450 $photo_failure = true;
453 $suffix = "?ts=" . time();
455 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
456 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
457 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
459 // Remove the cached photo
461 $basepath = $a->getBasePath();
463 if (is_dir($basepath . "/photo")) {
464 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
465 if (file_exists($filename)) {
468 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
469 if (file_exists($filename)) {
472 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
473 if (file_exists($filename)) {
478 $photo_failure = true;
481 if ($photo_failure && $quit_on_error) {
485 if ($photo_failure) {
486 $image_url = DI::baseUrl() . "/images/person-300.jpg";
487 $thumb = DI::baseUrl() . "/images/person-80.jpg";
488 $micro = DI::baseUrl() . "/images/person-48.jpg";
491 return [$image_url, $thumb, $micro];
495 * @param array $exifCoord coordinate
496 * @param string $hemi hemi
499 public static function getGps($exifCoord, $hemi)
501 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
502 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
503 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
505 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
507 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
511 * @param string $coordPart coordPart
514 private static function gps2Num($coordPart)
516 $parts = explode("/", $coordPart);
518 if (count($parts) <= 0) {
522 if (count($parts) == 1) {
526 return floatval($parts[0]) / floatval($parts[1]);
530 * @brief Fetch the photo albums that are available for a viewer
532 * The query in this function is cost intensive, so it is cached.
534 * @param int $uid User id of the photos
535 * @param bool $update Update the cache
537 * @return array Returns array of the photo albums
538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
540 public static function getAlbums($uid, $update = false)
542 $sql_extra = Security::getPermissionsSQLByUserId($uid);
544 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
545 $albums = Cache::get($key);
546 if (is_null($albums) || $update) {
547 if (!Config::get("system", "no_count", false)) {
548 /// @todo This query needs to be renewed. It is really slow
549 // At this time we just store the data in the cache
550 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
552 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
553 GROUP BY `album` ORDER BY `created` DESC",
555 DBA::escape("Contact Photos"),
556 DBA::escape(L10n::t("Contact Photos"))
559 // This query doesn't do the count and is much faster
560 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
561 FROM `photo` USE INDEX (`uid_album_scale_created`)
562 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
564 DBA::escape("Contact Photos"),
565 DBA::escape(L10n::t("Contact Photos"))
568 Cache::set($key, $albums, Cache::DAY);
574 * @param int $uid User id of the photos
578 public static function clearAlbumCache($uid)
580 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
581 Cache::set($key, null, Cache::DAY);
585 * Generate a unique photo ID.
590 public static function newResource()
592 return System::createGUID(32, false);
596 * Changes photo permissions that had been embedded in a post
598 * @todo This function currently does have some flaws:
599 * - Sharing a post with a forum will create a photo that only the forum can see.
600 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
605 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
607 // Simplify image codes
608 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
609 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
612 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
616 if (empty($images)) {
620 foreach ($images as $image) {
621 if (!stristr($image, DI::baseUrl() . '/photo/')) {
624 $image_uri = substr($image,strrpos($image,'/') + 1);
625 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
626 if (!strlen($image_uri)) {
630 // Ensure to only modify photos that you own
631 $srch = '<' . intval($original_contact_id) . '>';
634 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
635 'resource-id' => $image_uri, 'uid' => $uid
637 if (!Photo::exists($condition)) {
641 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
643 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
644 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
645 $condition = ['resource-id' => $image_uri, 'uid' => $uid];
646 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
647 Photo::update($fields, $condition);
654 * Strips known picture extensions from picture links
656 * @param string $name Picture link
657 * @return string stripped picture link
660 public static function stripExtension($name)
662 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
663 foreach (Images::supportedTypes() as $m => $e) {
664 $name = str_replace("." . $e, "", $name);
670 * Returns the GUID from picture links
672 * @param string $name Picture link
673 * @return string GUID
676 public static function getGUID($name)
678 $base = DI::baseUrl()->get();
680 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
682 $guid = self::stripExtension($guid);
683 if (substr($guid, -2, 1) != "-") {
687 $scale = intval(substr($guid, -1, 1));
688 if (!is_numeric($scale)) {
692 $guid = substr($guid, 0, -2);
697 * Tests if the picture link points to a locally stored picture
699 * @param string $name Picture link
703 public static function isLocal($name)
705 $guid = self::getGUID($name);
711 return DBA::exists('photo', ['resource-id' => $guid]);
715 * Tests if the link points to a locally stored picture page
717 * @param string $name Page link
721 public static function isLocalPage($name)
723 $base = DI::baseUrl()->get();
725 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
726 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
731 return DBA::exists('photo', ['resource-id' => $guid]);