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