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 $fields = 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, "no sign" image info, 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]);
86 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
89 "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
93 $params = [ "order" => ["scale" => true]];
95 $photo = self::selectFirst([], $condition, $params);
96 if ($photo === false) {
97 return self::createPhotoForSystemResource("images/nosign.jpg");
103 * @brief Check if photo with given resource id exists
105 * @param string $resourceid Resource ID of the photo
109 public static function exists($resourceid)
111 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
115 * @brief Get Image object for given row id. null if row id does not exist
117 * @param integer $id Row id
119 * @return \Friendica\Object\Image
121 public static function getImageForPhoto($photo)
124 if ($photo["backend-class"] == "") {
125 // legacy data storage in "data" column
126 $i = self::selectFirst(["data"], ["id"=>$photo["id"]]);
132 $backendClass = $photo["backend-class"];
133 $backendRef = $photo["backend-ref"];
134 $data = $backendClass::get($backendRef);
140 return new Image($data, $photo["type"]);
144 * @brief Return a list of fields that are associated with the photo table
146 * @return array field list
148 private static function getFields()
150 $allfields = DBStructure::definition(false);
151 $fields = array_keys($allfields["photo"]["fields"]);
152 array_splice($fields, array_search("data", $fields), 1);
157 * @brief Construct a photo array for a system resource image
159 * @param string $filename Image file name relative to code root
160 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
164 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
166 $fields = self::getFields();
167 $values = array_fill(0, count($fields), "");
168 $photo = array_combine($fields, $values);
169 $photo["backend-class"] = "\Friendica\Model\Storage\SystemResource";
170 $photo["backend-ref"] = $filename;
171 $photo["type"] = $mimetype;
172 $photo['cacheable'] = false;
178 * @brief store photo metadata in db and binary in default backend
180 * @param Image $Image image
181 * @param integer $uid uid
182 * @param integer $cid cid
183 * @param integer $rid rid
184 * @param string $filename filename
185 * @param string $album album name
186 * @param integer $scale scale
187 * @param integer $profile optional, default = 0
188 * @param string $allow_cid optional, default = ''
189 * @param string $allow_gid optional, default = ''
190 * @param string $deny_cid optional, default = ''
191 * @param string $deny_gid optional, default = ''
192 * @param string $desc optional, default = ''
194 * @return boolean True on success
196 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
198 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
199 if (DBA::isResult($photo)) {
200 $guid = $photo['guid'];
202 $guid = System::createGUID();
205 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
207 // Get defined storage backend.
208 // if no storage backend, we use old "data" column in photo table.
211 $backend_class = Config::get("storage", "class", "");
212 if ($backend_class === "") {
213 $data = $Image->asString();
215 $backend_ref = $backend_class::put($Image->asString());
220 'contact-id' => $cid,
222 'resource-id' => $rid,
223 'created' => DateTimeFormat::utcNow(),
224 'edited' => DateTimeFormat::utcNow(),
225 'filename' => basename($filename),
226 'type' => $Image->getType(),
228 'height' => $Image->getHeight(),
229 'width' => $Image->getWidth(),
230 'datasize' => strlen($Image->asString()),
233 'profile' => $profile,
234 'allow_cid' => $allow_cid,
235 'allow_gid' => $allow_gid,
236 'deny_cid' => $deny_cid,
237 'deny_gid' => $deny_gid,
239 'backend-class' => $backend_class,
240 'backend-ref' => $backend_ref
243 if (DBA::isResult($existing_photo)) {
244 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
246 $r = DBA::insert('photo', $fields);
253 * @param string $image_url Remote URL
254 * @param integer $uid user id
255 * @param integer $cid contact id
256 * @param boolean $quit_on_error optional, default false
259 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
264 $photo = DBA::selectFirst(
265 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
267 if (!empty($photo['resource-id'])) {
268 $hash = $photo['resource-id'];
270 $hash = self::newResource();
273 $photo_failure = false;
275 $filename = basename($image_url);
276 $img_str = Network::fetchUrl($image_url, true);
278 if ($quit_on_error && ($img_str == "")) {
282 $type = Image::guessType($image_url, true);
283 $Image = new Image($img_str, $type);
284 if ($Image->isValid()) {
285 $Image->scaleToSquare(300);
287 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
290 $photo_failure = true;
293 $Image->scaleDown(80);
295 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
298 $photo_failure = true;
301 $Image->scaleDown(48);
303 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
306 $photo_failure = true;
309 $suffix = '?ts=' . time();
311 $image_url = System::baseUrl() . '/photo/' . $hash . '-4.' . $Image->getExt() . $suffix;
312 $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $Image->getExt() . $suffix;
313 $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $Image->getExt() . $suffix;
315 // Remove the cached photo
317 $basepath = $a->getBasePath();
319 if (is_dir($basepath . "/photo")) {
320 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
321 if (file_exists($filename)) {
324 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
325 if (file_exists($filename)) {
328 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
329 if (file_exists($filename)) {
334 $photo_failure = true;
337 if ($photo_failure && $quit_on_error) {
341 if ($photo_failure) {
342 $image_url = System::baseUrl() . '/images/person-300.jpg';
343 $thumb = System::baseUrl() . '/images/person-80.jpg';
344 $micro = System::baseUrl() . '/images/person-48.jpg';
347 return [$image_url, $thumb, $micro];
351 * @param string $exifCoord coordinate
352 * @param string $hemi hemi
355 public static function getGps($exifCoord, $hemi)
357 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
358 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
359 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
361 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
363 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
367 * @param string $coordPart coordPart
370 private static function gps2Num($coordPart)
372 $parts = explode('/', $coordPart);
374 if (count($parts) <= 0) {
378 if (count($parts) == 1) {
382 return floatval($parts[0]) / floatval($parts[1]);
386 * @brief Fetch the photo albums that are available for a viewer
388 * The query in this function is cost intensive, so it is cached.
390 * @param int $uid User id of the photos
391 * @param bool $update Update the cache
393 * @return array Returns array of the photo albums
395 public static function getAlbums($uid, $update = false)
397 $sql_extra = Security::getPermissionsSQLByUserId($uid);
399 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
400 $albums = Cache::get($key);
401 if (is_null($albums) || $update) {
402 if (!Config::get('system', 'no_count', false)) {
403 /// @todo This query needs to be renewed. It is really slow
404 // At this time we just store the data in the cache
405 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
407 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
408 GROUP BY `album` ORDER BY `created` DESC",
410 DBA::escape('Contact Photos'),
411 DBA::escape(L10n::t('Contact Photos'))
414 // This query doesn't do the count and is much faster
415 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
416 FROM `photo` USE INDEX (`uid_album_scale_created`)
417 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
419 DBA::escape('Contact Photos'),
420 DBA::escape(L10n::t('Contact Photos'))
423 Cache::set($key, $albums, Cache::DAY);
429 * @param int $uid User id of the photos
432 public static function clearAlbumCache($uid)
434 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
435 Cache::set($key, null, Cache::DAY);
439 * Generate a unique photo ID.
443 public static function newResource()
445 return system::createGUID(32, false);