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\Core\StorageManager;
15 use Friendica\Database\DBA;
16 use Friendica\Database\DBStructure;
17 use Friendica\Object\Image;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\Security;
22 require_once "include/dba.php";
25 * Class to handle photo dabatase table
27 class Photo extends BaseObject
30 * @brief Select rows from the photo table
32 * @param array $fields Array of selected fields, empty for all
33 * @param array $conditions Array of fields for conditions
34 * @param array $params Array of several parameters
36 * @return boolean|array
39 * @see \Friendica\Database\DBA::select
41 public static function select(array $fields = [], array $conditions = [], array $params = [])
44 $fields = self::getFields();
47 $r = DBA::select("photo", $fields, $conditions, $params);
48 return DBA::toArray($r);
52 * @brief Retrieve a single record from the photo table
54 * @param array $fields Array of selected fields, empty for all
55 * @param array $conditions Array of fields for conditions
56 * @param array $params Array of several parameters
61 * @see \Friendica\Database\DBA::select
63 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
66 $fields = self::getFields();
69 return DBA::selectFirst("photo", $fields, $conditions, $params);
73 * @brief Get photos for user id
75 * @param integer $uid User id
76 * @param string $resourceid Rescource ID of the photo
77 * @param array $conditions Array of fields for conditions
78 * @param array $params Array of several parameters
83 * @see \Friendica\Database\DBA::select
85 public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
87 $conditions["resource-id"] = $resourceid;
88 $conditions["uid"] = $uid;
90 return self::select([], $conditions, $params);
94 * @brief Get a photo for user id
96 * @param integer $uid User id
97 * @param string $resourceid Rescource ID of the photo
98 * @param integer $scale Scale of the photo. Defaults to 0
99 * @param array $conditions Array of fields for conditions
100 * @param array $params Array of several parameters
105 * @see \Friendica\Database\DBA::select
107 public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
109 $conditions["resource-id"] = $resourceid;
110 $conditions["uid"] = $uid;
111 $conditions["scale"] = $scale;
113 return self::selectFirst([], $conditions, $params);
117 * @brief Get a single photo given resource id and scale
119 * This method checks for permissions. Returns associative array
120 * on success, "no sign" image info, if user has no permission,
121 * false if photo does not exists
123 * @param string $resourceid Rescource ID of the photo
124 * @param integer $scale Scale of the photo. Defaults to 0
126 * @return boolean|array
129 public static function getPhoto($resourceid, $scale = 0)
131 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
136 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
139 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
143 $params = ["order" => ["scale" => true]];
145 $photo = self::selectFirst([], $conditions, $params);
151 * @brief Check if photo with given conditions exists
153 * @param array $conditions Array of extra conditions
158 public static function exists(array $conditions)
160 return DBA::exists("photo", $conditions);
165 * @brief Get Image object for given row id. null if row id does not exist
167 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
169 * @return \Friendica\Object\Image
170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171 * @throws \ImagickException
173 public static function getImageForPhoto(array $photo)
175 if ($photo["backend-class"] == "") {
176 // legacy data storage in "data" column
177 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
183 $backendClass = $photo["backend-class"];
184 $backendRef = $photo["backend-ref"];
185 $data = $backendClass::get($backendRef);
191 return new Image($data, $photo["type"]);
195 * @brief Return a list of fields that are associated with the photo table
197 * @return array field list
200 private static function getFields()
202 $allfields = DBStructure::definition(false);
203 $fields = array_keys($allfields["photo"]["fields"]);
204 array_splice($fields, array_search("data", $fields), 1);
209 * @brief Construct a photo array for a system resource image
211 * @param string $filename Image file name relative to code root
212 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
217 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
219 $fields = self::getFields();
220 $values = array_fill(0, count($fields), "");
221 $photo = array_combine($fields, $values);
222 $photo["backend-class"] = Storage\SystemResource::class;
223 $photo["backend-ref"] = $filename;
224 $photo["type"] = $mimetype;
225 $photo["cacheable"] = false;
231 * @brief store photo metadata in db and binary in default backend
233 * @param Image $Image Image object with data
234 * @param integer $uid User ID
235 * @param integer $cid Contact ID
236 * @param integer $rid Resource ID
237 * @param string $filename Filename
238 * @param string $album Album name
239 * @param integer $scale Scale
240 * @param integer $profile Is a profile image? optional, default = 0
241 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
242 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
243 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
244 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
245 * @param string $desc Photo caption. optional, default = ""
247 * @return boolean True on success
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
252 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
253 if (DBA::isResult($photo)) {
254 $guid = $photo["guid"];
256 $guid = System::createGUID();
259 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
260 $created = DateTimeFormat::utcNow();
261 if (DBA::isResult($existing_photo)) {
262 $created = $existing_photo["created"];
265 // Get defined storage backend.
266 // if no storage backend, we use old "data" column in photo table.
267 // if is an existing photo, reuse same backend
271 if (DBA::isResult($existing_photo)) {
272 $backend_ref = (string)$existing_photo["backend-ref"];
273 $backend_class = (string)$existing_photo["backend-class"];
275 $backend_class = StorageManager::getBackend();
278 if ($backend_class === "") {
279 $data = $Image->asString();
281 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
287 "contact-id" => $cid,
289 "resource-id" => $rid,
290 "created" => $created,
291 "edited" => DateTimeFormat::utcNow(),
292 "filename" => basename($filename),
293 "type" => $Image->getType(),
295 "height" => $Image->getHeight(),
296 "width" => $Image->getWidth(),
297 "datasize" => strlen($Image->asString()),
300 "profile" => $profile,
301 "allow_cid" => $allow_cid,
302 "allow_gid" => $allow_gid,
303 "deny_cid" => $deny_cid,
304 "deny_gid" => $deny_gid,
306 "backend-class" => $backend_class,
307 "backend-ref" => $backend_ref
310 if (DBA::isResult($existing_photo)) {
311 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
313 $r = DBA::insert("photo", $fields);
321 * @brief Delete info from table and data from storage
323 * @param array $conditions Field condition(s)
324 * @param array $options Options array, Optional
329 * @see \Friendica\Database\DBA::delete
331 public static function delete(array $conditions, array $options = [])
333 // get photo to delete data info
334 $photos = self::select(["backend-class","backend-ref"], $conditions);
336 foreach($photos as $photo) {
337 $backend_class = (string)$photo["backend-class"];
338 if ($backend_class !== "") {
339 $backend_class::delete($photo["backend-ref"]);
343 return DBA::delete("photo", $conditions, $options);
347 * @brief Update a photo
349 * @param array $fields Contains the fields that are updated
350 * @param array $conditions Condition array with the key values
351 * @param Image $img Image to update. Optional, default null.
352 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
354 * @return boolean Was the update successfull?
356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
357 * @see \Friendica\Database\DBA::update
359 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
361 if (!is_null($img)) {
362 // get photo to update
363 $photos = self::select(["backend-class","backend-ref"], $conditions);
365 foreach($photos as $photo) {
366 $backend_class = (string)$photo["backend-class"];
367 if ($backend_class !== "") {
368 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
370 $fields["data"] = $img->asString();
373 $fields['updated'] = DateTimeFormat::utcNow();
376 $fields['edited'] = DateTimeFormat::utcNow();
378 return DBA::update("photo", $fields, $conditions, $old_fields);
382 * @param string $image_url Remote URL
383 * @param integer $uid user id
384 * @param integer $cid contact id
385 * @param boolean $quit_on_error optional, default false
387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
388 * @throws \ImagickException
390 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
395 $photo = DBA::selectFirst(
396 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
398 if (!empty($photo['resource-id'])) {
399 $hash = $photo["resource-id"];
401 $hash = self::newResource();
404 $photo_failure = false;
406 $filename = basename($image_url);
407 $img_str = Network::fetchUrl($image_url, true);
409 if ($quit_on_error && ($img_str == "")) {
413 $type = Image::guessType($image_url, true);
414 $Image = new Image($img_str, $type);
415 if ($Image->isValid()) {
416 $Image->scaleToSquare(300);
418 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
421 $photo_failure = true;
424 $Image->scaleDown(80);
426 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
429 $photo_failure = true;
432 $Image->scaleDown(48);
434 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
437 $photo_failure = true;
440 $suffix = "?ts=" . time();
442 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
443 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
444 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
446 // Remove the cached photo
448 $basepath = $a->getBasePath();
450 if (is_dir($basepath . "/photo")) {
451 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
452 if (file_exists($filename)) {
455 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
456 if (file_exists($filename)) {
459 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
460 if (file_exists($filename)) {
465 $photo_failure = true;
468 if ($photo_failure && $quit_on_error) {
472 if ($photo_failure) {
473 $image_url = System::baseUrl() . "/images/person-300.jpg";
474 $thumb = System::baseUrl() . "/images/person-80.jpg";
475 $micro = System::baseUrl() . "/images/person-48.jpg";
478 return [$image_url, $thumb, $micro];
482 * @param string $exifCoord coordinate
483 * @param string $hemi hemi
486 public static function getGps($exifCoord, $hemi)
488 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
489 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
490 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
492 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
494 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
498 * @param string $coordPart coordPart
501 private static function gps2Num($coordPart)
503 $parts = explode("/", $coordPart);
505 if (count($parts) <= 0) {
509 if (count($parts) == 1) {
513 return floatval($parts[0]) / floatval($parts[1]);
517 * @brief Fetch the photo albums that are available for a viewer
519 * The query in this function is cost intensive, so it is cached.
521 * @param int $uid User id of the photos
522 * @param bool $update Update the cache
524 * @return array Returns array of the photo albums
525 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527 public static function getAlbums($uid, $update = false)
529 $sql_extra = Security::getPermissionsSQLByUserId($uid);
531 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
532 $albums = Cache::get($key);
533 if (is_null($albums) || $update) {
534 if (!Config::get("system", "no_count", false)) {
535 /// @todo This query needs to be renewed. It is really slow
536 // At this time we just store the data in the cache
537 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
539 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
540 GROUP BY `album` ORDER BY `created` DESC",
542 DBA::escape("Contact Photos"),
543 DBA::escape(L10n::t("Contact Photos"))
546 // This query doesn't do the count and is much faster
547 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
548 FROM `photo` USE INDEX (`uid_album_scale_created`)
549 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
551 DBA::escape("Contact Photos"),
552 DBA::escape(L10n::t("Contact Photos"))
555 Cache::set($key, $albums, Cache::DAY);
561 * @param int $uid User id of the photos
565 public static function clearAlbumCache($uid)
567 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
568 Cache::set($key, null, Cache::DAY);
572 * Generate a unique photo ID.
577 public static function newResource()
579 return System::createGUID(32, false);