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