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