3 // See here for a documentation for portable contacts:
4 // https://web.archive.org/web/20160405005550/http://portablecontacts.net/draft-spec.html
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Logger;
10 use Friendica\Core\Protocol;
11 use Friendica\Core\Renderer;
12 use Friendica\Database\DBA;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Strings;
17 use Friendica\Util\XML;
19 function poco_init(App $a) {
22 if (intval(DI::config()->get('system', 'block_public')) || (DI::config()->get('system', 'block_local_dir'))) {
23 throw new \Friendica\Network\HTTPException\ForbiddenException();
27 $nickname = Strings::escapeTags(trim($a->argv[1]));
29 if (empty($nickname)) {
30 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
31 if (!DBA::isResult($c)) {
32 throw new \Friendica\Network\HTTPException\ForbiddenException();
37 $format = ($_GET['format'] ?? '') ?: 'json';
42 if ($a->argc > 1 && $a->argv[1] === '@server') {
43 // List of all servers that this server knows
44 $ret = PortableContact::serverlist();
45 header('Content-type: application/json');
46 echo json_encode($ret);
50 if ($a->argc > 1 && $a->argv[1] === '@global') {
51 // List of all profiles that this server recently had data from
53 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
55 if ($a->argc > 2 && $a->argv[2] === '@me') {
58 if ($a->argc > 3 && $a->argv[3] === '@all') {
61 if ($a->argc > 3 && $a->argv[3] === '@self') {
64 if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
65 $cid = intval($a->argv[4]);
68 if (! $system_mode && ! $global) {
69 $users = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
70 where `user`.`nickname` = '%s' limit 1",
71 DBA::escape($nickname)
73 if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
74 throw new \Friendica\Network\HTTPException\NotFoundException();
81 $sql_extra = " AND `contact`.`self` = 1 ";
87 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
89 if (!empty($_GET['updatedSince'])) {
90 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
93 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
94 DBA::escape($update_limit),
95 DBA::escape(Protocol::DFRN),
96 DBA::escape(Protocol::DIASPORA),
97 DBA::escape(Protocol::OSTATUS)
99 } elseif ($system_mode) {
100 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
101 AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
103 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
104 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
105 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
106 intval($user['uid']),
107 DBA::escape(Protocol::DFRN),
108 DBA::escape(Protocol::DIASPORA),
109 DBA::escape(Protocol::OSTATUS),
110 DBA::escape(Protocol::STATUSNET)
113 if (DBA::isResult($contacts)) {
114 $totalResults = intval($contacts[0]['total']);
118 if (!empty($_GET['startIndex'])) {
119 $startIndex = intval($_GET['startIndex']);
123 $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
126 Logger::log("Start global query", Logger::DEBUG);
127 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
128 ORDER BY `updated` DESC LIMIT %d, %d",
129 DBA::escape($update_limit),
130 DBA::escape(Protocol::DFRN),
131 DBA::escape(Protocol::DIASPORA),
132 DBA::escape(Protocol::OSTATUS),
134 intval($itemsPerPage)
136 } elseif ($system_mode) {
137 Logger::log("Start system mode query", Logger::DEBUG);
138 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
139 `profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
140 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
141 FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
142 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
144 AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
146 intval($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,
193 'contactType' => false,
194 'generation' => false
197 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
198 foreach ($fields_ret as $k => $v) {
199 $fields_ret[$k] = true;
202 $fields_req = explode(',', $_GET['fields']);
203 foreach ($fields_req as $f) {
204 $fields_ret[trim($f)] = true;
208 if (is_array($contacts)) {
209 if (DBA::isResult($contacts)) {
210 foreach ($contacts as $contact) {
211 if (!isset($contact['updated'])) {
212 $contact['updated'] = '';
215 if (! isset($contact['generation'])) {
217 $contact['generation'] = 3;
218 } elseif ($system_mode) {
219 $contact['generation'] = 1;
221 $contact['generation'] = 2;
225 if (($contact['about'] == "") && isset($contact['pabout'])) {
226 $contact['about'] = $contact['pabout'];
228 if ($contact['location'] == "") {
229 if (isset($contact['plocation'])) {
230 $contact['location'] = $contact['plocation'];
232 if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
233 if ($contact['location'] != "") {
234 $contact['location'] .= ", ";
236 $contact['location'] .= $contact['pregion'];
239 if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
240 if ($contact['location'] != "") {
241 $contact['location'] .= ", ";
243 $contact['location'] .= $contact['pcountry'];
247 if (($contact['gender'] == "") && isset($contact['pgender'])) {
248 $contact['gender'] = $contact['pgender'];
250 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
251 $contact['keywords'] = $contact['pub_keywords'];
253 if (isset($contact['account-type'])) {
254 $contact['contact-type'] = $contact['account-type'];
256 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
257 if (is_null($about)) {
258 $about = BBCode::convert($contact['about'], false);
259 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
262 // Non connected persons can only see the keywords of a Diaspora account
263 if ($contact['network'] == Protocol::DIASPORA) {
264 $contact['location'] = "";
266 $contact['gender'] = "";
270 if ($fields_ret['id']) {
271 $entry['id'] = (int)$contact['id'];
273 if ($fields_ret['displayName']) {
274 $entry['displayName'] = $contact['name'];
276 if ($fields_ret['aboutMe']) {
277 $entry['aboutMe'] = $about;
279 if ($fields_ret['currentLocation']) {
280 $entry['currentLocation'] = $contact['location'];
282 if ($fields_ret['gender']) {
283 $entry['gender'] = $contact['gender'];
285 if ($fields_ret['generation']) {
286 $entry['generation'] = (int)$contact['generation'];
288 if ($fields_ret['urls']) {
289 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
290 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
291 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
294 if ($fields_ret['preferredUsername']) {
295 $entry['preferredUsername'] = $contact['nick'];
297 if ($fields_ret['updated']) {
299 $entry['updated'] = $contact['success_update'];
301 if ($contact['name-date'] > $entry['updated']) {
302 $entry['updated'] = $contact['name-date'];
304 if ($contact['uri-date'] > $entry['updated']) {
305 $entry['updated'] = $contact['uri-date'];
307 if ($contact['avatar-date'] > $entry['updated']) {
308 $entry['updated'] = $contact['avatar-date'];
311 $entry['updated'] = $contact['updated'];
313 $entry['updated'] = date("c", strtotime($entry['updated']));
315 if ($fields_ret['photos']) {
316 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
318 if ($fields_ret['network']) {
319 $entry['network'] = $contact['network'];
320 if ($entry['network'] == Protocol::STATUSNET) {
321 $entry['network'] = Protocol::OSTATUS;
323 if (($entry['network'] == "") && ($contact['self'])) {
324 $entry['network'] = Protocol::DFRN;
327 if ($fields_ret['tags']) {
328 $tags = str_replace(",", " ", $contact['keywords']);
329 $tags = explode(" ", $tags);
332 foreach ($tags as $tag) {
333 $tag = trim(strtolower($tag));
339 $entry['tags'] = [$cleaned];
341 if ($fields_ret['address']) {
342 $entry['address'] = [];
344 // Deactivated. It just reveals too much data. (Although its from the default profile)
345 //if (isset($rr['paddress']))
346 // $entry['address']['streetAddress'] = $rr['paddress'];
348 if (isset($contact['plocation'])) {
349 $entry['address']['locality'] = $contact['plocation'];
351 if (isset($contact['pregion'])) {
352 $entry['address']['region'] = $contact['pregion'];
355 //if (isset($rr['ppostalcode']))
356 // $entry['address']['postalCode'] = $rr['ppostalcode'];
358 if (isset($contact['pcountry'])) {
359 $entry['address']['country'] = $contact['pcountry'];
363 if ($fields_ret['contactType']) {
364 $entry['contactType'] = intval($contact['contact-type']);
366 $ret['entry'][] = $entry;
369 $ret['entry'][] = [];
372 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
375 Logger::log("End of poco", Logger::DEBUG);
377 if ($format === 'xml') {
378 header('Content-type: text/xml');
379 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
382 if ($format === 'json') {
383 header('Content-type: application/json');
384 echo json_encode($ret);
387 throw new \Friendica\Network\HTTPException\InternalServerErrorException();