]> git.mxchange.org Git - friendica.git/blob - mod/poco.php
Merge pull request #3088 from beardyunixer/patch-1
[friendica.git] / mod / poco.php
1 <?php
2 // See here for a documentation for portable contacts:
3 // https://web.archive.org/web/20160405005550/http://portablecontacts.net/draft-spec.html
4
5 function poco_init(App $a) {
6         require_once("include/bbcode.php");
7
8         $system_mode = false;
9
10         if(intval(get_config('system','block_public')) || (get_config('system','block_local_dir')))
11                 http_status_exit(401);
12
13
14         if($a->argc > 1) {
15                 $user = notags(trim($a->argv[1]));
16         }
17         if(! x($user)) {
18                 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
19                 if (! dbm::is_result($c)) {
20                         http_status_exit(401);
21                 }
22                 $system_mode = true;
23         }
24
25         $format = (($_GET['format']) ? $_GET['format'] : 'json');
26
27         $justme = false;
28         $global = false;
29
30         if($a->argc > 1 && $a->argv[1] === '@global') {
31                 $global = true;
32                 $update_limit = date("Y-m-d H:i:s", time() - 30 * 86400);
33         }
34         if($a->argc > 2 && $a->argv[2] === '@me')
35                 $justme = true;
36         if($a->argc > 3 && $a->argv[3] === '@all')
37                 $justme = false;
38         if($a->argc > 3 && $a->argv[3] === '@self')
39                 $justme = true;
40         if($a->argc > 4 && intval($a->argv[4]) && $justme == false)
41                 $cid = intval($a->argv[4]);
42
43
44         if(!$system_mode AND !$global) {
45                 $r = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
46                         where `user`.`nickname` = '%s' and `profile`.`is-default` = 1 limit 1",
47                         dbesc($user)
48                 );
49                 if(! dbm::is_result($r) || $r[0]['hidewall'] || $r[0]['hide-friends'])
50                         http_status_exit(404);
51
52                 $user = $r[0];
53         }
54
55         if($justme)
56                 $sql_extra = " AND `contact`.`self` = 1 ";
57 //      else
58 //              $sql_extra = " AND `contact`.`self` = 0 ";
59
60         if($cid)
61                 $sql_extra = sprintf(" AND `contact`.`id` = %d ",intval($cid));
62
63         if(x($_GET,'updatedSince'))
64                 $update_limit =  date("Y-m-d H:i:s",strtotime($_GET['updatedSince']));
65
66         if ($global) {
67                 $r = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
68                         dbesc($update_limit),
69                         dbesc(NETWORK_DFRN),
70                         dbesc(NETWORK_DIASPORA),
71                         dbesc(NETWORK_OSTATUS)
72                 );
73         } elseif($system_mode) {
74                 $r = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
75                         AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
76         } else {
77                 $r = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
78                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
79                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
80                         intval($user['uid']),
81                         dbesc(NETWORK_DFRN),
82                         dbesc(NETWORK_DIASPORA),
83                         dbesc(NETWORK_OSTATUS),
84                         dbesc(NETWORK_STATUSNET)
85                 );
86         }
87         if (dbm::is_result($r))
88                 $totalResults = intval($r[0]['total']);
89         else
90                 $totalResults = 0;
91
92         $startIndex = intval($_GET['startIndex']);
93         if(! $startIndex)
94                 $startIndex = 0;
95         $itemsPerPage = ((x($_GET,'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults);
96
97         if ($global) {
98                 logger("Start global query", LOGGER_DEBUG);
99                 $r = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
100                         ORDER BY `updated` DESC LIMIT %d, %d",
101                         dbesc($update_limit),
102                         dbesc(NETWORK_DFRN),
103                         dbesc(NETWORK_DIASPORA),
104                         dbesc(NETWORK_OSTATUS),
105                         intval($startIndex),
106                         intval($itemsPerPage)
107                 );
108         } elseif($system_mode) {
109                 logger("Start system mode query", LOGGER_DEBUG);
110                 $r = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
111                                 `profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
112                                 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
113                         FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
114                                 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
115                         WHERE `self` = 1 AND `profile`.`is-default`
116                         AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
117                         intval($startIndex),
118                         intval($itemsPerPage)
119                 );
120         } else {
121                 logger("Start query for user ".$user['nickname'], LOGGER_DEBUG);
122                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
123                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
124                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
125                         intval($user['uid']),
126                         dbesc(NETWORK_DFRN),
127                         dbesc(NETWORK_DIASPORA),
128                         dbesc(NETWORK_OSTATUS),
129                         dbesc(NETWORK_STATUSNET),
130                         intval($startIndex),
131                         intval($itemsPerPage)
132                 );
133         }
134         logger("Query done", LOGGER_DEBUG);
135
136         $ret = array();
137         if(x($_GET,'sorted'))
138                 $ret['sorted'] = false;
139         if(x($_GET,'filtered'))
140                 $ret['filtered'] = false;
141         if(x($_GET,'updatedSince') AND !$global)
142                 $ret['updatedSince'] = false;
143
144         $ret['startIndex']   = (int) $startIndex;
145         $ret['itemsPerPage'] = (int) $itemsPerPage;
146         $ret['totalResults'] = (int) $totalResults;
147         $ret['entry']        = array();
148
149
150         $fields_ret = array(
151                 'id' => false,
152                 'displayName' => false,
153                 'urls' => false,
154                 'updated' => false,
155                 'preferredUsername' => false,
156                 'photos' => false,
157                 'aboutMe' => false,
158                 'currentLocation' => false,
159                 'network' => false,
160                 'gender' => false,
161                 'tags' => false,
162                 'address' => false,
163                 'contactType' => false,
164                 'generation' => false
165         );
166
167         if((! x($_GET,'fields')) || ($_GET['fields'] === '@all'))
168                 foreach($fields_ret as $k => $v)
169                         $fields_ret[$k] = true;
170         else {
171                 $fields_req = explode(',',$_GET['fields']);
172                 foreach($fields_req as $f)
173                         $fields_ret[trim($f)] = true;
174         }
175
176         if(is_array($r)) {
177                 if (dbm::is_result($r)) {
178                         foreach ($r as $rr) {
179                                 if (!isset($rr['generation'])) {
180                                         if ($global)
181                                                 $rr['generation'] = 3;
182                                         elseif ($system_mode)
183                                                 $rr['generation'] = 1;
184                                         else
185                                                 $rr['generation'] = 2;
186                                 }
187
188                                 if (($rr['about'] == "") AND isset($rr['pabout']))
189                                         $rr['about'] = $rr['pabout'];
190
191                                 if ($rr['location'] == "") {
192                                         if (isset($rr['plocation']))
193                                                 $rr['location'] = $rr['plocation'];
194
195                                         if (isset($rr['pregion']) AND ($rr['pregion'] != "")) {
196                                                 if ($rr['location'] != "")
197                                                         $rr['location'] .= ", ";
198
199                                                 $rr['location'] .= $rr['pregion'];
200                                         }
201
202                                         if (isset($rr['pcountry']) AND ($rr['pcountry'] != "")) {
203                                                 if ($rr['location'] != "")
204                                                         $rr['location'] .= ", ";
205
206                                                 $rr['location'] .= $rr['pcountry'];
207                                         }
208                                 }
209
210                                 if (($rr['gender'] == "") AND isset($rr['pgender']))
211                                         $rr['gender'] = $rr['pgender'];
212
213                                 if (($rr['keywords'] == "") AND isset($rr['pub_keywords']))
214                                         $rr['keywords'] = $rr['pub_keywords'];
215
216                                 if (isset($rr['account-type']))
217                                         $rr['contact-type'] = $rr['account-type'];
218
219                                 $about = Cache::get("about:".$rr['updated'].":".$rr['nurl']);
220                                 if (is_null($about)) {
221                                         $about = bbcode($rr['about'], false, false);
222                                         Cache::set("about:".$rr['updated'].":".$rr['nurl'],$about);
223                                 }
224
225                                 // Non connected persons can only see the keywords of a Diaspora account
226                                 if ($rr['network'] == NETWORK_DIASPORA) {
227                                         $rr['location'] = "";
228                                         $about = "";
229                                         $rr['gender'] = "";
230                                 }
231
232                                 $entry = array();
233                                 if($fields_ret['id'])
234                                         $entry['id'] = (int)$rr['id'];
235                                 if($fields_ret['displayName'])
236                                         $entry['displayName'] = $rr['name'];
237                                 if($fields_ret['aboutMe'])
238                                         $entry['aboutMe'] = $about;
239                                 if($fields_ret['currentLocation'])
240                                         $entry['currentLocation'] = $rr['location'];
241                                 if($fields_ret['gender'])
242                                         $entry['gender'] = $rr['gender'];
243                                 if($fields_ret['generation'])
244                                         $entry['generation'] = (int)$rr['generation'];
245                                 if($fields_ret['urls']) {
246                                         $entry['urls'] = array(array('value' => $rr['url'], 'type' => 'profile'));
247                                         if($rr['addr'] && ($rr['network'] !== NETWORK_MAIL))
248                                                 $entry['urls'][] = array('value' => 'acct:' . $rr['addr'], 'type' => 'webfinger');
249                                 }
250                                 if($fields_ret['preferredUsername'])
251                                         $entry['preferredUsername'] = $rr['nick'];
252                                 if($fields_ret['updated']) {
253                                         if (!$global) {
254                                                 $entry['updated'] = $rr['success_update'];
255
256                                                 if ($rr['name-date'] > $entry['updated'])
257                                                         $entry['updated'] = $rr['name-date'];
258
259                                                 if ($rr['uri-date'] > $entry['updated'])
260                                                         $entry['updated'] = $rr['uri-date'];
261
262                                                 if ($rr['avatar-date'] > $entry['updated'])
263                                                         $entry['updated'] = $rr['avatar-date'];
264                                         } else
265                                                 $entry['updated'] = $rr['updated'];
266
267                                         $entry['updated'] = date("c", strtotime($entry['updated']));
268                                 }
269                                 if($fields_ret['photos'])
270                                         $entry['photos'] = array(array('value' => $rr['photo'], 'type' => 'profile'));
271                                 if($fields_ret['network']) {
272                                         $entry['network'] = $rr['network'];
273                                         if ($entry['network'] == NETWORK_STATUSNET)
274                                                 $entry['network'] = NETWORK_OSTATUS;
275                                         if (($entry['network'] == "") AND ($rr['self']))
276                                                 $entry['network'] = NETWORK_DFRN;
277                                 }
278                                 if($fields_ret['tags']) {
279                                         $tags = str_replace(","," ",$rr['keywords']);
280                                         $tags = explode(" ", $tags);
281
282                                         $cleaned = array();
283                                         foreach ($tags as $tag) {
284                                                 $tag = trim(strtolower($tag));
285                                                 if ($tag != "")
286                                                         $cleaned[] = $tag;
287                                         }
288
289                                         $entry['tags'] = array($cleaned);
290                                 }
291                                 if($fields_ret['address']) {
292                                         $entry['address'] = array();
293
294                                         // Deactivated. It just reveals too much data. (Although its from the default profile)
295                                         //if (isset($rr['paddress']))
296                                         //       $entry['address']['streetAddress'] = $rr['paddress'];
297
298                                         if (isset($rr['plocation']))
299                                                  $entry['address']['locality'] = $rr['plocation'];
300
301                                         if (isset($rr['pregion']))
302                                                  $entry['address']['region'] = $rr['pregion'];
303
304                                         // See above
305                                         //if (isset($rr['ppostalcode']))
306                                         //       $entry['address']['postalCode'] = $rr['ppostalcode'];
307
308                                         if (isset($rr['pcountry']))
309                                                  $entry['address']['country'] = $rr['pcountry'];
310                                 }
311
312                                 if($fields_ret['contactType'])
313                                         $entry['contactType'] = intval($rr['contact-type']);
314
315                                 $ret['entry'][] = $entry;
316                         }
317                 }
318                 else
319                         $ret['entry'][] = array();
320         }
321         else
322                 http_status_exit(500);
323
324         logger("End of poco", LOGGER_DEBUG);
325
326         if($format === 'xml') {
327                 header('Content-type: text/xml');
328                 echo replace_macros(get_markup_template('poco_xml.tpl'),array_xmlify(array('$response' => $ret)));
329                 killme();
330         }
331         if($format === 'json') {
332                 header('Content-type: application/json');
333                 echo json_encode($ret);
334                 killme();
335         }
336         else
337                 http_status_exit(500);
338
339
340 }