3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
20 * @see https://web.archive.org/web/20160405005550/http://portablecontacts.net/draft-spec.html
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;
30 use Friendica\Protocol\PortableContact;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Strings;
33 use Friendica\Util\XML;
35 function poco_init(App $a) {
38 if (intval(DI::config()->get('system', 'block_public')) || (DI::config()->get('system', 'block_local_dir'))) {
39 throw new \Friendica\Network\HTTPException\ForbiddenException();
43 $nickname = Strings::escapeTags(trim($a->argv[1]));
45 if (empty($nickname)) {
46 if (!DBA::exists('profile', ['net-publish' => true])) {
47 throw new \Friendica\Network\HTTPException\ForbiddenException();
52 $format = ($_GET['format'] ?? '') ?: 'json';
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);
65 if ($a->argc > 1 && $a->argv[1] === '@global') {
66 // List of all profiles that this server recently had data from
68 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
70 if ($a->argc > 2 && $a->argv[2] === '@me') {
73 if ($a->argc > 3 && $a->argv[3] === '@all') {
76 if ($a->argc > 3 && $a->argv[3] === '@self') {
79 if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
80 $cid = intval($a->argv[4]);
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`",
88 if (!DBA::isResult($user)) {
89 throw new \Friendica\Network\HTTPException\NotFoundException();
94 $sql_extra = " AND `contact`.`self` = 1 ";
100 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
102 if (!empty($_GET['updatedSince'])) {
103 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
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)
112 } elseif ($system_mode) {
113 $totalResults = DBA::count('profile', ['net-publish' => true]);
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)
125 if (empty($totalResults) && DBA::isResult($contacts)) {
126 $totalResults = intval($contacts[0]['total']);
127 } elseif (empty($totalResults)) {
130 if (!empty($_GET['startIndex'])) {
131 $startIndex = intval($_GET['startIndex']);
135 $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
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),
146 intval($itemsPerPage)
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`
158 intval($itemsPerPage)
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),
171 intval($itemsPerPage)
174 Logger::log("Query done", Logger::DEBUG);
177 if (!empty($_GET['sorted'])) {
178 $ret['sorted'] = false;
180 if (!empty($_GET['filtered'])) {
181 $ret['filtered'] = false;
183 if (!empty($_GET['updatedSince']) && ! $global) {
184 $ret['updatedSince'] = false;
186 $ret['startIndex'] = (int) $startIndex;
187 $ret['itemsPerPage'] = (int) $itemsPerPage;
188 $ret['totalResults'] = (int) $totalResults;
194 'displayName' => false,
197 'preferredUsername' => false,
200 'currentLocation' => false,
204 'contactType' => false,
205 'generation' => false
208 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
209 foreach ($fields_ret as $k => $v) {
210 $fields_ret[$k] = true;
213 $fields_req = explode(',', $_GET['fields']);
214 foreach ($fields_req as $f) {
215 $fields_ret[trim($f)] = true;
219 if (is_array($contacts)) {
220 if (DBA::isResult($contacts)) {
221 foreach ($contacts as $contact) {
222 if (!isset($contact['updated'])) {
223 $contact['updated'] = '';
226 if (! isset($contact['generation'])) {
228 $contact['generation'] = 3;
229 } elseif ($system_mode) {
230 $contact['generation'] = 1;
232 $contact['generation'] = 2;
236 if (($contact['about'] == "") && isset($contact['pabout'])) {
237 $contact['about'] = $contact['pabout'];
239 if ($contact['location'] == "") {
240 if (isset($contact['plocation'])) {
241 $contact['location'] = $contact['plocation'];
243 if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
244 if ($contact['location'] != "") {
245 $contact['location'] .= ", ";
247 $contact['location'] .= $contact['pregion'];
250 if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
251 if ($contact['location'] != "") {
252 $contact['location'] .= ", ";
254 $contact['location'] .= $contact['pcountry'];
258 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
259 $contact['keywords'] = $contact['pub_keywords'];
261 if (isset($contact['account-type'])) {
262 $contact['contact-type'] = $contact['account-type'];
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);
270 // Non connected persons can only see the keywords of a Diaspora account
271 if ($contact['network'] == Protocol::DIASPORA) {
272 $contact['location'] = "";
277 if ($fields_ret['id']) {
278 $entry['id'] = (int)$contact['id'];
280 if ($fields_ret['displayName']) {
281 $entry['displayName'] = $contact['name'];
283 if ($fields_ret['aboutMe']) {
284 $entry['aboutMe'] = $about;
286 if ($fields_ret['currentLocation']) {
287 $entry['currentLocation'] = $contact['location'];
289 if ($fields_ret['generation']) {
290 $entry['generation'] = (int)$contact['generation'];
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'];
298 if ($fields_ret['preferredUsername']) {
299 $entry['preferredUsername'] = $contact['nick'];
301 if ($fields_ret['updated']) {
303 $entry['updated'] = $contact['success_update'];
305 if ($contact['name-date'] > $entry['updated']) {
306 $entry['updated'] = $contact['name-date'];
308 if ($contact['uri-date'] > $entry['updated']) {
309 $entry['updated'] = $contact['uri-date'];
311 if ($contact['avatar-date'] > $entry['updated']) {
312 $entry['updated'] = $contact['avatar-date'];
315 $entry['updated'] = $contact['updated'];
317 $entry['updated'] = date("c", strtotime($entry['updated']));
319 if ($fields_ret['photos']) {
320 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
322 if ($fields_ret['network']) {
323 $entry['network'] = $contact['network'];
324 if ($entry['network'] == Protocol::STATUSNET) {
325 $entry['network'] = Protocol::OSTATUS;
327 if (($entry['network'] == "") && ($contact['self'])) {
328 $entry['network'] = Protocol::DFRN;
331 if ($fields_ret['tags']) {
332 $tags = str_replace(",", " ", $contact['keywords']);
333 $tags = explode(" ", $tags);
336 foreach ($tags as $tag) {
337 $tag = trim(strtolower($tag));
343 $entry['tags'] = [$cleaned];
345 if ($fields_ret['address']) {
346 $entry['address'] = [];
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'];
352 if (isset($contact['plocation'])) {
353 $entry['address']['locality'] = $contact['plocation'];
355 if (isset($contact['pregion'])) {
356 $entry['address']['region'] = $contact['pregion'];
359 //if (isset($rr['ppostalcode']))
360 // $entry['address']['postalCode'] = $rr['ppostalcode'];
362 if (isset($contact['pcountry'])) {
363 $entry['address']['country'] = $contact['pcountry'];
367 if ($fields_ret['contactType']) {
368 $entry['contactType'] = intval($contact['contact-type']);
370 $ret['entry'][] = $entry;
373 $ret['entry'][] = [];
376 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
379 Logger::log("End of poco", Logger::DEBUG);
381 if ($format === 'xml') {
382 header('Content-type: text/xml');
383 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
386 if ($format === 'json') {
387 header('Content-type: application/json');
388 echo json_encode($ret);
391 throw new \Friendica\Network\HTTPException\InternalServerErrorException();