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\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Model\GContact;
20 use Friendica\Model\Profile;
21 use Friendica\Network\Probe;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\XML;
26 require_once 'include/dba.php';
31 * @brief Fetch POCO data
33 * @param integer $cid Contact ID
34 * @param integer $uid User ID
35 * @param integer $zcid Global Contact ID
36 * @param integer $url POCO address that should be polled
38 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
39 * and add the entries to the gcontact (Global Contact) table, or update existing entries
40 * if anything (name or photo) has changed.
41 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
43 * Once the global contact is stored add (if necessary) the contact linkage which associates
44 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
45 * pointing to the same global contact id.
48 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
50 // Call the function "load" via the worker
51 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
55 * @brief Fetch POCO data from the worker
57 * @param integer $cid Contact ID
58 * @param integer $uid User ID
59 * @param integer $zcid Global Contact ID
60 * @param integer $url POCO address that should be polled
63 public static function load($cid, $uid, $zcid, $url)
69 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
70 if (DBA::isResult($contact)) {
71 $url = $contact['poco'];
72 $uid = $contact['uid'];
84 $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') ;
86 logger('load: ' . $url, LOGGER_DEBUG);
88 $s = Network::fetchUrl($url);
90 logger('load: returns ' . $s, LOGGER_DATA);
92 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
94 if (($a->get_curl_code() > 299) || (! $s)) {
98 $j = json_decode($s, true);
100 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
102 if (!isset($j['entry'])) {
107 foreach ($j['entry'] as $entry) {
114 $updated = NULL_DATE;
122 if (!empty($entry['displayName'])) {
123 $name = $entry['displayName'];
126 if (isset($entry['urls'])) {
127 foreach ($entry['urls'] as $url) {
128 if ($url['type'] == 'profile') {
129 $profile_url = $url['value'];
132 if ($url['type'] == 'webfinger') {
133 $connect_url = str_replace('acct:', '', $url['value']);
138 if (isset($entry['photos'])) {
139 foreach ($entry['photos'] as $photo) {
140 if ($photo['type'] == 'profile') {
141 $profile_photo = $photo['value'];
147 if (isset($entry['updated'])) {
148 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
151 if (isset($entry['network'])) {
152 $network = $entry['network'];
155 if (isset($entry['currentLocation'])) {
156 $location = $entry['currentLocation'];
159 if (isset($entry['aboutMe'])) {
160 $about = HTML::toBBCode($entry['aboutMe']);
163 if (isset($entry['gender'])) {
164 $gender = $entry['gender'];
167 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
168 $generation = ++$entry['generation'];
171 if (isset($entry['tags'])) {
172 foreach ($entry['tags'] as $tag) {
173 $keywords = implode(", ", $tag);
177 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
178 $contact_type = $entry['contactType'];
181 $gcontact = ["url" => $profile_url,
183 "network" => $network,
184 "photo" => $profile_photo,
186 "location" => $location,
188 "keywords" => $keywords,
189 "connect" => $connect_url,
190 "updated" => $updated,
191 "contact-type" => $contact_type,
192 "generation" => $generation];
195 $gcontact = GContact::sanitize($gcontact);
196 $gcid = GContact::update($gcontact);
198 GContact::link($gcid, $uid, $cid, $zcid);
199 } catch (Exception $e) {
200 logger($e->getMessage(), LOGGER_DEBUG);
203 logger("load: loaded $total entries", LOGGER_DEBUG);
205 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
206 DBA::delete('glink', $condition);
209 public static function reachable($profile, $server = "", $network = "", $force = false)
212 $server = self::detectServer($profile);
219 return self::checkServer($server, $network, $force);
222 public static function detectServer($profile)
224 // Try to detect the server path based upon some known standard paths
227 if ($server_url == "") {
228 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
229 if ($friendica != $profile) {
230 $server_url = $friendica;
231 $network = NETWORK_DFRN;
235 if ($server_url == "") {
236 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
237 if ($diaspora != $profile) {
238 $server_url = $diaspora;
239 $network = NETWORK_DIASPORA;
243 if ($server_url == "") {
244 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
245 if ($red != $profile) {
247 $network = NETWORK_DIASPORA;
252 if ($server_url == "") {
253 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
254 if ($mastodon != $profile) {
255 $server_url = $mastodon;
256 $network = NETWORK_OSTATUS;
260 // Numeric OStatus variant
261 if ($server_url == "") {
262 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
263 if ($ostatus != $profile) {
264 $server_url = $ostatus;
265 $network = NETWORK_OSTATUS;
270 if ($server_url == "") {
271 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
272 if ($base != $profile) {
274 $network = NETWORK_PHANTOM;
278 if ($server_url == "") {
283 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
284 DBA::escape(normalise_link($server_url))
287 if (DBA::isResult($r)) {
291 // Fetch the host-meta to check if this really is a server
292 $serverret = Network::curl($server_url."/.well-known/host-meta");
293 if (!$serverret["success"]) {
300 public static function alternateOStatusUrl($url)
302 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
305 public static function lastUpdated($profile, $force = false)
308 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
309 DBA::escape(normalise_link($profile))
312 if (!DBA::isResult($gcontacts)) {
316 $contact = ["url" => $profile];
318 if ($gcontacts[0]["created"] <= NULL_DATE) {
319 $contact['created'] = DateTimeFormat::utcNow();
324 $server_url = normalise_link(self::detectServer($profile));
327 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
328 $server_url = $gcontacts[0]["server_url"];
331 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
332 $server_url = normalise_link(self::detectServer($profile));
335 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
336 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
340 if ($server_url != "") {
341 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
343 $fields = ['last_failure' => DateTimeFormat::utcNow()];
344 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
347 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
350 $contact['server_url'] = $server_url;
353 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
355 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
356 DBA::escape(normalise_link($server_url))
360 $contact['network'] = $server[0]["network"];
366 // noscrape is really fast so we don't cache the call.
367 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
368 // Use noscrape if possible
369 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(normalise_link($server_url)));
372 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
374 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
375 $noscrape = json_decode($noscraperet["body"], true);
377 if (is_array($noscrape)) {
378 $contact["network"] = $server[0]["network"];
380 if (isset($noscrape["fn"])) {
381 $contact["name"] = $noscrape["fn"];
383 if (isset($noscrape["comm"])) {
384 $contact["community"] = $noscrape["comm"];
386 if (isset($noscrape["tags"])) {
387 $keywords = implode(" ", $noscrape["tags"]);
388 if ($keywords != "") {
389 $contact["keywords"] = $keywords;
393 $location = Profile::formatLocation($noscrape);
395 $contact["location"] = $location;
397 if (isset($noscrape["dfrn-notify"])) {
398 $contact["notify"] = $noscrape["dfrn-notify"];
400 // Remove all fields that are not present in the gcontact table
401 unset($noscrape["fn"]);
402 unset($noscrape["key"]);
403 unset($noscrape["homepage"]);
404 unset($noscrape["comm"]);
405 unset($noscrape["tags"]);
406 unset($noscrape["locality"]);
407 unset($noscrape["region"]);
408 unset($noscrape["country-name"]);
409 unset($noscrape["contacts"]);
410 unset($noscrape["dfrn-request"]);
411 unset($noscrape["dfrn-confirm"]);
412 unset($noscrape["dfrn-notify"]);
413 unset($noscrape["dfrn-poll"]);
415 // Set the date of the last contact
416 /// @todo By now the function "update_gcontact" doesn't work with this field
417 //$contact["last_contact"] = DateTimeFormat::utcNow();
419 $contact = array_merge($contact, $noscrape);
421 GContact::update($contact);
423 if (!empty($noscrape["updated"])) {
424 $fields = ['last_contact' => DateTimeFormat::utcNow()];
425 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
427 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
429 return $noscrape["updated"];
436 // If we only can poll the feed, then we only do this once a while
437 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
438 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
440 GContact::update($contact);
441 return $gcontacts[0]["updated"];
444 $data = Probe::uri($profile);
446 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
447 // Then check the other link and delete this one
448 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
449 && (normalise_link($profile) == normalise_link($data["alias"]))
450 && (normalise_link($profile) != normalise_link($data["url"]))
452 // Delete the old entry
453 DBA::delete('gcontact', ['nurl' => normalise_link($profile)]);
455 $gcontact = array_merge($gcontacts[0], $data);
457 $gcontact["server_url"] = $data["baseurl"];
460 $gcontact = GContact::sanitize($gcontact);
461 GContact::update($gcontact);
463 self::lastUpdated($data["url"], $force);
464 } catch (Exception $e) {
465 logger($e->getMessage(), LOGGER_DEBUG);
468 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
472 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
473 $fields = ['last_failure' => DateTimeFormat::utcNow()];
474 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
476 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
480 $contact = array_merge($contact, $data);
482 $contact["server_url"] = $data["baseurl"];
484 GContact::update($contact);
486 $feedret = Network::curl($data["poll"]);
488 if (!$feedret["success"]) {
489 $fields = ['last_failure' => DateTimeFormat::utcNow()];
490 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
492 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
496 $doc = new DOMDocument();
497 /// @TODO Avoid error supression here
498 @$doc->loadXML($feedret["body"]);
500 $xpath = new DOMXPath($doc);
501 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
503 $entries = $xpath->query('/atom:feed/atom:entry');
507 foreach ($entries as $entry) {
508 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
509 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
511 if ($last_updated < $published) {
512 $last_updated = $published;
515 if ($last_updated < $updated) {
516 $last_updated = $updated;
520 // Maybe there aren't any entries. Then check if it is a valid feed
521 if ($last_updated == "") {
522 if ($xpath->query('/atom:feed')->length > 0) {
523 $last_updated = NULL_DATE;
527 $fields = ['last_contact' => DateTimeFormat::utcNow()];
529 if (!empty($last_updated)) {
530 $fields['updated'] = $last_updated;
533 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
535 if (($gcontacts[0]["generation"] == 0)) {
536 $fields = ['generation' => 9];
537 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
540 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
542 return $last_updated;
545 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
547 $now = strtotime(DateTimeFormat::utcNow());
549 if ($updated > $last_contact) {
550 $contact_time = strtotime($updated);
552 $contact_time = strtotime($last_contact);
555 $failure_time = strtotime($last_failure);
556 $created_time = strtotime($created);
558 // If there is no "created" time then use the current time
559 if ($created_time <= 0) {
560 $created_time = $now;
563 // If the last contact was less than 24 hours then don't update
564 if (($now - $contact_time) < (60 * 60 * 24)) {
568 // If the last failure was less than 24 hours then don't update
569 if (($now - $failure_time) < (60 * 60 * 24)) {
573 // If the last contact was less than a week ago and the last failure is older than a week then don't update
574 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
577 // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
578 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
582 // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
583 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
590 /// @TODO Maybe move this out to an utilities class?
591 private static function toBoolean($val)
593 if (($val == "true") || ($val == 1)) {
595 } elseif (($val == "false") || ($val == 0)) {
603 * @brief Detect server type (Hubzilla or Friendica) via the poco data
605 * @param array $data POCO data
606 * @return array Server data
608 private static function detectPocoData(array $data)
612 if (!isset($data['entry'])) {
616 if (count($data['entry']) == 0) {
620 if (!isset($data['entry'][0]['urls'])) {
624 if (count($data['entry'][0]['urls']) == 0) {
628 foreach ($data['entry'][0]['urls'] as $url) {
629 if ($url['type'] == 'zot') {
631 $server["platform"] = 'Hubzilla';
632 $server["network"] = NETWORK_DIASPORA;
640 * @brief Detect server type by using the nodeinfo data
642 * @param string $server_url address of the server
643 * @return array Server data
645 private static function fetchNodeinfo($server_url)
647 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
648 if (!$serverret["success"]) {
652 $nodeinfo = json_decode($serverret['body'], true);
654 if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
661 foreach ($nodeinfo['links'] as $link) {
662 if (!is_array($link) || empty($link['rel'])) {
663 logger('Invalid nodeinfo format for ' . $server_url, LOGGER_DEBUG);
666 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
667 $nodeinfo1_url = $link['href'];
668 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
669 $nodeinfo2_url = $link['href'];
673 if ($nodeinfo1_url . $nodeinfo2_url == '') {
679 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
680 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
681 $server = self::parseNodeinfo2($nodeinfo2_url);
684 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
685 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
686 $server = self::parseNodeinfo1($nodeinfo1_url);
693 * @brief Parses Nodeinfo 1
695 * @param string $nodeinfo_url address of the nodeinfo path
696 * @return array Server data
698 private static function parseNodeinfo1($nodeinfo_url)
700 $serverret = Network::curl($nodeinfo_url);
702 if (!$serverret["success"]) {
706 $nodeinfo = json_decode($serverret['body'], true);
708 if (!is_array($nodeinfo)) {
714 $server['register_policy'] = REGISTER_CLOSED;
716 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
717 $server['register_policy'] = REGISTER_OPEN;
720 if (is_array($nodeinfo['software'])) {
721 if (isset($nodeinfo['software']['name'])) {
722 $server['platform'] = $nodeinfo['software']['name'];
725 if (isset($nodeinfo['software']['version'])) {
726 $server['version'] = $nodeinfo['software']['version'];
727 // Version numbers on Nodeinfo are presented with additional info, e.g.:
728 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
729 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
733 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
734 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
737 if (!empty($nodeinfo['usage']['users']['total'])) {
738 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
745 if (is_array($nodeinfo['protocols']['inbound'])) {
746 foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
747 if ($inbound == 'diaspora') {
750 if ($inbound == 'friendica') {
753 if ($inbound == 'gnusocial') {
760 $server['network'] = NETWORK_OSTATUS;
763 $server['network'] = NETWORK_DIASPORA;
766 $server['network'] = NETWORK_DFRN;
777 * @brief Parses Nodeinfo 2
779 * @param string $nodeinfo_url address of the nodeinfo path
780 * @return array Server data
782 private static function parseNodeinfo2($nodeinfo_url)
784 $serverret = Network::curl($nodeinfo_url);
785 if (!$serverret["success"]) {
789 $nodeinfo = json_decode($serverret['body'], true);
791 if (!is_array($nodeinfo)) {
797 $server['register_policy'] = REGISTER_CLOSED;
799 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
800 $server['register_policy'] = REGISTER_OPEN;
803 if (is_array($nodeinfo['software'])) {
804 if (isset($nodeinfo['software']['name'])) {
805 $server['platform'] = $nodeinfo['software']['name'];
808 if (isset($nodeinfo['software']['version'])) {
809 $server['version'] = $nodeinfo['software']['version'];
810 // Version numbers on Nodeinfo are presented with additional info, e.g.:
811 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
812 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
816 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
817 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
820 if (!empty($nodeinfo['usage']['users']['total'])) {
821 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
828 if (!empty($nodeinfo['protocols'])) {
829 foreach ($nodeinfo['protocols'] as $protocol) {
830 if ($protocol == 'diaspora') {
832 } elseif ($protocol == 'friendica') {
834 } elseif ($protocol == 'gnusocial') {
841 $server['network'] = NETWORK_OSTATUS;
842 } elseif ($diaspora) {
843 $server['network'] = NETWORK_DIASPORA;
844 } elseif ($friendica) {
845 $server['network'] = NETWORK_DFRN;
848 if (empty($server)) {
856 * @brief Detect server type (Hubzilla or Friendica) via the front page body
858 * @param string $body Front page of the server
859 * @return array Server data
861 private static function detectServerType($body)
865 $doc = new DOMDocument();
866 /// @TODO Acoid supressing error
867 @$doc->loadHTML($body);
868 $xpath = new DOMXPath($doc);
870 $list = $xpath->query("//meta[@name]");
872 foreach ($list as $node) {
874 if ($node->attributes->length) {
875 foreach ($node->attributes as $attribute) {
876 $attr[$attribute->name] = $attribute->value;
879 if ($attr['name'] == 'generator') {
880 $version_part = explode(" ", $attr['content']);
881 if (count($version_part) == 2) {
882 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
884 $server["platform"] = $version_part[0];
885 $server["version"] = $version_part[1];
886 $server["network"] = NETWORK_DFRN;
893 $list = $xpath->query("//meta[@property]");
895 foreach ($list as $node) {
897 if ($node->attributes->length) {
898 foreach ($node->attributes as $attribute) {
899 $attr[$attribute->name] = $attribute->value;
902 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
904 $server["platform"] = $attr['content'];
905 $server["version"] = "";
906 $server["network"] = NETWORK_DIASPORA;
915 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
920 public static function checkServer($server_url, $network = "", $force = false)
922 // Unify the server address
923 $server_url = trim($server_url, "/");
924 $server_url = str_replace("/index.php", "", $server_url);
926 if ($server_url == "") {
930 $gserver = DBA::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
931 if (DBA::isResult($gserver)) {
932 if ($gserver["created"] <= NULL_DATE) {
933 $fields = ['created' => DateTimeFormat::utcNow()];
934 $condition = ['nurl' => normalise_link($server_url)];
935 DBA::update('gserver', $fields, $condition);
937 $poco = $gserver["poco"];
938 $noscrape = $gserver["noscrape"];
940 if ($network == "") {
941 $network = $gserver["network"];
944 $last_contact = $gserver["last_contact"];
945 $last_failure = $gserver["last_failure"];
946 $version = $gserver["version"];
947 $platform = $gserver["platform"];
948 $site_name = $gserver["site_name"];
949 $info = $gserver["info"];
950 $register_policy = $gserver["register_policy"];
951 $registered_users = $gserver["registered-users"];
953 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
954 // It can happen that a zero date is in the database, but storing it again is forbidden.
955 if ($last_contact < NULL_DATE) {
956 $last_contact = NULL_DATE;
959 if ($last_failure < NULL_DATE) {
960 $last_failure = NULL_DATE;
963 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
964 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
965 return ($last_contact >= $last_failure);
974 $register_policy = -1;
975 $registered_users = 0;
977 $last_contact = NULL_DATE;
978 $last_failure = NULL_DATE;
980 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
983 $possible_failure = false;
984 $orig_last_failure = $last_failure;
985 $orig_last_contact = $last_contact;
987 // Mastodon uses the "@" for user profiles.
988 // But this can be misunderstood.
989 if (parse_url($server_url, PHP_URL_USER) != '') {
990 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
994 // Check if the page is accessible via SSL.
995 $orig_server_url = $server_url;
996 $server_url = str_replace("http://", "https://", $server_url);
998 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
999 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1001 // Quit if there is a timeout.
1002 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1003 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1004 (!empty($serverret["errno"]) && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT))) {
1005 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1006 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1010 // Maybe the page is unencrypted only?
1011 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1012 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1013 $server_url = str_replace("https://", "http://", $server_url);
1015 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1016 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1018 // Quit if there is a timeout
1019 if (!empty($serverret["errno"]) && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1020 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1021 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1025 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1028 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1029 // Workaround for bad configured servers (known nginx problem)
1030 if (!empty($serverret["debug"]) && !in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1034 $possible_failure = true;
1037 // If the server has no possible failure we reset the cached data
1038 if (!$possible_failure) {
1043 $register_policy = -1;
1047 // This will be too low, but better than no value at all.
1048 $registered_users = DBA::count('gcontact', ['server_url' => normalise_link($server_url)]);
1053 $serverret = Network::curl($server_url."/poco");
1055 if ($serverret["success"]) {
1056 $data = json_decode($serverret["body"], true);
1058 if (isset($data['totalResults'])) {
1059 $registered_users = $data['totalResults'];
1060 $poco = $server_url . "/poco";
1061 $server = self::detectPocoData($data);
1063 if (!empty($server)) {
1064 $platform = $server['platform'];
1065 $network = $server['network'];
1072 * There are servers out there who don't return 404 on a failure
1073 * We have to be sure that don't misunderstand this
1075 if (is_null($data)) {
1084 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1085 $serverret = Network::curl($server_url);
1087 if (!$serverret["success"] || ($serverret["body"] == "")) {
1090 $server = self::detectServerType($serverret["body"]);
1092 if (!empty($server)) {
1093 $platform = $server['platform'];
1094 $network = $server['network'];
1095 $version = $server['version'];
1096 $site_name = $server['site_name'];
1099 $lines = explode("\n", $serverret["header"]);
1101 if (count($lines)) {
1102 foreach ($lines as $line) {
1103 $line = trim($line);
1105 if (stristr($line, 'X-Diaspora-Version:')) {
1106 $platform = "Diaspora";
1107 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1108 $version = trim(str_replace("x-diaspora-version:", "", $version));
1109 $network = NETWORK_DIASPORA;
1110 $versionparts = explode("-", $version);
1111 $version = $versionparts[0];
1114 if (stristr($line, 'Server: Mastodon')) {
1115 $platform = "Mastodon";
1116 $network = NETWORK_OSTATUS;
1123 if (!$failure && ($poco == "")) {
1124 // Test for Statusnet
1125 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1126 // The "not implemented" is a special treatment for really, really old Friendica versions
1127 $serverret = Network::curl($server_url."/api/statusnet/version.json");
1129 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1130 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1131 $platform = "StatusNet";
1132 // Remove junk that some GNU Social servers return
1133 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1134 $version = trim($version, '"');
1135 $network = NETWORK_OSTATUS;
1138 // Test for GNU Social
1139 $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1141 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1142 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1143 $platform = "GNU Social";
1144 // Remove junk that some GNU Social servers return
1145 $version = str_replace(chr(239) . chr(187) . chr(191), "", $serverret["body"]);
1146 $version = trim($version, '"');
1147 $network = NETWORK_OSTATUS;
1150 // Test for Mastodon
1151 $orig_version = $version;
1152 $serverret = Network::curl($server_url . "/api/v1/instance");
1154 if ($serverret["success"] && ($serverret["body"] != '')) {
1155 $data = json_decode($serverret["body"], true);
1157 if (isset($data['version'])) {
1158 $platform = "Mastodon";
1159 $version = $data['version'];
1160 $site_name = $data['title'];
1161 $info = $data['description'];
1162 $network = NETWORK_OSTATUS;
1165 if (!empty($data['stats']['user_count'])) {
1166 $registered_users = $data['stats']['user_count'];
1170 if (strstr($orig_version . $version, 'Pleroma')) {
1171 $platform = 'Pleroma';
1172 $version = trim(str_replace('Pleroma', '', $version));
1177 // Test for Hubzilla and Red
1178 $serverret = Network::curl($server_url . "/siteinfo.json");
1180 if ($serverret["success"]) {
1181 $data = json_decode($serverret["body"], true);
1183 if (isset($data['url'])) {
1184 $platform = $data['platform'];
1185 $version = $data['version'];
1186 $network = NETWORK_DIASPORA;
1189 if (!empty($data['site_name'])) {
1190 $site_name = $data['site_name'];
1193 if (!empty($data['channels_total'])) {
1194 $registered_users = $data['channels_total'];
1197 if (!empty($data['register_policy'])) {
1198 switch ($data['register_policy']) {
1199 case "REGISTER_OPEN":
1200 $register_policy = REGISTER_OPEN;
1203 case "REGISTER_APPROVE":
1204 $register_policy = REGISTER_APPROVE;
1207 case "REGISTER_CLOSED":
1209 $register_policy = REGISTER_CLOSED;
1214 // Test for Hubzilla, Redmatrix or Friendica
1215 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1217 if ($serverret["success"]) {
1218 $data = json_decode($serverret["body"], true);
1220 if (isset($data['site']['server'])) {
1221 if (isset($data['site']['platform'])) {
1222 $platform = $data['site']['platform']['PLATFORM_NAME'];
1223 $version = $data['site']['platform']['STD_VERSION'];
1224 $network = NETWORK_DIASPORA;
1227 if (isset($data['site']['BlaBlaNet'])) {
1228 $platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
1229 $version = $data['site']['BlaBlaNet']['STD_VERSION'];
1230 $network = NETWORK_DIASPORA;
1233 if (isset($data['site']['hubzilla'])) {
1234 $platform = $data['site']['hubzilla']['PLATFORM_NAME'];
1235 $version = $data['site']['hubzilla']['RED_VERSION'];
1236 $network = NETWORK_DIASPORA;
1239 if (isset($data['site']['redmatrix'])) {
1240 if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
1241 $platform = $data['site']['redmatrix']['PLATFORM_NAME'];
1242 } elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
1243 $platform = $data['site']['redmatrix']['RED_PLATFORM'];
1246 $version = $data['site']['redmatrix']['RED_VERSION'];
1247 $network = NETWORK_DIASPORA;
1250 if (isset($data['site']['friendica'])) {
1251 $platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
1252 $version = $data['site']['friendica']['FRIENDICA_VERSION'];
1253 $network = NETWORK_DFRN;
1256 $site_name = $data['site']['name'];
1259 $inviteonly = false;
1262 if (!empty($data['site']['closed'])) {
1263 $closed = self::toBoolean($data['site']['closed']);
1266 if (!empty($data['site']['private'])) {
1267 $private = self::toBoolean($data['site']['private']);
1270 if (!empty($data['site']['inviteonly'])) {
1271 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1274 if (!$closed && !$private and $inviteonly) {
1275 $register_policy = REGISTER_APPROVE;
1276 } elseif (!$closed && !$private) {
1277 $register_policy = REGISTER_OPEN;
1279 $register_policy = REGISTER_CLOSED;
1286 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1288 $serverret = Network::curl($server_url . "/statistics.json");
1290 if ($serverret["success"]) {
1291 $data = json_decode($serverret["body"], true);
1293 if (isset($data['version'])) {
1294 $version = $data['version'];
1295 // Version numbers on statistics.json are presented with additional info, e.g.:
1296 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1297 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1300 if (!empty($data['name'])) {
1301 $site_name = $data['name'];
1304 if (!empty($data['network'])) {
1305 $platform = $data['network'];
1308 if ($platform == "Diaspora") {
1309 $network = NETWORK_DIASPORA;
1312 if (!empty($data['registrations_open']) && $data['registrations_open']) {
1313 $register_policy = REGISTER_OPEN;
1315 $register_policy = REGISTER_CLOSED;
1320 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1322 $server = self::fetchNodeinfo($server_url);
1324 if (!empty($server)) {
1325 $register_policy = $server['register_policy'];
1327 if (isset($server['platform'])) {
1328 $platform = $server['platform'];
1331 if (isset($server['network'])) {
1332 $network = $server['network'];
1335 if (isset($server['version'])) {
1336 $version = $server['version'];
1339 if (isset($server['site_name'])) {
1340 $site_name = $server['site_name'];
1343 if (isset($server['registered-users'])) {
1344 $registered_users = $server['registered-users'];
1349 // Check for noscrape
1350 // Friendica servers could be detected as OStatus servers
1351 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1352 $serverret = Network::curl($server_url . "/friendica/json");
1354 if (!$serverret["success"]) {
1355 $serverret = Network::curl($server_url . "/friendika/json");
1358 if ($serverret["success"]) {
1359 $data = json_decode($serverret["body"], true);
1361 if (isset($data['version'])) {
1362 $network = NETWORK_DFRN;
1364 if (!empty($data['no_scrape_url'])) {
1365 $noscrape = $data['no_scrape_url'];
1368 $version = $data['version'];
1370 if (!empty($data['site_name'])) {
1371 $site_name = $data['site_name'];
1374 $info = $data['info'];
1375 $register_policy = constant($data['register_policy']);
1376 $platform = $data['platform'];
1381 // Every server has got at least an admin account
1382 if (!$failure && ($registered_users == 0)) {
1383 $registered_users = 1;
1386 if ($possible_failure && !$failure) {
1391 $last_contact = $orig_last_contact;
1392 $last_failure = DateTimeFormat::utcNow();
1394 $last_contact = DateTimeFormat::utcNow();
1395 $last_failure = $orig_last_failure;
1398 if (($last_contact <= $last_failure) && !$failure) {
1399 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1400 } elseif (($last_contact >= $last_failure) && $failure) {
1401 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1404 // Check again if the server exists
1405 $found = DBA::exists('gserver', ['nurl' => normalise_link($server_url)]);
1407 $version = strip_tags($version);
1408 $site_name = strip_tags($site_name);
1409 $info = strip_tags($info);
1410 $platform = strip_tags($platform);
1412 $fields = ['url' => $server_url, 'version' => $version,
1413 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1414 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1415 'platform' => $platform, 'registered-users' => $registered_users,
1416 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1419 DBA::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1420 } elseif (!$failure) {
1421 $fields['nurl'] = normalise_link($server_url);
1422 $fields['created'] = DateTimeFormat::utcNow();
1423 DBA::insert('gserver', $fields);
1426 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1427 self::discoverRelay($server_url);
1430 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1436 * @brief Fetch relay data from a given server url
1438 * @param string $server_url address of the server
1440 private static function discoverRelay($server_url)
1442 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1444 $serverret = Network::curl($server_url . "/.well-known/x-social-relay");
1446 if (!$serverret["success"]) {
1450 $data = json_decode($serverret['body'], true);
1452 if (!is_array($data)) {
1456 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1458 if (!DBA::isResult($gserver)) {
1462 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
1463 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
1464 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1467 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1469 if ($data['scope'] == 'tags') {
1472 foreach ($data['tags'] as $tag) {
1473 $tag = mb_strtolower($tag);
1474 if (count($tag) < 100) {
1479 foreach ($tags as $tag) {
1480 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1484 // Create or update the relay contact
1486 if (isset($data['protocols'])) {
1487 if (isset($data['protocols']['diaspora'])) {
1488 $fields['network'] = NETWORK_DIASPORA;
1490 if (isset($data['protocols']['diaspora']['receive'])) {
1491 $fields['batch'] = $data['protocols']['diaspora']['receive'];
1492 } elseif (is_string($data['protocols']['diaspora'])) {
1493 $fields['batch'] = $data['protocols']['diaspora'];
1497 if (isset($data['protocols']['dfrn'])) {
1498 $fields['network'] = NETWORK_DFRN;
1500 if (isset($data['protocols']['dfrn']['receive'])) {
1501 $fields['batch'] = $data['protocols']['dfrn']['receive'];
1502 } elseif (is_string($data['protocols']['dfrn'])) {
1503 $fields['batch'] = $data['protocols']['dfrn'];
1507 Diaspora::setRelayContact($server_url, $fields);
1511 * @brief Returns a list of all known servers
1512 * @return array List of server urls
1514 public static function serverlist()
1517 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1518 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1519 ORDER BY `last_contact`
1521 DBA::escape(NETWORK_DFRN),
1522 DBA::escape(NETWORK_DIASPORA),
1523 DBA::escape(NETWORK_OSTATUS)
1526 if (!DBA::isResult($r)) {
1534 * @brief Fetch server list from remote servers and adds them when they are new.
1536 * @param string $poco URL to the POCO endpoint
1538 private static function fetchServerlist($poco)
1540 $serverret = Network::curl($poco . "/@server");
1542 if (!$serverret["success"]) {
1546 $serverlist = json_decode($serverret['body'], true);
1548 if (!is_array($serverlist)) {
1552 foreach ($serverlist as $server) {
1553 $server_url = str_replace("/index.php", "", $server['url']);
1555 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(normalise_link($server_url)));
1557 if (!DBA::isResult($r)) {
1558 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1559 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1564 private static function discoverFederation()
1566 $last = Config::get('poco', 'last_federation_discovery');
1569 $next = $last + (24 * 60 * 60);
1571 if ($next > time()) {
1576 // Discover Friendica, Hubzilla and Diaspora servers
1577 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1579 if (!empty($serverdata)) {
1580 $servers = json_decode($serverdata, true);
1582 if (!empty($servers['pods'])) {
1583 foreach ($servers['pods'] as $server) {
1584 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://" . $server['host']);
1589 // Disvover Mastodon servers
1590 if (!Config::get('system', 'ostatus_disabled')) {
1591 $accesstoken = Config::get('system', 'instances_social_key');
1593 if (!empty($accesstoken)) {
1594 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1595 $header = ['Authorization: Bearer '.$accesstoken];
1596 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1598 if ($serverdata['success']) {
1599 $servers = json_decode($serverdata['body'], true);
1601 foreach ($servers['instances'] as $server) {
1602 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1603 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1609 // Currently disabled, since the service isn't available anymore.
1610 // It is not removed since I hope that there will be a successor.
1611 // Discover GNU Social Servers.
1612 //if (!Config::get('system','ostatus_disabled')) {
1613 // $serverdata = "http://gstools.org/api/get_open_instances/";
1615 // $result = Network::curl($serverdata);
1616 // if ($result["success"]) {
1617 // $servers = json_decode($result["body"], true);
1619 // foreach($servers['data'] as $server)
1620 // self::checkServer($server['instance_address']);
1624 Config::set('poco', 'last_federation_discovery', time());
1627 public static function discoverSingleServer($id)
1629 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1631 if (!DBA::isResult($r)) {
1637 // Discover new servers out there (Works from Friendica version 3.5.2)
1638 self::fetchServerlist($server["poco"]);
1640 // Fetch all users from the other server
1641 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1643 logger("Fetch all users from the server " . $server["url"], LOGGER_DEBUG);
1645 $retdata = Network::curl($url);
1647 if ($retdata["success"] && !empty($retdata["body"])) {
1648 $data = json_decode($retdata["body"], true);
1650 if (!empty($data)) {
1651 self::discoverServer($data, 2);
1654 if (Config::get('system', 'poco_discovery') > 1) {
1655 $timeframe = Config::get('system', 'poco_discovery_since');
1657 if ($timeframe == 0) {
1661 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1663 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1664 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1668 $retdata = Network::curl($url);
1670 if ($retdata["success"] && !empty($retdata["body"])) {
1671 logger("Fetch all global contacts from the server " . $server["nurl"], LOGGER_DEBUG);
1672 $data = json_decode($retdata["body"], true);
1674 if (!empty($data)) {
1675 $success = self::discoverServer($data);
1679 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1680 logger("Fetch contacts from users of the server " . $server["nurl"], LOGGER_DEBUG);
1681 self::discoverServerUsers($data, $server);
1685 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1686 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1690 // If the server hadn't replied correctly, then force a sanity check
1691 self::checkServer($server["url"], $server["network"], true);
1693 // If we couldn't reach the server, we will try it some time later
1694 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1695 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1701 public static function discover($complete = false)
1703 // Update the server list
1704 self::discoverFederation();
1708 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1710 if ($requery_days == 0) {
1714 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1716 $gservers = q("SELECT `id`, `url`, `nurl`, `network`
1718 WHERE `last_contact` >= `last_failure`
1720 AND `last_poco_query` < '%s'
1721 ORDER BY RAND()", DBA::escape($last_update)
1724 if (DBA::isResult($gservers)) {
1725 foreach ($gservers as $gserver) {
1726 if (!self::checkServer($gserver['url'], $gserver['network'])) {
1727 // The server is not reachable? Okay, then we will try it later
1728 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1729 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1733 logger('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], LOGGER_DEBUG);
1734 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
1736 if (!$complete && ( --$no_of_queries == 0)) {
1743 private static function discoverServerUsers(array $data, array $server)
1745 if (!isset($data['entry'])) {
1749 foreach ($data['entry'] as $entry) {
1752 if (isset($entry['urls'])) {
1753 foreach ($entry['urls'] as $url) {
1754 if ($url['type'] == 'profile') {
1755 $profile_url = $url['value'];
1756 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1757 $username = end($path_array);
1762 if ($username != '') {
1763 logger('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], LOGGER_DEBUG);
1765 // Fetch all contacts from a given user from the other server
1766 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1768 $retdata = Network::curl($url);
1770 if (!empty($retdata['success'])) {
1771 $data = json_decode($retdata["body"], true);
1773 if (!empty($data)) {
1774 self::discoverServer($data, 3);
1781 private static function discoverServer(array $data, $default_generation = 0)
1783 if (empty($data['entry'])) {
1789 foreach ($data['entry'] as $entry) {
1791 $profile_photo = '';
1795 $updated = NULL_DATE;
1801 $generation = $default_generation;
1803 if (!empty($entry['displayName'])) {
1804 $name = $entry['displayName'];
1807 if (isset($entry['urls'])) {
1808 foreach ($entry['urls'] as $url) {
1809 if ($url['type'] == 'profile') {
1810 $profile_url = $url['value'];
1813 if ($url['type'] == 'webfinger') {
1814 $connect_url = str_replace('acct:' , '', $url['value']);
1820 if (isset($entry['photos'])) {
1821 foreach ($entry['photos'] as $photo) {
1822 if ($photo['type'] == 'profile') {
1823 $profile_photo = $photo['value'];
1829 if (isset($entry['updated'])) {
1830 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
1833 if (isset($entry['network'])) {
1834 $network = $entry['network'];
1837 if (isset($entry['currentLocation'])) {
1838 $location = $entry['currentLocation'];
1841 if (isset($entry['aboutMe'])) {
1842 $about = HTML::toBBCode($entry['aboutMe']);
1845 if (isset($entry['gender'])) {
1846 $gender = $entry['gender'];
1849 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
1850 $generation = ++$entry['generation'];
1853 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
1854 $contact_type = $entry['contactType'];
1857 if (isset($entry['tags'])) {
1858 foreach ($entry['tags'] as $tag) {
1859 $keywords = implode(", ", $tag);
1863 if ($generation > 0) {
1866 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1868 $gcontact = ["url" => $profile_url,
1870 "network" => $network,
1871 "photo" => $profile_photo,
1873 "location" => $location,
1874 "gender" => $gender,
1875 "keywords" => $keywords,
1876 "connect" => $connect_url,
1877 "updated" => $updated,
1878 "contact-type" => $contact_type,
1879 "generation" => $generation];
1882 $gcontact = GContact::sanitize($gcontact);
1883 GContact::update($gcontact);
1884 } catch (Exception $e) {
1885 logger($e->getMessage(), LOGGER_DEBUG);
1888 logger("Done for profile ".$profile_url, LOGGER_DEBUG);