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`.`gender` AS `pgender`, `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,
209 'contactType' => false,
210 'generation' => false
213 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
214 foreach ($fields_ret as $k => $v) {
215 $fields_ret[$k] = true;
218 $fields_req = explode(',', $_GET['fields']);
219 foreach ($fields_req as $f) {
220 $fields_ret[trim($f)] = true;
224 if (is_array($contacts)) {
225 if (DBA::isResult($contacts)) {
226 foreach ($contacts as $contact) {
227 if (!isset($contact['updated'])) {
228 $contact['updated'] = '';
231 if (! isset($contact['generation'])) {
233 $contact['generation'] = 3;
234 } elseif ($system_mode) {
235 $contact['generation'] = 1;
237 $contact['generation'] = 2;
241 if (($contact['about'] == "") && isset($contact['pabout'])) {
242 $contact['about'] = $contact['pabout'];
244 if ($contact['location'] == "") {
245 if (isset($contact['plocation'])) {
246 $contact['location'] = $contact['plocation'];
248 if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
249 if ($contact['location'] != "") {
250 $contact['location'] .= ", ";
252 $contact['location'] .= $contact['pregion'];
255 if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
256 if ($contact['location'] != "") {
257 $contact['location'] .= ", ";
259 $contact['location'] .= $contact['pcountry'];
263 if (($contact['gender'] == "") && isset($contact['pgender'])) {
264 $contact['gender'] = $contact['pgender'];
266 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
267 $contact['keywords'] = $contact['pub_keywords'];
269 if (isset($contact['account-type'])) {
270 $contact['contact-type'] = $contact['account-type'];
272 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
273 if (is_null($about)) {
274 $about = BBCode::convert($contact['about'], false);
275 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
278 // Non connected persons can only see the keywords of a Diaspora account
279 if ($contact['network'] == Protocol::DIASPORA) {
280 $contact['location'] = "";
282 $contact['gender'] = "";
286 if ($fields_ret['id']) {
287 $entry['id'] = (int)$contact['id'];
289 if ($fields_ret['displayName']) {
290 $entry['displayName'] = $contact['name'];
292 if ($fields_ret['aboutMe']) {
293 $entry['aboutMe'] = $about;
295 if ($fields_ret['currentLocation']) {
296 $entry['currentLocation'] = $contact['location'];
298 if ($fields_ret['gender']) {
299 $entry['gender'] = $contact['gender'];
301 if ($fields_ret['generation']) {
302 $entry['generation'] = (int)$contact['generation'];
304 if ($fields_ret['urls']) {
305 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
306 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
307 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
310 if ($fields_ret['preferredUsername']) {
311 $entry['preferredUsername'] = $contact['nick'];
313 if ($fields_ret['updated']) {
315 $entry['updated'] = $contact['success_update'];
317 if ($contact['name-date'] > $entry['updated']) {
318 $entry['updated'] = $contact['name-date'];
320 if ($contact['uri-date'] > $entry['updated']) {
321 $entry['updated'] = $contact['uri-date'];
323 if ($contact['avatar-date'] > $entry['updated']) {
324 $entry['updated'] = $contact['avatar-date'];
327 $entry['updated'] = $contact['updated'];
329 $entry['updated'] = date("c", strtotime($entry['updated']));
331 if ($fields_ret['photos']) {
332 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
334 if ($fields_ret['network']) {
335 $entry['network'] = $contact['network'];
336 if ($entry['network'] == Protocol::STATUSNET) {
337 $entry['network'] = Protocol::OSTATUS;
339 if (($entry['network'] == "") && ($contact['self'])) {
340 $entry['network'] = Protocol::DFRN;
343 if ($fields_ret['tags']) {
344 $tags = str_replace(",", " ", $contact['keywords']);
345 $tags = explode(" ", $tags);
348 foreach ($tags as $tag) {
349 $tag = trim(strtolower($tag));
355 $entry['tags'] = [$cleaned];
357 if ($fields_ret['address']) {
358 $entry['address'] = [];
360 // Deactivated. It just reveals too much data. (Although its from the default profile)
361 //if (isset($rr['paddress']))
362 // $entry['address']['streetAddress'] = $rr['paddress'];
364 if (isset($contact['plocation'])) {
365 $entry['address']['locality'] = $contact['plocation'];
367 if (isset($contact['pregion'])) {
368 $entry['address']['region'] = $contact['pregion'];
371 //if (isset($rr['ppostalcode']))
372 // $entry['address']['postalCode'] = $rr['ppostalcode'];
374 if (isset($contact['pcountry'])) {
375 $entry['address']['country'] = $contact['pcountry'];
379 if ($fields_ret['contactType']) {
380 $entry['contactType'] = intval($contact['contact-type']);
382 $ret['entry'][] = $entry;
385 $ret['entry'][] = [];
388 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
391 Logger::log("End of poco", Logger::DEBUG);
393 if ($format === 'xml') {
394 header('Content-type: text/xml');
395 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
398 if ($format === 'json') {
399 header('Content-type: application/json');
400 echo json_encode($ret);
403 throw new \Friendica\Network\HTTPException\InternalServerErrorException();