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