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