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