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]);
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 self::createPhotoForSystemResource("images/nosign.jpg");
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 getImageForPhoto($photo)
122 if ($photo["backend-class"] == "") {
123 // legacy data storage in "data" column
124 $i = self::selectFirst(["data"], ["id"=>$photo["id"]]);
130 $backendClass = $photo["backend-class"];
131 $backendRef = $photo["backend-ref"];
132 $data = $backendClass::get($backendRef);
138 return new Image($data, $photo["type"]);
142 * @brief Return a list of fields that are associated with the photo table
144 * @return array field list
146 private static function getFields()
148 $allfields = DBStructure::definition(false);
149 $fields = array_keys($allfields["photo"]["fields"]);
150 array_splice($fields, array_search("data", $fields), 1);
155 * @brief Construct a photo array for a system resource image
157 * @param string $filename Image file name relative to code root
158 * @param string $mimetype Image mime type. Defaults to "image/jpeg"
162 public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
164 $fields = self::getFields();
165 $values = array_fill(0, count($fields), "");
166 $photo = array_combine($fields, $values);
167 $photo["backend-class"] = "\Friendica\Model\Storage\SystemResource";
168 $photo["backend-ref"] = $filename;
169 $photo["type"] = $mimetype;
170 $photo['cacheable'] = false;
176 * @brief store photo metadata in db and binary in default backend
178 * @param Image $Image image
179 * @param integer $uid uid
180 * @param integer $cid cid
181 * @param integer $rid rid
182 * @param string $filename filename
183 * @param string $album album name
184 * @param integer $scale scale
185 * @param integer $profile optional, default = 0
186 * @param string $allow_cid optional, default = ''
187 * @param string $allow_gid optional, default = ''
188 * @param string $deny_cid optional, default = ''
189 * @param string $deny_gid optional, default = ''
190 * @param string $desc optional, default = ''
192 * @return boolean True on success
194 public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
196 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
197 if (DBA::isResult($photo)) {
198 $guid = $photo['guid'];
200 $guid = System::createGUID();
203 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
207 'contact-id' => $cid,
209 'resource-id' => $rid,
210 'created' => DateTimeFormat::utcNow(),
211 'edited' => DateTimeFormat::utcNow(),
212 'filename' => basename($filename),
213 'type' => $Image->getType(),
215 'height' => $Image->getHeight(),
216 'width' => $Image->getWidth(),
217 'datasize' => strlen($Image->asString()),
218 'data' => $Image->asString(),
220 'profile' => $profile,
221 'allow_cid' => $allow_cid,
222 'allow_gid' => $allow_gid,
223 'deny_cid' => $deny_cid,
224 'deny_gid' => $deny_gid,
228 if (DBA::isResult($existing_photo)) {
229 $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
231 $r = DBA::insert('photo', $fields);
238 * @param string $image_url Remote URL
239 * @param integer $uid user id
240 * @param integer $cid contact id
241 * @param boolean $quit_on_error optional, default false
244 public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
249 $photo = DBA::selectFirst(
250 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
252 if (!empty($photo['resource-id'])) {
253 $hash = $photo['resource-id'];
255 $hash = self::newResource();
258 $photo_failure = false;
260 $filename = basename($image_url);
261 $img_str = Network::fetchUrl($image_url, true);
263 if ($quit_on_error && ($img_str == "")) {
267 $type = Image::guessType($image_url, true);
268 $Image = new Image($img_str, $type);
269 if ($Image->isValid()) {
270 $Image->scaleToSquare(300);
272 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
275 $photo_failure = true;
278 $Image->scaleDown(80);
280 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
283 $photo_failure = true;
286 $Image->scaleDown(48);
288 $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
291 $photo_failure = true;
294 $suffix = '?ts=' . time();
296 $image_url = System::baseUrl() . '/photo/' . $hash . '-4.' . $Image->getExt() . $suffix;
297 $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $Image->getExt() . $suffix;
298 $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $Image->getExt() . $suffix;
300 // Remove the cached photo
302 $basepath = $a->getBasePath();
304 if (is_dir($basepath . "/photo")) {
305 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
306 if (file_exists($filename)) {
309 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
310 if (file_exists($filename)) {
313 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
314 if (file_exists($filename)) {
319 $photo_failure = true;
322 if ($photo_failure && $quit_on_error) {
326 if ($photo_failure) {
327 $image_url = System::baseUrl() . '/images/person-300.jpg';
328 $thumb = System::baseUrl() . '/images/person-80.jpg';
329 $micro = System::baseUrl() . '/images/person-48.jpg';
332 return [$image_url, $thumb, $micro];
336 * @param string $exifCoord coordinate
337 * @param string $hemi hemi
340 public static function getGps($exifCoord, $hemi)
342 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
343 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
344 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
346 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
348 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
352 * @param string $coordPart coordPart
355 private static function gps2Num($coordPart)
357 $parts = explode('/', $coordPart);
359 if (count($parts) <= 0) {
363 if (count($parts) == 1) {
367 return floatval($parts[0]) / floatval($parts[1]);
371 * @brief Fetch the photo albums that are available for a viewer
373 * The query in this function is cost intensive, so it is cached.
375 * @param int $uid User id of the photos
376 * @param bool $update Update the cache
378 * @return array Returns array of the photo albums
380 public static function getAlbums($uid, $update = false)
382 $sql_extra = Security::getPermissionsSQLByUserId($uid);
384 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
385 $albums = Cache::get($key);
386 if (is_null($albums) || $update) {
387 if (!Config::get('system', 'no_count', false)) {
388 /// @todo This query needs to be renewed. It is really slow
389 // At this time we just store the data in the cache
390 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
392 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra
393 GROUP BY `album` ORDER BY `created` DESC",
395 DBA::escape('Contact Photos'),
396 DBA::escape(L10n::t('Contact Photos'))
399 // This query doesn't do the count and is much faster
400 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
401 FROM `photo` USE INDEX (`uid_album_scale_created`)
402 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' $sql_extra",
404 DBA::escape('Contact Photos'),
405 DBA::escape(L10n::t('Contact Photos'))
408 Cache::set($key, $albums, Cache::DAY);
414 * @param int $uid User id of the photos
417 public static function clearAlbumCache($uid)
419 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
420 Cache::set($key, null, Cache::DAY);
424 * Generate a unique photo ID.
428 public static function newResource()
430 return system::createGUID(32, false);