]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Code standards
[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 require_once "include/dba.php";
22
23 /**
24  * Class to handle photo dabatase table
25  */
26 class Photo extends BaseObject
27 {
28         /**
29          * @brief Select rows from the photo table
30          *
31          * @param array  $fields     Array of selected fields, empty for all
32          * @param array  $conditions Array of fields for conditions
33          * @param array  $params     Array of several parameters
34          *
35          * @return boolean|array
36          *
37          * @see \Friendica\Database\DBA::select
38          */
39         public static function select(array $fields = [], array $conditions = [], array $params = [])
40         {
41                 if (empty($fields)) {
42                         $selected = self::getFields();
43                 }
44
45                 $r = DBA::select("photo", $fields, $conditions, $params);
46                 return DBA::toArray($r);
47         }
48
49         /**
50          * @brief Retrieve a single record from the photo table
51          *
52          * @param array  $fields     Array of selected fields, empty for all
53          * @param array  $conditions Array of fields for conditions
54          * @param array  $params     Array of several parameters
55          *
56          * @return bool|array
57          *
58          * @see \Friendica\Database\DBA::select
59          */
60         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
61         {
62                 if (empty($fields)) {
63                         $fields = self::getFields();
64                 }
65
66                 return DBA::selectFirst("photo", $fields, $conditions, $params);
67         }
68
69         /**
70          * @brief Get photos for user id
71          *
72          * @param integer  $uid          User id
73          * @param string   $resourceid   Rescource ID of the photo
74          * @param array    $conditions   Array of fields for conditions
75          * @param array    $params       Array of several parameters
76          *
77          * @return bool|array
78          *
79          * @see \Friendica\Database\DBA::select
80          */
81         public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = [])
82         {
83                 $conditions["resource-id"] = $resourceid;
84                 $conditions["uid"] = $uid;
85
86                 return self::select([], $conditions, $params);
87         }
88
89         /**
90          * @brief Get a photo for user id
91          *
92          * @param integer  $uid          User id
93          * @param string   $resourceid   Rescource ID of the photo
94          * @param integer  $scale        Scale of the photo. Defaults to 0
95          * @param array    $conditions   Array of fields for conditions
96          * @param array    $params       Array of several parameters
97          *
98          * @return bool|array
99          *
100          * @see \Friendica\Database\DBA::select
101          */
102         public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
103         {
104                 $conditions["resource-id"] = $resourceid;
105                 $conditions["uid"] = $uid;
106                 $conditions["scale"] = $scale;
107
108                 return self::selectFirst([], $conditions, $params);
109         }
110
111         /**
112          * @brief Get a single photo given resource id and scale
113          *
114          * This method checks for permissions. Returns associative array
115          * on success, "no sign" image info, if user has no permission,
116          * false if photo does not exists
117          *
118          * @param string  $resourceid  Rescource ID of the photo
119          * @param integer $scale       Scale of the photo. Defaults to 0
120          *
121          * @return boolean|array
122          */
123         public static function getPhoto($resourceid, $scale = 0)
124         {
125                 $r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
126                 if ($r === false) {
127                         return false;
128                 }
129
130                 $sql_acl = Security::getPermissionsSQLByUserId($r["uid"]);
131
132                 $conditions = [
133                         "`resource-id` = ? AND `scale` <= ? " . $sql_acl,
134                         $resourceid, $scale
135                 ];
136
137                 $params = ["order" => ["scale" => true]];
138
139                 $photo = self::selectFirst([], $conditions, $params);
140                 if ($photo === false) {
141                         return self::createPhotoForSystemResource("images/nosign.jpg");
142                 }
143                 return $photo;
144         }
145
146         /**
147          * @brief Check if photo with given resource id exists
148          *
149          * @param string  $resourceid  Resource ID of the photo
150          *
151          * @return boolean
152          */
153         public static function exists($resourceid)
154         {
155                 return DBA::count("photo", ["resource-id" => $resourceid]) > 0;
156         }
157
158         /**
159          * @brief Get Image object for given row id. null if row id does not exist
160          *
161          * @param integer  $id  Row id
162          *
163          * @return \Friendica\Object\Image
164          */
165         public static function getImageForPhoto($photo)
166         {
167                 $data = "";
168                 if ($photo["backend-class"] == "") {
169                         // legacy data storage in "data" column
170                         $i = self::selectFirst(["data"], ["id" => $photo["id"]]);
171                         if ($i === false) {
172                                 return null;
173                         }
174                         $data = $i["data"];
175                 } else {
176                         $backendClass = $photo["backend-class"];
177                         $backendRef = $photo["backend-ref"];
178                         $data = $backendClass::get($backendRef);
179                 }
180
181                 if ($data === "") {
182                         return null;
183                 }
184                 return new Image($data, $photo["type"]);
185         }
186
187         /**
188          * @brief Return a list of fields that are associated with the photo table
189          *
190          * @return array field list
191          */
192         private static function getFields()
193         {
194                 $allfields = DBStructure::definition(false);
195                 $fields = array_keys($allfields["photo"]["fields"]);
196                 array_splice($fields, array_search("data", $fields), 1);
197                 return $fields;
198         }
199
200         /**
201          * @brief Construct a photo array for a system resource image
202          *
203          * @param string  $filename  Image file name relative to code root
204          * @param string  $mimetype  Image mime type. Defaults to "image/jpeg"
205          *
206          * @return array
207          */
208         public static function createPhotoForSystemResource($filename, $mimetype = "image/jpeg")
209         {
210                 $fields = self::getFields();
211                 $values = array_fill(0, count($fields), "");
212                 $photo = array_combine($fields, $values);
213                 $photo["backend-class"] = \Friendica\Model\Storage\SystemResource::class;
214                 $photo["backend-ref"] = $filename;
215                 $photo["type"] = $mimetype;
216                 $photo["cacheable"] = false;
217                 return $photo;
218         }
219
220
221         /**
222          * @brief store photo metadata in db and binary in default backend
223          *
224          * @param Image   $Image     image
225          * @param integer $uid       uid
226          * @param integer $cid       cid
227          * @param integer $rid       rid
228          * @param string  $filename  filename
229          * @param string  $album     album name
230          * @param integer $scale     scale
231          * @param integer $profile   optional, default = 0
232          * @param string  $allow_cid optional, default = ""
233          * @param string  $allow_gid optional, default = ""
234          * @param string  $deny_cid  optional, default = ""
235          * @param string  $deny_gid  optional, default = ""
236          * @param string  $desc      optional, default = ""
237          *
238          * @return boolean True on success
239          */
240         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
241         {
242                 $photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
243                 if (DBA::isResult($photo)) {
244                         $guid = $photo["guid"];
245                 } else {
246                         $guid = System::createGUID();
247                 }
248
249                 $existing_photo = self::selectFirst(["id", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
250
251                 // Get defined storage backend.
252                 // if no storage backend, we use old "data" column in photo table.
253                 // if is an existing photo, reuse same backend
254                 $data = "";
255                 $backend_ref = "";
256                 $backend_class = "";
257
258                 if (DBA::isResult($existing_photo)) {
259                         $backend_ref = (string)$existing_photo["backend-ref"];
260                         $backend_class = (string)$existing_photo["backend-class"];
261                 } else {
262                         $backend_class = Config::get("storage", "class", "");
263                 }
264                 if ($backend_class === "") {
265                         $data = $Image->asString();
266                 } else {
267                         $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
268                 }
269
270
271                 $fields = [
272                         "uid" => $uid,
273                         "contact-id" => $cid,
274                         "guid" => $guid,
275                         "resource-id" => $rid,
276                         "created" => DateTimeFormat::utcNow(),
277                         "edited" => DateTimeFormat::utcNow(),
278                         "filename" => basename($filename),
279                         "type" => $Image->getType(),
280                         "album" => $album,
281                         "height" => $Image->getHeight(),
282                         "width" => $Image->getWidth(),
283                         "datasize" => strlen($Image->asString()),
284                         "data" => $data,
285                         "scale" => $scale,
286                         "profile" => $profile,
287                         "allow_cid" => $allow_cid,
288                         "allow_gid" => $allow_gid,
289                         "deny_cid" => $deny_cid,
290                         "deny_gid" => $deny_gid,
291                         "desc" => $desc,
292                         "backend-class" => $backend_class,
293                         "backend-ref" => $backend_ref
294                 ];
295
296                 if (DBA::isResult($existing_photo)) {
297                         $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
298                 } else {
299                         $r = DBA::insert("photo", $fields);
300                 }
301
302                 return $r;
303         }
304
305         public static function delete(array $conditions, $options = [])
306         {
307                 // get photo to delete data info
308                 $photos = self::select(["backend-class","backend-ref"], $conditions);
309                 
310                 foreach($photos as $photo) {
311                         $backend_class = (string)$photo["backend-class"];
312                         if ($backend_class !== "") {
313                                 $backend_class::delete($photo["backend-ref"]);
314                         }
315                 }
316
317                 return DBA::delete("photo", $conditions, $options);
318         }
319
320         /**
321          * @brief Update a photo
322          *
323          * @param array         $fields     Contains the fields that are updated
324          * @param array         $conditions Condition array with the key values
325          * @param Image         $img        Image to update. Optional, default null.
326          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
327          *
328          * @return boolean  Was the update successfull?
329          *
330          * @see \Friendica\Database\DBA::update
331          */
332         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
333         {
334                 if (!is_null($img)) {
335                         // get photo to update
336                         $photos = self::select(["backend-class","backend-ref"], $conditions);
337
338                         foreach($photos as $photo) {
339                                 $backend_class = (string)$photo["backend-class"];
340                                 if ($backend_class !== "") {
341                                         $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
342                                 } else {
343                                         $fields["data"] = $img->asString();
344                                 }
345                         }
346                 }
347
348                 $fields['updated'] = DateTimeFormat::utcNow();
349
350                 return DBA::update("photo", $fields, $conditions);
351         }
352
353         /**
354          * @param string  $image_url     Remote URL
355          * @param integer $uid           user id
356          * @param integer $cid           contact id
357          * @param boolean $quit_on_error optional, default false
358          * @return array
359          */
360         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
361         {
362                 $thumb = "";
363                 $micro = "";
364
365                 $photo = DBA::selectFirst(
366                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
367                 );
368                 if (!empty($photo['resource-id'])) {
369                         $hash = $photo["resource-id"];
370                 } else {
371                         $hash = self::newResource();
372                 }
373
374                 $photo_failure = false;
375
376                 $filename = basename($image_url);
377                 $img_str = Network::fetchUrl($image_url, true);
378
379                 if ($quit_on_error && ($img_str == "")) {
380                         return false;
381                 }
382
383                 $type = Image::guessType($image_url, true);
384                 $Image = new Image($img_str, $type);
385                 if ($Image->isValid()) {
386                         $Image->scaleToSquare(300);
387
388                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
389
390                         if ($r === false) {
391                                 $photo_failure = true;
392                         }
393
394                         $Image->scaleDown(80);
395
396                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
397
398                         if ($r === false) {
399                                 $photo_failure = true;
400                         }
401
402                         $Image->scaleDown(48);
403
404                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
405
406                         if ($r === false) {
407                                 $photo_failure = true;
408                         }
409
410                         $suffix = "?ts=" . time();
411
412                         $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
413                         $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
414                         $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
415
416                         // Remove the cached photo
417                         $a = \get_app();
418                         $basepath = $a->getBasePath();
419
420                         if (is_dir($basepath . "/photo")) {
421                                 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
422                                 if (file_exists($filename)) {
423                                         unlink($filename);
424                                 }
425                                 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
426                                 if (file_exists($filename)) {
427                                         unlink($filename);
428                                 }
429                                 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
430                                 if (file_exists($filename)) {
431                                         unlink($filename);
432                                 }
433                         }
434                 } else {
435                         $photo_failure = true;
436                 }
437
438                 if ($photo_failure && $quit_on_error) {
439                         return false;
440                 }
441
442                 if ($photo_failure) {
443                         $image_url = System::baseUrl() . "/images/person-300.jpg";
444                         $thumb = System::baseUrl() . "/images/person-80.jpg";
445                         $micro = System::baseUrl() . "/images/person-48.jpg";
446                 }
447
448                 return [$image_url, $thumb, $micro];
449         }
450
451         /**
452          * @param string $exifCoord coordinate
453          * @param string $hemi      hemi
454          * @return float
455          */
456         public static function getGps($exifCoord, $hemi)
457         {
458                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
459                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
460                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
461
462                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
463
464                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
465         }
466
467         /**
468          * @param string $coordPart coordPart
469          * @return float
470          */
471         private static function gps2Num($coordPart)
472         {
473                 $parts = explode("/", $coordPart);
474
475                 if (count($parts) <= 0) {
476                         return 0;
477                 }
478
479                 if (count($parts) == 1) {
480                         return $parts[0];
481                 }
482
483                 return floatval($parts[0]) / floatval($parts[1]);
484         }
485
486         /**
487          * @brief Fetch the photo albums that are available for a viewer
488          *
489          * The query in this function is cost intensive, so it is cached.
490          *
491          * @param int  $uid    User id of the photos
492          * @param bool $update Update the cache
493          *
494          * @return array Returns array of the photo albums
495          */
496         public static function getAlbums($uid, $update = false)
497         {
498                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
499
500                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
501                 $albums = Cache::get($key);
502                 if (is_null($albums) || $update) {
503                         if (!Config::get("system", "no_count", false)) {
504                                 /// @todo This query needs to be renewed. It is really slow
505                                 // At this time we just store the data in the cache
506                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
507                                         FROM `photo`
508                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
509                                         GROUP BY `album` ORDER BY `created` DESC",
510                                         intval($uid),
511                                         DBA::escape("Contact Photos"),
512                                         DBA::escape(L10n::t("Contact Photos"))
513                                 );
514                         } else {
515                                 // This query doesn't do the count and is much faster
516                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
517                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
518                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
519                                         intval($uid),
520                                         DBA::escape("Contact Photos"),
521                                         DBA::escape(L10n::t("Contact Photos"))
522                                 );
523                         }
524                         Cache::set($key, $albums, Cache::DAY);
525                 }
526                 return $albums;
527         }
528
529         /**
530          * @param int $uid User id of the photos
531          * @return void
532          */
533         public static function clearAlbumCache($uid)
534         {
535                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
536                 Cache::set($key, null, Cache::DAY);
537         }
538
539         /**
540          * Generate a unique photo ID.
541          *
542          * @return string
543          */
544         public static function newResource()
545         {
546                 return System::createGUID(32, false);
547         }
548 }