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;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBM;
18 use Friendica\Model\GlobalContact;
19 use Friendica\Network\Probe;
20 use Friendica\Object\Profile;
26 require_once 'include/datetime.php';
27 require_once 'include/network.php';
28 require_once 'include/html2bbcode.php';
29 require_once 'include/Photo.php';
34 * @brief Fetch POCO data
36 * @param integer $cid Contact ID
37 * @param integer $uid User ID
38 * @param integer $zcid Global Contact ID
39 * @param integer $url POCO address that should be polled
41 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
42 * and add the entries to the gcontact (Global Contact) table, or update existing entries
43 * if anything (name or photo) has changed.
44 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
46 * Once the global contact is stored add (if necessary) the contact linkage which associates
47 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
48 * pointing to the same global contact id.
51 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
53 // Call the function "load" via the worker
54 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
58 * @brief Fetch POCO data from the worker
60 * @param integer $cid Contact ID
61 * @param integer $uid User ID
62 * @param integer $zcid Global Contact ID
63 * @param integer $url POCO address that should be polled
66 public static function load($cid, $uid, $zcid, $url)
71 if ((! $url) || (! $uid)) {
73 "select `poco`, `uid` from `contact` where `id` = %d limit 1",
76 if (DBM::is_result($r)) {
90 $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') ;
92 logger('load: ' . $url, LOGGER_DEBUG);
96 logger('load: returns ' . $s, LOGGER_DATA);
98 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
100 if (($a->get_curl_code() > 299) || (! $s)) {
104 $j = json_decode($s);
106 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
108 if (! isset($j->entry)) {
113 foreach ($j->entry as $entry) {
120 $updated = NULL_DATE;
128 $name = $entry->displayName;
130 if (isset($entry->urls)) {
131 foreach ($entry->urls as $url) {
132 if ($url->type == 'profile') {
133 $profile_url = $url->value;
136 if ($url->type == 'webfinger') {
137 $connect_url = str_replace('acct:', '', $url->value);
142 if (isset($entry->photos)) {
143 foreach ($entry->photos as $photo) {
144 if ($photo->type == 'profile') {
145 $profile_photo = $photo->value;
151 if (isset($entry->updated)) {
152 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
155 if (isset($entry->network)) {
156 $network = $entry->network;
159 if (isset($entry->currentLocation)) {
160 $location = $entry->currentLocation;
163 if (isset($entry->aboutMe)) {
164 $about = html2bbcode($entry->aboutMe);
167 if (isset($entry->gender)) {
168 $gender = $entry->gender;
171 if (isset($entry->generation) && ($entry->generation > 0)) {
172 $generation = ++$entry->generation;
175 if (isset($entry->tags)) {
176 foreach ($entry->tags as $tag) {
177 $keywords = implode(", ", $tag);
181 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
182 $contact_type = $entry->contactType;
185 $gcontact = array("url" => $profile_url,
187 "network" => $network,
188 "photo" => $profile_photo,
190 "location" => $location,
192 "keywords" => $keywords,
193 "connect" => $connect_url,
194 "updated" => $updated,
195 "contact-type" => $contact_type,
196 "generation" => $generation);
199 $gcontact = GlobalContact::sanitize($gcontact);
200 $gcid = GlobalContact::update($gcontact);
202 GlobalContact::link($gcid, $uid, $cid, $zcid);
203 } catch (Exception $e) {
204 logger($e->getMessage(), LOGGER_DEBUG);
207 logger("load: loaded $total entries", LOGGER_DEBUG);
210 "DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
217 public static function reachable($profile, $server = "", $network = "", $force = false)
220 $server = self::detectServer($profile);
227 return self::checkServer($server, $network, $force);
230 public static function detectServer($profile)
232 // Try to detect the server path based upon some known standard paths
235 if ($server_url == "") {
236 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
237 if ($friendica != $profile) {
238 $server_url = $friendica;
239 $network = NETWORK_DFRN;
243 if ($server_url == "") {
244 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
245 if ($diaspora != $profile) {
246 $server_url = $diaspora;
247 $network = NETWORK_DIASPORA;
251 if ($server_url == "") {
252 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
253 if ($red != $profile) {
255 $network = NETWORK_DIASPORA;
260 if ($server_url == "") {
261 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
262 if ($mastodon != $profile) {
263 $server_url = $mastodon;
264 $network = NETWORK_OSTATUS;
268 // Numeric OStatus variant
269 if ($server_url == "") {
270 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
271 if ($ostatus != $profile) {
272 $server_url = $ostatus;
273 $network = NETWORK_OSTATUS;
278 if ($server_url == "") {
279 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
280 if ($base != $profile) {
282 $network = NETWORK_PHANTOM;
286 if ($server_url == "") {
291 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
292 dbesc(normalise_link($server_url))
295 if (DBM::is_result($r)) {
299 // Fetch the host-meta to check if this really is a server
300 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
301 if (!$serverret["success"]) {
308 public static function alternateOStatusUrl($url)
310 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
313 public static function lastUpdated($profile, $force = false)
316 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
317 dbesc(normalise_link($profile))
320 if (!DBM::is_result($gcontacts)) {
324 $contact = array("url" => $profile);
326 if ($gcontacts[0]["created"] <= NULL_DATE) {
327 $contact['created'] = datetime_convert();
331 $server_url = normalise_link(self::detectServer($profile));
334 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
335 $server_url = $gcontacts[0]["server_url"];
338 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
339 $server_url = normalise_link(self::detectServer($profile));
342 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
343 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
347 if ($server_url != "") {
348 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
351 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
352 dbesc(datetime_convert()),
353 dbesc(normalise_link($profile))
357 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
360 $contact['server_url'] = $server_url;
363 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
365 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
366 dbesc(normalise_link($server_url))
370 $contact['network'] = $server[0]["network"];
376 // noscrape is really fast so we don't cache the call.
377 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
378 // Use noscrape if possible
379 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
382 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
384 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
385 $noscrape = json_decode($noscraperet["body"], true);
387 if (is_array($noscrape)) {
388 $contact["network"] = $server[0]["network"];
390 if (isset($noscrape["fn"])) {
391 $contact["name"] = $noscrape["fn"];
393 if (isset($noscrape["comm"])) {
394 $contact["community"] = $noscrape["comm"];
396 if (isset($noscrape["tags"])) {
397 $keywords = implode(" ", $noscrape["tags"]);
398 if ($keywords != "") {
399 $contact["keywords"] = $keywords;
403 $location = Profile::formatLocation($noscrape);
405 $contact["location"] = $location;
407 if (isset($noscrape["dfrn-notify"])) {
408 $contact["notify"] = $noscrape["dfrn-notify"];
410 // Remove all fields that are not present in the gcontact table
411 unset($noscrape["fn"]);
412 unset($noscrape["key"]);
413 unset($noscrape["homepage"]);
414 unset($noscrape["comm"]);
415 unset($noscrape["tags"]);
416 unset($noscrape["locality"]);
417 unset($noscrape["region"]);
418 unset($noscrape["country-name"]);
419 unset($noscrape["contacts"]);
420 unset($noscrape["dfrn-request"]);
421 unset($noscrape["dfrn-confirm"]);
422 unset($noscrape["dfrn-notify"]);
423 unset($noscrape["dfrn-poll"]);
425 // Set the date of the last contact
426 /// @todo By now the function "update_gcontact" doesn't work with this field
427 //$contact["last_contact"] = datetime_convert();
429 $contact = array_merge($contact, $noscrape);
431 GlobalContact::update($contact);
433 if (trim($noscrape["updated"]) != "") {
435 "UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
436 dbesc(datetime_convert()),
437 dbesc(normalise_link($profile))
440 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
442 return $noscrape["updated"];
449 // If we only can poll the feed, then we only do this once a while
450 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
451 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
453 GlobalContact::update($contact);
454 return $gcontacts[0]["updated"];
457 $data = Probe::uri($profile);
459 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
460 // Then check the other link and delete this one
461 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
462 && (normalise_link($profile) == normalise_link($data["alias"]))
463 && (normalise_link($profile) != normalise_link($data["url"]))
465 // Delete the old entry
466 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
467 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
469 $gcontact = array_merge($gcontacts[0], $data);
471 $gcontact["server_url"] = $data["baseurl"];
474 $gcontact = GlobalContact::sanitize($gcontact);
475 GlobalContact::update($gcontact);
477 self::lastUpdated($data["url"], $force);
478 } catch (Exception $e) {
479 logger($e->getMessage(), LOGGER_DEBUG);
482 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
486 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
488 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
489 dbesc(datetime_convert()),
490 dbesc(normalise_link($profile))
493 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
497 $contact = array_merge($contact, $data);
499 $contact["server_url"] = $data["baseurl"];
501 GlobalContact::update($contact);
503 $feedret = z_fetch_url($data["poll"]);
505 if (!$feedret["success"]) {
507 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
508 dbesc(datetime_convert()),
509 dbesc(normalise_link($profile))
512 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
516 $doc = new DOMDocument();
517 @$doc->loadXML($feedret["body"]);
519 $xpath = new DomXPath($doc);
520 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
522 $entries = $xpath->query('/atom:feed/atom:entry');
526 foreach ($entries as $entry) {
527 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
528 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
530 if ($last_updated < $published)
531 $last_updated = $published;
533 if ($last_updated < $updated)
534 $last_updated = $updated;
537 // Maybe there aren't any entries. Then check if it is a valid feed
538 if ($last_updated == "") {
539 if ($xpath->query('/atom:feed')->length > 0) {
540 $last_updated = NULL_DATE;
544 "UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
545 dbesc(DBM::date($last_updated)),
547 dbesc(normalise_link($profile))
550 if (($gcontacts[0]["generation"] == 0)) {
552 "UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
553 dbesc(normalise_link($profile))
557 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
559 return($last_updated);
562 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
564 $now = strtotime(datetime_convert());
566 if ($updated > $last_contact) {
567 $contact_time = strtotime($updated);
569 $contact_time = strtotime($last_contact);
572 $failure_time = strtotime($last_failure);
573 $created_time = strtotime($created);
575 // If there is no "created" time then use the current time
576 if ($created_time <= 0) {
577 $created_time = $now;
580 // If the last contact was less than 24 hours then don't update
581 if (($now - $contact_time) < (60 * 60 * 24)) {
585 // If the last failure was less than 24 hours then don't update
586 if (($now - $failure_time) < (60 * 60 * 24)) {
590 // If the last contact was less than a week ago and the last failure is older than a week then don't update
591 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
594 // 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
595 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
599 // 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
600 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
607 public static function toBoolean($val)
609 if (($val == "true") || ($val == 1)) {
611 } elseif (($val == "false") || ($val == 0)) {
619 * @brief Detect server type (Hubzilla or Friendica) via the poco data
621 * @param object $data POCO data
622 * @return array Server data
624 public static function detectPocoData($data)
628 if (!isset($data->entry)) {
632 if (count($data->entry) == 0) {
636 if (!isset($data->entry[0]->urls)) {
640 if (count($data->entry[0]->urls) == 0) {
644 foreach ($data->entry[0]->urls as $url) {
645 if ($url->type == 'zot') {
647 $server["platform"] = 'Hubzilla';
648 $server["network"] = NETWORK_DIASPORA;
656 * @brief Detect server type by using the nodeinfo data
658 * @param string $server_url address of the server
659 * @return array Server data
661 public static function fetchNodeinfo($server_url)
663 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
664 if (!$serverret["success"]) {
668 $nodeinfo = json_decode($serverret['body']);
670 if (!is_object($nodeinfo)) {
674 if (!is_array($nodeinfo->links)) {
680 foreach ($nodeinfo->links as $link) {
681 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
682 $nodeinfo_url = $link->href;
686 if ($nodeinfo_url == '') {
690 $serverret = z_fetch_url($nodeinfo_url);
691 if (!$serverret["success"]) {
695 $nodeinfo = json_decode($serverret['body']);
697 if (!is_object($nodeinfo)) {
703 $server['register_policy'] = REGISTER_CLOSED;
705 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
706 $server['register_policy'] = REGISTER_OPEN;
709 if (is_object($nodeinfo->software)) {
710 if (isset($nodeinfo->software->name)) {
711 $server['platform'] = $nodeinfo->software->name;
714 if (isset($nodeinfo->software->version)) {
715 $server['version'] = $nodeinfo->software->version;
716 // Version numbers on Nodeinfo are presented with additional info, e.g.:
717 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
718 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
722 if (is_object($nodeinfo->metadata)) {
723 if (isset($nodeinfo->metadata->nodeName)) {
724 $server['site_name'] = $nodeinfo->metadata->nodeName;
732 if (is_array($nodeinfo->protocols->inbound)) {
733 foreach ($nodeinfo->protocols->inbound as $inbound) {
734 if ($inbound == 'diaspora') {
737 if ($inbound == 'friendica') {
740 if ($inbound == 'gnusocial') {
747 $server['network'] = NETWORK_OSTATUS;
750 $server['network'] = NETWORK_DIASPORA;
753 $server['network'] = NETWORK_DFRN;
764 * @brief Detect server type (Hubzilla or Friendica) via the front page body
766 * @param string $body Front page of the server
767 * @return array Server data
769 public static function detectServerType($body)
773 $doc = new DOMDocument();
774 @$doc->loadHTML($body);
775 $xpath = new DomXPath($doc);
777 $list = $xpath->query("//meta[@name]");
779 foreach ($list as $node) {
781 if ($node->attributes->length) {
782 foreach ($node->attributes as $attribute) {
783 $attr[$attribute->name] = $attribute->value;
786 if ($attr['name'] == 'generator') {
787 $version_part = explode(" ", $attr['content']);
788 if (count($version_part) == 2) {
789 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
791 $server["platform"] = $version_part[0];
792 $server["version"] = $version_part[1];
793 $server["network"] = NETWORK_DFRN;
800 $list = $xpath->query("//meta[@property]");
802 foreach ($list as $node) {
804 if ($node->attributes->length) {
805 foreach ($node->attributes as $attribute) {
806 $attr[$attribute->name] = $attribute->value;
809 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
811 $server["platform"] = $attr['content'];
812 $server["version"] = "";
813 $server["network"] = NETWORK_DIASPORA;
822 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
826 public static function checkServer($server_url, $network = "", $force = false)
828 // Unify the server address
829 $server_url = trim($server_url, "/");
830 $server_url = str_replace("/index.php", "", $server_url);
832 if ($server_url == "") {
836 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
837 if (DBM::is_result($servers)) {
838 if ($servers[0]["created"] <= NULL_DATE) {
840 "UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
841 dbesc(datetime_convert()),
842 dbesc(normalise_link($server_url))
845 $poco = $servers[0]["poco"];
846 $noscrape = $servers[0]["noscrape"];
848 if ($network == "") {
849 $network = $servers[0]["network"];
852 $last_contact = $servers[0]["last_contact"];
853 $last_failure = $servers[0]["last_failure"];
854 $version = $servers[0]["version"];
855 $platform = $servers[0]["platform"];
856 $site_name = $servers[0]["site_name"];
857 $info = $servers[0]["info"];
858 $register_policy = $servers[0]["register_policy"];
860 if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
861 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
862 return ($last_contact >= $last_failure);
871 $register_policy = -1;
873 $last_contact = NULL_DATE;
874 $last_failure = NULL_DATE;
876 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
879 $possible_failure = false;
880 $orig_last_failure = $last_failure;
881 $orig_last_contact = $last_contact;
883 // Check if the page is accessible via SSL.
884 $orig_server_url = $server_url;
885 $server_url = str_replace("http://", "https://", $server_url);
887 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
888 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
890 // Quit if there is a timeout.
891 // But we want to make sure to only quit if we are mostly sure that this server url fits.
892 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
893 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
894 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
895 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
899 // Maybe the page is unencrypted only?
900 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
901 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
902 $server_url = str_replace("https://", "http://", $server_url);
904 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
905 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
907 // Quit if there is a timeout
908 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
909 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
910 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
914 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
917 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
918 // Workaround for bad configured servers (known nginx problem)
919 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
922 $possible_failure = true;
925 // If the server has no possible failure we reset the cached data
926 if (!$possible_failure) {
931 $register_policy = -1;
936 $serverret = z_fetch_url($server_url."/poco");
937 if ($serverret["success"]) {
938 $data = json_decode($serverret["body"]);
939 if (isset($data->totalResults)) {
940 $poco = $server_url."/poco";
941 $server = self::detectPocoData($data);
943 $platform = $server['platform'];
944 $network = $server['network'];
953 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
954 $serverret = z_fetch_url($server_url);
956 if (!$serverret["success"] || ($serverret["body"] == "")) {
959 $server = self::detectServerType($serverret["body"]);
961 $platform = $server['platform'];
962 $network = $server['network'];
963 $version = $server['version'];
964 $site_name = $server['site_name'];
967 $lines = explode("\n", $serverret["header"]);
969 foreach ($lines as $line) {
971 if (stristr($line, 'X-Diaspora-Version:')) {
972 $platform = "Diaspora";
973 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
974 $version = trim(str_replace("x-diaspora-version:", "", $version));
975 $network = NETWORK_DIASPORA;
976 $versionparts = explode("-", $version);
977 $version = $versionparts[0];
980 if (stristr($line, 'Server: Mastodon')) {
981 $platform = "Mastodon";
982 $network = NETWORK_OSTATUS;
989 if (!$failure && ($poco == "")) {
990 // Test for Statusnet
991 // Will also return data for Friendica and GNU Social - but it will be overwritten later
992 // The "not implemented" is a special treatment for really, really old Friendica versions
993 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
994 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
995 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
996 $platform = "StatusNet";
997 // Remove junk that some GNU Social servers return
998 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
999 $version = trim($version, '"');
1000 $network = NETWORK_OSTATUS;
1003 // Test for GNU Social
1004 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1005 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1006 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1007 $platform = "GNU Social";
1008 // Remove junk that some GNU Social servers return
1009 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1010 $version = trim($version, '"');
1011 $network = NETWORK_OSTATUS;
1014 // Test for Mastodon
1015 $orig_version = $version;
1016 $serverret = z_fetch_url($server_url."/api/v1/instance");
1017 if ($serverret["success"] && ($serverret["body"] != '')) {
1018 $data = json_decode($serverret["body"]);
1019 if (isset($data->version)) {
1020 $platform = "Mastodon";
1021 $version = $data->version;
1022 $site_name = $data->title;
1023 $info = $data->description;
1024 $network = NETWORK_OSTATUS;
1027 if (strstr($orig_version.$version, 'Pleroma')) {
1028 $platform = 'Pleroma';
1029 $version = trim(str_replace('Pleroma', '', $version));
1034 // Test for Hubzilla and Red
1035 $serverret = z_fetch_url($server_url."/siteinfo.json");
1036 if ($serverret["success"]) {
1037 $data = json_decode($serverret["body"]);
1038 if (isset($data->url)) {
1039 $platform = $data->platform;
1040 $version = $data->version;
1041 $network = NETWORK_DIASPORA;
1043 if (!empty($data->site_name)) {
1044 $site_name = $data->site_name;
1046 switch ($data->register_policy) {
1047 case "REGISTER_OPEN":
1048 $register_policy = REGISTER_OPEN;
1050 case "REGISTER_APPROVE":
1051 $register_policy = REGISTER_APPROVE;
1053 case "REGISTER_CLOSED":
1055 $register_policy = REGISTER_CLOSED;
1059 // Test for Hubzilla, Redmatrix or Friendica
1060 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1061 if ($serverret["success"]) {
1062 $data = json_decode($serverret["body"]);
1063 if (isset($data->site->server)) {
1064 if (isset($data->site->platform)) {
1065 $platform = $data->site->platform->PLATFORM_NAME;
1066 $version = $data->site->platform->STD_VERSION;
1067 $network = NETWORK_DIASPORA;
1069 if (isset($data->site->BlaBlaNet)) {
1070 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1071 $version = $data->site->BlaBlaNet->STD_VERSION;
1072 $network = NETWORK_DIASPORA;
1074 if (isset($data->site->hubzilla)) {
1075 $platform = $data->site->hubzilla->PLATFORM_NAME;
1076 $version = $data->site->hubzilla->RED_VERSION;
1077 $network = NETWORK_DIASPORA;
1079 if (isset($data->site->redmatrix)) {
1080 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1081 $platform = $data->site->redmatrix->PLATFORM_NAME;
1082 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1083 $platform = $data->site->redmatrix->RED_PLATFORM;
1086 $version = $data->site->redmatrix->RED_VERSION;
1087 $network = NETWORK_DIASPORA;
1089 if (isset($data->site->friendica)) {
1090 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1091 $version = $data->site->friendica->FRIENDICA_VERSION;
1092 $network = NETWORK_DFRN;
1095 $site_name = $data->site->name;
1097 $data->site->closed = self::toBoolean($data->site->closed);
1098 $data->site->private = self::toBoolean($data->site->private);
1099 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1101 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1102 $register_policy = REGISTER_APPROVE;
1103 } elseif (!$data->site->closed && !$data->site->private) {
1104 $register_policy = REGISTER_OPEN;
1106 $register_policy = REGISTER_CLOSED;
1113 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1115 $serverret = z_fetch_url($server_url."/statistics.json");
1116 if ($serverret["success"]) {
1117 $data = json_decode($serverret["body"]);
1118 if (isset($data->version)) {
1119 $version = $data->version;
1120 // Version numbers on statistics.json are presented with additional info, e.g.:
1121 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1122 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1125 if (!empty($data->name)) {
1126 $site_name = $data->name;
1129 if (!empty($data->network)) {
1130 $platform = $data->network;
1133 if ($platform == "Diaspora") {
1134 $network = NETWORK_DIASPORA;
1137 if ($data->registrations_open) {
1138 $register_policy = REGISTER_OPEN;
1140 $register_policy = REGISTER_CLOSED;
1145 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1147 $server = self::fetchNodeinfo($server_url);
1149 $register_policy = $server['register_policy'];
1151 if (isset($server['platform'])) {
1152 $platform = $server['platform'];
1155 if (isset($server['network'])) {
1156 $network = $server['network'];
1159 if (isset($server['version'])) {
1160 $version = $server['version'];
1163 if (isset($server['site_name'])) {
1164 $site_name = $server['site_name'];
1169 // Check for noscrape
1170 // Friendica servers could be detected as OStatus servers
1171 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1172 $serverret = z_fetch_url($server_url."/friendica/json");
1174 if (!$serverret["success"]) {
1175 $serverret = z_fetch_url($server_url."/friendika/json");
1178 if ($serverret["success"]) {
1179 $data = json_decode($serverret["body"]);
1181 if (isset($data->version)) {
1182 $network = NETWORK_DFRN;
1184 $noscrape = $data->no_scrape_url;
1185 $version = $data->version;
1186 $site_name = $data->site_name;
1187 $info = $data->info;
1188 $register_policy_str = $data->register_policy;
1189 $platform = $data->platform;
1191 switch ($register_policy_str) {
1192 case "REGISTER_CLOSED":
1193 $register_policy = REGISTER_CLOSED;
1195 case "REGISTER_APPROVE":
1196 $register_policy = REGISTER_APPROVE;
1198 case "REGISTER_OPEN":
1199 $register_policy = REGISTER_OPEN;
1206 if ($possible_failure && !$failure) {
1211 $last_contact = $orig_last_contact;
1212 $last_failure = datetime_convert();
1214 $last_contact = datetime_convert();
1215 $last_failure = $orig_last_failure;
1218 if (($last_contact <= $last_failure) && !$failure) {
1219 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1220 } elseif (($last_contact >= $last_failure) && $failure) {
1221 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1224 // Check again if the server exists
1225 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1227 $version = strip_tags($version);
1228 $site_name = strip_tags($site_name);
1229 $info = strip_tags($info);
1230 $platform = strip_tags($platform);
1234 "UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1235 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1240 intval($register_policy),
1245 dbesc($last_contact),
1246 dbesc($last_failure),
1247 dbesc(normalise_link($server_url))
1249 } elseif (!$failure) {
1251 "INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1252 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1254 dbesc(normalise_link($server_url)),
1258 intval($register_policy),
1263 dbesc(datetime_convert()),
1264 dbesc($last_contact),
1265 dbesc($last_failure),
1266 dbesc(datetime_convert())
1269 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1275 * @brief Returns a list of all known servers
1276 * @return array List of server urls
1278 public static function serverlist()
1281 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1282 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1283 ORDER BY `last_contact`
1285 dbesc(NETWORK_DFRN),
1286 dbesc(NETWORK_DIASPORA),
1287 dbesc(NETWORK_OSTATUS)
1290 if (!DBM::is_result($r)) {
1298 * @brief Fetch server list from remote servers and adds them when they are new.
1300 * @param string $poco URL to the POCO endpoint
1302 public static function fetchServerlist($poco)
1304 $serverret = z_fetch_url($poco."/@server");
1305 if (!$serverret["success"]) {
1308 $serverlist = json_decode($serverret['body']);
1310 if (!is_array($serverlist)) {
1314 foreach ($serverlist as $server) {
1315 $server_url = str_replace("/index.php", "", $server->url);
1317 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1318 if (!DBM::is_result($r)) {
1319 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1320 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1325 public static function discoverFederation()
1327 $last = Config::get('poco', 'last_federation_discovery');
1330 $next = $last + (24 * 60 * 60);
1331 if ($next > time()) {
1336 // Discover Friendica, Hubzilla and Diaspora servers
1337 $serverdata = fetch_url("http://the-federation.info/pods.json");
1340 $servers = json_decode($serverdata);
1342 foreach ($servers->pods as $server) {
1343 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1347 // Disvover Mastodon servers
1348 if (!Config::get('system', 'ostatus_disabled')) {
1349 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1352 $servers = json_decode($serverdata);
1354 foreach ($servers as $server) {
1355 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1356 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1361 // Currently disabled, since the service isn't available anymore.
1362 // It is not removed since I hope that there will be a successor.
1363 // Discover GNU Social Servers.
1364 //if (!Config::get('system','ostatus_disabled')) {
1365 // $serverdata = "http://gstools.org/api/get_open_instances/";
1367 // $result = z_fetch_url($serverdata);
1368 // if ($result["success"]) {
1369 // $servers = json_decode($result["body"]);
1371 // foreach($servers->data as $server)
1372 // self::checkServer($server->instance_address);
1376 Config::set('poco', 'last_federation_discovery', time());
1379 public static function discoverSingleServer($id)
1381 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1382 if (!DBM::is_result($r)) {
1388 // Discover new servers out there (Works from Friendica version 3.5.2)
1389 self::fetchServerlist($server["poco"]);
1391 // Fetch all users from the other server
1392 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1394 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1396 $retdata = z_fetch_url($url);
1397 if ($retdata["success"]) {
1398 $data = json_decode($retdata["body"]);
1400 self::discoverServer($data, 2);
1402 if (Config::get('system', 'poco_discovery') > 1) {
1403 $timeframe = Config::get('system', 'poco_discovery_since');
1404 if ($timeframe == 0) {
1408 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1410 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1411 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1415 $retdata = z_fetch_url($url);
1416 if ($retdata["success"]) {
1417 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1418 $success = self::discoverServer(json_decode($retdata["body"]));
1421 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1422 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1423 self::discoverServerUsers($data, $server);
1427 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1431 // If the server hadn't replied correctly, then force a sanity check
1432 self::checkServer($server["url"], $server["network"], true);
1434 // If we couldn't reach the server, we will try it some time later
1435 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1441 public static function discover($complete = false)
1443 // Update the server list
1444 self::discoverFederation();
1448 $requery_days = intval(Config::get("system", "poco_requery_days"));
1450 if ($requery_days == 0) {
1453 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1455 $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));
1456 if (DBM::is_result($r)) {
1457 foreach ($r as $server) {
1458 if (!self::checkServer($server["url"], $server["network"])) {
1459 // The server is not reachable? Okay, then we will try it later
1460 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1464 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1465 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1467 if (!$complete && (--$no_of_queries == 0)) {
1474 public static function discoverServerUsers($data, $server)
1476 if (!isset($data->entry)) {
1480 foreach ($data->entry as $entry) {
1482 if (isset($entry->urls)) {
1483 foreach ($entry->urls as $url) {
1484 if ($url->type == 'profile') {
1485 $profile_url = $url->value;
1486 $urlparts = parse_url($profile_url);
1487 $username = end(explode("/", $urlparts["path"]));
1491 if ($username != "") {
1492 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1494 // Fetch all contacts from a given user from the other server
1495 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1497 $retdata = z_fetch_url($url);
1498 if ($retdata["success"]) {
1499 self::discoverServer(json_decode($retdata["body"]), 3);
1505 public static function discoverServer($data, $default_generation = 0)
1507 if (!isset($data->entry) || !count($data->entry)) {
1513 foreach ($data->entry as $entry) {
1515 $profile_photo = '';
1519 $updated = NULL_DATE;
1525 $generation = $default_generation;
1527 $name = $entry->displayName;
1529 if (isset($entry->urls)) {
1530 foreach ($entry->urls as $url) {
1531 if ($url->type == 'profile') {
1532 $profile_url = $url->value;
1535 if ($url->type == 'webfinger') {
1536 $connect_url = str_replace('acct:' , '', $url->value);
1542 if (isset($entry->photos)) {
1543 foreach ($entry->photos as $photo) {
1544 if ($photo->type == 'profile') {
1545 $profile_photo = $photo->value;
1551 if (isset($entry->updated)) {
1552 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1555 if (isset($entry->network)) {
1556 $network = $entry->network;
1559 if (isset($entry->currentLocation)) {
1560 $location = $entry->currentLocation;
1563 if (isset($entry->aboutMe)) {
1564 $about = html2bbcode($entry->aboutMe);
1567 if (isset($entry->gender)) {
1568 $gender = $entry->gender;
1571 if (isset($entry->generation) && ($entry->generation > 0)) {
1572 $generation = ++$entry->generation;
1575 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1576 $contact_type = $entry->contactType;
1579 if (isset($entry->tags)) {
1580 foreach ($entry->tags as $tag) {
1581 $keywords = implode(", ", $tag);
1585 if ($generation > 0) {
1588 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1590 $gcontact = array("url" => $profile_url,
1592 "network" => $network,
1593 "photo" => $profile_photo,
1595 "location" => $location,
1596 "gender" => $gender,
1597 "keywords" => $keywords,
1598 "connect" => $connect_url,
1599 "updated" => $updated,
1600 "contact-type" => $contact_type,
1601 "generation" => $generation);
1604 $gcontact = GlobalContact::sanitize($gcontact);
1605 GlobalContact::update($gcontact);
1606 } catch (Exception $e) {
1607 logger($e->getMessage(), LOGGER_DEBUG);
1610 logger("Done for profile ".$profile_url, LOGGER_DEBUG);