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"], ["resource-id" => $resourceid]);
139 // This is the first place, when retrieving just a photo, that we know who owns the photo.
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 $r = DBA::selectFirst("user", ["nickname"], ["uid" => $uid], []);
143 // this will either just return (if auth all ok) or will redirect and exit (starting over)
144 DFRN::autoRedir(self::getApp(), $r["nickname"]);
146 $sql_acl = Security::getPermissionsSQLByUserId($uid);
149 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
153 $params = ["order" => ["scale" => true]];
155 $photo = self::selectFirst([], $conditions, $params);
161 * @brief Check if photo with given conditions exists
163 * @param array $conditions Array of extra conditions
168 public static function exists(array $conditions)
170 return DBA::exists("photo", $conditions);
175 * @brief Get Image object for given row id. null if row id does not exist
177 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
179 * @return \Friendica\Object\Image
180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
181 * @throws \ImagickException
183 public static function getImageForPhoto(array $photo)
187 if ($photo["backend-class"] == "") {
188 // legacy data storage in "data" column
189 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
195 $backendClass = $photo["backend-class"];
196 $backendRef = $photo["backend-ref"];
197 $data = $backendClass::get($backendRef);
204 return new Image($data, $photo["type"]);
208 * @brief Return a list of fields that are associated with the photo table
210 * @return array field list
213 private static function getFields()
215 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
216 $fields = array_keys($allfields["photo"]["fields"]);
217 array_splice($fields, array_search("data", $fields), 1);
222 * @brief Construct a photo array for a system resource image
224 * @param string $filename Image file name relative to code root
225 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
230 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
232 $fields = self::getFields();
233 $values = array_fill(0, count($fields), "");
235 $photo = array_combine($fields, $values);
236 $photo["backend-class"] = Storage\SystemResource::class;
237 $photo["backend-ref"] = $filename;
238 $photo["type"] = $mimetype;
239 $photo["cacheable"] = false;
246 * @brief store photo metadata in db and binary in default backend
248 * @param Image $Image Image object with data
249 * @param integer $uid User ID
250 * @param integer $cid Contact ID
251 * @param integer $rid Resource ID
252 * @param string $filename Filename
253 * @param string $album Album name
254 * @param integer $scale Scale
255 * @param integer $profile Is a profile image? optional, default = 0
256 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
257 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
258 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
259 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
260 * @param string $desc Photo caption. optional, default = ""
262 * @return boolean True on success
263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
265 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
267 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
268 if (DBA::isResult($photo)) {
269 $guid = $photo["guid"];
271 $guid = System::createGUID();
274 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
275 $created = DateTimeFormat::utcNow();
276 if (DBA::isResult($existing_photo)) {
277 $created = $existing_photo["created"];
280 // Get defined storage backend.
281 // if no storage backend, we use old "data" column in photo table.
282 // if is an existing photo, reuse same backend
286 /** @var IStorage $backend_class */
287 if (DBA::isResult($existing_photo)) {
288 $backend_ref = (string)$existing_photo["backend-ref"];
289 $backend_class = (string)$existing_photo["backend-class"];
291 $backend_class = StorageManager::getBackend();
294 if ($backend_class === "") {
295 $data = $Image->asString();
297 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
303 "contact-id" => $cid,
305 "resource-id" => $rid,
306 "created" => $created,
307 "edited" => DateTimeFormat::utcNow(),
308 "filename" => basename($filename),
309 "type" => $Image->getType(),
311 "height" => $Image->getHeight(),
312 "width" => $Image->getWidth(),
313 "datasize" => strlen($Image->asString()),
316 "profile" => $profile,
317 "allow_cid" => $allow_cid,
318 "allow_gid" => $allow_gid,
319 "deny_cid" => $deny_cid,
320 "deny_gid" => $deny_gid,
322 "backend-class" => $backend_class,
323 "backend-ref" => $backend_ref
326 if (DBA::isResult($existing_photo)) {
327 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
329 $r = DBA::insert("photo", $fields);
337 * @brief Delete info from table and data from storage
339 * @param array $conditions Field condition(s)
340 * @param array $options Options array, Optional
345 * @see \Friendica\Database\DBA::delete
347 public static function delete(array $conditions, array $options = [])
349 // get photo to delete data info
350 $photos = self::select(["backend-class","backend-ref"], $conditions);
352 foreach($photos as $photo) {
353 /** @var IStorage $backend_class */
354 $backend_class = (string)$photo["backend-class"];
355 if ($backend_class !== "") {
356 $backend_class::delete($photo["backend-ref"]);
360 return DBA::delete("photo", $conditions, $options);
364 * @brief Update a photo
366 * @param array $fields Contains the fields that are updated
367 * @param array $conditions Condition array with the key values
368 * @param Image $img Image to update. Optional, default null.
369 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
371 * @return boolean Was the update successfull?
373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
374 * @see \Friendica\Database\DBA::update
376 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
378 if (!is_null($img)) {
379 // get photo to update
380 $photos = self::select(["backend-class","backend-ref"], $conditions);
382 foreach($photos as $photo) {
383 /** @var IStorage $backend_class */
384 $backend_class = (string)$photo["backend-class"];
385 if ($backend_class !== "") {
386 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
388 $fields["data"] = $img->asString();
391 $fields['updated'] = DateTimeFormat::utcNow();
394 $fields['edited'] = DateTimeFormat::utcNow();
396 return DBA::update("photo", $fields, $conditions, $old_fields);
400 * @param string $image_url Remote URL
401 * @param integer $uid user id
402 * @param integer $cid contact id
403 * @param boolean $quit_on_error optional, default false
405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 * @throws \ImagickException
408 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
413 $photo = DBA::selectFirst(
414 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
416 if (!empty($photo['resource-id'])) {
417 $hash = $photo["resource-id"];
419 $hash = self::newResource();
422 $photo_failure = false;
424 $filename = basename($image_url);
425 if (!empty($image_url)) {
426 $ret = Network::curl($image_url, true);
427 $img_str = $ret->getBody();
428 $type = $ret->getContentType();
433 if ($quit_on_error && ($img_str == "")) {
438 $type = Image::guessType($image_url, true);
441 $Image = new Image($img_str, $type);
442 if ($Image->isValid()) {
443 $Image->scaleToSquare(300);
445 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
448 $photo_failure = true;
451 $Image->scaleDown(80);
453 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
456 $photo_failure = true;
459 $Image->scaleDown(48);
461 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
464 $photo_failure = true;
467 $suffix = "?ts=" . time();
469 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
470 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
471 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
473 // Remove the cached photo
475 $basepath = $a->getBasePath();
477 if (is_dir($basepath . "/photo")) {
478 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
479 if (file_exists($filename)) {
482 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
483 if (file_exists($filename)) {
486 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
487 if (file_exists($filename)) {
492 $photo_failure = true;
495 if ($photo_failure && $quit_on_error) {
499 if ($photo_failure) {
500 $image_url = System::baseUrl() . "/images/person-300.jpg";
501 $thumb = System::baseUrl() . "/images/person-80.jpg";
502 $micro = System::baseUrl() . "/images/person-48.jpg";
505 return [$image_url, $thumb, $micro];
509 * @param array $exifCoord coordinate
510 * @param string $hemi hemi
513 public static function getGps($exifCoord, $hemi)
515 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
516 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
517 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
519 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
521 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
525 * @param string $coordPart coordPart
528 private static function gps2Num($coordPart)
530 $parts = explode("/", $coordPart);
532 if (count($parts) <= 0) {
536 if (count($parts) == 1) {
540 return floatval($parts[0]) / floatval($parts[1]);
544 * @brief Fetch the photo albums that are available for a viewer
546 * The query in this function is cost intensive, so it is cached.
548 * @param int $uid User id of the photos
549 * @param bool $update Update the cache
551 * @return array Returns array of the photo albums
552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
554 public static function getAlbums($uid, $update = false)
556 $sql_extra = Security::getPermissionsSQLByUserId($uid);
558 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
559 $albums = Cache::get($key);
560 if (is_null($albums) || $update) {
561 if (!Config::get("system", "no_count", false)) {
562 /// @todo This query needs to be renewed. It is really slow
563 // At this time we just store the data in the cache
564 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
566 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
567 GROUP BY `album` ORDER BY `created` DESC",
569 DBA::escape("Contact Photos"),
570 DBA::escape(L10n::t("Contact Photos"))
573 // This query doesn't do the count and is much faster
574 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
575 FROM `photo` USE INDEX (`uid_album_scale_created`)
576 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
578 DBA::escape("Contact Photos"),
579 DBA::escape(L10n::t("Contact Photos"))
582 Cache::set($key, $albums, Cache::DAY);
588 * @param int $uid User id of the photos
592 public static function clearAlbumCache($uid)
594 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
595 Cache::set($key, null, Cache::DAY);
599 * Generate a unique photo ID.
604 public static function newResource()
606 return System::createGUID(32, false);