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\System;
14 use Friendica\Database\DBA;
15 use Friendica\Database\DBStructure;
16 use Friendica\Object\Image;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
19 use Friendica\Util\Security;
21 require_once "include/dba.php";
24 * Class to handle photo dabatase table
26 class Photo extends BaseObject
29 * @brief Select rows from the photo table
31 * @param array $fields Array of selected fields, empty for all
32 * @param array $conditions Array of fields for conditions
33 * @param array $params Array of several parameters
35 * @return boolean|array
37 * @see \Friendica\Database\DBA::select
39 public static function select(array $fields = [], array $conditions = [], array $params = [])
42 $selected = self::getFields();
45 $r = DBA::select("photo", $fields, $conditions, $params);
46 return DBA::toArray($r);
50 * @brief Retrieve a single record from the photo table
52 * @param array $fields Array of selected fields, empty for all
53 * @param array $conditions Array of fields for conditions
54 * @param array $params Array of several parameters
58 * @see \Friendica\Database\DBA::select
60 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
63 $fields = self::getFields();
66 return DBA::selectFirst("photo", $fields, $conditions, $params);
70 * @brief Get a photo for user id
72 * @param integer $uid User id
73 * @param string $resourceid Rescource ID of the photo
74 * @param array $conditions Array of fields for conditions
75 * @param array $params Array of several parameters
79 * @see \Friendica\Database\DBA::select
81 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
83 $conditions["resource-id"] = $resourceid;
84 $conditions["uid"] = $uid;
86 return self::select([], $conditions, $params);
90 * @brief Get a photo for user id
92 * @param integer $uid User id
93 * @param string $resourceid Rescource ID of the photo
94 * @param integer $scale Scale of the photo. Defaults to 0
95 * @param array $conditions Array of fields for conditions
96 * @param array $params Array of several parameters
100 * @see \Friendica\Database\DBA::select
102 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
104 $conditions["resource-id"] = $resourceid;
105 $conditions["uid"] = $uid;
106 $conditions["scale"] = $scale;
108 return self::selectFirst([], $conditions, $params);
112 * @brief Get a single photo given resource id and scale
114 * This method checks for permissions. Returns associative array
115 * on success, "no sign" image info, if user has no permission,
116 * false if photo does not exists
118 * @param string $resourceid Rescource ID of the photo
119 * @param integer $scale Scale of the photo. Defaults to 0
121 * @return boolean|array
123 public static function getPhoto($resourceid, $scale = 0)
125 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
130 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
133 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
137 $params = ["order" => ["scale" => true]];
139 $photo = self::selectFirst([], $conditions, $params);
140 if ($photo === false) {
141 return self::createPhotoForSystemResource("images/nosign.jpg");
147 * @brief Check if photo with given resource id exists
149 * @param string $resourceid Resource ID of the photo
153 public static function exists($resourceid)
155 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
159 * @brief Get Image object for given row id. null if row id does not exist
161 * @param integer $id Row id
163 * @return \Friendica\Object\Image
165 public static function getImageForPhoto($photo)
168 if ($photo["backend-class"] == "") {
169 // legacy data storage in "data" column
170 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
176 $backendClass = $photo["backend-class"];
177 $backendRef = $photo["backend-ref"];
178 $data = $backendClass::get($backendRef);
184 return new Image($data, $photo["type"]);
188 * @brief Return a list of fields that are associated with the photo table
190 * @return array field list
192 private static function getFields()
194 $allfields = DBStructure::definition(false);
195 $fields = array_keys($allfields["photo"]["fields"]);
196 array_splice($fields, array_search("data", $fields), 1);
201 * @brief Construct a photo array for a system resource image
203 * @param string $filename Image file name relative to code root
204 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
208 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
210 $fields = self::getFields();
211 $values = array_fill(0, count($fields), "");
212 $photo = array_combine($fields, $values);
213 $photo["backend-class"] = \Friendica\Model\Storage\SystemResource::class;
214 $photo["backend-ref"] = $filename;
215 $photo["type"] = $mimetype;
216 $photo["cacheable"] = false;
222 * @brief store photo metadata in db and binary in default backend
224 * @param Image $Image image
225 * @param integer $uid uid
226 * @param integer $cid cid
227 * @param integer $rid rid
228 * @param string $filename filename
229 * @param string $album album name
230 * @param integer $scale scale
231 * @param integer $profile optional, default = 0
232 * @param string $allow_cid optional, default = ""
233 * @param string $allow_gid optional, default = ""
234 * @param string $deny_cid optional, default = ""
235 * @param string $deny_gid optional, default = ""
236 * @param string $desc optional, default = ""
238 * @return boolean True on success
240 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
242 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
243 if (DBA::isResult($photo)) {
244 $guid = $photo["guid"];
246 $guid = System::createGUID();
249 $existing_photo = self::selectFirst(["id", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
251 // Get defined storage backend.
252 // if no storage backend, we use old "data" column in photo table.
253 // if is an existing photo, reuse same backend
258 if (DBA::isResult($existing_photo)) {
259 $backend_ref = (string)$existing_photo["backend-ref"];
260 $backend_class = (string)$existing_photo["backend-class"];
262 $backend_class = Config::get("storage", "class", "");
264 if ($backend_class === "") {
265 $data = $Image->asString();
267 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
273 "contact-id" => $cid,
275 "resource-id" => $rid,
276 "created" => DateTimeFormat::utcNow(),
277 "edited" => DateTimeFormat::utcNow(),
278 "filename" => basename($filename),
279 "type" => $Image->getType(),
281 "height" => $Image->getHeight(),
282 "width" => $Image->getWidth(),
283 "datasize" => strlen($Image->asString()),
286 "profile" => $profile,
287 "allow_cid" => $allow_cid,
288 "allow_gid" => $allow_gid,
289 "deny_cid" => $deny_cid,
290 "deny_gid" => $deny_gid,
292 "backend-class" => $backend_class,
293 "backend-ref" => $backend_ref
296 if (DBA::isResult($existing_photo)) {
297 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
299 $r = DBA::insert("photo", $fields);
305 public static function delete(array $conditions, $options = [])
307 // get photo to delete data info
308 $photos = self::select(["backend-class","backend-ref"], $conditions);
310 foreach($photos as $photo) {
311 $backend_class = (string)$photo["backend-class"];
312 if ($backend_class !== "") {
313 $backend_class::delete($photo["backend-ref"]);
317 return DBA::delete("photo", $conditions, $options);
321 * @brief Update a photo
323 * @param array $fields Contains the fields that are updated
324 * @param array $conditions Condition array with the key values
325 * @param Image $img Image to update. Optional, default null.
326 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
328 * @return boolean Was the update successfull?
330 * @see \Friendica\Database\DBA::update
332 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
334 if (!is_null($img)) {
335 // get photo to update
336 $photos = self::select(["backend-class","backend-ref"], $conditions);
338 foreach($photos as $photo) {
339 $backend_class = (string)$photo["backend-class"];
340 if ($backend_class !== "") {
341 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
343 $fields["data"] = $img->asString();
348 $fields['updated'] = DateTimeFormat::utcNow();
350 return DBA::update("photo", $fields, $conditions);
354 * @param string $image_url Remote URL
355 * @param integer $uid user id
356 * @param integer $cid contact id
357 * @param boolean $quit_on_error optional, default false
360 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
365 $photo = DBA::selectFirst(
366 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
368 if (!empty($photo['resource-id'])) {
369 $hash = $photo["resource-id"];
371 $hash = self::newResource();
374 $photo_failure = false;
376 $filename = basename($image_url);
377 $img_str = Network::fetchUrl($image_url, true);
379 if ($quit_on_error && ($img_str == "")) {
383 $type = Image::guessType($image_url, true);
384 $Image = new Image($img_str, $type);
385 if ($Image->isValid()) {
386 $Image->scaleToSquare(300);
388 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
391 $photo_failure = true;
394 $Image->scaleDown(80);
396 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
399 $photo_failure = true;
402 $Image->scaleDown(48);
404 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
407 $photo_failure = true;
410 $suffix = "?ts=" . time();
412 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
413 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
414 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
416 // Remove the cached photo
418 $basepath = $a->getBasePath();
420 if (is_dir($basepath . "/photo")) {
421 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
422 if (file_exists($filename)) {
425 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
426 if (file_exists($filename)) {
429 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
430 if (file_exists($filename)) {
435 $photo_failure = true;
438 if ($photo_failure && $quit_on_error) {
442 if ($photo_failure) {
443 $image_url = System::baseUrl() . "/images/person-300.jpg";
444 $thumb = System::baseUrl() . "/images/person-80.jpg";
445 $micro = System::baseUrl() . "/images/person-48.jpg";
448 return [$image_url, $thumb, $micro];
452 * @param string $exifCoord coordinate
453 * @param string $hemi hemi
456 public static function getGps($exifCoord, $hemi)
458 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
459 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
460 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
462 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
464 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
468 * @param string $coordPart coordPart
471 private static function gps2Num($coordPart)
473 $parts = explode("/", $coordPart);
475 if (count($parts) <= 0) {
479 if (count($parts) == 1) {
483 return floatval($parts[0]) / floatval($parts[1]);
487 * @brief Fetch the photo albums that are available for a viewer
489 * The query in this function is cost intensive, so it is cached.
491 * @param int $uid User id of the photos
492 * @param bool $update Update the cache
494 * @return array Returns array of the photo albums
496 public static function getAlbums($uid, $update = false)
498 $sql_extra = Security::getPermissionsSQLByUserId($uid);
500 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
501 $albums = Cache::get($key);
502 if (is_null($albums) || $update) {
503 if (!Config::get("system", "no_count", false)) {
504 /// @todo This query needs to be renewed. It is really slow
505 // At this time we just store the data in the cache
506 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
508 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
509 GROUP BY `album` ORDER BY `created` DESC",
511 DBA::escape("Contact Photos"),
512 DBA::escape(L10n::t("Contact Photos"))
515 // This query doesn't do the count and is much faster
516 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
517 FROM `photo` USE INDEX (`uid_album_scale_created`)
518 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
520 DBA::escape("Contact Photos"),
521 DBA::escape(L10n::t("Contact Photos"))
524 Cache::set($key, $albums, Cache::DAY);
530 * @param int $uid User id of the photos
533 public static function clearAlbumCache($uid)
535 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
536 Cache::set($key, null, Cache::DAY);
540 * Generate a unique photo ID.
544 public static function newResource()
546 return system::createGUID(32, false);