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 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
47 if (!DBA::isResult($c)) {
48 throw new \Friendica\Network\HTTPException\ForbiddenException();
53 $format = ($_GET['format'] ?? '') ?: 'json';
58 if ($a->argc > 1 && $a->argv[1] === '@server') {
59 // List of all servers that this server knows
60 $ret = PortableContact::serverlist();
61 header('Content-type: application/json');
62 echo json_encode($ret);
66 if ($a->argc > 1 && $a->argv[1] === '@global') {
67 // List of all profiles that this server recently had data from
69 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
71 if ($a->argc > 2 && $a->argv[2] === '@me') {
74 if ($a->argc > 3 && $a->argv[3] === '@all') {
77 if ($a->argc > 3 && $a->argv[3] === '@self') {
80 if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
81 $cid = intval($a->argv[4]);
84 if (! $system_mode && ! $global) {
85 $users = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
86 where `user`.`nickname` = '%s' limit 1",
87 DBA::escape($nickname)
89 if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
90 throw new \Friendica\Network\HTTPException\NotFoundException();
97 $sql_extra = " AND `contact`.`self` = 1 ";
103 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
105 if (!empty($_GET['updatedSince'])) {
106 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
109 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
110 DBA::escape($update_limit),
111 DBA::escape(Protocol::DFRN),
112 DBA::escape(Protocol::DIASPORA),
113 DBA::escape(Protocol::OSTATUS)
115 } elseif ($system_mode) {
116 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
117 AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
119 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
120 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
121 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
122 intval($user['uid']),
123 DBA::escape(Protocol::DFRN),
124 DBA::escape(Protocol::DIASPORA),
125 DBA::escape(Protocol::OSTATUS),
126 DBA::escape(Protocol::STATUSNET)
129 if (DBA::isResult($contacts)) {
130 $totalResults = intval($contacts[0]['total']);
134 if (!empty($_GET['startIndex'])) {
135 $startIndex = intval($_GET['startIndex']);
139 $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
142 Logger::log("Start global query", Logger::DEBUG);
143 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
144 ORDER BY `updated` DESC LIMIT %d, %d",
145 DBA::escape($update_limit),
146 DBA::escape(Protocol::DFRN),
147 DBA::escape(Protocol::DIASPORA),
148 DBA::escape(Protocol::OSTATUS),
150 intval($itemsPerPage)
152 } elseif ($system_mode) {
153 Logger::log("Start system mode query", Logger::DEBUG);
154 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
155 `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
156 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
157 FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
158 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
160 AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
162 intval($itemsPerPage)
165 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
166 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
167 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
168 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
169 intval($user['uid']),
170 DBA::escape(Protocol::DFRN),
171 DBA::escape(Protocol::DIASPORA),
172 DBA::escape(Protocol::OSTATUS),
173 DBA::escape(Protocol::STATUSNET),
175 intval($itemsPerPage)
178 Logger::log("Query done", Logger::DEBUG);
181 if (!empty($_GET['sorted'])) {
182 $ret['sorted'] = false;
184 if (!empty($_GET['filtered'])) {
185 $ret['filtered'] = false;
187 if (!empty($_GET['updatedSince']) && ! $global) {
188 $ret['updatedSince'] = false;
190 $ret['startIndex'] = (int) $startIndex;
191 $ret['itemsPerPage'] = (int) $itemsPerPage;
192 $ret['totalResults'] = (int) $totalResults;
198 'displayName' => false,
201 'preferredUsername' => false,
204 'currentLocation' => false,
208 'contactType' => false,
209 'generation' => false
212 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
213 foreach ($fields_ret as $k => $v) {
214 $fields_ret[$k] = true;
217 $fields_req = explode(',', $_GET['fields']);
218 foreach ($fields_req as $f) {
219 $fields_ret[trim($f)] = true;
223 if (is_array($contacts)) {
224 if (DBA::isResult($contacts)) {
225 foreach ($contacts as $contact) {
226 if (!isset($contact['updated'])) {
227 $contact['updated'] = '';
230 if (! isset($contact['generation'])) {
232 $contact['generation'] = 3;
233 } elseif ($system_mode) {
234 $contact['generation'] = 1;
236 $contact['generation'] = 2;
240 if (($contact['about'] == "") && isset($contact['pabout'])) {
241 $contact['about'] = $contact['pabout'];
243 if ($contact['location'] == "") {
244 if (isset($contact['plocation'])) {
245 $contact['location'] = $contact['plocation'];
247 if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
248 if ($contact['location'] != "") {
249 $contact['location'] .= ", ";
251 $contact['location'] .= $contact['pregion'];
254 if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
255 if ($contact['location'] != "") {
256 $contact['location'] .= ", ";
258 $contact['location'] .= $contact['pcountry'];
262 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
263 $contact['keywords'] = $contact['pub_keywords'];
265 if (isset($contact['account-type'])) {
266 $contact['contact-type'] = $contact['account-type'];
268 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
269 if (is_null($about)) {
270 $about = BBCode::convert($contact['about'], false);
271 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
274 // Non connected persons can only see the keywords of a Diaspora account
275 if ($contact['network'] == Protocol::DIASPORA) {
276 $contact['location'] = "";
281 if ($fields_ret['id']) {
282 $entry['id'] = (int)$contact['id'];
284 if ($fields_ret['displayName']) {
285 $entry['displayName'] = $contact['name'];
287 if ($fields_ret['aboutMe']) {
288 $entry['aboutMe'] = $about;
290 if ($fields_ret['currentLocation']) {
291 $entry['currentLocation'] = $contact['location'];
293 if ($fields_ret['generation']) {
294 $entry['generation'] = (int)$contact['generation'];
296 if ($fields_ret['urls']) {
297 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
298 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
299 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
302 if ($fields_ret['preferredUsername']) {
303 $entry['preferredUsername'] = $contact['nick'];
305 if ($fields_ret['updated']) {
307 $entry['updated'] = $contact['success_update'];
309 if ($contact['name-date'] > $entry['updated']) {
310 $entry['updated'] = $contact['name-date'];
312 if ($contact['uri-date'] > $entry['updated']) {
313 $entry['updated'] = $contact['uri-date'];
315 if ($contact['avatar-date'] > $entry['updated']) {
316 $entry['updated'] = $contact['avatar-date'];
319 $entry['updated'] = $contact['updated'];
321 $entry['updated'] = date("c", strtotime($entry['updated']));
323 if ($fields_ret['photos']) {
324 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
326 if ($fields_ret['network']) {
327 $entry['network'] = $contact['network'];
328 if ($entry['network'] == Protocol::STATUSNET) {
329 $entry['network'] = Protocol::OSTATUS;
331 if (($entry['network'] == "") && ($contact['self'])) {
332 $entry['network'] = Protocol::DFRN;
335 if ($fields_ret['tags']) {
336 $tags = str_replace(",", " ", $contact['keywords']);
337 $tags = explode(" ", $tags);
340 foreach ($tags as $tag) {
341 $tag = trim(strtolower($tag));
347 $entry['tags'] = [$cleaned];
349 if ($fields_ret['address']) {
350 $entry['address'] = [];
352 // Deactivated. It just reveals too much data. (Although its from the default profile)
353 //if (isset($rr['paddress']))
354 // $entry['address']['streetAddress'] = $rr['paddress'];
356 if (isset($contact['plocation'])) {
357 $entry['address']['locality'] = $contact['plocation'];
359 if (isset($contact['pregion'])) {
360 $entry['address']['region'] = $contact['pregion'];
363 //if (isset($rr['ppostalcode']))
364 // $entry['address']['postalCode'] = $rr['ppostalcode'];
366 if (isset($contact['pcountry'])) {
367 $entry['address']['country'] = $contact['pcountry'];
371 if ($fields_ret['contactType']) {
372 $entry['contactType'] = intval($contact['contact-type']);
374 $ret['entry'][] = $entry;
377 $ret['entry'][] = [];
380 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
383 Logger::log("End of poco", Logger::DEBUG);
385 if ($format === 'xml') {
386 header('Content-type: text/xml');
387 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
390 if ($format === 'json') {
391 header('Content-type: application/json');
392 echo json_encode($ret);
395 throw new \Friendica\Network\HTTPException\InternalServerErrorException();