]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Pluggable storage backends: first steps
[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                         $fields = 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, "no sign" image info, 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 self::createPhotoForSystemResource("images/nosign.jpg");
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 getImageForPhoto($photo)
120         {
121                 $data = "";
122                 if ($photo["backend-class"] == "") {
123                         // legacy data storage in "data" column
124                         $i = self::selectFirst(["data"], ["id"=>$photo["id"]]);
125                         if ($i===false) {
126                                 return null;
127                         }
128                         $data = $i["data"];
129                 } else {
130                         $backendClass = $photo["backend-class"];
131                         $backendRef = $photo["backend-ref"];
132                         $data = $backendClass::get($backendRef);
133                 }
134
135                 if ($data === "") {
136                         return null;
137                 }
138                 return new Image($data, $photo["type"]);
139         }
140
141         /**
142          * @brief Return a list of fields that are associated with the photo table
143          *
144          * @return array field list
145          */
146         private static function getFields()
147         {
148                 $allfields = DBStructure::definition(false);
149                 $fields = array_keys($allfields["photo"]["fields"]);
150                 array_splice($fields, array_search("data", $fields), 1);
151                 return $fields;
152         }
153
154         /**
155          * @brief Construct a photo array for a system resource image
156          *
157          * @param string  $filename  Image file name relative to code root
158          * @param string  $mimetype  Image mime type. Defaults to "image/jpeg"
159          *
160          * @return array
161          */
162         public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
163         {
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;
171                 return $photo;
172         }
173
174
175         /**
176          * @brief store photo metadata in db and binary in default backend
177          *
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 = ''
191          *
192          * @return boolean True on success
193          */
194         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
195         {
196                 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
197                 if (DBA::isResult($photo)) {
198                         $guid = $photo['guid'];
199                 } else {
200                         $guid = System::createGUID();
201                 }
202
203                 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
204
205                 $fields = [
206                         'uid' => $uid,
207                         'contact-id' => $cid,
208                         'guid' => $guid,
209                         'resource-id' => $rid,
210                         'created' => DateTimeFormat::utcNow(),
211                         'edited' => DateTimeFormat::utcNow(),
212                         'filename' => basename($filename),
213                         'type' => $Image->getType(),
214                         'album' => $album,
215                         'height' => $Image->getHeight(),
216                         'width' => $Image->getWidth(),
217                         'datasize' => strlen($Image->asString()),
218                         'data' => $Image->asString(),
219                         'scale' => $scale,
220                         'profile' => $profile,
221                         'allow_cid' => $allow_cid,
222                         'allow_gid' => $allow_gid,
223                         'deny_cid' => $deny_cid,
224                         'deny_gid' => $deny_gid,
225                         'desc' => $desc
226                 ];
227
228                 if (DBA::isResult($existing_photo)) {
229                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
230                 } else {
231                         $r = DBA::insert('photo', $fields);
232                 }
233
234                 return $r;
235         }
236
237         /**
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
242          * @return array
243          */
244         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
245         {
246                 $thumb = '';
247                 $micro = '';
248
249                 $photo = DBA::selectFirst(
250                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
251                 );
252                 if (!empty($photo['resource-id'])) {
253                         $hash = $photo['resource-id'];
254                 } else {
255                         $hash = self::newResource();
256                 }
257
258                 $photo_failure = false;
259
260                 $filename = basename($image_url);
261                 $img_str = Network::fetchUrl($image_url, true);
262
263                 if ($quit_on_error && ($img_str == "")) {
264                         return false;
265                 }
266
267                 $type = Image::guessType($image_url, true);
268                 $Image = new Image($img_str, $type);
269                 if ($Image->isValid()) {
270                         $Image->scaleToSquare(300);
271
272                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
273
274                         if ($r === false) {
275                                 $photo_failure = true;
276                         }
277
278                         $Image->scaleDown(80);
279
280                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
281
282                         if ($r === false) {
283                                 $photo_failure = true;
284                         }
285
286                         $Image->scaleDown(48);
287
288                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
289
290                         if ($r === false) {
291                                 $photo_failure = true;
292                         }
293
294                         $suffix = '?ts=' . time();
295
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;
299
300                         // Remove the cached photo
301                         $a = \get_app();
302                         $basepath = $a->getBasePath();
303
304                         if (is_dir($basepath . "/photo")) {
305                                 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
306                                 if (file_exists($filename)) {
307                                         unlink($filename);
308                                 }
309                                 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
310                                 if (file_exists($filename)) {
311                                         unlink($filename);
312                                 }
313                                 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
314                                 if (file_exists($filename)) {
315                                         unlink($filename);
316                                 }
317                         }
318                 } else {
319                         $photo_failure = true;
320                 }
321
322                 if ($photo_failure && $quit_on_error) {
323                         return false;
324                 }
325
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';
330                 }
331
332                 return [$image_url, $thumb, $micro];
333         }
334
335         /**
336          * @param string $exifCoord coordinate
337          * @param string $hemi      hemi
338          * @return float
339          */
340         public static function getGps($exifCoord, $hemi)
341         {
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;
345
346                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
347
348                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
349         }
350
351         /**
352          * @param string $coordPart coordPart
353          * @return float
354          */
355         private static function gps2Num($coordPart)
356         {
357                 $parts = explode('/', $coordPart);
358
359                 if (count($parts) <= 0) {
360                         return 0;
361                 }
362
363                 if (count($parts) == 1) {
364                         return $parts[0];
365                 }
366
367                 return floatval($parts[0]) / floatval($parts[1]);
368         }
369
370         /**
371          * @brief Fetch the photo albums that are available for a viewer
372          *
373          * The query in this function is cost intensive, so it is cached.
374          *
375          * @param int  $uid    User id of the photos
376          * @param bool $update Update the cache
377          *
378          * @return array Returns array of the photo albums
379          */
380         public static function getAlbums($uid, $update = false)
381         {
382                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
383
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`
391                                         FROM `photo`
392                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
393                                         GROUP BY `album` ORDER BY `created` DESC",
394                                         intval($uid),
395                                         DBA::escape('Contact Photos'),
396                                         DBA::escape(L10n::t('Contact Photos'))
397                                 );
398                         } else {
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",
403                                         intval($uid),
404                                         DBA::escape('Contact Photos'),
405                                         DBA::escape(L10n::t('Contact Photos'))
406                                 );
407                         }
408                         Cache::set($key, $albums, Cache::DAY);
409                 }
410                 return $albums;
411         }
412
413         /**
414          * @param int $uid User id of the photos
415          * @return void
416          */
417         public static function clearAlbumCache($uid)
418         {
419                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
420                 Cache::set($key, null, Cache::DAY);
421         }
422
423         /**
424          * Generate a unique photo ID.
425          *
426          * @return string
427          */
428         public static function newResource()
429         {
430                 return system::createGUID(32, false);
431         }
432 }