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\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
17 use Friendica\Protocol\PortableContact;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Strings;
20 use Friendica\Util\XML;
22 function poco_init(App $a) {
25 if (intval(Config::get('system', 'block_public')) || (Config::get('system', 'block_local_dir'))) {
26 throw new \Friendica\Network\HTTPException\ForbiddenException();
30 $nickname = Strings::escapeTags(trim($a->argv[1]));
32 if (empty($nickname)) {
33 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
34 if (!DBA::isResult($c)) {
35 throw new \Friendica\Network\HTTPException\ForbiddenException();
40 $format = ($_GET['format'] ?? '') ?: 'json';
45 if ($a->argc > 1 && $a->argv[1] === '@server') {
46 // List of all servers that this server knows
47 $ret = PortableContact::serverlist();
48 header('Content-type: application/json');
49 echo json_encode($ret);
53 if ($a->argc > 1 && $a->argv[1] === '@global') {
54 // List of all profiles that this server recently had data from
56 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
58 if ($a->argc > 2 && $a->argv[2] === '@me') {
61 if ($a->argc > 3 && $a->argv[3] === '@all') {
64 if ($a->argc > 3 && $a->argv[3] === '@self') {
67 if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
68 $cid = intval($a->argv[4]);
71 if (! $system_mode && ! $global) {
72 $users = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
73 where `user`.`nickname` = '%s' and `profile`.`is-default` = 1 limit 1",
74 DBA::escape($nickname)
76 if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
77 throw new \Friendica\Network\HTTPException\NotFoundException();
84 $sql_extra = " AND `contact`.`self` = 1 ";
90 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
92 if (!empty($_GET['updatedSince'])) {
93 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
96 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
97 DBA::escape($update_limit),
98 DBA::escape(Protocol::DFRN),
99 DBA::escape(Protocol::DIASPORA),
100 DBA::escape(Protocol::OSTATUS)
102 } elseif ($system_mode) {
103 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
104 AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
106 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
107 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
108 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
109 intval($user['uid']),
110 DBA::escape(Protocol::DFRN),
111 DBA::escape(Protocol::DIASPORA),
112 DBA::escape(Protocol::OSTATUS),
113 DBA::escape(Protocol::STATUSNET)
116 if (DBA::isResult($contacts)) {
117 $totalResults = intval($contacts[0]['total']);
121 if (!empty($_GET['startIndex'])) {
122 $startIndex = intval($_GET['startIndex']);
126 $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
129 Logger::log("Start global query", Logger::DEBUG);
130 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
131 ORDER BY `updated` DESC LIMIT %d, %d",
132 DBA::escape($update_limit),
133 DBA::escape(Protocol::DFRN),
134 DBA::escape(Protocol::DIASPORA),
135 DBA::escape(Protocol::OSTATUS),
137 intval($itemsPerPage)
139 } elseif ($system_mode) {
140 Logger::log("Start system mode query", Logger::DEBUG);
141 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
142 `profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
143 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
144 FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
145 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
146 WHERE `self` = 1 AND `profile`.`is-default`
147 AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
149 intval($itemsPerPage)
152 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
153 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
154 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
155 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
156 intval($user['uid']),
157 DBA::escape(Protocol::DFRN),
158 DBA::escape(Protocol::DIASPORA),
159 DBA::escape(Protocol::OSTATUS),
160 DBA::escape(Protocol::STATUSNET),
162 intval($itemsPerPage)
165 Logger::log("Query done", Logger::DEBUG);
168 if (!empty($_GET['sorted'])) {
169 $ret['sorted'] = false;
171 if (!empty($_GET['filtered'])) {
172 $ret['filtered'] = false;
174 if (!empty($_GET['updatedSince']) && ! $global) {
175 $ret['updatedSince'] = false;
177 $ret['startIndex'] = (int) $startIndex;
178 $ret['itemsPerPage'] = (int) $itemsPerPage;
179 $ret['totalResults'] = (int) $totalResults;
185 'displayName' => false,
188 'preferredUsername' => false,
191 'currentLocation' => false,
196 'contactType' => false,
197 'generation' => false
200 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
201 foreach ($fields_ret as $k => $v) {
202 $fields_ret[$k] = true;
205 $fields_req = explode(',', $_GET['fields']);
206 foreach ($fields_req as $f) {
207 $fields_ret[trim($f)] = true;
211 if (is_array($contacts)) {
212 if (DBA::isResult($contacts)) {
213 foreach ($contacts as $contact) {
214 if (!isset($contact['updated'])) {
215 $contact['updated'] = '';
218 if (! isset($contact['generation'])) {
220 $contact['generation'] = 3;
221 } elseif ($system_mode) {
222 $contact['generation'] = 1;
224 $contact['generation'] = 2;
228 if (($contact['about'] == "") && isset($contact['pabout'])) {
229 $contact['about'] = $contact['pabout'];
231 if ($contact['location'] == "") {
232 if (isset($contact['plocation'])) {
233 $contact['location'] = $contact['plocation'];
235 if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
236 if ($contact['location'] != "") {
237 $contact['location'] .= ", ";
239 $contact['location'] .= $contact['pregion'];
242 if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
243 if ($contact['location'] != "") {
244 $contact['location'] .= ", ";
246 $contact['location'] .= $contact['pcountry'];
250 if (($contact['gender'] == "") && isset($contact['pgender'])) {
251 $contact['gender'] = $contact['pgender'];
253 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
254 $contact['keywords'] = $contact['pub_keywords'];
256 if (isset($contact['account-type'])) {
257 $contact['contact-type'] = $contact['account-type'];
259 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
260 if (is_null($about)) {
261 $about = BBCode::convert($contact['about'], false);
262 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
265 // Non connected persons can only see the keywords of a Diaspora account
266 if ($contact['network'] == Protocol::DIASPORA) {
267 $contact['location'] = "";
269 $contact['gender'] = "";
273 if ($fields_ret['id']) {
274 $entry['id'] = (int)$contact['id'];
276 if ($fields_ret['displayName']) {
277 $entry['displayName'] = $contact['name'];
279 if ($fields_ret['aboutMe']) {
280 $entry['aboutMe'] = $about;
282 if ($fields_ret['currentLocation']) {
283 $entry['currentLocation'] = $contact['location'];
285 if ($fields_ret['gender']) {
286 $entry['gender'] = $contact['gender'];
288 if ($fields_ret['generation']) {
289 $entry['generation'] = (int)$contact['generation'];
291 if ($fields_ret['urls']) {
292 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
293 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
294 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
297 if ($fields_ret['preferredUsername']) {
298 $entry['preferredUsername'] = $contact['nick'];
300 if ($fields_ret['updated']) {
302 $entry['updated'] = $contact['success_update'];
304 if ($contact['name-date'] > $entry['updated']) {
305 $entry['updated'] = $contact['name-date'];
307 if ($contact['uri-date'] > $entry['updated']) {
308 $entry['updated'] = $contact['uri-date'];
310 if ($contact['avatar-date'] > $entry['updated']) {
311 $entry['updated'] = $contact['avatar-date'];
314 $entry['updated'] = $contact['updated'];
316 $entry['updated'] = date("c", strtotime($entry['updated']));
318 if ($fields_ret['photos']) {
319 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
321 if ($fields_ret['network']) {
322 $entry['network'] = $contact['network'];
323 if ($entry['network'] == Protocol::STATUSNET) {
324 $entry['network'] = Protocol::OSTATUS;
326 if (($entry['network'] == "") && ($contact['self'])) {
327 $entry['network'] = Protocol::DFRN;
330 if ($fields_ret['tags']) {
331 $tags = str_replace(",", " ", $contact['keywords']);
332 $tags = explode(" ", $tags);
335 foreach ($tags as $tag) {
336 $tag = trim(strtolower($tag));
342 $entry['tags'] = [$cleaned];
344 if ($fields_ret['address']) {
345 $entry['address'] = [];
347 // Deactivated. It just reveals too much data. (Although its from the default profile)
348 //if (isset($rr['paddress']))
349 // $entry['address']['streetAddress'] = $rr['paddress'];
351 if (isset($contact['plocation'])) {
352 $entry['address']['locality'] = $contact['plocation'];
354 if (isset($contact['pregion'])) {
355 $entry['address']['region'] = $contact['pregion'];
358 //if (isset($rr['ppostalcode']))
359 // $entry['address']['postalCode'] = $rr['ppostalcode'];
361 if (isset($contact['pcountry'])) {
362 $entry['address']['country'] = $contact['pcountry'];
366 if ($fields_ret['contactType']) {
367 $entry['contactType'] = intval($contact['contact-type']);
369 $ret['entry'][] = $entry;
372 $ret['entry'][] = [];
375 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
378 Logger::log("End of poco", Logger::DEBUG);
380 if ($format === 'xml') {
381 header('Content-type: text/xml');
382 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
385 if ($format === 'json') {
386 header('Content-type: application/json');
387 echo json_encode($ret);
390 throw new \Friendica\Network\HTTPException\InternalServerErrorException();