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 single photo given resource id and scale
72 * This method checks for permissions. Returns associative array
73 * on success, "no sign" image info, if user has no permission,
74 * false if photo does not exists
76 * @param string $resourceid Rescource ID for the photo
77 * @param integer $scale Scale of the photo. Defaults to 0
79 * @return boolean|array
81 public static function getPhoto($resourceid, $scale = 0)
83 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
88 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
91 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
95 $params = ["order" => ["scale" => true]];
97 $photo = self::selectFirst([], $conditions, $params);
98 if ($photo === false) {
99 return self::createPhotoForSystemResource("images/nosign.jpg");
105 * @brief Check if photo with given resource id exists
107 * @param string $resourceid Resource ID of the photo
111 public static function exists($resourceid)
113 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
117 * @brief Get Image object for given row id. null if row id does not exist
119 * @param integer $id Row id
121 * @return \Friendica\Object\Image
123 public static function getImageForPhoto($photo)
126 if ($photo["backend-class"] == "") {
127 // legacy data storage in "data" column
128 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
134 $backendClass = $photo["backend-class"];
135 $backendRef = $photo["backend-ref"];
136 $data = $backendClass::get($backendRef);
142 return new Image($data, $photo["type"]);
146 * @brief Return a list of fields that are associated with the photo table
148 * @return array field list
150 private static function getFields()
152 $allfields = DBStructure::definition(false);
153 $fields = array_keys($allfields["photo"]["fields"]);
154 array_splice($fields, array_search("data", $fields), 1);
159 * @brief Construct a photo array for a system resource image
161 * @param string $filename Image file name relative to code root
162 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
166 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
168 $fields = self::getFields();
169 $values = array_fill(0, count($fields), "");
170 $photo = array_combine($fields, $values);
171 $photo["backend-class"] = \Friendica\Model\Storage\SystemResource::class;
172 $photo["backend-ref"] = $filename;
173 $photo["type"] = $mimetype;
174 $photo["cacheable"] = false;
180 * @brief store photo metadata in db and binary in default backend
182 * @param Image $Image image
183 * @param integer $uid uid
184 * @param integer $cid cid
185 * @param integer $rid rid
186 * @param string $filename filename
187 * @param string $album album name
188 * @param integer $scale scale
189 * @param integer $profile optional, default = 0
190 * @param string $allow_cid optional, default = ""
191 * @param string $allow_gid optional, default = ""
192 * @param string $deny_cid optional, default = ""
193 * @param string $deny_gid optional, default = ""
194 * @param string $desc optional, default = ""
196 * @return boolean True on success
198 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
200 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
201 if (DBA::isResult($photo)) {
202 $guid = $photo["guid"];
204 $guid = System::createGUID();
207 $existing_photo = self::selectFirst(["id", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
209 // Get defined storage backend.
210 // if no storage backend, we use old "data" column in photo table.
211 // if is an existing photo, reuse same backend
216 if (DBA::isResult($existing_photo)) {
217 $backend_ref = (string)$existing_photo["backend-ref"];
218 $backend_class = (string)$existing_photo["backend-class"];
220 $backend_class = Config::get("storage", "class", "");
222 if ($backend_class === "") {
223 $data = $Image->asString();
225 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
231 "contact-id" => $cid,
233 "resource-id" => $rid,
234 "created" => DateTimeFormat::utcNow(),
235 "edited" => DateTimeFormat::utcNow(),
236 "filename" => basename($filename),
237 "type" => $Image->getType(),
239 "height" => $Image->getHeight(),
240 "width" => $Image->getWidth(),
241 "datasize" => strlen($Image->asString()),
244 "profile" => $profile,
245 "allow_cid" => $allow_cid,
246 "allow_gid" => $allow_gid,
247 "deny_cid" => $deny_cid,
248 "deny_gid" => $deny_gid,
250 "backend-class" => $backend_class,
251 "backend-ref" => $backend_ref
254 if (DBA::isResult($existing_photo)) {
255 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
257 $r = DBA::insert("photo", $fields);
263 public static function delete(array $conditions, $options = [])
265 // get photo to delete data info
266 $photos = self::select(["backend-class","backend-ref"], $conditions);
268 foreach($photos as $photo) {
269 $backend_class = (string)$photo["backend-class"];
270 if ($backend_class !== "") {
271 $backend_class::delete($photo["backend-ref"]);
275 return DBA::delete("photo", $conditions, $options);
279 * @param string $image_url Remote URL
280 * @param integer $uid user id
281 * @param integer $cid contact id
282 * @param boolean $quit_on_error optional, default false
285 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
290 $photo = DBA::selectFirst(
291 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
293 if (!empty($photo['resource-id'])) {
294 $hash = $photo["resource-id"];
296 $hash = self::newResource();
299 $photo_failure = false;
301 $filename = basename($image_url);
302 $img_str = Network::fetchUrl($image_url, true);
304 if ($quit_on_error && ($img_str == "")) {
308 $type = Image::guessType($image_url, true);
309 $Image = new Image($img_str, $type);
310 if ($Image->isValid()) {
311 $Image->scaleToSquare(300);
313 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
316 $photo_failure = true;
319 $Image->scaleDown(80);
321 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
324 $photo_failure = true;
327 $Image->scaleDown(48);
329 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
332 $photo_failure = true;
335 $suffix = "?ts=" . time();
337 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
338 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
339 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
341 // Remove the cached photo
343 $basepath = $a->getBasePath();
345 if (is_dir($basepath . "/photo")) {
346 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
347 if (file_exists($filename)) {
350 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
351 if (file_exists($filename)) {
354 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
355 if (file_exists($filename)) {
360 $photo_failure = true;
363 if ($photo_failure && $quit_on_error) {
367 if ($photo_failure) {
368 $image_url = System::baseUrl() . "/images/person-300.jpg";
369 $thumb = System::baseUrl() . "/images/person-80.jpg";
370 $micro = System::baseUrl() . "/images/person-48.jpg";
373 return [$image_url, $thumb, $micro];
377 * @param string $exifCoord coordinate
378 * @param string $hemi hemi
381 public static function getGps($exifCoord, $hemi)
383 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
384 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
385 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
387 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
389 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
393 * @param string $coordPart coordPart
396 private static function gps2Num($coordPart)
398 $parts = explode("/", $coordPart);
400 if (count($parts) <= 0) {
404 if (count($parts) == 1) {
408 return floatval($parts[0]) / floatval($parts[1]);
412 * @brief Fetch the photo albums that are available for a viewer
414 * The query in this function is cost intensive, so it is cached.
416 * @param int $uid User id of the photos
417 * @param bool $update Update the cache
419 * @return array Returns array of the photo albums
421 public static function getAlbums($uid, $update = false)
423 $sql_extra = Security::getPermissionsSQLByUserId($uid);
425 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
426 $albums = Cache::get($key);
427 if (is_null($albums) || $update) {
428 if (!Config::get("system", "no_count", false)) {
429 /// @todo This query needs to be renewed. It is really slow
430 // At this time we just store the data in the cache
431 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
433 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
434 GROUP BY `album` ORDER BY `created` DESC",
436 DBA::escape("Contact Photos"),
437 DBA::escape(L10n::t("Contact Photos"))
440 // This query doesn't do the count and is much faster
441 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
442 FROM `photo` USE INDEX (`uid_album_scale_created`)
443 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
445 DBA::escape("Contact Photos"),
446 DBA::escape(L10n::t("Contact Photos"))
449 Cache::set($key, $albums, Cache::DAY);
455 * @param int $uid User id of the photos
458 public static function clearAlbumCache($uid)
460 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
461 Cache::set($key, null, Cache::DAY);
465 * Generate a unique photo ID.
469 public static function newResource()
471 return system::createGUID(32, false);