4 * @file src/Model/Photo.php
5 * This file contains the Photo class for database interface
7 namespace Friendica\Model;
9 use Friendica\Core\Cache\Duration;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Database\DBStructure;
16 use Friendica\Model\Storage\SystemResource;
17 use Friendica\Object\Image;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Images;
20 use Friendica\Util\Network;
21 use Friendica\Util\Security;
22 use Friendica\Util\Strings;
24 require_once "include/dba.php";
27 * Class to handle photo dabatase table
32 * Select rows from the photo table and returns them as array
34 * @param array $fields Array of selected fields, empty for all
35 * @param array $conditions Array of fields for conditions
36 * @param array $params Array of several parameters
38 * @return boolean|array
41 * @see \Friendica\Database\DBA::selectToArray
43 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
46 $fields = self::getFields();
49 return DBA::selectToArray('photo', $fields, $conditions, $params);
53 * Retrieve a single record from the photo table
55 * @param array $fields Array of selected fields, empty for all
56 * @param array $conditions Array of fields for conditions
57 * @param array $params Array of several parameters
62 * @see \Friendica\Database\DBA::select
64 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
67 $fields = self::getFields();
70 return DBA::selectFirst("photo", $fields, $conditions, $params);
74 * Get photos for user id
76 * @param integer $uid User id
77 * @param string $resourceid Rescource ID of the photo
78 * @param array $conditions Array of fields for conditions
79 * @param array $params Array of several parameters
84 * @see \Friendica\Database\DBA::select
86 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
88 $conditions["resource-id"] = $resourceid;
89 $conditions["uid"] = $uid;
91 return self::selectToArray([], $conditions, $params);
95 * Get a photo for user id
97 * @param integer $uid User id
98 * @param string $resourceid Rescource ID of the photo
99 * @param integer $scale Scale of the photo. Defaults to 0
100 * @param array $conditions Array of fields for conditions
101 * @param array $params Array of several parameters
106 * @see \Friendica\Database\DBA::select
108 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
110 $conditions["resource-id"] = $resourceid;
111 $conditions["uid"] = $uid;
112 $conditions["scale"] = $scale;
114 return self::selectFirst([], $conditions, $params);
118 * Get a single photo given resource id and scale
120 * This method checks for permissions. Returns associative array
121 * on success, "no sign" image info, if user has no permission,
122 * false if photo does not exists
124 * @param string $resourceid Rescource ID of the photo
125 * @param integer $scale Scale of the photo. Defaults to 0
127 * @return boolean|array
130 public static function getPhoto($resourceid, $scale = 0)
132 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
133 if (!DBA::isResult($r)) {
139 $sql_acl = Security::getPermissionsSQLByUserId($uid);
141 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
142 $params = ["order" => ["scale" => true]];
143 $photo = self::selectFirst([], $conditions, $params);
149 * Check if photo with given conditions exists
151 * @param array $conditions Array of extra conditions
156 public static function exists(array $conditions)
158 return DBA::exists("photo", $conditions);
163 * Get Image object for given row id. null if row id does not exist
165 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
167 * @return \Friendica\Object\Image
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 * @throws \ImagickException
171 public static function getImageForPhoto(array $photo)
173 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
174 if ($backendClass === null) {
175 // legacy data storage in "data" column
176 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
182 $backendRef = $photo['backend-ref'] ?? '';
183 $data = $backendClass->get($backendRef);
190 return new Image($data, $photo['type']);
194 * Return a list of fields that are associated with the photo table
196 * @return array field list
199 private static function getFields()
201 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
202 $fields = array_keys($allfields["photo"]["fields"]);
203 array_splice($fields, array_search("data", $fields), 1);
208 * Construct a photo array for a system resource image
210 * @param string $filename Image file name relative to code root
211 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
216 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
218 $fields = self::getFields();
219 $values = array_fill(0, count($fields), "");
221 $photo = array_combine($fields, $values);
222 $photo['backend-class'] = SystemResource::NAME;
223 $photo['backend-ref'] = $filename;
224 $photo['type'] = $mimetype;
225 $photo['cacheable'] = false;
232 * store photo metadata in db and binary in default backend
234 * @param Image $Image Image object with data
235 * @param integer $uid User ID
236 * @param integer $cid Contact ID
237 * @param integer $rid Resource ID
238 * @param string $filename Filename
239 * @param string $album Album name
240 * @param integer $scale Scale
241 * @param integer $profile Is a profile image? optional, default = 0
242 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
243 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
244 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
245 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
246 * @param string $desc Photo caption. optional, default = ""
248 * @return boolean True on success
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
253 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
254 if (DBA::isResult($photo)) {
255 $guid = $photo["guid"];
257 $guid = System::createGUID();
260 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
261 $created = DateTimeFormat::utcNow();
262 if (DBA::isResult($existing_photo)) {
263 $created = $existing_photo["created"];
266 // Get defined storage backend.
267 // if no storage backend, we use old "data" column in photo table.
268 // if is an existing photo, reuse same backend
272 if (DBA::isResult($existing_photo)) {
273 $backend_ref = (string)$existing_photo["backend-ref"];
274 $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
276 $storage = DI::storage();
279 if ($storage === null) {
280 $data = $Image->asString();
282 $backend_ref = $storage->put($Image->asString(), $backend_ref);
288 "contact-id" => $cid,
290 "resource-id" => $rid,
291 "created" => $created,
292 "edited" => DateTimeFormat::utcNow(),
293 "filename" => basename($filename),
294 "type" => $Image->getType(),
296 "height" => $Image->getHeight(),
297 "width" => $Image->getWidth(),
298 "datasize" => strlen($Image->asString()),
301 "profile" => $profile,
302 "allow_cid" => $allow_cid,
303 "allow_gid" => $allow_gid,
304 "deny_cid" => $deny_cid,
305 "deny_gid" => $deny_gid,
307 "backend-class" => (string)$storage,
308 "backend-ref" => $backend_ref
311 if (DBA::isResult($existing_photo)) {
312 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
314 $r = DBA::insert("photo", $fields);
322 * Delete info from table and data from storage
324 * @param array $conditions Field condition(s)
325 * @param array $options Options array, Optional
330 * @see \Friendica\Database\DBA::delete
332 public static function delete(array $conditions, array $options = [])
334 // get photo to delete data info
335 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
337 foreach($photos as $photo) {
338 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
339 if ($backend_class !== null) {
340 $backend_class->delete($photo["backend-ref"] ?? '');
344 return DBA::delete("photo", $conditions, $options);
350 * @param array $fields Contains the fields that are updated
351 * @param array $conditions Condition array with the key values
352 * @param Image $img Image to update. Optional, default null.
353 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
355 * @return boolean Was the update successfull?
357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
358 * @see \Friendica\Database\DBA::update
360 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
362 if (!is_null($img)) {
363 // get photo to update
364 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
366 foreach($photos as $photo) {
367 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
368 if ($backend_class !== null) {
369 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
371 $fields["data"] = $img->asString();
374 $fields['updated'] = DateTimeFormat::utcNow();
377 $fields['edited'] = DateTimeFormat::utcNow();
379 return DBA::update("photo", $fields, $conditions, $old_fields);
383 * @param string $image_url Remote URL
384 * @param integer $uid user id
385 * @param integer $cid contact id
386 * @param boolean $quit_on_error optional, default false
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 * @throws \ImagickException
391 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
396 $photo = DBA::selectFirst(
397 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
399 if (!empty($photo['resource-id'])) {
400 $resource_id = $photo["resource-id"];
402 $resource_id = self::newResource();
405 $photo_failure = false;
407 $filename = basename($image_url);
408 if (!empty($image_url)) {
409 $ret = Network::curl($image_url, true);
410 $img_str = $ret->getBody();
411 $type = $ret->getContentType();
416 if ($quit_on_error && ($img_str == "")) {
421 $type = Images::guessType($image_url, true);
424 $Image = new Image($img_str, $type);
425 if ($Image->isValid()) {
426 $Image->scaleToSquare(300);
428 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
431 $photo_failure = true;
434 $Image->scaleDown(80);
436 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
439 $photo_failure = true;
442 $Image->scaleDown(48);
444 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
447 $photo_failure = true;
450 $suffix = "?ts=" . time();
452 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
453 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
454 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
456 // Remove the cached photo
458 $basepath = $a->getBasePath();
460 if (is_dir($basepath . "/photo")) {
461 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
462 if (file_exists($filename)) {
465 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
466 if (file_exists($filename)) {
469 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
470 if (file_exists($filename)) {
475 $photo_failure = true;
478 if ($photo_failure && $quit_on_error) {
482 if ($photo_failure) {
483 $image_url = DI::baseUrl() . "/images/person-300.jpg";
484 $thumb = DI::baseUrl() . "/images/person-80.jpg";
485 $micro = DI::baseUrl() . "/images/person-48.jpg";
488 return [$image_url, $thumb, $micro];
492 * @param array $exifCoord coordinate
493 * @param string $hemi hemi
496 public static function getGps($exifCoord, $hemi)
498 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
499 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
500 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
502 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
504 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
508 * @param string $coordPart coordPart
511 private static function gps2Num($coordPart)
513 $parts = explode("/", $coordPart);
515 if (count($parts) <= 0) {
519 if (count($parts) == 1) {
523 return floatval($parts[0]) / floatval($parts[1]);
527 * Fetch the photo albums that are available for a viewer
529 * The query in this function is cost intensive, so it is cached.
531 * @param int $uid User id of the photos
532 * @param bool $update Update the cache
534 * @return array Returns array of the photo albums
535 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537 public static function getAlbums($uid, $update = false)
539 $sql_extra = Security::getPermissionsSQLByUserId($uid);
541 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
542 $albums = DI::cache()->get($key);
543 if (is_null($albums) || $update) {
544 if (!DI::config()->get("system", "no_count", false)) {
545 /// @todo This query needs to be renewed. It is really slow
546 // At this time we just store the data in the cache
547 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
549 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
550 GROUP BY `album` ORDER BY `created` DESC",
552 DBA::escape("Contact Photos"),
553 DBA::escape(DI::l10n()->t("Contact Photos"))
556 // This query doesn't do the count and is much faster
557 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
558 FROM `photo` USE INDEX (`uid_album_scale_created`)
559 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
561 DBA::escape("Contact Photos"),
562 DBA::escape(DI::l10n()->t("Contact Photos"))
565 DI::cache()->set($key, $albums, Duration::DAY);
571 * @param int $uid User id of the photos
575 public static function clearAlbumCache($uid)
577 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
578 DI::cache()->set($key, null, Duration::DAY);
582 * Generate a unique photo ID.
587 public static function newResource()
589 return System::createGUID(32, false);
593 * Extracts the rid from a local photo URI
595 * @param string $image_uri The URI of the photo
596 * @return string The rid of the photo, or an empty string if the URI is not local
598 public static function ridFromURI(string $image_uri)
600 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
603 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
604 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
605 if (!strlen($image_uri)) {
612 * Changes photo permissions that had been embedded in a post
614 * @todo This function currently does have some flaws:
615 * - Sharing a post with a forum will create a photo that only the forum can see.
616 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
621 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
623 // Simplify image codes
624 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
625 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
628 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
632 if (empty($images)) {
636 foreach ($images as $image) {
637 $image_rid = self::ridFromURI($image);
638 if (empty($image_rid)) {
642 // Ensure to only modify photos that you own
643 $srch = '<' . intval($original_contact_id) . '>';
646 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
647 'resource-id' => $image_rid, 'uid' => $uid
649 if (!Photo::exists($condition)) {
653 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
655 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
656 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
657 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
658 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
659 Photo::update($fields, $condition);
666 * Strips known picture extensions from picture links
668 * @param string $name Picture link
669 * @return string stripped picture link
672 public static function stripExtension($name)
674 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
675 foreach (Images::supportedTypes() as $m => $e) {
676 $name = str_replace("." . $e, "", $name);
682 * Returns the GUID from picture links
684 * @param string $name Picture link
685 * @return string GUID
688 public static function getGUID($name)
690 $base = DI::baseUrl()->get();
692 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
694 $guid = self::stripExtension($guid);
695 if (substr($guid, -2, 1) != "-") {
699 $scale = intval(substr($guid, -1, 1));
700 if (!is_numeric($scale)) {
704 $guid = substr($guid, 0, -2);
709 * Tests if the picture link points to a locally stored picture
711 * @param string $name Picture link
715 public static function isLocal($name)
717 $guid = self::getGUID($name);
723 return DBA::exists('photo', ['resource-id' => $guid]);
727 * Tests if the link points to a locally stored picture page
729 * @param string $name Page link
733 public static function isLocalPage($name)
735 $base = DI::baseUrl()->get();
737 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
738 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
743 return DBA::exists('photo', ['resource-id' => $guid]);