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