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\StorageManager;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Database\DBStructure;
17 use Friendica\Model\Storage\IStorage;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\DFRN;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\Security;
24 require_once "include/dba.php";
27 * Class to handle photo dabatase table
29 class Photo extends BaseObject
32 * @brief Select rows from the photo table
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::select
43 public static function select(array $fields = [], array $conditions = [], array $params = [])
46 $fields = self::getFields();
49 $r = DBA::select("photo", $fields, $conditions, $params);
50 return DBA::toArray($r);
54 * @brief Retrieve a single record from the photo table
56 * @param array $fields Array of selected fields, empty for all
57 * @param array $conditions Array of fields for conditions
58 * @param array $params Array of several parameters
63 * @see \Friendica\Database\DBA::select
65 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
68 $fields = self::getFields();
71 return DBA::selectFirst("photo", $fields, $conditions, $params);
75 * @brief Get photos for user id
77 * @param integer $uid User id
78 * @param string $resourceid Rescource ID of the photo
79 * @param array $conditions Array of fields for conditions
80 * @param array $params Array of several parameters
85 * @see \Friendica\Database\DBA::select
87 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
89 $conditions["resource-id"] = $resourceid;
90 $conditions["uid"] = $uid;
92 return self::select([], $conditions, $params);
96 * @brief Get a photo for user id
98 * @param integer $uid User id
99 * @param string $resourceid Rescource ID of the photo
100 * @param integer $scale Scale of the photo. Defaults to 0
101 * @param array $conditions Array of fields for conditions
102 * @param array $params Array of several parameters
107 * @see \Friendica\Database\DBA::select
109 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
111 $conditions["resource-id"] = $resourceid;
112 $conditions["uid"] = $uid;
113 $conditions["scale"] = $scale;
115 return self::selectFirst([], $conditions, $params);
119 * @brief Get a single photo given resource id and scale
121 * This method checks for permissions. Returns associative array
122 * on success, "no sign" image info, if user has no permission,
123 * false if photo does not exists
125 * @param string $resourceid Rescource ID of the photo
126 * @param integer $scale Scale of the photo. Defaults to 0
128 * @return boolean|array
131 public static function getPhoto($resourceid, $scale = 0)
133 $r = self::selectFirst(["uid", "allow_cid", "allow_gid", "deny_cid", "deny_gid"], ["resource-id" => $resourceid]);
139 // This is the first place, when retrieving just a photo, that we know who owns the photo.
140 // Check if the photo is public (empty allow and deny means public), if so, skip auth attempt, if not
141 // make sure that the requester's session is appropriately authenticated to that user
142 // otherwise permissions checks done by getPermissionsSQLByUserId() won't work correctly
143 if (!empty($r["allow_cid"]) || !empty($r["allow_gid"]) || !empty($r["deny_cid"]) || !empty($r["deny_gid"])) {
144 $r = DBA::selectFirst("user", ["nickname"], ["uid" => $uid], []);
145 // this will either just return (if auth all ok) or will redirect and exit (starting over)
146 DFRN::autoRedir(self::getApp(), $r["nickname"]);
149 $sql_acl = Security::getPermissionsSQLByUserId($uid);
152 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
156 $params = ["order" => ["scale" => true]];
158 $photo = self::selectFirst([], $conditions, $params);
164 * @brief Check if photo with given conditions exists
166 * @param array $conditions Array of extra conditions
171 public static function exists(array $conditions)
173 return DBA::exists("photo", $conditions);
178 * @brief Get Image object for given row id. null if row id does not exist
180 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
182 * @return \Friendica\Object\Image
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function getImageForPhoto(array $photo)
190 if ($photo["backend-class"] == "") {
191 // legacy data storage in "data" column
192 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
198 $backendClass = $photo["backend-class"];
199 $backendRef = $photo["backend-ref"];
200 $data = $backendClass::get($backendRef);
207 return new Image($data, $photo["type"]);
211 * @brief Return a list of fields that are associated with the photo table
213 * @return array field list
216 private static function getFields()
218 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
219 $fields = array_keys($allfields["photo"]["fields"]);
220 array_splice($fields, array_search("data", $fields), 1);
225 * @brief Construct a photo array for a system resource image
227 * @param string $filename Image file name relative to code root
228 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
233 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
235 $fields = self::getFields();
236 $values = array_fill(0, count($fields), "");
238 $photo = array_combine($fields, $values);
239 $photo["backend-class"] = Storage\SystemResource::class;
240 $photo["backend-ref"] = $filename;
241 $photo["type"] = $mimetype;
242 $photo["cacheable"] = false;
249 * @brief store photo metadata in db and binary in default backend
251 * @param Image $Image Image object with data
252 * @param integer $uid User ID
253 * @param integer $cid Contact ID
254 * @param integer $rid Resource ID
255 * @param string $filename Filename
256 * @param string $album Album name
257 * @param integer $scale Scale
258 * @param integer $profile Is a profile image? optional, default = 0
259 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
260 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
261 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
262 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
263 * @param string $desc Photo caption. optional, default = ""
265 * @return boolean True on success
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
270 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
271 if (DBA::isResult($photo)) {
272 $guid = $photo["guid"];
274 $guid = System::createGUID();
277 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
278 $created = DateTimeFormat::utcNow();
279 if (DBA::isResult($existing_photo)) {
280 $created = $existing_photo["created"];
283 // Get defined storage backend.
284 // if no storage backend, we use old "data" column in photo table.
285 // if is an existing photo, reuse same backend
289 /** @var IStorage $backend_class */
290 if (DBA::isResult($existing_photo)) {
291 $backend_ref = (string)$existing_photo["backend-ref"];
292 $backend_class = (string)$existing_photo["backend-class"];
294 $backend_class = StorageManager::getBackend();
297 if ($backend_class === "") {
298 $data = $Image->asString();
300 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
306 "contact-id" => $cid,
308 "resource-id" => $rid,
309 "created" => $created,
310 "edited" => DateTimeFormat::utcNow(),
311 "filename" => basename($filename),
312 "type" => $Image->getType(),
314 "height" => $Image->getHeight(),
315 "width" => $Image->getWidth(),
316 "datasize" => strlen($Image->asString()),
319 "profile" => $profile,
320 "allow_cid" => $allow_cid,
321 "allow_gid" => $allow_gid,
322 "deny_cid" => $deny_cid,
323 "deny_gid" => $deny_gid,
325 "backend-class" => $backend_class,
326 "backend-ref" => $backend_ref
329 if (DBA::isResult($existing_photo)) {
330 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
332 $r = DBA::insert("photo", $fields);
340 * @brief Delete info from table and data from storage
342 * @param array $conditions Field condition(s)
343 * @param array $options Options array, Optional
348 * @see \Friendica\Database\DBA::delete
350 public static function delete(array $conditions, array $options = [])
352 // get photo to delete data info
353 $photos = self::select(["backend-class","backend-ref"], $conditions);
355 foreach($photos as $photo) {
356 /** @var IStorage $backend_class */
357 $backend_class = (string)$photo["backend-class"];
358 if ($backend_class !== "") {
359 $backend_class::delete($photo["backend-ref"]);
363 return DBA::delete("photo", $conditions, $options);
367 * @brief Update a photo
369 * @param array $fields Contains the fields that are updated
370 * @param array $conditions Condition array with the key values
371 * @param Image $img Image to update. Optional, default null.
372 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
374 * @return boolean Was the update successfull?
376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
377 * @see \Friendica\Database\DBA::update
379 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
381 if (!is_null($img)) {
382 // get photo to update
383 $photos = self::select(["backend-class","backend-ref"], $conditions);
385 foreach($photos as $photo) {
386 /** @var IStorage $backend_class */
387 $backend_class = (string)$photo["backend-class"];
388 if ($backend_class !== "") {
389 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
391 $fields["data"] = $img->asString();
394 $fields['updated'] = DateTimeFormat::utcNow();
397 $fields['edited'] = DateTimeFormat::utcNow();
399 return DBA::update("photo", $fields, $conditions, $old_fields);
403 * @param string $image_url Remote URL
404 * @param integer $uid user id
405 * @param integer $cid contact id
406 * @param boolean $quit_on_error optional, default false
408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
409 * @throws \ImagickException
411 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
416 $photo = DBA::selectFirst(
417 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
419 if (!empty($photo['resource-id'])) {
420 $hash = $photo["resource-id"];
422 $hash = self::newResource();
425 $photo_failure = false;
427 $filename = basename($image_url);
428 if (!empty($image_url)) {
429 $ret = Network::curl($image_url, true);
430 $img_str = $ret->getBody();
431 $type = $ret->getContentType();
436 if ($quit_on_error && ($img_str == "")) {
441 $type = Image::guessType($image_url, true);
444 $Image = new Image($img_str, $type);
445 if ($Image->isValid()) {
446 $Image->scaleToSquare(300);
448 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
451 $photo_failure = true;
454 $Image->scaleDown(80);
456 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
459 $photo_failure = true;
462 $Image->scaleDown(48);
464 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
467 $photo_failure = true;
470 $suffix = "?ts=" . time();
472 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
473 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
474 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
476 // Remove the cached photo
478 $basepath = $a->getBasePath();
480 if (is_dir($basepath . "/photo")) {
481 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
482 if (file_exists($filename)) {
485 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
486 if (file_exists($filename)) {
489 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
490 if (file_exists($filename)) {
495 $photo_failure = true;
498 if ($photo_failure && $quit_on_error) {
502 if ($photo_failure) {
503 $image_url = System::baseUrl() . "/images/person-300.jpg";
504 $thumb = System::baseUrl() . "/images/person-80.jpg";
505 $micro = System::baseUrl() . "/images/person-48.jpg";
508 return [$image_url, $thumb, $micro];
512 * @param array $exifCoord coordinate
513 * @param string $hemi hemi
516 public static function getGps($exifCoord, $hemi)
518 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
519 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
520 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
522 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
524 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
528 * @param string $coordPart coordPart
531 private static function gps2Num($coordPart)
533 $parts = explode("/", $coordPart);
535 if (count($parts) <= 0) {
539 if (count($parts) == 1) {
543 return floatval($parts[0]) / floatval($parts[1]);
547 * @brief Fetch the photo albums that are available for a viewer
549 * The query in this function is cost intensive, so it is cached.
551 * @param int $uid User id of the photos
552 * @param bool $update Update the cache
554 * @return array Returns array of the photo albums
555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
557 public static function getAlbums($uid, $update = false)
559 $sql_extra = Security::getPermissionsSQLByUserId($uid);
561 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
562 $albums = Cache::get($key);
563 if (is_null($albums) || $update) {
564 if (!Config::get("system", "no_count", false)) {
565 /// @todo This query needs to be renewed. It is really slow
566 // At this time we just store the data in the cache
567 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
569 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
570 GROUP BY `album` ORDER BY `created` DESC",
572 DBA::escape("Contact Photos"),
573 DBA::escape(L10n::t("Contact Photos"))
576 // This query doesn't do the count and is much faster
577 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
578 FROM `photo` USE INDEX (`uid_album_scale_created`)
579 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
581 DBA::escape("Contact Photos"),
582 DBA::escape(L10n::t("Contact Photos"))
585 Cache::set($key, $albums, Cache::DAY);
591 * @param int $uid User id of the photos
595 public static function clearAlbumCache($uid)
597 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
598 Cache::set($key, null, Cache::DAY);
602 * Generate a unique photo ID.
607 public static function newResource()
609 return System::createGUID(32, false);