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