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;
22 * Class to handle photo dabatase table
24 class Photo extends BaseObject
27 * @brief Select rows from the photo table
29 * @param array $fields Array of selected fields, empty for all
30 * @param array $condition Array of fields for condition
31 * @param array $params Array of several parameters
33 * @return boolean|array
35 * @see \Friendica\Database\DBA::select
37 public static function select(array $fields = [], array $condition = [], array $params = [])
40 $selected = self::getFields();
43 $r = DBA::select("photo", $fields, $condition, $params);
44 return DBA::toArray($r);
48 * @brief Retrieve a single record from the photo table
50 * @param array $fields Array of selected fields, empty for all
51 * @param array $condition Array of fields for condition
52 * @param array $params Array of several parameters
56 * @see \Friendica\Database\DBA::select
58 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
61 $selected = self::getFields();
64 return DBA::selectFirst("photo", $fields, $condition, $params);
68 * @brief Get a single photo given resource id and scale
70 * This method checks for permissions. Returns associative array
71 * on success, a generic "red sign" data if user has no permission,
72 * false if photo does not exists
74 * @param string $resourceid Rescource ID for the photo
75 * @param integer $scale Scale of the photo. Defaults to 0
77 * @return boolean|array
79 public static function getPhoto($resourceid, $scale = 0)
81 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
82 if ($r===false) return false;
84 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
87 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
91 $params = [ "order" => ["scale" => true]];
93 $photo = self::selectFirst([], $condition, $params);
94 if ($photo === false) {
95 return false; ///TODO: Return info for red sign image
101 * @brief Check if photo with given resource id exists
103 * @param string $resourceid Resource ID of the photo
107 public static function exists($resourceid)
109 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
113 * @brief Get Image object for given row id. null if row id does not exist
115 * @param integer $id Row id
117 * @return \Friendica\Object\Image
119 public static function getImageForPhotoId($id)
121 $i = self::selectFirst(["data", "type"],["id"=>$id]);
125 return new Image($i["data"], $i["type"]);
129 * @brief Return a list of fields that are associated with the photo table
131 * @return array field list
133 private static function getFields()
135 $allfields = DBStructure::definition(false);
136 $fields = array_keys($allfields["photo"]["fields"]);
137 array_splice($fields, array_search("data", $fields), 1);
144 * @brief store photo metadata in db and binary in default backend
146 * @param Image $Image image
147 * @param integer $uid uid
148 * @param integer $cid cid
149 * @param integer $rid rid
150 * @param string $filename filename
151 * @param string $album album name
152 * @param integer $scale scale
153 * @param integer $profile optional, default = 0
154 * @param string $allow_cid optional, default = ''
155 * @param string $allow_gid optional, default = ''
156 * @param string $deny_cid optional, default = ''
157 * @param string $deny_gid optional, default = ''
158 * @param string $desc optional, default = ''
160 * @return boolean True on success
162 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
164 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
165 if (DBA::isResult($photo)) {
166 $guid = $photo['guid'];
168 $guid = System::createGUID();
171 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
175 'contact-id' => $cid,
177 'resource-id' => $rid,
178 'created' => DateTimeFormat::utcNow(),
179 'edited' => DateTimeFormat::utcNow(),
180 'filename' => basename($filename),
181 'type' => $Image->getType(),
183 'height' => $Image->getHeight(),
184 'width' => $Image->getWidth(),
185 'datasize' => strlen($Image->asString()),
186 'data' => $Image->asString(),
188 'profile' => $profile,
189 'allow_cid' => $allow_cid,
190 'allow_gid' => $allow_gid,
191 'deny_cid' => $deny_cid,
192 'deny_gid' => $deny_gid,
196 if (DBA::isResult($existing_photo)) {
197 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
199 $r = DBA::insert('photo', $fields);
206 * @param string $image_url Remote URL
207 * @param integer $uid user id
208 * @param integer $cid contact id
209 * @param boolean $quit_on_error optional, default false
212 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
217 $photo = DBA::selectFirst(
218 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
220 if (!empty($photo['resource-id'])) {
221 $hash = $photo['resource-id'];
223 $hash = self::newResource();
226 $photo_failure = false;
228 $filename = basename($image_url);
229 $img_str = Network::fetchUrl($image_url, true);
231 if ($quit_on_error && ($img_str == "")) {
235 $type = Image::guessType($image_url, true);
236 $Image = new Image($img_str, $type);
237 if ($Image->isValid()) {
238 $Image->scaleToSquare(300);
240 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
243 $photo_failure = true;
246 $Image->scaleDown(80);
248 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
251 $photo_failure = true;
254 $Image->scaleDown(48);
256 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
259 $photo_failure = true;
262 $suffix = '?ts=' . time();
264 $image_url = System::baseUrl() . '/photo/' . $hash . '-4.' . $Image->getExt() . $suffix;
265 $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $Image->getExt() . $suffix;
266 $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $Image->getExt() . $suffix;
268 // Remove the cached photo
270 $basepath = $a->getBasePath();
272 if (is_dir($basepath . "/photo")) {
273 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
274 if (file_exists($filename)) {
277 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
278 if (file_exists($filename)) {
281 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
282 if (file_exists($filename)) {
287 $photo_failure = true;
290 if ($photo_failure && $quit_on_error) {
294 if ($photo_failure) {
295 $image_url = System::baseUrl() . '/images/person-300.jpg';
296 $thumb = System::baseUrl() . '/images/person-80.jpg';
297 $micro = System::baseUrl() . '/images/person-48.jpg';
300 return [$image_url, $thumb, $micro];
304 * @param string $exifCoord coordinate
305 * @param string $hemi hemi
308 public static function getGps($exifCoord, $hemi)
310 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
311 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
312 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
314 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
316 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
320 * @param string $coordPart coordPart
323 private static function gps2Num($coordPart)
325 $parts = explode('/', $coordPart);
327 if (count($parts) <= 0) {
331 if (count($parts) == 1) {
335 return floatval($parts[0]) / floatval($parts[1]);
339 * @brief Fetch the photo albums that are available for a viewer
341 * The query in this function is cost intensive, so it is cached.
343 * @param int $uid User id of the photos
344 * @param bool $update Update the cache
346 * @return array Returns array of the photo albums
348 public static function getAlbums($uid, $update = false)
350 $sql_extra = Security::getPermissionsSQLByUserId($uid);
352 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
353 $albums = Cache::get($key);
354 if (is_null($albums) || $update) {
355 if (!Config::get('system', 'no_count', false)) {
356 /// @todo This query needs to be renewed. It is really slow
357 // At this time we just store the data in the cache
358 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
360 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
361 GROUP BY `album` ORDER BY `created` DESC",
363 DBA::escape('Contact Photos'),
364 DBA::escape(L10n::t('Contact Photos'))
367 // This query doesn't do the count and is much faster
368 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
369 FROM `photo` USE INDEX (`uid_album_scale_created`)
370 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
372 DBA::escape('Contact Photos'),
373 DBA::escape(L10n::t('Contact Photos'))
376 Cache::set($key, $albums, Cache::DAY);
382 * @param int $uid User id of the photos
385 public static function clearAlbumCache($uid)
387 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
388 Cache::set($key, null, Cache::DAY);
392 * Generate a unique photo ID.
396 public static function newResource()
398 return system::createGUID(32, false);