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