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