]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Refactor namespaces
[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                         $selected = 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                 $data = "";
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                 $backend_class = "";
272
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                 if ($backend_class === "") {
280                         $data = $Image->asString();
281                 } else {
282                         $backend_ref = $backend_class::put($Image->asString(), $backend_ref);
283                 }
284
285
286                 $fields = [
287                         "uid" => $uid,
288                         "contact-id" => $cid,
289                         "guid" => $guid,
290                         "resource-id" => $rid,
291                         "created" => $created,
292                         "edited" => DateTimeFormat::utcNow(),
293                         "filename" => basename($filename),
294                         "type" => $Image->getType(),
295                         "album" => $album,
296                         "height" => $Image->getHeight(),
297                         "width" => $Image->getWidth(),
298                         "datasize" => strlen($Image->asString()),
299                         "data" => $data,
300                         "scale" => $scale,
301                         "profile" => $profile,
302                         "allow_cid" => $allow_cid,
303                         "allow_gid" => $allow_gid,
304                         "deny_cid" => $deny_cid,
305                         "deny_gid" => $deny_gid,
306                         "desc" => $desc,
307                         "backend-class" => $backend_class,
308                         "backend-ref" => $backend_ref
309                 ];
310
311                 if (DBA::isResult($existing_photo)) {
312                         $r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
313                 } else {
314                         $r = DBA::insert("photo", $fields);
315                 }
316
317                 return $r;
318         }
319
320
321         /**
322          * @brief Delete info from table and data from storage
323          *
324          * @param array $conditions Field condition(s)
325          * @param array $options    Options array, Optional
326          *
327          * @return boolean
328          *
329          * @throws \Exception
330          * @see   \Friendica\Database\DBA::delete
331          */
332         public static function delete(array $conditions, array $options = [])
333         {
334                 // get photo to delete data info
335                 $photos = self::select(["backend-class","backend-ref"], $conditions);
336
337                 foreach($photos as $photo) {
338                         $backend_class = (string)$photo["backend-class"];
339                         if ($backend_class !== "") {
340                                 $backend_class::delete($photo["backend-ref"]);
341                         }
342                 }
343
344                 return DBA::delete("photo", $conditions, $options);
345         }
346
347         /**
348          * @brief Update a photo
349          *
350          * @param array         $fields     Contains the fields that are updated
351          * @param array         $conditions Condition array with the key values
352          * @param Image         $img        Image to update. Optional, default null.
353          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
354          *
355          * @return boolean  Was the update successfull?
356          *
357          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
358          * @see   \Friendica\Database\DBA::update
359          */
360         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
361         {
362                 if (!is_null($img)) {
363                         // get photo to update
364                         $photos = self::select(["backend-class","backend-ref"], $conditions);
365
366                         foreach($photos as $photo) {
367                                 $backend_class = (string)$photo["backend-class"];
368                                 if ($backend_class !== "") {
369                                         $fields["backend-ref"] = $backend_class::put($img->asString(), $photo["backend-ref"]);
370                                 } else {
371                                         $fields["data"] = $img->asString();
372                                 }
373                         }
374                         $fields['updated'] = DateTimeFormat::utcNow();
375                 }
376
377                 $fields['edited'] = DateTimeFormat::utcNow();
378
379                 return DBA::update("photo", $fields, $conditions, $old_fields);
380         }
381
382         /**
383          * @param string  $image_url     Remote URL
384          * @param integer $uid           user id
385          * @param integer $cid           contact id
386          * @param boolean $quit_on_error optional, default false
387          * @return array
388          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389          * @throws \ImagickException
390          */
391         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
392         {
393                 $thumb = "";
394                 $micro = "";
395
396                 $photo = DBA::selectFirst(
397                         "photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "album" => "Contact Photos"]
398                 );
399                 if (!empty($photo['resource-id'])) {
400                         $hash = $photo["resource-id"];
401                 } else {
402                         $hash = self::newResource();
403                 }
404
405                 $photo_failure = false;
406
407                 $filename = basename($image_url);
408                 $img_str = Network::fetchUrl($image_url, true);
409
410                 if ($quit_on_error && ($img_str == "")) {
411                         return false;
412                 }
413
414                 $type = Image::guessType($image_url, true);
415                 $Image = new Image($img_str, $type);
416                 if ($Image->isValid()) {
417                         $Image->scaleToSquare(300);
418
419                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 4);
420
421                         if ($r === false) {
422                                 $photo_failure = true;
423                         }
424
425                         $Image->scaleDown(80);
426
427                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 5);
428
429                         if ($r === false) {
430                                 $photo_failure = true;
431                         }
432
433                         $Image->scaleDown(48);
434
435                         $r = self::store($Image, $uid, $cid, $hash, $filename, "Contact Photos", 6);
436
437                         if ($r === false) {
438                                 $photo_failure = true;
439                         }
440
441                         $suffix = "?ts=" . time();
442
443                         $image_url = System::baseUrl() . "/photo/" . $hash . "-4." . $Image->getExt() . $suffix;
444                         $thumb = System::baseUrl() . "/photo/" . $hash . "-5." . $Image->getExt() . $suffix;
445                         $micro = System::baseUrl() . "/photo/" . $hash . "-6." . $Image->getExt() . $suffix;
446
447                         // Remove the cached photo
448                         $a = \get_app();
449                         $basepath = $a->getBasePath();
450
451                         if (is_dir($basepath . "/photo")) {
452                                 $filename = $basepath . "/photo/" . $hash . "-4." . $Image->getExt();
453                                 if (file_exists($filename)) {
454                                         unlink($filename);
455                                 }
456                                 $filename = $basepath . "/photo/" . $hash . "-5." . $Image->getExt();
457                                 if (file_exists($filename)) {
458                                         unlink($filename);
459                                 }
460                                 $filename = $basepath . "/photo/" . $hash . "-6." . $Image->getExt();
461                                 if (file_exists($filename)) {
462                                         unlink($filename);
463                                 }
464                         }
465                 } else {
466                         $photo_failure = true;
467                 }
468
469                 if ($photo_failure && $quit_on_error) {
470                         return false;
471                 }
472
473                 if ($photo_failure) {
474                         $image_url = System::baseUrl() . "/images/person-300.jpg";
475                         $thumb = System::baseUrl() . "/images/person-80.jpg";
476                         $micro = System::baseUrl() . "/images/person-48.jpg";
477                 }
478
479                 return [$image_url, $thumb, $micro];
480         }
481
482         /**
483          * @param string $exifCoord coordinate
484          * @param string $hemi      hemi
485          * @return float
486          */
487         public static function getGps($exifCoord, $hemi)
488         {
489                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
490                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
491                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
492
493                 $flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
494
495                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
496         }
497
498         /**
499          * @param string $coordPart coordPart
500          * @return float
501          */
502         private static function gps2Num($coordPart)
503         {
504                 $parts = explode("/", $coordPart);
505
506                 if (count($parts) <= 0) {
507                         return 0;
508                 }
509
510                 if (count($parts) == 1) {
511                         return $parts[0];
512                 }
513
514                 return floatval($parts[0]) / floatval($parts[1]);
515         }
516
517         /**
518          * @brief Fetch the photo albums that are available for a viewer
519          *
520          * The query in this function is cost intensive, so it is cached.
521          *
522          * @param int  $uid    User id of the photos
523          * @param bool $update Update the cache
524          *
525          * @return array Returns array of the photo albums
526          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527          */
528         public static function getAlbums($uid, $update = false)
529         {
530                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
531
532                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
533                 $albums = Cache::get($key);
534                 if (is_null($albums) || $update) {
535                         if (!Config::get("system", "no_count", false)) {
536                                 /// @todo This query needs to be renewed. It is really slow
537                                 // At this time we just store the data in the cache
538                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
539                                         FROM `photo`
540                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
541                                         GROUP BY `album` ORDER BY `created` DESC",
542                                         intval($uid),
543                                         DBA::escape("Contact Photos"),
544                                         DBA::escape(L10n::t("Contact Photos"))
545                                 );
546                         } else {
547                                 // This query doesn't do the count and is much faster
548                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
549                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
550                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
551                                         intval($uid),
552                                         DBA::escape("Contact Photos"),
553                                         DBA::escape(L10n::t("Contact Photos"))
554                                 );
555                         }
556                         Cache::set($key, $albums, Cache::DAY);
557                 }
558                 return $albums;
559         }
560
561         /**
562          * @param int $uid User id of the photos
563          * @return void
564          * @throws \Exception
565          */
566         public static function clearAlbumCache($uid)
567         {
568                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
569                 Cache::set($key, null, Cache::DAY);
570         }
571
572         /**
573          * Generate a unique photo ID.
574          *
575          * @return string
576          * @throws \Exception
577          */
578         public static function newResource()
579         {
580                 return System::createGUID(32, false);
581         }
582 }