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 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 * @brief 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 * @brief 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 * @brief 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 * @brief 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", "allow_cid", "allow_gid", "deny_cid", "deny_gid"], ["resource-id" => $resourceid]);
138 // This is the first place, when retrieving just a photo, that we know who owns the photo.
139 // Check if the photo is public (empty allow and deny means public), if so, skip auth attempt, if not
140 // make sure that the requester's session is appropriately authenticated to that user
141 // otherwise permissions checks done by getPermissionsSQLByUserId() won't work correctly
142 if (!empty($r["allow_cid"]) || !empty($r["allow_gid"]) || !empty($r["deny_cid"]) || !empty($r["deny_gid"])) {
143 $r = DBA::selectFirst("user", ["nickname"], ["uid" => $uid], []);
144 // this will either just return (if auth all ok) or will redirect and exit (starting over)
145 DFRN::autoRedir(self::getApp(), $r["nickname"]);
148 $sql_acl = Security::getPermissionsSQLByUserId($uid);
151 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
155 $params = ["order" => ["scale" => true]];
157 $photo = self::selectFirst([], $conditions, $params);
163 * @brief Check if photo with given conditions exists
165 * @param array $conditions Array of extra conditions
170 public static function exists(array $conditions)
172 return DBA::exists("photo", $conditions);
177 * @brief Get Image object for given row id. null if row id does not exist
179 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
181 * @return \Friendica\Object\Image
182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
183 * @throws \ImagickException
185 public static function getImageForPhoto(array $photo)
189 if ($photo["backend-class"] == "") {
190 // legacy data storage in "data" column
191 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
197 $backendClass = $photo["backend-class"];
198 $backendRef = $photo["backend-ref"];
199 $data = $backendClass::get($backendRef);
206 return new Image($data, $photo["type"]);
210 * @brief Return a list of fields that are associated with the photo table
212 * @return array field list
215 private static function getFields()
217 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
218 $fields = array_keys($allfields["photo"]["fields"]);
219 array_splice($fields, array_search("data", $fields), 1);
224 * @brief Construct a photo array for a system resource image
226 * @param string $filename Image file name relative to code root
227 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
232 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
234 $fields = self::getFields();
235 $values = array_fill(0, count($fields), "");
237 $photo = array_combine($fields, $values);
238 $photo["backend-class"] = Storage\SystemResource::class;
239 $photo["backend-ref"] = $filename;
240 $photo["type"] = $mimetype;
241 $photo["cacheable"] = false;
248 * @brief store photo metadata in db and binary in default backend
250 * @param Image $Image Image object with data
251 * @param integer $uid User ID
252 * @param integer $cid Contact ID
253 * @param integer $rid Resource ID
254 * @param string $filename Filename
255 * @param string $album Album name
256 * @param integer $scale Scale
257 * @param integer $profile Is a profile image? optional, default = 0
258 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
259 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
260 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
261 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
262 * @param string $desc Photo caption. optional, default = ""
264 * @return boolean True on success
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
269 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
270 if (DBA::isResult($photo)) {
271 $guid = $photo["guid"];
273 $guid = System::createGUID();
276 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
277 $created = DateTimeFormat::utcNow();
278 if (DBA::isResult($existing_photo)) {
279 $created = $existing_photo["created"];
282 // Get defined storage backend.
283 // if no storage backend, we use old "data" column in photo table.
284 // if is an existing photo, reuse same backend
288 /** @var IStorage $backend_class */
289 if (DBA::isResult($existing_photo)) {
290 $backend_ref = (string)$existing_photo["backend-ref"];
291 $backend_class = (string)$existing_photo["backend-class"];
293 $backend_class = StorageManager::getBackend();
296 if ($backend_class === "") {
297 $data = $Image->asString();
299 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
305 "contact-id" => $cid,
307 "resource-id" => $rid,
308 "created" => $created,
309 "edited" => DateTimeFormat::utcNow(),
310 "filename" => basename($filename),
311 "type" => $Image->getType(),
313 "height" => $Image->getHeight(),
314 "width" => $Image->getWidth(),
315 "datasize" => strlen($Image->asString()),
318 "profile" => $profile,
319 "allow_cid" => $allow_cid,
320 "allow_gid" => $allow_gid,
321 "deny_cid" => $deny_cid,
322 "deny_gid" => $deny_gid,
324 "backend-class" => $backend_class,
325 "backend-ref" => $backend_ref
328 if (DBA::isResult($existing_photo)) {
329 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
331 $r = DBA::insert("photo", $fields);
339 * @brief Delete info from table and data from storage
341 * @param array $conditions Field condition(s)
342 * @param array $options Options array, Optional
347 * @see \Friendica\Database\DBA::delete
349 public static function delete(array $conditions, array $options = [])
351 // get photo to delete data info
352 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
354 foreach($photos as $photo) {
355 /** @var IStorage $backend_class */
356 $backend_class = (string)$photo["backend-class"];
357 if ($backend_class !== "") {
358 $backend_class::delete($photo["backend-ref"]);
362 return DBA::delete("photo", $conditions, $options);
366 * @brief Update a photo
368 * @param array $fields Contains the fields that are updated
369 * @param array $conditions Condition array with the key values
370 * @param Image $img Image to update. Optional, default null.
371 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
373 * @return boolean Was the update successfull?
375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376 * @see \Friendica\Database\DBA::update
378 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
380 if (!is_null($img)) {
381 // get photo to update
382 $photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
384 foreach($photos as $photo) {
385 /** @var IStorage $backend_class */
386 $backend_class = (string)$photo["backend-class"];
387 if ($backend_class !== "") {
388 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
390 $fields["data"] = $img->asString();
393 $fields['updated'] = DateTimeFormat::utcNow();
396 $fields['edited'] = DateTimeFormat::utcNow();
398 return DBA::update("photo", $fields, $conditions, $old_fields);
402 * @param string $image_url Remote URL
403 * @param integer $uid user id
404 * @param integer $cid contact id
405 * @param boolean $quit_on_error optional, default false
407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
408 * @throws \ImagickException
410 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
415 $photo = DBA::selectFirst(
416 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
418 if (!empty($photo['resource-id'])) {
419 $hash = $photo["resource-id"];
421 $hash = self::newResource();
424 $photo_failure = false;
426 $filename = basename($image_url);
427 if (!empty($image_url)) {
428 $ret = Network::curl($image_url, true);
429 $img_str = $ret->getBody();
430 $type = $ret->getContentType();
435 if ($quit_on_error && ($img_str == "")) {
440 $type = Image::guessType($image_url, true);
443 $Image = new Image($img_str, $type);
444 if ($Image->isValid()) {
445 $Image->scaleToSquare(300);
447 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
450 $photo_failure = true;
453 $Image->scaleDown(80);
455 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
458 $photo_failure = true;
461 $Image->scaleDown(48);
463 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
466 $photo_failure = true;
469 $suffix = "?ts=" . time();
471 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
472 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
473 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
475 // Remove the cached photo
477 $basepath = $a->getBasePath();
479 if (is_dir($basepath . "/photo")) {
480 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
481 if (file_exists($filename)) {
484 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
485 if (file_exists($filename)) {
488 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
489 if (file_exists($filename)) {
494 $photo_failure = true;
497 if ($photo_failure && $quit_on_error) {
501 if ($photo_failure) {
502 $image_url = System::baseUrl() . "/images/person-300.jpg";
503 $thumb = System::baseUrl() . "/images/person-80.jpg";
504 $micro = System::baseUrl() . "/images/person-48.jpg";
507 return [$image_url, $thumb, $micro];
511 * @param array $exifCoord coordinate
512 * @param string $hemi hemi
515 public static function getGps($exifCoord, $hemi)
517 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
518 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
519 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
521 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
523 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
527 * @param string $coordPart coordPart
530 private static function gps2Num($coordPart)
532 $parts = explode("/", $coordPart);
534 if (count($parts) <= 0) {
538 if (count($parts) == 1) {
542 return floatval($parts[0]) / floatval($parts[1]);
546 * @brief Fetch the photo albums that are available for a viewer
548 * The query in this function is cost intensive, so it is cached.
550 * @param int $uid User id of the photos
551 * @param bool $update Update the cache
553 * @return array Returns array of the photo albums
554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556 public static function getAlbums($uid, $update = false)
558 $sql_extra = Security::getPermissionsSQLByUserId($uid);
560 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
561 $albums = Cache::get($key);
562 if (is_null($albums) || $update) {
563 if (!Config::get("system", "no_count", false)) {
564 /// @todo This query needs to be renewed. It is really slow
565 // At this time we just store the data in the cache
566 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
568 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
569 GROUP BY `album` ORDER BY `created` DESC",
571 DBA::escape("Contact Photos"),
572 DBA::escape(L10n::t("Contact Photos"))
575 // This query doesn't do the count and is much faster
576 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
577 FROM `photo` USE INDEX (`uid_album_scale_created`)
578 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
580 DBA::escape("Contact Photos"),
581 DBA::escape(L10n::t("Contact Photos"))
584 Cache::set($key, $albums, Cache::DAY);
590 * @param int $uid User id of the photos
594 public static function clearAlbumCache($uid)
596 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
597 Cache::set($key, null, Cache::DAY);
601 * Generate a unique photo ID.
606 public static function newResource()
608 return System::createGUID(32, false);