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\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\Renderer;
13 use Friendica\Database\DBA;
15 use Friendica\Protocol\PortableContact;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Strings;
18 use Friendica\Util\XML;
20 function poco_init(App $a) {
23 if (intval(Config::get('system', 'block_public')) || (Config::get('system', 'block_local_dir'))) {
24 throw new \Friendica\Network\HTTPException\ForbiddenException();
28 $nickname = Strings::escapeTags(trim($a->argv[1]));
30 if (empty($nickname)) {
31 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
32 if (!DBA::isResult($c)) {
33 throw new \Friendica\Network\HTTPException\ForbiddenException();
38 $format = ($_GET['format'] ?? '') ?: 'json';
43 if ($a->argc > 1 && $a->argv[1] === '@server') {
44 // List of all servers that this server knows
45 $ret = PortableContact::serverlist();
46 header('Content-type: application/json');
47 echo json_encode($ret);
51 if ($a->argc > 1 && $a->argv[1] === '@global') {
52 // List of all profiles that this server recently had data from
54 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
56 if ($a->argc > 2 && $a->argv[2] === '@me') {
59 if ($a->argc > 3 && $a->argv[3] === '@all') {
62 if ($a->argc > 3 && $a->argv[3] === '@self') {
65 if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
66 $cid = intval($a->argv[4]);
69 if (! $system_mode && ! $global) {
70 $users = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
71 where `user`.`nickname` = '%s' and `profile`.`is-default` = 1 limit 1",
72 DBA::escape($nickname)
74 if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
75 throw new \Friendica\Network\HTTPException\NotFoundException();
82 $sql_extra = " AND `contact`.`self` = 1 ";
88 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
90 if (!empty($_GET['updatedSince'])) {
91 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
94 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
95 DBA::escape($update_limit),
96 DBA::escape(Protocol::DFRN),
97 DBA::escape(Protocol::DIASPORA),
98 DBA::escape(Protocol::OSTATUS)
100 } elseif ($system_mode) {
101 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
102 AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
104 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
105 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
106 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
107 intval($user['uid']),
108 DBA::escape(Protocol::DFRN),
109 DBA::escape(Protocol::DIASPORA),
110 DBA::escape(Protocol::OSTATUS),
111 DBA::escape(Protocol::STATUSNET)
114 if (DBA::isResult($contacts)) {
115 $totalResults = intval($contacts[0]['total']);
119 if (!empty($_GET['startIndex'])) {
120 $startIndex = intval($_GET['startIndex']);
124 $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
127 Logger::log("Start global query", Logger::DEBUG);
128 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
129 ORDER BY `updated` DESC LIMIT %d, %d",
130 DBA::escape($update_limit),
131 DBA::escape(Protocol::DFRN),
132 DBA::escape(Protocol::DIASPORA),
133 DBA::escape(Protocol::OSTATUS),
135 intval($itemsPerPage)
137 } elseif ($system_mode) {
138 Logger::log("Start system mode query", Logger::DEBUG);
139 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
140 `profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
141 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
142 FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
143 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
144 WHERE `self` = 1 AND `profile`.`is-default`
145 AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
147 intval($itemsPerPage)
150 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
151 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
152 AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
153 AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
154 intval($user['uid']),
155 DBA::escape(Protocol::DFRN),
156 DBA::escape(Protocol::DIASPORA),
157 DBA::escape(Protocol::OSTATUS),
158 DBA::escape(Protocol::STATUSNET),
160 intval($itemsPerPage)
163 Logger::log("Query done", Logger::DEBUG);
166 if (!empty($_GET['sorted'])) {
167 $ret['sorted'] = false;
169 if (!empty($_GET['filtered'])) {
170 $ret['filtered'] = false;
172 if (!empty($_GET['updatedSince']) && ! $global) {
173 $ret['updatedSince'] = false;
175 $ret['startIndex'] = (int) $startIndex;
176 $ret['itemsPerPage'] = (int) $itemsPerPage;
177 $ret['totalResults'] = (int) $totalResults;
183 'displayName' => false,
186 'preferredUsername' => false,
189 'currentLocation' => false,
194 'contactType' => false,
195 'generation' => false
198 if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
199 foreach ($fields_ret as $k => $v) {
200 $fields_ret[$k] = true;
203 $fields_req = explode(',', $_GET['fields']);
204 foreach ($fields_req as $f) {
205 $fields_ret[trim($f)] = true;
209 if (is_array($contacts)) {
210 if (DBA::isResult($contacts)) {
211 foreach ($contacts as $contact) {
212 if (!isset($contact['updated'])) {
213 $contact['updated'] = '';
216 if (! isset($contact['generation'])) {
218 $contact['generation'] = 3;
219 } elseif ($system_mode) {
220 $contact['generation'] = 1;
222 $contact['generation'] = 2;
226 if (($contact['about'] == "") && isset($contact['pabout'])) {
227 $contact['about'] = $contact['pabout'];
229 if ($contact['location'] == "") {
230 if (isset($contact['plocation'])) {
231 $contact['location'] = $contact['plocation'];
233 if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
234 if ($contact['location'] != "") {
235 $contact['location'] .= ", ";
237 $contact['location'] .= $contact['pregion'];
240 if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
241 if ($contact['location'] != "") {
242 $contact['location'] .= ", ";
244 $contact['location'] .= $contact['pcountry'];
248 if (($contact['gender'] == "") && isset($contact['pgender'])) {
249 $contact['gender'] = $contact['pgender'];
251 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
252 $contact['keywords'] = $contact['pub_keywords'];
254 if (isset($contact['account-type'])) {
255 $contact['contact-type'] = $contact['account-type'];
257 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
258 if (is_null($about)) {
259 $about = BBCode::convert($contact['about'], false);
260 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
263 // Non connected persons can only see the keywords of a Diaspora account
264 if ($contact['network'] == Protocol::DIASPORA) {
265 $contact['location'] = "";
267 $contact['gender'] = "";
271 if ($fields_ret['id']) {
272 $entry['id'] = (int)$contact['id'];
274 if ($fields_ret['displayName']) {
275 $entry['displayName'] = $contact['name'];
277 if ($fields_ret['aboutMe']) {
278 $entry['aboutMe'] = $about;
280 if ($fields_ret['currentLocation']) {
281 $entry['currentLocation'] = $contact['location'];
283 if ($fields_ret['gender']) {
284 $entry['gender'] = $contact['gender'];
286 if ($fields_ret['generation']) {
287 $entry['generation'] = (int)$contact['generation'];
289 if ($fields_ret['urls']) {
290 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
291 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
292 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
295 if ($fields_ret['preferredUsername']) {
296 $entry['preferredUsername'] = $contact['nick'];
298 if ($fields_ret['updated']) {
300 $entry['updated'] = $contact['success_update'];
302 if ($contact['name-date'] > $entry['updated']) {
303 $entry['updated'] = $contact['name-date'];
305 if ($contact['uri-date'] > $entry['updated']) {
306 $entry['updated'] = $contact['uri-date'];
308 if ($contact['avatar-date'] > $entry['updated']) {
309 $entry['updated'] = $contact['avatar-date'];
312 $entry['updated'] = $contact['updated'];
314 $entry['updated'] = date("c", strtotime($entry['updated']));
316 if ($fields_ret['photos']) {
317 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
319 if ($fields_ret['network']) {
320 $entry['network'] = $contact['network'];
321 if ($entry['network'] == Protocol::STATUSNET) {
322 $entry['network'] = Protocol::OSTATUS;
324 if (($entry['network'] == "") && ($contact['self'])) {
325 $entry['network'] = Protocol::DFRN;
328 if ($fields_ret['tags']) {
329 $tags = str_replace(",", " ", $contact['keywords']);
330 $tags = explode(" ", $tags);
333 foreach ($tags as $tag) {
334 $tag = trim(strtolower($tag));
340 $entry['tags'] = [$cleaned];
342 if ($fields_ret['address']) {
343 $entry['address'] = [];
345 // Deactivated. It just reveals too much data. (Although its from the default profile)
346 //if (isset($rr['paddress']))
347 // $entry['address']['streetAddress'] = $rr['paddress'];
349 if (isset($contact['plocation'])) {
350 $entry['address']['locality'] = $contact['plocation'];
352 if (isset($contact['pregion'])) {
353 $entry['address']['region'] = $contact['pregion'];
356 //if (isset($rr['ppostalcode']))
357 // $entry['address']['postalCode'] = $rr['ppostalcode'];
359 if (isset($contact['pcountry'])) {
360 $entry['address']['country'] = $contact['pcountry'];
364 if ($fields_ret['contactType']) {
365 $entry['contactType'] = intval($contact['contact-type']);
367 $ret['entry'][] = $entry;
370 $ret['entry'][] = [];
373 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
376 Logger::log("End of poco", Logger::DEBUG);
378 if ($format === 'xml') {
379 header('Content-type: text/xml');
380 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
383 if ($format === 'json') {
384 header('Content-type: application/json');
385 echo json_encode($ret);
388 throw new \Friendica\Network\HTTPException\InternalServerErrorException();