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