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