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::selectFirst('owner-view', ['uid', 'nickname'], ['nickname' => $nickname, 'hide-friends' => false]);
85 if (!DBA::isResult($user)) {
86 throw new \Friendica\Network\HTTPException\NotFoundException();
91 $sql_extra = " AND `contact`.`self` = 1 ";
97 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
99 if (!empty($_GET['updatedSince'])) {
100 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
103 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
104 DBA::escape($update_limit),
105 DBA::escape(Protocol::DFRN),
106 DBA::escape(Protocol::DIASPORA),
107 DBA::escape(Protocol::OSTATUS)
109 } elseif ($system_mode) {
110 $totalResults = DBA::count('profile', ['net-publish' => true]);
112 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
113 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
114 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
115 intval($user['uid']),
116 DBA::escape(Protocol::DFRN),
117 DBA::escape(Protocol::DIASPORA),
118 DBA::escape(Protocol::OSTATUS),
119 DBA::escape(Protocol::STATUSNET)
122 if (empty($totalResults) && DBA::isResult($contacts)) {
123 $totalResults = intval($contacts[0]['total']);
124 } elseif (empty($totalResults)) {
127 if (!empty($_GET['startIndex'])) {
128 $startIndex = intval($_GET['startIndex']);
132 $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
135 Logger::log("Start global query", Logger::DEBUG);
136 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
137 ORDER BY `updated` DESC LIMIT %d, %d",
138 DBA::escape($update_limit),
139 DBA::escape(Protocol::DFRN),
140 DBA::escape(Protocol::DIASPORA),
141 DBA::escape(Protocol::OSTATUS),
143 intval($itemsPerPage)
145 } elseif ($system_mode) {
146 Logger::log("Start system mode query", Logger::DEBUG);
147 $contacts = DBA::selectToArray('owner-view', [], ['net-publish' => true], ['limit' => [$startIndex, $itemsPerPage]]);
149 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
150 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
151 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
152 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
153 intval($user['uid']),
154 DBA::escape(Protocol::DFRN),
155 DBA::escape(Protocol::DIASPORA),
156 DBA::escape(Protocol::OSTATUS),
157 DBA::escape(Protocol::STATUSNET),
159 intval($itemsPerPage)
162 Logger::log("Query done", Logger::DEBUG);
165 if (!empty($_GET['sorted'])) {
166 $ret['sorted'] = false;
168 if (!empty($_GET['filtered'])) {
169 $ret['filtered'] = false;
171 if (!empty($_GET['updatedSince']) && ! $global) {
172 $ret['updatedSince'] = false;
174 $ret['startIndex'] = (int) $startIndex;
175 $ret['itemsPerPage'] = (int) $itemsPerPage;
176 $ret['totalResults'] = (int) $totalResults;
182 'displayName' => false,
185 'preferredUsername' => false,
188 'currentLocation' => false,
192 'contactType' => false,
193 'generation' => false
196 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
197 foreach ($fields_ret as $k => $v) {
198 $fields_ret[$k] = true;
201 $fields_req = explode(',', $_GET['fields']);
202 foreach ($fields_req as $f) {
203 $fields_ret[trim($f)] = true;
207 if (is_array($contacts)) {
208 if (DBA::isResult($contacts)) {
209 foreach ($contacts as $contact) {
210 if (!isset($contact['updated'])) {
211 $contact['updated'] = '';
214 if (! isset($contact['generation'])) {
216 $contact['generation'] = 3;
217 } elseif ($system_mode) {
218 $contact['generation'] = 1;
220 $contact['generation'] = 2;
224 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
225 $contact['keywords'] = $contact['pub_keywords'];
227 if (isset($contact['account-type'])) {
228 $contact['contact-type'] = $contact['account-type'];
230 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
231 if (is_null($about)) {
232 $about = BBCode::convert($contact['about'], false);
233 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
236 // Non connected persons can only see the keywords of a Diaspora account
237 if ($contact['network'] == Protocol::DIASPORA) {
238 $contact['location'] = "";
243 if ($fields_ret['id']) {
244 $entry['id'] = (int)$contact['id'];
246 if ($fields_ret['displayName']) {
247 $entry['displayName'] = $contact['name'];
249 if ($fields_ret['aboutMe']) {
250 $entry['aboutMe'] = $about;
252 if ($fields_ret['currentLocation']) {
253 $entry['currentLocation'] = $contact['location'];
255 if ($fields_ret['generation']) {
256 $entry['generation'] = (int)$contact['generation'];
258 if ($fields_ret['urls']) {
259 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
260 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
261 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
264 if ($fields_ret['preferredUsername']) {
265 $entry['preferredUsername'] = $contact['nick'];
267 if ($fields_ret['updated']) {
269 $entry['updated'] = $contact['success_update'];
271 if ($contact['name-date'] > $entry['updated']) {
272 $entry['updated'] = $contact['name-date'];
274 if ($contact['uri-date'] > $entry['updated']) {
275 $entry['updated'] = $contact['uri-date'];
277 if ($contact['avatar-date'] > $entry['updated']) {
278 $entry['updated'] = $contact['avatar-date'];
281 $entry['updated'] = $contact['updated'];
283 $entry['updated'] = date("c", strtotime($entry['updated']));
285 if ($fields_ret['photos']) {
286 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
288 if ($fields_ret['network']) {
289 $entry['network'] = $contact['network'];
290 if ($entry['network'] == Protocol::STATUSNET) {
291 $entry['network'] = Protocol::OSTATUS;
293 if (($entry['network'] == "") && ($contact['self'])) {
294 $entry['network'] = Protocol::DFRN;
297 if ($fields_ret['tags']) {
298 $tags = str_replace(",", " ", $contact['keywords']);
299 $tags = explode(" ", $tags);
302 foreach ($tags as $tag) {
303 $tag = trim(strtolower($tag));
309 $entry['tags'] = [$cleaned];
311 if ($fields_ret['address']) {
312 $entry['address'] = [];
314 // Deactivated. It just reveals too much data. (Although its from the default profile)
315 //if (isset($rr['address']))
316 // $entry['address']['streetAddress'] = $rr['address'];
318 if (isset($contact['locality'])) {
319 $entry['address']['locality'] = $contact['locality'];
321 if (isset($contact['region'])) {
322 $entry['address']['region'] = $contact['region'];
325 //if (isset($rr['postal-code']))
326 // $entry['address']['postalCode'] = $rr['postal-code'];
328 if (isset($contact['country'])) {
329 $entry['address']['country'] = $contact['country'];
333 if ($fields_ret['contactType']) {
334 $entry['contactType'] = intval($contact['contact-type']);
336 $ret['entry'][] = $entry;
339 $ret['entry'][] = [];
342 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
345 Logger::log("End of poco", Logger::DEBUG);
347 if ($format === 'xml') {
348 header('Content-type: text/xml');
349 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
352 if ($format === 'json') {
353 header('Content-type: application/json');
354 echo json_encode($ret);
357 throw new \Friendica\Network\HTTPException\InternalServerErrorException();