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