]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Merge branch '2019.01-rc' into bug/6334-escape-get-app
[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\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Object\Image;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Network;
17 use Friendica\Util\Security;
18
19 /**
20  * Class to handle photo dabatase table
21  */
22 class Photo
23 {
24         /**
25          * @param Image   $Image     image
26          * @param integer $uid       uid
27          * @param integer $cid       cid
28          * @param integer $rid       rid
29          * @param string  $filename  filename
30          * @param string  $album     album name
31          * @param integer $scale     scale
32          * @param integer $profile   optional, default = 0
33          * @param string  $allow_cid optional, default = ''
34          * @param string  $allow_gid optional, default = ''
35          * @param string  $deny_cid  optional, default = ''
36          * @param string  $deny_gid  optional, default = ''
37          * @param string  $desc      optional, default = ''
38          * @return object
39          */
40         public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '')
41         {
42                 $photo = DBA::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
43                 if (DBA::isResult($photo)) {
44                         $guid = $photo['guid'];
45                 } else {
46                         $guid = System::createGUID();
47                 }
48
49                 $existing_photo = DBA::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
50
51                 $fields = [
52                         'uid' => $uid,
53                         'contact-id' => $cid,
54                         'guid' => $guid,
55                         'resource-id' => $rid,
56                         'created' => DateTimeFormat::utcNow(),
57                         'edited' => DateTimeFormat::utcNow(),
58                         'filename' => basename($filename),
59                         'type' => $Image->getType(),
60                         'album' => $album,
61                         'height' => $Image->getHeight(),
62                         'width' => $Image->getWidth(),
63                         'datasize' => strlen($Image->asString()),
64                         'data' => $Image->asString(),
65                         'scale' => $scale,
66                         'profile' => $profile,
67                         'allow_cid' => $allow_cid,
68                         'allow_gid' => $allow_gid,
69                         'deny_cid' => $deny_cid,
70                         'deny_gid' => $deny_gid,
71                         'desc' => $desc
72                 ];
73
74                 if (DBA::isResult($existing_photo)) {
75                         $r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
76                 } else {
77                         $r = DBA::insert('photo', $fields);
78                 }
79
80                 return $r;
81         }
82
83         /**
84          * @param string  $image_url     Remote URL
85          * @param integer $uid           user id
86          * @param integer $cid           contact id
87          * @param boolean $quit_on_error optional, default false
88          * @return array
89          */
90         public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
91         {
92                 $thumb = '';
93                 $micro = '';
94
95                 $photo = DBA::selectFirst(
96                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
97                 );
98                 if (!empty($photo['resource-id'])) {
99                         $hash = $photo['resource-id'];
100                 } else {
101                         $hash = self::newResource();
102                 }
103
104                 $photo_failure = false;
105
106                 $filename = basename($image_url);
107                 $img_str = Network::fetchUrl($image_url, true);
108
109                 if ($quit_on_error && ($img_str == "")) {
110                         return false;
111                 }
112
113                 $type = Image::guessType($image_url, true);
114                 $Image = new Image($img_str, $type);
115                 if ($Image->isValid()) {
116                         $Image->scaleToSquare(300);
117
118                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
119
120                         if ($r === false) {
121                                 $photo_failure = true;
122                         }
123
124                         $Image->scaleDown(80);
125
126                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
127
128                         if ($r === false) {
129                                 $photo_failure = true;
130                         }
131
132                         $Image->scaleDown(48);
133
134                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
135
136                         if ($r === false) {
137                                 $photo_failure = true;
138                         }
139
140                         $suffix = '?ts=' . time();
141
142                         $image_url = System::baseUrl() . '/photo/' . $hash . '-4.' . $Image->getExt() . $suffix;
143                         $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $Image->getExt() . $suffix;
144                         $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $Image->getExt() . $suffix;
145
146                         // Remove the cached photo
147                         $a = \get_app();
148                         $basepath = $a->getBasePath();
149
150                         if (is_dir($basepath . "/photo")) {
151                                 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
152                                 if (file_exists($filename)) {
153                                         unlink($filename);
154                                 }
155                                 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
156                                 if (file_exists($filename)) {
157                                         unlink($filename);
158                                 }
159                                 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
160                                 if (file_exists($filename)) {
161                                         unlink($filename);
162                                 }
163                         }
164                 } else {
165                         $photo_failure = true;
166                 }
167
168                 if ($photo_failure && $quit_on_error) {
169                         return false;
170                 }
171
172                 if ($photo_failure) {
173                         $image_url = System::baseUrl() . '/images/person-300.jpg';
174                         $thumb = System::baseUrl() . '/images/person-80.jpg';
175                         $micro = System::baseUrl() . '/images/person-48.jpg';
176                 }
177
178                 return [$image_url, $thumb, $micro];
179         }
180
181         /**
182          * @param string $exifCoord coordinate
183          * @param string $hemi      hemi
184          * @return float
185          */
186         public static function getGps($exifCoord, $hemi)
187         {
188                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
189                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
190                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
191
192                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
193
194                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
195         }
196
197         /**
198          * @param string $coordPart coordPart
199          * @return float
200          */
201         private static function gps2Num($coordPart)
202         {
203                 $parts = explode('/', $coordPart);
204
205                 if (count($parts) <= 0) {
206                         return 0;
207                 }
208
209                 if (count($parts) == 1) {
210                         return $parts[0];
211                 }
212
213                 return floatval($parts[0]) / floatval($parts[1]);
214         }
215
216         /**
217          * @brief Fetch the photo albums that are available for a viewer
218          *
219          * The query in this function is cost intensive, so it is cached.
220          *
221          * @param int  $uid    User id of the photos
222          * @param bool $update Update the cache
223          *
224          * @return array Returns array of the photo albums
225          */
226         public static function getAlbums($uid, $update = false)
227         {
228                 $sql_extra = Security::getPermissionsSQLByUserId($uid);
229
230                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
231                 $albums = Cache::get($key);
232                 if (is_null($albums) || $update) {
233                         if (!Config::get('system', 'no_count', false)) {
234                                 /// @todo This query needs to be renewed. It is really slow
235                                 // At this time we just store the data in the cache
236                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
237                                         FROM `photo`
238                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
239                                         GROUP BY `album` ORDER BY `created` DESC",
240                                         intval($uid),
241                                         DBA::escape('Contact Photos'),
242                                         DBA::escape(L10n::t('Contact Photos'))
243                                 );
244                         } else {
245                                 // This query doesn't do the count and is much faster
246                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
247                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
248                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
249                                         intval($uid),
250                                         DBA::escape('Contact Photos'),
251                                         DBA::escape(L10n::t('Contact Photos'))
252                                 );
253                         }
254                         Cache::set($key, $albums, Cache::DAY);
255                 }
256                 return $albums;
257         }
258
259         /**
260          * @param int $uid User id of the photos
261          * @return void
262          */
263         public static function clearAlbumCache($uid)
264         {
265                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
266                 Cache::set($key, null, Cache::DAY);
267         }
268
269         /**
270          * Generate a unique photo ID.
271          *
272          * @return string
273          */
274         public static function newResource()
275         {
276                 return system::createGUID(32, false);
277         }
278 }