]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
3200c7f6ee33255b30c08947af5138da11a68929
[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                 // Get defined storage backend.
206                 // if no storage backend, we use old "data" column in photo table.
207                 $data = "";
208                 $backend_ref = "";
209                 $backend_class = Config::get("storage", "class", "");
210                 if ($backend_class==="") {
211                         $data = $Image->asString();
212                 } else {
213                         $backend_ref = $backend_class::put($Image->asString());
214                 }
215
216                 $fields = [
217                         'uid' => $uid,
218                         'contact-id' => $cid,
219                         'guid' => $guid,
220                         'resource-id' => $rid,
221                         'created' => DateTimeFormat::utcNow(),
222                         'edited' => DateTimeFormat::utcNow(),
223                         'filename' => basename($filename),
224                         'type' => $Image->getType(),
225                         'album' => $album,
226                         'height' => $Image->getHeight(),
227                         'width' => $Image->getWidth(),
228                         'datasize' => strlen($Image->asString()),
229                         'data' => $data,
230                         'scale' => $scale,
231                         'profile' => $profile,
232                         'allow_cid' => $allow_cid,
233                         'allow_gid' => $allow_gid,
234                         'deny_cid' => $deny_cid,
235                         'deny_gid' => $deny_gid,
236                         'desc' => $desc,
237                         'backend-class' => $backend_class,
238                         'backend-ref' => $backend_ref
239                 ];
240
241                 if (DBA::isResult($existing_photo)) {
242                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
243                 } else {
244                         $r = DBA::insert('photo', $fields);
245                 }
246
247                 return $r;
248         }
249
250         /**
251          * @param string  $image_url     Remote URL
252          * @param integer $uid           user id
253          * @param integer $cid           contact id
254          * @param boolean $quit_on_error optional, default false
255          * @return array
256          */
257         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
258         {
259                 $thumb = '';
260                 $micro = '';
261
262                 $photo = DBA::selectFirst(
263                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
264                 );
265                 if (!empty($photo['resource-id'])) {
266                         $hash = $photo['resource-id'];
267                 } else {
268                         $hash = self::newResource();
269                 }
270
271                 $photo_failure = false;
272
273                 $filename = basename($image_url);
274                 $img_str = Network::fetchUrl($image_url, true);
275
276                 if ($quit_on_error && ($img_str == "")) {
277                         return false;
278                 }
279
280                 $type = Image::guessType($image_url, true);
281                 $Image = new Image($img_str, $type);
282                 if ($Image->isValid()) {
283                         $Image->scaleToSquare(300);
284
285                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
286
287                         if ($r === false) {
288                                 $photo_failure = true;
289                         }
290
291                         $Image->scaleDown(80);
292
293                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
294
295                         if ($r === false) {
296                                 $photo_failure = true;
297                         }
298
299                         $Image->scaleDown(48);
300
301                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
302
303                         if ($r === false) {
304                                 $photo_failure = true;
305                         }
306
307                         $suffix = '?ts=' . time();
308
309                         $image_url = System::baseUrl() . '/photo/' . $hash . '-4.' . $Image->getExt() . $suffix;
310                         $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $Image->getExt() . $suffix;
311                         $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $Image->getExt() . $suffix;
312
313                         // Remove the cached photo
314                         $a = \get_app();
315                         $basepath = $a->getBasePath();
316
317                         if (is_dir($basepath . "/photo")) {
318                                 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
319                                 if (file_exists($filename)) {
320                                         unlink($filename);
321                                 }
322                                 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
323                                 if (file_exists($filename)) {
324                                         unlink($filename);
325                                 }
326                                 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
327                                 if (file_exists($filename)) {
328                                         unlink($filename);
329                                 }
330                         }
331                 } else {
332                         $photo_failure = true;
333                 }
334
335                 if ($photo_failure && $quit_on_error) {
336                         return false;
337                 }
338
339                 if ($photo_failure) {
340                         $image_url = System::baseUrl() . '/images/person-300.jpg';
341                         $thumb = System::baseUrl() . '/images/person-80.jpg';
342                         $micro = System::baseUrl() . '/images/person-48.jpg';
343                 }
344
345                 return [$image_url, $thumb, $micro];
346         }
347
348         /**
349          * @param string $exifCoord coordinate
350          * @param string $hemi      hemi
351          * @return float
352          */
353         public static function getGps($exifCoord, $hemi)
354         {
355                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
356                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
357                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
358
359                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
360
361                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
362         }
363
364         /**
365          * @param string $coordPart coordPart
366          * @return float
367          */
368         private static function gps2Num($coordPart)
369         {
370                 $parts = explode('/', $coordPart);
371
372                 if (count($parts) <= 0) {
373                         return 0;
374                 }
375
376                 if (count($parts) == 1) {
377                         return $parts[0];
378                 }
379
380                 return floatval($parts[0]) / floatval($parts[1]);
381         }
382
383         /**
384          * @brief Fetch the photo albums that are available for a viewer
385          *
386          * The query in this function is cost intensive, so it is cached.
387          *
388          * @param int  $uid    User id of the photos
389          * @param bool $update Update the cache
390          *
391          * @return array Returns array of the photo albums
392          */
393         public static function getAlbums($uid, $update = false)
394         {
395                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
396
397                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
398                 $albums = Cache::get($key);
399                 if (is_null($albums) || $update) {
400                         if (!Config::get('system', 'no_count', false)) {
401                                 /// @todo This query needs to be renewed. It is really slow
402                                 // At this time we just store the data in the cache
403                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
404                                         FROM `photo`
405                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
406                                         GROUP BY `album` ORDER BY `created` DESC",
407                                         intval($uid),
408                                         DBA::escape('Contact Photos'),
409                                         DBA::escape(L10n::t('Contact Photos'))
410                                 );
411                         } else {
412                                 // This query doesn't do the count and is much faster
413                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
414                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
415                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
416                                         intval($uid),
417                                         DBA::escape('Contact Photos'),
418                                         DBA::escape(L10n::t('Contact Photos'))
419                                 );
420                         }
421                         Cache::set($key, $albums, Cache::DAY);
422                 }
423                 return $albums;
424         }
425
426         /**
427          * @param int $uid User id of the photos
428          * @return void
429          */
430         public static function clearAlbumCache($uid)
431         {
432                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
433                 Cache::set($key, null, Cache::DAY);
434         }
435
436         /**
437          * Generate a unique photo ID.
438          *
439          * @return string
440          */
441         public static function newResource()
442         {
443                 return system::createGUID(32, false);
444         }
445 }