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