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\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\Security;
23 require_once "include/dba.php";
26 * Class to handle photo dabatase table
28 class Photo extends BaseObject
31 * @brief Select rows from the photo table
33 * @param array $fields Array of selected fields, empty for all
34 * @param array $conditions Array of fields for conditions
35 * @param array $params Array of several parameters
37 * @return boolean|array
40 * @see \Friendica\Database\DBA::select
42 public static function select(array $fields = [], array $conditions = [], array $params = [])
45 $fields = self::getFields();
48 $r = DBA::select("photo", $fields, $conditions, $params);
49 return DBA::toArray($r);
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::select([], $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"], ["resource-id" => $resourceid]);
137 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
140 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
144 $params = ["order" => ["scale" => true]];
146 $photo = self::selectFirst([], $conditions, $params);
152 * @brief Check if photo with given conditions exists
154 * @param array $conditions Array of extra conditions
159 public static function exists(array $conditions)
161 return DBA::exists("photo", $conditions);
166 * @brief Get Image object for given row id. null if row id does not exist
168 * @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
170 * @return \Friendica\Object\Image
171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
172 * @throws \ImagickException
174 public static function getImageForPhoto(array $photo)
178 if ($photo["backend-class"] == "") {
179 // legacy data storage in "data" column
180 $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
186 $backendClass = $photo["backend-class"];
187 $backendRef = $photo["backend-ref"];
188 $data = $backendClass::get($backendRef);
195 return new Image($data, $photo["type"]);
199 * @brief Return a list of fields that are associated with the photo table
201 * @return array field list
204 private static function getFields()
206 $allfields = DBStructure::definition(self::getApp()->getBasePath(), false);
207 $fields = array_keys($allfields["photo"]["fields"]);
208 array_splice($fields, array_search("data", $fields), 1);
213 * @brief Construct a photo array for a system resource image
215 * @param string $filename Image file name relative to code root
216 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
221 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
223 $fields = self::getFields();
224 $values = array_fill(0, count($fields), "");
226 $photo = array_combine($fields, $values);
227 $photo["backend-class"] = Storage\SystemResource::class;
228 $photo["backend-ref"] = $filename;
229 $photo["type"] = $mimetype;
230 $photo["cacheable"] = false;
237 * @brief store photo metadata in db and binary in default backend
239 * @param Image $Image Image object with data
240 * @param integer $uid User ID
241 * @param integer $cid Contact ID
242 * @param integer $rid Resource ID
243 * @param string $filename Filename
244 * @param string $album Album name
245 * @param integer $scale Scale
246 * @param integer $profile Is a profile image? optional, default = 0
247 * @param string $allow_cid Permissions, allowed contacts. optional, default = ""
248 * @param string $allow_gid Permissions, allowed groups. optional, default = ""
249 * @param string $deny_cid Permissions, denied contacts.optional, default = ""
250 * @param string $deny_gid Permissions, denied greoup.optional, default = ""
251 * @param string $desc Photo caption. optional, default = ""
253 * @return boolean True on success
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
258 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
259 if (DBA::isResult($photo)) {
260 $guid = $photo["guid"];
262 $guid = System::createGUID();
265 $existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
266 $created = DateTimeFormat::utcNow();
267 if (DBA::isResult($existing_photo)) {
268 $created = $existing_photo["created"];
271 // Get defined storage backend.
272 // if no storage backend, we use old "data" column in photo table.
273 // if is an existing photo, reuse same backend
277 /** @var IStorage $backend_class */
278 if (DBA::isResult($existing_photo)) {
279 $backend_ref = (string)$existing_photo["backend-ref"];
280 $backend_class = (string)$existing_photo["backend-class"];
282 $backend_class = StorageManager::getBackend();
285 if ($backend_class === "") {
286 $data = $Image->asString();
288 $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
294 "contact-id" => $cid,
296 "resource-id" => $rid,
297 "created" => $created,
298 "edited" => DateTimeFormat::utcNow(),
299 "filename" => basename($filename),
300 "type" => $Image->getType(),
302 "height" => $Image->getHeight(),
303 "width" => $Image->getWidth(),
304 "datasize" => strlen($Image->asString()),
307 "profile" => $profile,
308 "allow_cid" => $allow_cid,
309 "allow_gid" => $allow_gid,
310 "deny_cid" => $deny_cid,
311 "deny_gid" => $deny_gid,
313 "backend-class" => $backend_class,
314 "backend-ref" => $backend_ref
317 if (DBA::isResult($existing_photo)) {
318 $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
320 $r = DBA::insert("photo", $fields);
328 * @brief Delete info from table and data from storage
330 * @param array $conditions Field condition(s)
331 * @param array $options Options array, Optional
336 * @see \Friendica\Database\DBA::delete
338 public static function delete(array $conditions, array $options = [])
340 // get photo to delete data info
341 $photos = self::select(["backend-class","backend-ref"], $conditions);
343 foreach($photos as $photo) {
344 /** @var IStorage $backend_class */
345 $backend_class = (string)$photo["backend-class"];
346 if ($backend_class !== "") {
347 $backend_class::delete($photo["backend-ref"]);
351 return DBA::delete("photo", $conditions, $options);
355 * @brief This function is used by the fromgplus addon
357 * Stores a photo based on image data or an URL
359 * @param integer $uid user id
360 * @param string $imagedata optional, default empty
361 * @param string $url optional, default empty
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364 * @throws \ImagickException
366 public static function storeByData($uid, $imagedata = "", $url = "")
369 $logger = $a->getLogger();
370 $profiler = $a->getProfiler();
372 $user = User::getOwnerDataById($uid);
374 if (!DBA::isResult($user) || !empty($user['blocked'])) {
375 $logger->info("Can't detect user data.", ['uid' => $uid]);
379 $page_owner_nick = $user[0]['nickname'];
382 /// $default_cid = $isStored[0]['id'];
383 /// $community_page = (($isStored[0]['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
385 if ((strlen($imagedata) == 0) && ($url == "")) {
386 $logger->info("No image data and no url provided");
388 } elseif (strlen($imagedata) == 0) {
389 $logger->info("Uploading picture,", ['url' => $url]);
391 $stamp1 = microtime(true);
392 $imagedata = @file_get_contents($url);
393 $profiler->saveTimestamp($stamp1, "file", System::callstack());
396 $maxImageSize = Config::get('system', 'maximagesize');
398 if (($maxImageSize) && (strlen($imagedata) > $maxImageSize)) {
399 $logger->info("Image exceeds size limit.", ['max' => $maxImageSize, 'current' => strlen($imagedata)]);
403 $tempFile = tempnam(get_temppath(), "cache");
405 $stamp1 = microtime(true);
406 file_put_contents($tempFile, $imagedata);
407 $profiler->saveTimestamp($stamp1, "file", System::callstack());
409 $data = getimagesize($tempFile);
411 if (!isset($data["mime"])) {
413 $logger->info("File is no picture");
417 $image = new Image($imagedata, $data["mime"]);
419 if (!$image->isValid()) {
421 $logger->info("Picture is no valid picture");
425 $image->orient($tempFile);
428 $max_length = Config::get('system', 'max_image_length');
430 $max_length = MAX_IMAGE_LENGTH;
433 if ($max_length > 0) {
434 $image->scaleDown($max_length);
437 $width = $image->getWidth();
438 $height = $image->getHeight();
440 $hash = self::newResource();
442 // Pictures are always public by now
443 //$defperm = '<'.$default_cid.'>';
447 $isStored = Photo::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 0, 0, $defperm);
450 $logger->info("Picture couldn't be stored");
454 $image = ["page" => $a->getBaseURL() . '/photos/' . $page_owner_nick . '/image/' . $hash,
455 "full" => $a->getBaseURL() . "/photo/{$hash}-0." . $image->getExt()];
457 if ($width > 800 || $height > 800) {
458 $image["large"] = $a->getBaseURL() . "/photo/{$hash}-0." . $image->getExt();
461 if ($width > 640 || $height > 640) {
462 $image->scaleDown(640);
463 $isStored = self::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 1, 0, $defperm);
465 $image["medium"] = $a->getBaseURL() . "/photo/{$hash}-1." . $image->getExt();
469 if ($width > 320 || $height > 320) {
470 $image->scaleDown(320);
471 $isStored = self::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 2, 0, $defperm);
473 $image["small"] = $a->getBaseURL() . "/photo/{$hash}-2." . $image->getExt();
477 if ($width > 160 && $height > 160) {
481 $min = $image->getWidth();
483 $x = ($min - 160) / 2;
486 if ($image->getHeight() < $min) {
487 $min = $image->getHeight();
489 $y = ($min - 160) / 2;
494 $image->crop(160, $x, $y, $min, $min);
496 $isStored = self::store($image, $uid, $visitor, $hash, $tempFile, L10n::t('Wall Photos'), 3, 0, $defperm);
498 $image["thumb"] = $a->getBaseURL() . "/photo/{$hash}-3." . $image->getExt();
502 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
503 $image["preview"] = $image["full"];
505 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
506 //if (isset($image["thumb"]))
507 // $image["preview"] = $image["thumb"];
509 // Unsure, if this should be activated or deactivated
510 //if (isset($image["small"]))
511 // $image["preview"] = $image["small"];
513 if (isset($image["medium"])) {
514 $image["preview"] = $image["medium"];
521 * @brief Update a photo
523 * @param array $fields Contains the fields that are updated
524 * @param array $conditions Condition array with the key values
525 * @param Image $img Image to update. Optional, default null.
526 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
528 * @return boolean Was the update successfull?
530 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
531 * @see \Friendica\Database\DBA::update
533 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
535 if (!is_null($img)) {
536 // get photo to update
537 $photos = self::select(["backend-class","backend-ref"], $conditions);
539 foreach($photos as $photo) {
540 /** @var IStorage $backend_class */
541 $backend_class = (string)$photo["backend-class"];
542 if ($backend_class !== "") {
543 $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
545 $fields["data"] = $img->asString();
548 $fields['updated'] = DateTimeFormat::utcNow();
551 $fields['edited'] = DateTimeFormat::utcNow();
553 return DBA::update("photo", $fields, $conditions, $old_fields);
557 * @param string $image_url Remote URL
558 * @param integer $uid user id
559 * @param integer $cid contact id
560 * @param boolean $quit_on_error optional, default false
562 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
563 * @throws \ImagickException
565 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
570 $photo = DBA::selectFirst(
571 "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
573 if (!empty($photo['resource-id'])) {
574 $hash = $photo["resource-id"];
576 $hash = self::newResource();
579 $photo_failure = false;
581 $filename = basename($image_url);
582 $img_str = Network::fetchUrl($image_url, true);
584 if ($quit_on_error && ($img_str == "")) {
588 $type = Image::guessType($image_url, true);
589 $Image = new Image($img_str, $type);
590 if ($Image->isValid()) {
591 $Image->scaleToSquare(300);
593 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
596 $photo_failure = true;
599 $Image->scaleDown(80);
601 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
604 $photo_failure = true;
607 $Image->scaleDown(48);
609 $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
612 $photo_failure = true;
615 $suffix = "?ts=" . time();
617 $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
618 $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
619 $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
621 // Remove the cached photo
623 $basepath = $a->getBasePath();
625 if (is_dir($basepath . "/photo")) {
626 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
627 if (file_exists($filename)) {
630 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
631 if (file_exists($filename)) {
634 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
635 if (file_exists($filename)) {
640 $photo_failure = true;
643 if ($photo_failure && $quit_on_error) {
647 if ($photo_failure) {
648 $image_url = System::baseUrl() . "/images/person-300.jpg";
649 $thumb = System::baseUrl() . "/images/person-80.jpg";
650 $micro = System::baseUrl() . "/images/person-48.jpg";
653 return [$image_url, $thumb, $micro];
657 * @param array $exifCoord coordinate
658 * @param string $hemi hemi
661 public static function getGps($exifCoord, $hemi)
663 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
664 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
665 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
667 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
669 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
673 * @param string $coordPart coordPart
676 private static function gps2Num($coordPart)
678 $parts = explode("/", $coordPart);
680 if (count($parts) <= 0) {
684 if (count($parts) == 1) {
688 return floatval($parts[0]) / floatval($parts[1]);
692 * @brief Fetch the photo albums that are available for a viewer
694 * The query in this function is cost intensive, so it is cached.
696 * @param int $uid User id of the photos
697 * @param bool $update Update the cache
699 * @return array Returns array of the photo albums
700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
702 public static function getAlbums($uid, $update = false)
704 $sql_extra = Security::getPermissionsSQLByUserId($uid);
706 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
707 $albums = Cache::get($key);
708 if (is_null($albums) || $update) {
709 if (!Config::get("system", "no_count", false)) {
710 /// @todo This query needs to be renewed. It is really slow
711 // At this time we just store the data in the cache
712 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
714 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
715 GROUP BY `album` ORDER BY `created` DESC",
717 DBA::escape("Contact Photos"),
718 DBA::escape(L10n::t("Contact Photos"))
721 // This query doesn't do the count and is much faster
722 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
723 FROM `photo` USE INDEX (`uid_album_scale_created`)
724 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
726 DBA::escape("Contact Photos"),
727 DBA::escape(L10n::t("Contact Photos"))
730 Cache::set($key, $albums, Cache::DAY);
736 * @param int $uid User id of the photos
740 public static function clearAlbumCache($uid)
742 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
743 Cache::set($key, null, Cache::DAY);
747 * Generate a unique photo ID.
752 public static function newResource()
754 return System::createGUID(32, false);