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