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