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