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