]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Address code standards issues
[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) {
83                         return false;
84                 }
85
86                 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
87
88                 $condition = [
89                         "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
90                         $resourceid, $scale
91                 ];
92
93                 $params = [ "order" => ["scale" => true]];
94
95                 $photo = self::selectFirst([], $condition, $params);
96                 if ($photo === false) {
97                         return self::createPhotoForSystemResource("images/nosign.jpg");
98                 }
99                 return $photo;
100         }
101
102         /**
103          * @brief Check if photo with given resource id exists
104          *
105          * @param string  $resourceid  Resource ID of the photo
106          *
107          * @return boolean
108          */
109         public static function exists($resourceid)
110         {
111                 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
112         }
113
114         /**
115          * @brief Get Image object for given row id. null if row id does not exist
116          *
117          * @param integer  $id  Row id
118          *
119          * @return \Friendica\Object\Image
120          */
121         public static function getImageForPhoto($photo)
122         {
123                 $data = "";
124                 if ($photo["backend-class"] == "") {
125                         // legacy data storage in "data" column
126                         $i = self::selectFirst(["data"], ["id"=>$photo["id"]]);
127                         if ($i === false) {
128                                 return null;
129                         }
130                         $data = $i["data"];
131                 } else {
132                         $backendClass = $photo["backend-class"];
133                         $backendRef = $photo["backend-ref"];
134                         $data = $backendClass::get($backendRef);
135                 }
136
137                 if ($data === "") {
138                         return null;
139                 }
140                 return new Image($data, $photo["type"]);
141         }
142
143         /**
144          * @brief Return a list of fields that are associated with the photo table
145          *
146          * @return array field list
147          */
148         private static function getFields()
149         {
150                 $allfields = DBStructure::definition(false);
151                 $fields = array_keys($allfields["photo"]["fields"]);
152                 array_splice($fields, array_search("data", $fields), 1);
153                 return $fields;
154         }
155
156         /**
157          * @brief Construct a photo array for a system resource image
158          *
159          * @param string  $filename  Image file name relative to code root
160          * @param string  $mimetype  Image mime type. Defaults to "image/jpeg"
161          *
162          * @return array
163          */
164         public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
165         {
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;
173                 return $photo;
174         }
175
176
177         /**
178          * @brief store photo metadata in db and binary in default backend
179          *
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 = ''
193          *
194          * @return boolean True on success
195          */
196         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
197         {
198                 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
199                 if (DBA::isResult($photo)) {
200                         $guid = $photo['guid'];
201                 } else {
202                         $guid = System::createGUID();
203                 }
204
205                 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
206
207                 // Get defined storage backend.
208                 // if no storage backend, we use old "data" column in photo table.
209                 $data = "";
210                 $backend_ref = "";
211                 $backend_class = Config::get("storage", "class", "");
212                 if ($backend_class === "") {
213                         $data = $Image->asString();
214                 } else {
215                         $backend_ref = $backend_class::put($Image->asString());
216                 }
217
218                 $fields = [
219                         'uid' => $uid,
220                         'contact-id' => $cid,
221                         'guid' => $guid,
222                         'resource-id' => $rid,
223                         'created' => DateTimeFormat::utcNow(),
224                         'edited' => DateTimeFormat::utcNow(),
225                         'filename' => basename($filename),
226                         'type' => $Image->getType(),
227                         'album' => $album,
228                         'height' => $Image->getHeight(),
229                         'width' => $Image->getWidth(),
230                         'datasize' => strlen($Image->asString()),
231                         'data' => $data,
232                         'scale' => $scale,
233                         'profile' => $profile,
234                         'allow_cid' => $allow_cid,
235                         'allow_gid' => $allow_gid,
236                         'deny_cid' => $deny_cid,
237                         'deny_gid' => $deny_gid,
238                         'desc' => $desc,
239                         'backend-class' => $backend_class,
240                         'backend-ref' => $backend_ref
241                 ];
242
243                 if (DBA::isResult($existing_photo)) {
244                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
245                 } else {
246                         $r = DBA::insert('photo', $fields);
247                 }
248
249                 return $r;
250         }
251
252         /**
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
257          * @return array
258          */
259         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
260         {
261                 $thumb = '';
262                 $micro = '';
263
264                 $photo = DBA::selectFirst(
265                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
266                 );
267                 if (!empty($photo['resource-id'])) {
268                         $hash = $photo['resource-id'];
269                 } else {
270                         $hash = self::newResource();
271                 }
272
273                 $photo_failure = false;
274
275                 $filename = basename($image_url);
276                 $img_str = Network::fetchUrl($image_url, true);
277
278                 if ($quit_on_error && ($img_str == "")) {
279                         return false;
280                 }
281
282                 $type = Image::guessType($image_url, true);
283                 $Image = new Image($img_str, $type);
284                 if ($Image->isValid()) {
285                         $Image->scaleToSquare(300);
286
287                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
288
289                         if ($r === false) {
290                                 $photo_failure = true;
291                         }
292
293                         $Image->scaleDown(80);
294
295                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
296
297                         if ($r === false) {
298                                 $photo_failure = true;
299                         }
300
301                         $Image->scaleDown(48);
302
303                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
304
305                         if ($r === false) {
306                                 $photo_failure = true;
307                         }
308
309                         $suffix = '?ts=' . time();
310
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;
314
315                         // Remove the cached photo
316                         $a = \get_app();
317                         $basepath = $a->getBasePath();
318
319                         if (is_dir($basepath . "/photo")) {
320                                 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
321                                 if (file_exists($filename)) {
322                                         unlink($filename);
323                                 }
324                                 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
325                                 if (file_exists($filename)) {
326                                         unlink($filename);
327                                 }
328                                 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
329                                 if (file_exists($filename)) {
330                                         unlink($filename);
331                                 }
332                         }
333                 } else {
334                         $photo_failure = true;
335                 }
336
337                 if ($photo_failure && $quit_on_error) {
338                         return false;
339                 }
340
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';
345                 }
346
347                 return [$image_url, $thumb, $micro];
348         }
349
350         /**
351          * @param string $exifCoord coordinate
352          * @param string $hemi      hemi
353          * @return float
354          */
355         public static function getGps($exifCoord, $hemi)
356         {
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;
360
361                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
362
363                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
364         }
365
366         /**
367          * @param string $coordPart coordPart
368          * @return float
369          */
370         private static function gps2Num($coordPart)
371         {
372                 $parts = explode('/', $coordPart);
373
374                 if (count($parts) <= 0) {
375                         return 0;
376                 }
377
378                 if (count($parts) == 1) {
379                         return $parts[0];
380                 }
381
382                 return floatval($parts[0]) / floatval($parts[1]);
383         }
384
385         /**
386          * @brief Fetch the photo albums that are available for a viewer
387          *
388          * The query in this function is cost intensive, so it is cached.
389          *
390          * @param int  $uid    User id of the photos
391          * @param bool $update Update the cache
392          *
393          * @return array Returns array of the photo albums
394          */
395         public static function getAlbums($uid, $update = false)
396         {
397                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
398
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`
406                                         FROM `photo`
407                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
408                                         GROUP BY `album` ORDER BY `created` DESC",
409                                         intval($uid),
410                                         DBA::escape('Contact Photos'),
411                                         DBA::escape(L10n::t('Contact Photos'))
412                                 );
413                         } else {
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",
418                                         intval($uid),
419                                         DBA::escape('Contact Photos'),
420                                         DBA::escape(L10n::t('Contact Photos'))
421                                 );
422                         }
423                         Cache::set($key, $albums, Cache::DAY);
424                 }
425                 return $albums;
426         }
427
428         /**
429          * @param int $uid User id of the photos
430          * @return void
431          */
432         public static function clearAlbumCache($uid)
433         {
434                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
435                 Cache::set($key, null, Cache::DAY);
436         }
437
438         /**
439          * Generate a unique photo ID.
440          *
441          * @return string
442          */
443         public static function newResource()
444         {
445                 return system::createGUID(32, false);
446         }
447 }