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\Logger;
11 use Friendica\Core\System;
12 use Friendica\Database\DBA;
13 use Friendica\Database\DBStructure;
15 use Friendica\Model\Storage\SystemResource;
16 use Friendica\Object\Image;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Images;
19 use Friendica\Util\Network;
20 use Friendica\Util\Security;
21 use Friendica\Util\Strings;
23 require_once "include/dba.php";
26 * Class to handle photo dabatase table
31 * Select rows from the photo table and returns them as array
33 * @param array $fields Array of selected fields, empty for all
34 * @param array $conditions Array of fields for conditions
35 * @param array $params Array of several parameters
37 * @return boolean|array
40 * @see \Friendica\Database\DBA::selectToArray
42 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
45 $fields = self::getFields();
48 return DBA::selectToArray('photo', $fields, $conditions, $params);
52 * Retrieve a single record from the photo table
54 * @param array $fields Array of selected fields, empty for all
55 * @param array $conditions Array of fields for conditions
56 * @param array $params Array of several parameters
61 * @see \Friendica\Database\DBA::select
63 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
66 $fields = self::getFields();
69 return DBA::selectFirst("photo", $fields, $conditions, $params);
73 * Get photos for user id
75 * @param integer $uid User id
76 * @param string $resourceid Rescource ID of the photo
77 * @param array $conditions Array of fields for conditions
78 * @param array $params Array of several parameters
83 * @see \Friendica\Database\DBA::select
85 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
87 $conditions["resource-id"] = $resourceid;
88 $conditions["uid"] = $uid;
90 return self::selectToArray([], $conditions, $params);
94 * Get a photo for user id
96 * @param integer $uid User id
97 * @param string $resourceid Rescource ID of the photo
98 * @param integer $scale Scale of the photo. Defaults to 0
99 * @param array $conditions Array of fields for conditions
100 * @param array $params Array of several parameters
105 * @see \Friendica\Database\DBA::select
107 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
109 $conditions["resource-id"] = $resourceid;
110 $conditions["uid"] = $uid;
111 $conditions["scale"] = $scale;
113 return self::selectFirst([], $conditions, $params);
117 * Get a single photo given resource id and scale
119 * This method checks for permissions. Returns associative array
120 * on success, "no sign" image info, if user has no permission,
121 * false if photo does not exists
123 * @param string $resourceid Rescource ID of the photo
124 * @param integer $scale Scale of the photo. Defaults to 0
126 * @return boolean|array
129 public static function getPhoto($resourceid, $scale = 0)
131 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
132 if (!DBA::isResult($r)) {
138 $sql_acl = Security::getPermissionsSQLByUserId($uid);
140 $conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
141 $params = ["order" => ["scale" => true]];
142 $photo = self::selectFirst([], $conditions, $params);
148 * Check if photo with given conditions exists
150 * @param array $conditions Array of extra conditions
155 public static function exists(array $conditions)
157 return DBA::exists("photo", $conditions);
162 * Get Image object for given row id. null if row id does not exist
164 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
166 * @return \Friendica\Object\Image
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168 * @throws \ImagickException
170 public static function getImageForPhoto(array $photo)
172 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
173 if ($backendClass === null) {
174 // legacy data storage in "data" column
175 $i = self::selectFirst(['data'], ['id' => $photo['id']]);
181 $backendRef = $photo['backend-ref'] ?? '';
182 $data = $backendClass->get($backendRef);
189 return new Image($data, $photo['type']);
193 * Return a list of fields that are associated with the photo table
195 * @return array field list
198 private static function getFields()
200 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
201 $fields = array_keys($allfields["photo"]["fields"]);
202 array_splice($fields, array_search("data", $fields), 1);
207 * Construct a photo array for a system resource image
209 * @param string $filename Image file name relative to code root
210 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
215 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
217 $fields = self::getFields();
218 $values = array_fill(0, count($fields), "");
220 $photo = array_combine($fields, $values);
221 $photo['backend-class'] = SystemResource::NAME;
222 $photo['backend-ref'] = $filename;
223 $photo['type'] = $mimetype;
224 $photo['cacheable'] = false;
231 * store photo metadata in db and binary in default backend
233 * @param Image $Image Image object with data
234 * @param integer $uid User ID
235 * @param integer $cid Contact ID
236 * @param integer $rid Resource ID
237 * @param string $filename Filename
238 * @param string $album Album name
239 * @param integer $scale Scale
240 * @param integer $profile Is a profile image? optional, default = 0
241 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
242 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
243 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
244 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
245 * @param string $desc Photo caption. optional, default = ""
247 * @return boolean True on success
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
252 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
253 if (DBA::isResult($photo)) {
254 $guid = $photo["guid"];
256 $guid = System::createGUID();
259 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
260 $created = DateTimeFormat::utcNow();
261 if (DBA::isResult($existing_photo)) {
262 $created = $existing_photo["created"];
265 // Get defined storage backend.
266 // if no storage backend, we use old "data" column in photo table.
267 // if is an existing photo, reuse same backend
271 if (DBA::isResult($existing_photo)) {
272 $backend_ref = (string)$existing_photo["backend-ref"];
273 $storage = DI::storageManager()->getByName($existing_photo["backend-class"] ?? '');
275 $storage = DI::storage();
278 if ($storage === null) {
279 $data = $Image->asString();
281 $backend_ref = $storage->put($Image->asString(), $backend_ref);
287 "contact-id" => $cid,
289 "resource-id" => $rid,
290 "created" => $created,
291 "edited" => DateTimeFormat::utcNow(),
292 "filename" => basename($filename),
293 "type" => $Image->getType(),
295 "height" => $Image->getHeight(),
296 "width" => $Image->getWidth(),
297 "datasize" => strlen($Image->asString()),
300 "profile" => $profile,
301 "allow_cid" => $allow_cid,
302 "allow_gid" => $allow_gid,
303 "deny_cid" => $deny_cid,
304 "deny_gid" => $deny_gid,
306 "backend-class" => (string)$storage,
307 "backend-ref" => $backend_ref
310 if (DBA::isResult($existing_photo)) {
311 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
313 $r = DBA::insert("photo", $fields);
321 * Delete info from table and data from storage
323 * @param array $conditions Field condition(s)
324 * @param array $options Options array, Optional
329 * @see \Friendica\Database\DBA::delete
331 public static function delete(array $conditions, array $options = [])
333 // get photo to delete data info
334 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
336 foreach($photos as $photo) {
337 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
338 if ($backend_class !== null) {
339 $backend_class->delete($photo["backend-ref"] ?? '');
343 return DBA::delete("photo", $conditions, $options);
349 * @param array $fields Contains the fields that are updated
350 * @param array $conditions Condition array with the key values
351 * @param Image $img Image to update. Optional, default null.
352 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
354 * @return boolean Was the update successfull?
356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
357 * @see \Friendica\Database\DBA::update
359 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
361 if (!is_null($img)) {
362 // get photo to update
363 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
365 foreach($photos as $photo) {
366 $backend_class = DI::storageManager()->getByName($photo['backend-class'] ?? '');
367 if ($backend_class !== null) {
368 $fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
370 $fields["data"] = $img->asString();
373 $fields['updated'] = DateTimeFormat::utcNow();
376 $fields['edited'] = DateTimeFormat::utcNow();
378 return DBA::update("photo", $fields, $conditions, $old_fields);
382 * @param string $image_url Remote URL
383 * @param integer $uid user id
384 * @param integer $cid contact id
385 * @param boolean $quit_on_error optional, default false
387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
388 * @throws \ImagickException
390 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
395 $photo = DBA::selectFirst(
396 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
398 if (!empty($photo['resource-id'])) {
399 $resource_id = $photo["resource-id"];
401 $resource_id = self::newResource();
404 $photo_failure = false;
406 $filename = basename($image_url);
407 if (!empty($image_url)) {
408 $ret = Network::curl($image_url, true);
409 $img_str = $ret->getBody();
410 $type = $ret->getContentType();
415 if ($quit_on_error && ($img_str == "")) {
420 $type = Images::guessType($image_url, true);
423 $Image = new Image($img_str, $type);
424 if ($Image->isValid()) {
425 $Image->scaleToSquare(300);
427 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 4);
430 $photo_failure = true;
433 $Image->scaleDown(80);
435 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 5);
438 $photo_failure = true;
441 $Image->scaleDown(48);
443 $r = self::store($Image, $uid, $cid, $resource_id, $filename, "Contact Photos", 6);
446 $photo_failure = true;
449 $suffix = "?ts=" . time();
451 $image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
452 $thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
453 $micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
455 // Remove the cached photo
457 $basepath = $a->getBasePath();
459 if (is_dir($basepath . "/photo")) {
460 $filename = $basepath . "/photo/" . $resource_id . "-4." . $Image->getExt();
461 if (file_exists($filename)) {
464 $filename = $basepath . "/photo/" . $resource_id . "-5." . $Image->getExt();
465 if (file_exists($filename)) {
468 $filename = $basepath . "/photo/" . $resource_id . "-6." . $Image->getExt();
469 if (file_exists($filename)) {
474 $photo_failure = true;
477 if ($photo_failure && $quit_on_error) {
481 if ($photo_failure) {
482 $image_url = DI::baseUrl() . "/images/person-300.jpg";
483 $thumb = DI::baseUrl() . "/images/person-80.jpg";
484 $micro = DI::baseUrl() . "/images/person-48.jpg";
487 return [$image_url, $thumb, $micro];
491 * @param array $exifCoord coordinate
492 * @param string $hemi hemi
495 public static function getGps($exifCoord, $hemi)
497 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
498 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
499 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
501 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
503 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
507 * @param string $coordPart coordPart
510 private static function gps2Num($coordPart)
512 $parts = explode("/", $coordPart);
514 if (count($parts) <= 0) {
518 if (count($parts) == 1) {
522 return floatval($parts[0]) / floatval($parts[1]);
526 * Fetch the photo albums that are available for a viewer
528 * The query in this function is cost intensive, so it is cached.
530 * @param int $uid User id of the photos
531 * @param bool $update Update the cache
533 * @return array Returns array of the photo albums
534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
536 public static function getAlbums($uid, $update = false)
538 $sql_extra = Security::getPermissionsSQLByUserId($uid);
540 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
541 $albums = DI::cache()->get($key);
542 if (is_null($albums) || $update) {
543 if (!DI::config()->get("system", "no_count", false)) {
544 /// @todo This query needs to be renewed. It is really slow
545 // At this time we just store the data in the cache
546 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
548 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
549 GROUP BY `album` ORDER BY `created` DESC",
551 DBA::escape("Contact Photos"),
552 DBA::escape(DI::l10n()->t("Contact Photos"))
555 // This query doesn't do the count and is much faster
556 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
557 FROM `photo` USE INDEX (`uid_album_scale_created`)
558 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
560 DBA::escape("Contact Photos"),
561 DBA::escape(DI::l10n()->t("Contact Photos"))
564 DI::cache()->set($key, $albums, Duration::DAY);
570 * @param int $uid User id of the photos
574 public static function clearAlbumCache($uid)
576 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
577 DI::cache()->set($key, null, Duration::DAY);
581 * Generate a unique photo ID.
586 public static function newResource()
588 return System::createGUID(32, false);
592 * Extracts the rid from a local photo URI
594 * @param string $image_uri The URI of the photo
595 * @return string The rid of the photo, or an empty string if the URI is not local
597 public static function ridFromURI(string $image_uri)
599 if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
602 $image_uri = substr($image_uri, strrpos($image_uri, '/') + 1);
603 $image_uri = substr($image_uri, 0, strpos($image_uri, '-'));
604 if (!strlen($image_uri)) {
611 * Changes photo permissions that had been embedded in a post
613 * @todo This function currently does have some flaws:
614 * - Sharing a post with a forum will create a photo that only the forum can see.
615 * - Sharing a photo again that been shared non public before doesn't alter the permissions.
620 public static function setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)
622 // Simplify image codes
623 $img_body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
624 $img_body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $img_body);
627 if (!preg_match_all("/\[img\](.*?)\[\/img\]/", $img_body, $match)) {
631 if (empty($images)) {
635 foreach ($images as $image) {
636 $image_rid = self::ridFromURI($image);
637 if (empty($image_rid)) {
641 // Ensure to only modify photos that you own
642 $srch = '<' . intval($original_contact_id) . '>';
645 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
646 'resource-id' => $image_rid, 'uid' => $uid
648 if (!Photo::exists($condition)) {
652 /// @todo Check if $str_contact_allow does contain a public forum. Then set the permissions to public.
654 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
655 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
656 $condition = ['resource-id' => $image_rid, 'uid' => $uid];
657 Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
658 Photo::update($fields, $condition);
665 * Strips known picture extensions from picture links
667 * @param string $name Picture link
668 * @return string stripped picture link
671 public static function stripExtension($name)
673 $name = str_replace([".jpg", ".png", ".gif"], ["", "", ""], $name);
674 foreach (Images::supportedTypes() as $m => $e) {
675 $name = str_replace("." . $e, "", $name);
681 * Returns the GUID from picture links
683 * @param string $name Picture link
684 * @return string GUID
687 public static function getGUID($name)
689 $base = DI::baseUrl()->get();
691 $guid = str_replace([Strings::normaliseLink($base), '/photo/'], '', Strings::normaliseLink($name));
693 $guid = self::stripExtension($guid);
694 if (substr($guid, -2, 1) != "-") {
698 $scale = intval(substr($guid, -1, 1));
699 if (!is_numeric($scale)) {
703 $guid = substr($guid, 0, -2);
708 * Tests if the picture link points to a locally stored picture
710 * @param string $name Picture link
714 public static function isLocal($name)
716 $guid = self::getGUID($name);
722 return DBA::exists('photo', ['resource-id' => $guid]);
726 * Tests if the link points to a locally stored picture page
728 * @param string $name Page link
732 public static function isLocalPage($name)
734 $base = DI::baseUrl()->get();
736 $guid = str_replace(Strings::normaliseLink($base), '', Strings::normaliseLink($name));
737 $guid = preg_replace("=/photos/.*/image/(.*)=ism", '$1', $guid);
742 return DBA::exists('photo', ['resource-id' => $guid]);