3 * @file src/Protocol/PortableContact.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 namespace Friendica\Protocol;
15 use Friendica\Content\Text\HTML;
16 use Friendica\Core\Config;
17 use Friendica\Core\Logger;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBA;
21 use Friendica\Model\Contact;
22 use Friendica\Model\GContact;
23 use Friendica\Model\GServer;
24 use Friendica\Model\Profile;
25 use Friendica\Module\Register;
26 use Friendica\Network\Probe;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
36 const USERS_GCONTACTS = 2;
37 const USERS_GCONTACTS_FALLBACK = 3;
40 * @brief Fetch POCO data
42 * @param integer $cid Contact ID
43 * @param integer $uid User ID
44 * @param integer $zcid Global Contact ID
45 * @param integer $url POCO address that should be polled
47 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
48 * and add the entries to the gcontact (Global Contact) table, or update existing entries
49 * if anything (name or photo) has changed.
50 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
52 * Once the global contact is stored add (if necessary) the contact linkage which associates
53 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
54 * pointing to the same global contact id.
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
59 // Call the function "load" via the worker
60 Worker::add(PRIORITY_LOW, 'FetchPoCo', (int)$cid, (int)$uid, (int)$zcid, $url);
64 * @brief Fetch POCO data from the worker
66 * @param integer $cid Contact ID
67 * @param integer $uid User ID
68 * @param integer $zcid Global Contact ID
69 * @param integer $url POCO address that should be polled
70 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72 public static function load($cid, $uid, $zcid, $url)
76 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
77 if (DBA::isResult($contact)) {
78 $url = $contact['poco'];
79 $uid = $contact['uid'];
91 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation');
93 Logger::log('load: ' . $url, Logger::DEBUG);
95 $fetchresult = Network::fetchUrlFull($url);
96 $s = $fetchresult->getBody();
98 Logger::log('load: returns ' . $s, Logger::DATA);
100 Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
102 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
106 $j = json_decode($s, true);
108 Logger::log('load: json: ' . print_r($j, true), Logger::DATA);
110 if (!isset($j['entry'])) {
115 foreach ($j['entry'] as $entry) {
122 $updated = DBA::NULL_DATETIME;
130 if (!empty($entry['displayName'])) {
131 $name = $entry['displayName'];
134 if (isset($entry['urls'])) {
135 foreach ($entry['urls'] as $url) {
136 if ($url['type'] == 'profile') {
137 $profile_url = $url['value'];
140 if ($url['type'] == 'webfinger') {
141 $connect_url = str_replace('acct:', '', $url['value']);
146 if (isset($entry['photos'])) {
147 foreach ($entry['photos'] as $photo) {
148 if ($photo['type'] == 'profile') {
149 $profile_photo = $photo['value'];
155 if (isset($entry['updated'])) {
156 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
159 if (isset($entry['network'])) {
160 $network = $entry['network'];
163 if (isset($entry['currentLocation'])) {
164 $location = $entry['currentLocation'];
167 if (isset($entry['aboutMe'])) {
168 $about = HTML::toBBCode($entry['aboutMe']);
171 if (isset($entry['gender'])) {
172 $gender = $entry['gender'];
175 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
176 $generation = ++$entry['generation'];
179 if (isset($entry['tags'])) {
180 foreach ($entry['tags'] as $tag) {
181 $keywords = implode(", ", $tag);
185 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
186 $contact_type = $entry['contactType'];
189 $gcontact = ["url" => $profile_url,
191 "network" => $network,
192 "photo" => $profile_photo,
194 "location" => $location,
196 "keywords" => $keywords,
197 "connect" => $connect_url,
198 "updated" => $updated,
199 "contact-type" => $contact_type,
200 "generation" => $generation];
203 $gcontact = GContact::sanitize($gcontact);
204 $gcid = GContact::update($gcontact);
206 GContact::link($gcid, $uid, $cid, $zcid);
207 } catch (Exception $e) {
208 Logger::log($e->getMessage(), Logger::DEBUG);
211 Logger::log("load: loaded $total entries", Logger::DEBUG);
213 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
214 DBA::delete('glink', $condition);
218 * @brief Returns a list of all known servers
219 * @return array List of server urls
222 public static function serverlist()
225 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
226 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
227 ORDER BY `last_contact`
229 DBA::escape(Protocol::DFRN),
230 DBA::escape(Protocol::DIASPORA),
231 DBA::escape(Protocol::OSTATUS)
234 if (!DBA::isResult($r)) {
242 * @brief Fetch server list from remote servers and adds them when they are new.
244 * @param string $poco URL to the POCO endpoint
245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
247 private static function fetchServerlist($poco)
249 $curlResult = Network::curl($poco . "/@server");
251 if (!$curlResult->isSuccess()) {
255 $serverlist = json_decode($curlResult->getBody(), true);
257 if (!is_array($serverlist)) {
261 foreach ($serverlist as $server) {
262 $server_url = str_replace("/index.php", "", $server['url']);
264 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(Strings::normaliseLink($server_url)));
266 if (!DBA::isResult($r)) {
267 Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
268 Worker::add(PRIORITY_LOW, 'UpdateGServer', $server_url);
273 public static function discoverSingleServer($id)
275 $server = DBA::selectFirst('gserver', ['poco', 'nurl', 'url', 'network'], ['id' => $id]);
277 if (!DBA::isResult($server)) {
281 // Discover new servers out there (Works from Friendica version 3.5.2)
282 self::fetchServerlist($server["poco"]);
284 // Fetch all users from the other server
285 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
287 Logger::info("Fetch all users from the server " . $server["url"]);
289 $curlResult = Network::curl($url);
291 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
292 $data = json_decode($curlResult->getBody(), true);
295 self::discoverServer($data, 2);
298 if (Config::get('system', 'poco_discovery') >= self::USERS_GCONTACTS) {
299 $timeframe = Config::get('system', 'poco_discovery_since');
301 if ($timeframe == 0) {
305 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
307 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
308 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
312 $curlResult = Network::curl($url);
314 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
315 Logger::info("Fetch all global contacts from the server " . $server["nurl"]);
316 $data = json_decode($curlResult->getBody(), true);
319 $success = self::discoverServer($data);
323 if (!$success && !empty($data) && Config::get('system', 'poco_discovery') >= self::USERS_GCONTACTS_FALLBACK) {
324 Logger::info("Fetch contacts from users of the server " . $server["nurl"]);
325 self::discoverServerUsers($data, $server);
329 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
330 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
334 // If the server hadn't replied correctly, then force a sanity check
335 GServer::check($server["url"], $server["network"], true);
337 // If we couldn't reach the server, we will try it some time later
338 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
339 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
345 private static function discoverServerUsers(array $data, array $server)
347 if (!isset($data['entry'])) {
351 foreach ($data['entry'] as $entry) {
354 if (isset($entry['urls'])) {
355 foreach ($entry['urls'] as $url) {
356 if ($url['type'] == 'profile') {
357 $profile_url = $url['value'];
358 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
359 $username = end($path_array);
364 if ($username != '') {
365 Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
367 // Fetch all contacts from a given user from the other server
368 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
370 $curlResult = Network::curl($url);
372 if ($curlResult->isSuccess()) {
373 $data = json_decode($curlResult->getBody(), true);
376 self::discoverServer($data, 3);
383 private static function discoverServer(array $data, $default_generation = 0)
385 if (empty($data['entry'])) {
391 foreach ($data['entry'] as $entry) {
397 $updated = DBA::NULL_DATETIME;
403 $generation = $default_generation;
405 if (!empty($entry['displayName'])) {
406 $name = $entry['displayName'];
409 if (isset($entry['urls'])) {
410 foreach ($entry['urls'] as $url) {
411 if ($url['type'] == 'profile') {
412 $profile_url = $url['value'];
415 if ($url['type'] == 'webfinger') {
416 $connect_url = str_replace('acct:' , '', $url['value']);
422 if (isset($entry['photos'])) {
423 foreach ($entry['photos'] as $photo) {
424 if ($photo['type'] == 'profile') {
425 $profile_photo = $photo['value'];
431 if (isset($entry['updated'])) {
432 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
435 if (isset($entry['network'])) {
436 $network = $entry['network'];
439 if (isset($entry['currentLocation'])) {
440 $location = $entry['currentLocation'];
443 if (isset($entry['aboutMe'])) {
444 $about = HTML::toBBCode($entry['aboutMe']);
447 if (isset($entry['gender'])) {
448 $gender = $entry['gender'];
451 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
452 $generation = ++$entry['generation'];
455 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
456 $contact_type = $entry['contactType'];
459 if (isset($entry['tags'])) {
460 foreach ($entry['tags'] as $tag) {
461 $keywords = implode(", ", $tag);
465 if ($generation > 0) {
468 Logger::log("Store profile ".$profile_url, Logger::DEBUG);
470 $gcontact = ["url" => $profile_url,
472 "network" => $network,
473 "photo" => $profile_photo,
475 "location" => $location,
477 "keywords" => $keywords,
478 "connect" => $connect_url,
479 "updated" => $updated,
480 "contact-type" => $contact_type,
481 "generation" => $generation];
484 $gcontact = GContact::sanitize($gcontact);
485 GContact::update($gcontact);
486 } catch (Exception $e) {
487 Logger::log($e->getMessage(), Logger::DEBUG);
490 Logger::log("Done for profile ".$profile_url, Logger::DEBUG);