]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Move Photo module, update Photo model
[friendica.git] / src / Model / Photo.php
1 <?php
2
3 /**
4  * @file src/Model/Photo.php
5  * @brief This file contains the Photo class for database interface
6  */
7 namespace Friendica\Model;
8
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;
20
21 /**
22  * Class to handle photo dabatase table
23  */
24 class Photo extends BaseObject
25 {
26         /**
27          * @brief Select rows from the photo table
28          *
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
32          *
33          * @return boolean|array
34          *
35          * @see \Friendica\Database\DBA::select
36          */
37         public static function select(array $fields = [], array $condition = [], array $params = [])
38         {
39                 if (empty($fields)) {
40                         $selected = self::getFields();
41                 }
42
43                 $r = DBA::select("photo", $fields, $condition, $params);
44                 return DBA::toArray($r);
45         }
46
47         /**
48          * @brief Retrieve a single record from the photo table
49          *
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
53          *
54          * @return bool|array
55          *
56          * @see \Friendica\Database\DBA::select
57          */
58         public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
59         {
60                 if (empty($fields)) {
61                         $selected = self::getFields();
62                 }
63
64                 return DBA::selectFirst("photo", $fields, $condition, $params);
65         }
66
67         /**
68          * @brief Get a single photo given resource id and scale
69          *
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
73          *
74          * @param string  $resourceid  Rescource ID for the photo
75          * @param integer $scale       Scale of the photo. Defaults to 0
76          *
77          * @return boolean|array
78          */
79         public static function getPhoto($resourceid, $scale = 0)
80         {
81                 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
82                 if ($r===false) return false;
83
84                 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
85
86                 $condition = [
87                         "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
88                         $resourceid, $scale
89                 ];
90
91                 $params = [ "order" => ["scale" => true]];
92
93                 $photo = self::selectFirst([], $condition, $params);
94                 if ($photo === false) {
95                         return false; ///TODO: Return info for red sign image
96                 }
97                 return $photo;
98         }
99
100         /**
101          * @brief Check if photo with given resource id exists
102          *
103          * @param string  $resourceid  Resource ID of the photo
104          *
105          * @return boolean
106          */
107         public static function exists($resourceid)
108         {
109                 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
110         }
111
112         /**
113          * @brief Get Image object for given row id. null if row id does not exist
114          *
115          * @param integer  $id  Row id
116          *
117          * @return \Friendica\Object\Image
118          */
119         public static function getImageForPhotoId($id)
120         {
121                 $i = self::selectFirst(["data", "type"],["id"=>$id]);
122                 if ($i===false) {
123                         return null;
124                 }
125                 return new Image($i["data"], $i["type"]);
126         }
127
128         /**
129          * @brief Return a list of fields that are associated with the photo table
130          *
131          * @return array field list
132          */
133         private static function getFields()
134         {
135                 $allfields = DBStructure::definition(false);
136                 $fields = array_keys($allfields["photo"]["fields"]);
137                 array_splice($fields, array_search("data", $fields), 1);
138                 return $fields;
139         }
140
141
142
143         /**
144          * @brief store photo metadata in db and binary in default backend
145          *
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 = ''
159          *
160          * @return boolean True on success
161          */
162         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
163         {
164                 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
165                 if (DBA::isResult($photo)) {
166                         $guid = $photo['guid'];
167                 } else {
168                         $guid = System::createGUID();
169                 }
170
171                 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
172
173                 $fields = [
174                         'uid' => $uid,
175                         'contact-id' => $cid,
176                         'guid' => $guid,
177                         'resource-id' => $rid,
178                         'created' => DateTimeFormat::utcNow(),
179                         'edited' => DateTimeFormat::utcNow(),
180                         'filename' => basename($filename),
181                         'type' => $Image->getType(),
182                         'album' => $album,
183                         'height' => $Image->getHeight(),
184                         'width' => $Image->getWidth(),
185                         'datasize' => strlen($Image->asString()),
186                         'data' => $Image->asString(),
187                         'scale' => $scale,
188                         'profile' => $profile,
189                         'allow_cid' => $allow_cid,
190                         'allow_gid' => $allow_gid,
191                         'deny_cid' => $deny_cid,
192                         'deny_gid' => $deny_gid,
193                         'desc' => $desc
194                 ];
195
196                 if (DBA::isResult($existing_photo)) {
197                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
198                 } else {
199                         $r = DBA::insert('photo', $fields);
200                 }
201
202                 return $r;
203         }
204
205         /**
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
210          * @return array
211          */
212         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
213         {
214                 $thumb = '';
215                 $micro = '';
216
217                 $photo = DBA::selectFirst(
218                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
219                 );
220                 if (!empty($photo['resource-id'])) {
221                         $hash = $photo['resource-id'];
222                 } else {
223                         $hash = self::newResource();
224                 }
225
226                 $photo_failure = false;
227
228                 $filename = basename($image_url);
229                 $img_str = Network::fetchUrl($image_url, true);
230
231                 if ($quit_on_error && ($img_str == "")) {
232                         return false;
233                 }
234
235                 $type = Image::guessType($image_url, true);
236                 $Image = new Image($img_str, $type);
237                 if ($Image->isValid()) {
238                         $Image->scaleToSquare(300);
239
240                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
241
242                         if ($r === false) {
243                                 $photo_failure = true;
244                         }
245
246                         $Image->scaleDown(80);
247
248                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
249
250                         if ($r === false) {
251                                 $photo_failure = true;
252                         }
253
254                         $Image->scaleDown(48);
255
256                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
257
258                         if ($r === false) {
259                                 $photo_failure = true;
260                         }
261
262                         $suffix = '?ts=' . time();
263
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;
267
268                         // Remove the cached photo
269                         $a = \get_app();
270                         $basepath = $a->getBasePath();
271
272                         if (is_dir($basepath . "/photo")) {
273                                 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
274                                 if (file_exists($filename)) {
275                                         unlink($filename);
276                                 }
277                                 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
278                                 if (file_exists($filename)) {
279                                         unlink($filename);
280                                 }
281                                 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
282                                 if (file_exists($filename)) {
283                                         unlink($filename);
284                                 }
285                         }
286                 } else {
287                         $photo_failure = true;
288                 }
289
290                 if ($photo_failure && $quit_on_error) {
291                         return false;
292                 }
293
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';
298                 }
299
300                 return [$image_url, $thumb, $micro];
301         }
302
303         /**
304          * @param string $exifCoord coordinate
305          * @param string $hemi      hemi
306          * @return float
307          */
308         public static function getGps($exifCoord, $hemi)
309         {
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;
313
314                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
315
316                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
317         }
318
319         /**
320          * @param string $coordPart coordPart
321          * @return float
322          */
323         private static function gps2Num($coordPart)
324         {
325                 $parts = explode('/', $coordPart);
326
327                 if (count($parts) <= 0) {
328                         return 0;
329                 }
330
331                 if (count($parts) == 1) {
332                         return $parts[0];
333                 }
334
335                 return floatval($parts[0]) / floatval($parts[1]);
336         }
337
338         /**
339          * @brief Fetch the photo albums that are available for a viewer
340          *
341          * The query in this function is cost intensive, so it is cached.
342          *
343          * @param int  $uid    User id of the photos
344          * @param bool $update Update the cache
345          *
346          * @return array Returns array of the photo albums
347          */
348         public static function getAlbums($uid, $update = false)
349         {
350                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
351
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`
359                                         FROM `photo`
360                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
361                                         GROUP BY `album` ORDER BY `created` DESC",
362                                         intval($uid),
363                                         DBA::escape('Contact Photos'),
364                                         DBA::escape(L10n::t('Contact Photos'))
365                                 );
366                         } else {
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",
371                                         intval($uid),
372                                         DBA::escape('Contact Photos'),
373                                         DBA::escape(L10n::t('Contact Photos'))
374                                 );
375                         }
376                         Cache::set($key, $albums, Cache::DAY);
377                 }
378                 return $albums;
379         }
380
381         /**
382          * @param int $uid User id of the photos
383          * @return void
384          */
385         public static function clearAlbumCache($uid)
386         {
387                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
388                 Cache::set($key, null, Cache::DAY);
389         }
390
391         /**
392          * Generate a unique photo ID.
393          *
394          * @return string
395          */
396         public static function newResource()
397         {
398                 return system::createGUID(32, false);
399         }
400 }