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