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