]> git.mxchange.org Git - friendica.git/blob - src/Model/Photo.php
Merge pull request #4339 from zeroadam/feature/Network
[friendica.git] / src / Model / Photo.php
1 <?php
2 /**
3  * @file src/Model/Photo.php
4  * @brief This file contains the Photo class for database interface
5  */
6 namespace Friendica\Model;
7
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Object\Image;
15 use Friendica\Util\Network;
16 use dba;
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 (DBM::is_result($photo)) {
45                         $guid = $photo['guid'];
46                 } else {
47                         $guid = get_guid();
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' => datetime_convert(),
58                         'edited' => datetime_convert(),
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 (DBM::is_result($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                 $photo = dba::selectFirst(
94                         'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos']
95                 );
96                 if (x($photo['resource-id'])) {
97                         $hash = $photo['resource-id'];
98                 } else {
99                         $hash = photo_new_resource();
100                 }
101
102                 $photo_failure = false;
103
104                 $filename = basename($image_url);
105                 $img_str = Network::fetchUrl($image_url, true);
106
107                 if ($quit_on_error && ($img_str == "")) {
108                         return false;
109                 }
110
111                 $type = Image::guessType($image_url, true);
112                 $Image = new Image($img_str, $type);
113                 if ($Image->isValid()) {
114                         $Image->scaleToSquare(175);
115
116                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 4);
117
118                         if ($r === false) {
119                                 $photo_failure = true;
120                         }
121
122                         $Image->scaleDown(80);
123
124                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 5);
125
126                         if ($r === false) {
127                                 $photo_failure = true;
128                         }
129
130                         $Image->scaleDown(48);
131
132                         $r = self::store($Image, $uid, $cid, $hash, $filename, 'Contact Photos', 6);
133
134                         if ($r === false) {
135                                 $photo_failure = true;
136                         }
137
138                         $suffix = '?ts=' . time();
139
140                         $image_url = System::baseUrl() . '/photo/' . $hash . '-4.' . $Image->getExt() . $suffix;
141                         $thumb = System::baseUrl() . '/photo/' . $hash . '-5.' . $Image->getExt() . $suffix;
142                         $micro = System::baseUrl() . '/photo/' . $hash . '-6.' . $Image->getExt() . $suffix;
143
144                         // Remove the cached photo
145                         $a = get_app();
146                         $basepath = $a->get_basepath();
147
148                         if (is_dir($basepath . "/photo")) {
149                                 $filename = $basepath . '/photo/' . $hash . '-4.' . $Image->getExt();
150                                 if (file_exists($filename)) {
151                                         unlink($filename);
152                                 }
153                                 $filename = $basepath . '/photo/' . $hash . '-5.' . $Image->getExt();
154                                 if (file_exists($filename)) {
155                                         unlink($filename);
156                                 }
157                                 $filename = $basepath . '/photo/' . $hash . '-6.' . $Image->getExt();
158                                 if (file_exists($filename)) {
159                                         unlink($filename);
160                                 }
161                         }
162                 } else {
163                         $photo_failure = true;
164                 }
165
166                 if ($photo_failure && $quit_on_error) {
167                         return false;
168                 }
169
170                 if ($photo_failure) {
171                         $image_url = System::baseUrl() . '/images/person-175.jpg';
172                         $thumb = System::baseUrl() . '/images/person-80.jpg';
173                         $micro = System::baseUrl() . '/images/person-48.jpg';
174                 }
175
176                 return [$image_url, $thumb, $micro];
177         }
178
179         /**
180          * @param string $exifCoord coordinate
181          * @param string $hemi      hemi
182          * @return float
183          */
184         public static function getGps($exifCoord, $hemi)
185         {
186                 $degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
187                 $minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
188                 $seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
189
190                 $flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
191
192                 return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
193         }
194
195         /**
196          * @param string $coordPart coordPart
197          * @return float
198          */
199         private static function gps2Num($coordPart)
200         {
201                 $parts = explode('/', $coordPart);
202
203                 if (count($parts) <= 0) {
204                         return 0;
205                 }
206
207                 if (count($parts) == 1) {
208                         return $parts[0];
209                 }
210
211                 return floatval($parts[0]) / floatval($parts[1]);
212         }
213
214         /**
215          * @brief Fetch the photo albums that are available for a viewer
216          *
217          * The query in this function is cost intensive, so it is cached.
218          *
219          * @param int  $uid    User id of the photos
220          * @param bool $update Update the cache
221          *
222          * @return array Returns array of the photo albums
223          */
224         public static function getAlbums($uid, $update = false)
225         {
226                 $sql_extra = permissions_sql($uid);
227
228                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
229                 $albums = Cache::get($key);
230                 if (is_null($albums) || $update) {
231                         if (!Config::get('system', 'no_count', false)) {
232                                 /// @todo This query needs to be renewed. It is really slow
233                                 // At this time we just store the data in the cache
234                                 $albums = q("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
235                                         FROM `photo`
236                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra
237                                         GROUP BY `album` ORDER BY `created` DESC",
238                                         intval($uid),
239                                         dbesc('Contact Photos'),
240                                         dbesc(L10n::t('Contact Photos'))
241                                 );
242                         } else {
243                                 // This query doesn't do the count and is much faster
244                                 $albums = q("SELECT DISTINCT(`album`), '' AS `total`
245                                         FROM `photo` USE INDEX (`uid_album_scale_created`)
246                                         WHERE `uid` = %d  AND `album` != '%s' AND `album` != '%s' $sql_extra",
247                                         intval($uid),
248                                         dbesc('Contact Photos'),
249                                         dbesc(L10n::t('Contact Photos'))
250                                 );
251                         }
252                         Cache::set($key, $albums, CACHE_DAY);
253                 }
254                 return $albums;
255         }
256
257         /**
258          * @param int $uid User id of the photos
259          * @return void
260          */
261         public static function clearAlbumCache($uid)
262         {
263                 $key = "photo_albums:".$uid.":".local_user().":".remote_user();
264                 Cache::set($key, null, CACHE_DAY);
265         }
266 }