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;
12 use Friendica\Core\Config;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Profile;
17 use Friendica\Network\Probe;
23 require_once 'include/dba.php';
24 require_once 'include/datetime.php';
25 require_once 'include/network.php';
26 require_once 'include/html2bbcode.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)
68 if ((! $url) || (! $uid)) {
70 "select `poco`, `uid` from `contact` where `id` = %d limit 1",
73 if (DBM::is_result($r)) {
87 $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') ;
89 logger('load: ' . $url, LOGGER_DEBUG);
93 logger('load: returns ' . $s, LOGGER_DATA);
95 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
97 if (($a->get_curl_code() > 299) || (! $s)) {
101 $j = json_decode($s);
103 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
105 if (! isset($j->entry)) {
110 foreach ($j->entry as $entry) {
117 $updated = NULL_DATE;
125 $name = $entry->displayName;
127 if (isset($entry->urls)) {
128 foreach ($entry->urls as $url) {
129 if ($url->type == 'profile') {
130 $profile_url = $url->value;
133 if ($url->type == 'webfinger') {
134 $connect_url = str_replace('acct:', '', $url->value);
139 if (isset($entry->photos)) {
140 foreach ($entry->photos as $photo) {
141 if ($photo->type == 'profile') {
142 $profile_photo = $photo->value;
148 if (isset($entry->updated)) {
149 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
152 if (isset($entry->network)) {
153 $network = $entry->network;
156 if (isset($entry->currentLocation)) {
157 $location = $entry->currentLocation;
160 if (isset($entry->aboutMe)) {
161 $about = html2bbcode($entry->aboutMe);
164 if (isset($entry->gender)) {
165 $gender = $entry->gender;
168 if (isset($entry->generation) && ($entry->generation > 0)) {
169 $generation = ++$entry->generation;
172 if (isset($entry->tags)) {
173 foreach ($entry->tags as $tag) {
174 $keywords = implode(", ", $tag);
178 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
179 $contact_type = $entry->contactType;
182 $gcontact = array("url" => $profile_url,
184 "network" => $network,
185 "photo" => $profile_photo,
187 "location" => $location,
189 "keywords" => $keywords,
190 "connect" => $connect_url,
191 "updated" => $updated,
192 "contact-type" => $contact_type,
193 "generation" => $generation);
196 $gcontact = GContact::sanitize($gcontact);
197 $gcid = GContact::update($gcontact);
199 GContact::link($gcid, $uid, $cid, $zcid);
200 } catch (Exception $e) {
201 logger($e->getMessage(), LOGGER_DEBUG);
204 logger("load: loaded $total entries", LOGGER_DEBUG);
207 "DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
214 public static function reachable($profile, $server = "", $network = "", $force = false)
217 $server = self::detectServer($profile);
224 return self::checkServer($server, $network, $force);
227 public static function detectServer($profile)
229 // Try to detect the server path based upon some known standard paths
232 if ($server_url == "") {
233 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
234 if ($friendica != $profile) {
235 $server_url = $friendica;
236 $network = NETWORK_DFRN;
240 if ($server_url == "") {
241 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
242 if ($diaspora != $profile) {
243 $server_url = $diaspora;
244 $network = NETWORK_DIASPORA;
248 if ($server_url == "") {
249 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
250 if ($red != $profile) {
252 $network = NETWORK_DIASPORA;
257 if ($server_url == "") {
258 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
259 if ($mastodon != $profile) {
260 $server_url = $mastodon;
261 $network = NETWORK_OSTATUS;
265 // Numeric OStatus variant
266 if ($server_url == "") {
267 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
268 if ($ostatus != $profile) {
269 $server_url = $ostatus;
270 $network = NETWORK_OSTATUS;
275 if ($server_url == "") {
276 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
277 if ($base != $profile) {
279 $network = NETWORK_PHANTOM;
283 if ($server_url == "") {
288 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
289 dbesc(normalise_link($server_url))
292 if (DBM::is_result($r)) {
296 // Fetch the host-meta to check if this really is a server
297 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
298 if (!$serverret["success"]) {
305 public static function alternateOStatusUrl($url)
307 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
310 public static function lastUpdated($profile, $force = false)
313 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
314 dbesc(normalise_link($profile))
317 if (!DBM::is_result($gcontacts)) {
321 $contact = array("url" => $profile);
323 if ($gcontacts[0]["created"] <= NULL_DATE) {
324 $contact['created'] = datetime_convert();
328 $server_url = normalise_link(self::detectServer($profile));
331 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
332 $server_url = $gcontacts[0]["server_url"];
335 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
336 $server_url = normalise_link(self::detectServer($profile));
339 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
340 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
344 if ($server_url != "") {
345 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
348 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
349 dbesc(datetime_convert()),
350 dbesc(normalise_link($profile))
354 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
357 $contact['server_url'] = $server_url;
360 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
362 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
363 dbesc(normalise_link($server_url))
367 $contact['network'] = $server[0]["network"];
373 // noscrape is really fast so we don't cache the call.
374 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
375 // Use noscrape if possible
376 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
379 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
381 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
382 $noscrape = json_decode($noscraperet["body"], true);
384 if (is_array($noscrape)) {
385 $contact["network"] = $server[0]["network"];
387 if (isset($noscrape["fn"])) {
388 $contact["name"] = $noscrape["fn"];
390 if (isset($noscrape["comm"])) {
391 $contact["community"] = $noscrape["comm"];
393 if (isset($noscrape["tags"])) {
394 $keywords = implode(" ", $noscrape["tags"]);
395 if ($keywords != "") {
396 $contact["keywords"] = $keywords;
400 $location = Profile::formatLocation($noscrape);
402 $contact["location"] = $location;
404 if (isset($noscrape["dfrn-notify"])) {
405 $contact["notify"] = $noscrape["dfrn-notify"];
407 // Remove all fields that are not present in the gcontact table
408 unset($noscrape["fn"]);
409 unset($noscrape["key"]);
410 unset($noscrape["homepage"]);
411 unset($noscrape["comm"]);
412 unset($noscrape["tags"]);
413 unset($noscrape["locality"]);
414 unset($noscrape["region"]);
415 unset($noscrape["country-name"]);
416 unset($noscrape["contacts"]);
417 unset($noscrape["dfrn-request"]);
418 unset($noscrape["dfrn-confirm"]);
419 unset($noscrape["dfrn-notify"]);
420 unset($noscrape["dfrn-poll"]);
422 // Set the date of the last contact
423 /// @todo By now the function "update_gcontact" doesn't work with this field
424 //$contact["last_contact"] = datetime_convert();
426 $contact = array_merge($contact, $noscrape);
428 GContact::update($contact);
430 if (trim($noscrape["updated"]) != "") {
432 "UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
433 dbesc(datetime_convert()),
434 dbesc(normalise_link($profile))
437 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
439 return $noscrape["updated"];
446 // If we only can poll the feed, then we only do this once a while
447 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
448 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
450 GContact::update($contact);
451 return $gcontacts[0]["updated"];
454 $data = Probe::uri($profile);
456 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
457 // Then check the other link and delete this one
458 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
459 && (normalise_link($profile) == normalise_link($data["alias"]))
460 && (normalise_link($profile) != normalise_link($data["url"]))
462 // Delete the old entry
463 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
464 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
466 $gcontact = array_merge($gcontacts[0], $data);
468 $gcontact["server_url"] = $data["baseurl"];
471 $gcontact = GContact::sanitize($gcontact);
472 GContact::update($gcontact);
474 self::lastUpdated($data["url"], $force);
475 } catch (Exception $e) {
476 logger($e->getMessage(), LOGGER_DEBUG);
479 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
483 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
485 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
486 dbesc(datetime_convert()),
487 dbesc(normalise_link($profile))
490 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
494 $contact = array_merge($contact, $data);
496 $contact["server_url"] = $data["baseurl"];
498 GContact::update($contact);
500 $feedret = z_fetch_url($data["poll"]);
502 if (!$feedret["success"]) {
504 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
505 dbesc(datetime_convert()),
506 dbesc(normalise_link($profile))
509 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
513 $doc = new DOMDocument();
514 @$doc->loadXML($feedret["body"]);
516 $xpath = new DOMXPath($doc);
517 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
519 $entries = $xpath->query('/atom:feed/atom:entry');
523 foreach ($entries as $entry) {
524 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
525 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
527 if ($last_updated < $published)
528 $last_updated = $published;
530 if ($last_updated < $updated)
531 $last_updated = $updated;
534 // Maybe there aren't any entries. Then check if it is a valid feed
535 if ($last_updated == "") {
536 if ($xpath->query('/atom:feed')->length > 0) {
537 $last_updated = NULL_DATE;
541 "UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
542 dbesc(DBM::date($last_updated)),
544 dbesc(normalise_link($profile))
547 if (($gcontacts[0]["generation"] == 0)) {
549 "UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
550 dbesc(normalise_link($profile))
554 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
556 return($last_updated);
559 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
561 $now = strtotime(datetime_convert());
563 if ($updated > $last_contact) {
564 $contact_time = strtotime($updated);
566 $contact_time = strtotime($last_contact);
569 $failure_time = strtotime($last_failure);
570 $created_time = strtotime($created);
572 // If there is no "created" time then use the current time
573 if ($created_time <= 0) {
574 $created_time = $now;
577 // If the last contact was less than 24 hours then don't update
578 if (($now - $contact_time) < (60 * 60 * 24)) {
582 // If the last failure was less than 24 hours then don't update
583 if (($now - $failure_time) < (60 * 60 * 24)) {
587 // If the last contact was less than a week ago and the last failure is older than a week then don't update
588 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
591 // 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
592 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
596 // 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
597 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
604 public static function toBoolean($val)
606 if (($val == "true") || ($val == 1)) {
608 } elseif (($val == "false") || ($val == 0)) {
616 * @brief Detect server type (Hubzilla or Friendica) via the poco data
618 * @param object $data POCO data
619 * @return array Server data
621 public static function detectPocoData($data)
625 if (!isset($data->entry)) {
629 if (count($data->entry) == 0) {
633 if (!isset($data->entry[0]->urls)) {
637 if (count($data->entry[0]->urls) == 0) {
641 foreach ($data->entry[0]->urls as $url) {
642 if ($url->type == 'zot') {
644 $server["platform"] = 'Hubzilla';
645 $server["network"] = NETWORK_DIASPORA;
653 * @brief Detect server type by using the nodeinfo data
655 * @param string $server_url address of the server
656 * @return array Server data
658 public static function fetchNodeinfo($server_url)
660 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
661 if (!$serverret["success"]) {
665 $nodeinfo = json_decode($serverret['body']);
667 if (!is_object($nodeinfo)) {
671 if (!is_array($nodeinfo->links)) {
677 foreach ($nodeinfo->links as $link) {
678 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
679 $nodeinfo_url = $link->href;
683 if ($nodeinfo_url == '') {
687 $serverret = z_fetch_url($nodeinfo_url);
688 if (!$serverret["success"]) {
692 $nodeinfo = json_decode($serverret['body']);
694 if (!is_object($nodeinfo)) {
700 $server['register_policy'] = REGISTER_CLOSED;
702 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
703 $server['register_policy'] = REGISTER_OPEN;
706 if (is_object($nodeinfo->software)) {
707 if (isset($nodeinfo->software->name)) {
708 $server['platform'] = $nodeinfo->software->name;
711 if (isset($nodeinfo->software->version)) {
712 $server['version'] = $nodeinfo->software->version;
713 // Version numbers on Nodeinfo are presented with additional info, e.g.:
714 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
715 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
719 if (is_object($nodeinfo->metadata)) {
720 if (isset($nodeinfo->metadata->nodeName)) {
721 $server['site_name'] = $nodeinfo->metadata->nodeName;
729 if (is_array($nodeinfo->protocols->inbound)) {
730 foreach ($nodeinfo->protocols->inbound as $inbound) {
731 if ($inbound == 'diaspora') {
734 if ($inbound == 'friendica') {
737 if ($inbound == 'gnusocial') {
744 $server['network'] = NETWORK_OSTATUS;
747 $server['network'] = NETWORK_DIASPORA;
750 $server['network'] = NETWORK_DFRN;
761 * @brief Detect server type (Hubzilla or Friendica) via the front page body
763 * @param string $body Front page of the server
764 * @return array Server data
766 public static function detectServerType($body)
770 $doc = new DOMDocument();
771 @$doc->loadHTML($body);
772 $xpath = new DOMXPath($doc);
774 $list = $xpath->query("//meta[@name]");
776 foreach ($list as $node) {
778 if ($node->attributes->length) {
779 foreach ($node->attributes as $attribute) {
780 $attr[$attribute->name] = $attribute->value;
783 if ($attr['name'] == 'generator') {
784 $version_part = explode(" ", $attr['content']);
785 if (count($version_part) == 2) {
786 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
788 $server["platform"] = $version_part[0];
789 $server["version"] = $version_part[1];
790 $server["network"] = NETWORK_DFRN;
797 $list = $xpath->query("//meta[@property]");
799 foreach ($list as $node) {
801 if ($node->attributes->length) {
802 foreach ($node->attributes as $attribute) {
803 $attr[$attribute->name] = $attribute->value;
806 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
808 $server["platform"] = $attr['content'];
809 $server["version"] = "";
810 $server["network"] = NETWORK_DIASPORA;
819 /// @fixme $element is unavailable here
820 $server["site_name"] = $xpath->evaluate($element."//head/title/text()")->item(0)->nodeValue;
824 public static function checkServer($server_url, $network = "", $force = false)
826 // Unify the server address
827 $server_url = trim($server_url, "/");
828 $server_url = str_replace("/index.php", "", $server_url);
830 if ($server_url == "") {
834 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
835 if (DBM::is_result($servers)) {
836 if ($servers[0]["created"] <= NULL_DATE) {
838 "UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
839 dbesc(datetime_convert()),
840 dbesc(normalise_link($server_url))
843 $poco = $servers[0]["poco"];
844 $noscrape = $servers[0]["noscrape"];
846 if ($network == "") {
847 $network = $servers[0]["network"];
850 $last_contact = $servers[0]["last_contact"];
851 $last_failure = $servers[0]["last_failure"];
852 $version = $servers[0]["version"];
853 $platform = $servers[0]["platform"];
854 $site_name = $servers[0]["site_name"];
855 $info = $servers[0]["info"];
856 $register_policy = $servers[0]["register_policy"];
858 if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
859 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
860 return ($last_contact >= $last_failure);
869 $register_policy = -1;
871 $last_contact = NULL_DATE;
872 $last_failure = NULL_DATE;
874 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
877 $possible_failure = false;
878 $orig_last_failure = $last_failure;
879 $orig_last_contact = $last_contact;
881 // Check if the page is accessible via SSL.
882 $orig_server_url = $server_url;
883 $server_url = str_replace("http://", "https://", $server_url);
885 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
886 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
888 // Quit if there is a timeout.
889 // But we want to make sure to only quit if we are mostly sure that this server url fits.
890 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
891 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
892 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
893 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
897 // Maybe the page is unencrypted only?
898 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
899 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
900 $server_url = str_replace("https://", "http://", $server_url);
902 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
903 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
905 // Quit if there is a timeout
906 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
907 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
908 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
912 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
915 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
916 // Workaround for bad configured servers (known nginx problem)
917 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
920 $possible_failure = true;
923 // If the server has no possible failure we reset the cached data
924 if (!$possible_failure) {
929 $register_policy = -1;
934 $serverret = z_fetch_url($server_url."/poco");
935 if ($serverret["success"]) {
936 $data = json_decode($serverret["body"]);
937 if (isset($data->totalResults)) {
938 $poco = $server_url."/poco";
939 $server = self::detectPocoData($data);
941 $platform = $server['platform'];
942 $network = $server['network'];
951 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
952 $serverret = z_fetch_url($server_url);
954 if (!$serverret["success"] || ($serverret["body"] == "")) {
957 $server = self::detectServerType($serverret["body"]);
959 $platform = $server['platform'];
960 $network = $server['network'];
961 $version = $server['version'];
962 $site_name = $server['site_name'];
965 $lines = explode("\n", $serverret["header"]);
967 foreach ($lines as $line) {
969 if (stristr($line, 'X-Diaspora-Version:')) {
970 $platform = "Diaspora";
971 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
972 $version = trim(str_replace("x-diaspora-version:", "", $version));
973 $network = NETWORK_DIASPORA;
974 $versionparts = explode("-", $version);
975 $version = $versionparts[0];
978 if (stristr($line, 'Server: Mastodon')) {
979 $platform = "Mastodon";
980 $network = NETWORK_OSTATUS;
987 if (!$failure && ($poco == "")) {
988 // Test for Statusnet
989 // Will also return data for Friendica and GNU Social - but it will be overwritten later
990 // The "not implemented" is a special treatment for really, really old Friendica versions
991 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
992 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
993 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
994 $platform = "StatusNet";
995 // Remove junk that some GNU Social servers return
996 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
997 $version = trim($version, '"');
998 $network = NETWORK_OSTATUS;
1001 // Test for GNU Social
1002 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1003 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1004 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1005 $platform = "GNU Social";
1006 // Remove junk that some GNU Social servers return
1007 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1008 $version = trim($version, '"');
1009 $network = NETWORK_OSTATUS;
1012 // Test for Mastodon
1013 $orig_version = $version;
1014 $serverret = z_fetch_url($server_url."/api/v1/instance");
1015 if ($serverret["success"] && ($serverret["body"] != '')) {
1016 $data = json_decode($serverret["body"]);
1017 if (isset($data->version)) {
1018 $platform = "Mastodon";
1019 $version = $data->version;
1020 $site_name = $data->title;
1021 $info = $data->description;
1022 $network = NETWORK_OSTATUS;
1025 if (strstr($orig_version.$version, 'Pleroma')) {
1026 $platform = 'Pleroma';
1027 $version = trim(str_replace('Pleroma', '', $version));
1032 // Test for Hubzilla and Red
1033 $serverret = z_fetch_url($server_url."/siteinfo.json");
1034 if ($serverret["success"]) {
1035 $data = json_decode($serverret["body"]);
1036 if (isset($data->url)) {
1037 $platform = $data->platform;
1038 $version = $data->version;
1039 $network = NETWORK_DIASPORA;
1041 if (!empty($data->site_name)) {
1042 $site_name = $data->site_name;
1044 switch ($data->register_policy) {
1045 case "REGISTER_OPEN":
1046 $register_policy = REGISTER_OPEN;
1048 case "REGISTER_APPROVE":
1049 $register_policy = REGISTER_APPROVE;
1051 case "REGISTER_CLOSED":
1053 $register_policy = REGISTER_CLOSED;
1057 // Test for Hubzilla, Redmatrix or Friendica
1058 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1059 if ($serverret["success"]) {
1060 $data = json_decode($serverret["body"]);
1061 if (isset($data->site->server)) {
1062 if (isset($data->site->platform)) {
1063 $platform = $data->site->platform->PLATFORM_NAME;
1064 $version = $data->site->platform->STD_VERSION;
1065 $network = NETWORK_DIASPORA;
1067 if (isset($data->site->BlaBlaNet)) {
1068 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1069 $version = $data->site->BlaBlaNet->STD_VERSION;
1070 $network = NETWORK_DIASPORA;
1072 if (isset($data->site->hubzilla)) {
1073 $platform = $data->site->hubzilla->PLATFORM_NAME;
1074 $version = $data->site->hubzilla->RED_VERSION;
1075 $network = NETWORK_DIASPORA;
1077 if (isset($data->site->redmatrix)) {
1078 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1079 $platform = $data->site->redmatrix->PLATFORM_NAME;
1080 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1081 $platform = $data->site->redmatrix->RED_PLATFORM;
1084 $version = $data->site->redmatrix->RED_VERSION;
1085 $network = NETWORK_DIASPORA;
1087 if (isset($data->site->friendica)) {
1088 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1089 $version = $data->site->friendica->FRIENDICA_VERSION;
1090 $network = NETWORK_DFRN;
1093 $site_name = $data->site->name;
1095 $data->site->closed = self::toBoolean($data->site->closed);
1096 $data->site->private = self::toBoolean($data->site->private);
1097 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1099 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1100 $register_policy = REGISTER_APPROVE;
1101 } elseif (!$data->site->closed && !$data->site->private) {
1102 $register_policy = REGISTER_OPEN;
1104 $register_policy = REGISTER_CLOSED;
1111 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1113 $serverret = z_fetch_url($server_url."/statistics.json");
1114 if ($serverret["success"]) {
1115 $data = json_decode($serverret["body"]);
1116 if (isset($data->version)) {
1117 $version = $data->version;
1118 // Version numbers on statistics.json are presented with additional info, e.g.:
1119 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1120 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1123 if (!empty($data->name)) {
1124 $site_name = $data->name;
1127 if (!empty($data->network)) {
1128 $platform = $data->network;
1131 if ($platform == "Diaspora") {
1132 $network = NETWORK_DIASPORA;
1135 if ($data->registrations_open) {
1136 $register_policy = REGISTER_OPEN;
1138 $register_policy = REGISTER_CLOSED;
1143 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1145 $server = self::fetchNodeinfo($server_url);
1147 $register_policy = $server['register_policy'];
1149 if (isset($server['platform'])) {
1150 $platform = $server['platform'];
1153 if (isset($server['network'])) {
1154 $network = $server['network'];
1157 if (isset($server['version'])) {
1158 $version = $server['version'];
1161 if (isset($server['site_name'])) {
1162 $site_name = $server['site_name'];
1167 // Check for noscrape
1168 // Friendica servers could be detected as OStatus servers
1169 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1170 $serverret = z_fetch_url($server_url."/friendica/json");
1172 if (!$serverret["success"]) {
1173 $serverret = z_fetch_url($server_url."/friendika/json");
1176 if ($serverret["success"]) {
1177 $data = json_decode($serverret["body"]);
1179 if (isset($data->version)) {
1180 $network = NETWORK_DFRN;
1182 $noscrape = $data->no_scrape_url;
1183 $version = $data->version;
1184 $site_name = $data->site_name;
1185 $info = $data->info;
1186 $register_policy_str = $data->register_policy;
1187 $platform = $data->platform;
1189 switch ($register_policy_str) {
1190 case "REGISTER_CLOSED":
1191 $register_policy = REGISTER_CLOSED;
1193 case "REGISTER_APPROVE":
1194 $register_policy = REGISTER_APPROVE;
1196 case "REGISTER_OPEN":
1197 $register_policy = REGISTER_OPEN;
1204 if ($possible_failure && !$failure) {
1209 $last_contact = $orig_last_contact;
1210 $last_failure = datetime_convert();
1212 $last_contact = datetime_convert();
1213 $last_failure = $orig_last_failure;
1216 if (($last_contact <= $last_failure) && !$failure) {
1217 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1218 } elseif (($last_contact >= $last_failure) && $failure) {
1219 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1222 // Check again if the server exists
1223 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1225 $version = strip_tags($version);
1226 $site_name = strip_tags($site_name);
1227 $info = strip_tags($info);
1228 $platform = strip_tags($platform);
1232 "UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1233 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1238 intval($register_policy),
1243 dbesc($last_contact),
1244 dbesc($last_failure),
1245 dbesc(normalise_link($server_url))
1247 } elseif (!$failure) {
1249 "INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1250 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1252 dbesc(normalise_link($server_url)),
1256 intval($register_policy),
1261 dbesc(datetime_convert()),
1262 dbesc($last_contact),
1263 dbesc($last_failure),
1264 dbesc(datetime_convert())
1267 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1273 * @brief Returns a list of all known servers
1274 * @return array List of server urls
1276 public static function serverlist()
1279 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1280 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1281 ORDER BY `last_contact`
1283 dbesc(NETWORK_DFRN),
1284 dbesc(NETWORK_DIASPORA),
1285 dbesc(NETWORK_OSTATUS)
1288 if (!DBM::is_result($r)) {
1296 * @brief Fetch server list from remote servers and adds them when they are new.
1298 * @param string $poco URL to the POCO endpoint
1300 public static function fetchServerlist($poco)
1302 $serverret = z_fetch_url($poco."/@server");
1303 if (!$serverret["success"]) {
1306 $serverlist = json_decode($serverret['body']);
1308 if (!is_array($serverlist)) {
1312 foreach ($serverlist as $server) {
1313 $server_url = str_replace("/index.php", "", $server->url);
1315 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1316 if (!DBM::is_result($r)) {
1317 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1318 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1323 public static function discoverFederation()
1325 $last = Config::get('poco', 'last_federation_discovery');
1328 $next = $last + (24 * 60 * 60);
1329 if ($next > time()) {
1334 // Discover Friendica, Hubzilla and Diaspora servers
1335 $serverdata = fetch_url("http://the-federation.info/pods.json");
1338 $servers = json_decode($serverdata);
1340 foreach ($servers->pods as $server) {
1341 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1345 // Disvover Mastodon servers
1346 if (!Config::get('system', 'ostatus_disabled')) {
1347 $accesstoken = Config::get('system', 'instances_social_key');
1348 if (!empty($accesstoken)) {
1349 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1350 $header = array('Authorization: Bearer '.$accesstoken);
1351 $serverdata = z_fetch_url($api, false, $redirects, ['headers' => $header]);
1352 if ($serverdata['success']) {
1353 $servers = json_decode($serverdata['body']);
1354 foreach ($servers->instances as $server) {
1355 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1356 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1362 // Currently disabled, since the service isn't available anymore.
1363 // It is not removed since I hope that there will be a successor.
1364 // Discover GNU Social Servers.
1365 //if (!Config::get('system','ostatus_disabled')) {
1366 // $serverdata = "http://gstools.org/api/get_open_instances/";
1368 // $result = z_fetch_url($serverdata);
1369 // if ($result["success"]) {
1370 // $servers = json_decode($result["body"]);
1372 // foreach($servers->data as $server)
1373 // self::checkServer($server->instance_address);
1377 Config::set('poco', 'last_federation_discovery', time());
1380 public static function discoverSingleServer($id)
1382 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1383 if (!DBM::is_result($r)) {
1389 // Discover new servers out there (Works from Friendica version 3.5.2)
1390 self::fetchServerlist($server["poco"]);
1392 // Fetch all users from the other server
1393 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1395 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1397 $retdata = z_fetch_url($url);
1398 if ($retdata["success"]) {
1399 $data = json_decode($retdata["body"]);
1401 self::discoverServer($data, 2);
1403 if (Config::get('system', 'poco_discovery') > 1) {
1404 $timeframe = Config::get('system', 'poco_discovery_since');
1405 if ($timeframe == 0) {
1409 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1411 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1412 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1416 $retdata = z_fetch_url($url);
1417 if ($retdata["success"]) {
1418 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1419 $success = self::discoverServer(json_decode($retdata["body"]));
1422 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1423 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1424 self::discoverServerUsers($data, $server);
1428 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1432 // If the server hadn't replied correctly, then force a sanity check
1433 self::checkServer($server["url"], $server["network"], true);
1435 // If we couldn't reach the server, we will try it some time later
1436 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1442 public static function discover($complete = false)
1444 // Update the server list
1445 self::discoverFederation();
1449 $requery_days = intval(Config::get("system", "poco_requery_days"));
1451 if ($requery_days == 0) {
1454 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1456 $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1457 if (DBM::is_result($r)) {
1458 foreach ($r as $server) {
1459 if (!self::checkServer($server["url"], $server["network"])) {
1460 // The server is not reachable? Okay, then we will try it later
1461 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1465 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1466 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1468 if (!$complete && (--$no_of_queries == 0)) {
1475 public static function discoverServerUsers($data, $server)
1477 if (!isset($data->entry)) {
1481 foreach ($data->entry as $entry) {
1483 if (isset($entry->urls)) {
1484 foreach ($entry->urls as $url) {
1485 if ($url->type == 'profile') {
1486 $profile_url = $url->value;
1487 $urlparts = parse_url($profile_url);
1488 $username = end(explode("/", $urlparts["path"]));
1492 if ($username != "") {
1493 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1495 // Fetch all contacts from a given user from the other server
1496 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1498 $retdata = z_fetch_url($url);
1499 if ($retdata["success"]) {
1500 self::discoverServer(json_decode($retdata["body"]), 3);
1506 public static function discoverServer($data, $default_generation = 0)
1508 if (!isset($data->entry) || !count($data->entry)) {
1514 foreach ($data->entry as $entry) {
1516 $profile_photo = '';
1520 $updated = NULL_DATE;
1526 $generation = $default_generation;
1528 $name = $entry->displayName;
1530 if (isset($entry->urls)) {
1531 foreach ($entry->urls as $url) {
1532 if ($url->type == 'profile') {
1533 $profile_url = $url->value;
1536 if ($url->type == 'webfinger') {
1537 $connect_url = str_replace('acct:' , '', $url->value);
1543 if (isset($entry->photos)) {
1544 foreach ($entry->photos as $photo) {
1545 if ($photo->type == 'profile') {
1546 $profile_photo = $photo->value;
1552 if (isset($entry->updated)) {
1553 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1556 if (isset($entry->network)) {
1557 $network = $entry->network;
1560 if (isset($entry->currentLocation)) {
1561 $location = $entry->currentLocation;
1564 if (isset($entry->aboutMe)) {
1565 $about = html2bbcode($entry->aboutMe);
1568 if (isset($entry->gender)) {
1569 $gender = $entry->gender;
1572 if (isset($entry->generation) && ($entry->generation > 0)) {
1573 $generation = ++$entry->generation;
1576 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1577 $contact_type = $entry->contactType;
1580 if (isset($entry->tags)) {
1581 foreach ($entry->tags as $tag) {
1582 $keywords = implode(", ", $tag);
1586 if ($generation > 0) {
1589 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1591 $gcontact = array("url" => $profile_url,
1593 "network" => $network,
1594 "photo" => $profile_photo,
1596 "location" => $location,
1597 "gender" => $gender,
1598 "keywords" => $keywords,
1599 "connect" => $connect_url,
1600 "updated" => $updated,
1601 "contact-type" => $contact_type,
1602 "generation" => $generation);
1605 $gcontact = GContact::sanitize($gcontact);
1606 GContact::update($gcontact);
1607 } catch (Exception $e) {
1608 logger($e->getMessage(), LOGGER_DEBUG);
1611 logger("Done for profile ".$profile_url, LOGGER_DEBUG);