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