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