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;
725 if (!empty($nodeinfo->usage->users->total)) {
726 $server['registered-users'] = $nodeinfo->usage->users->total;
733 if (is_array($nodeinfo->protocols->inbound)) {
734 foreach ($nodeinfo->protocols->inbound as $inbound) {
735 if ($inbound == 'diaspora') {
738 if ($inbound == 'friendica') {
741 if ($inbound == 'gnusocial') {
748 $server['network'] = NETWORK_OSTATUS;
751 $server['network'] = NETWORK_DIASPORA;
754 $server['network'] = NETWORK_DFRN;
765 * @brief Detect server type (Hubzilla or Friendica) via the front page body
767 * @param string $body Front page of the server
768 * @return array Server data
770 public static function detectServerType($body)
774 $doc = new DOMDocument();
775 @$doc->loadHTML($body);
776 $xpath = new DOMXPath($doc);
778 $list = $xpath->query("//meta[@name]");
780 foreach ($list as $node) {
782 if ($node->attributes->length) {
783 foreach ($node->attributes as $attribute) {
784 $attr[$attribute->name] = $attribute->value;
787 if ($attr['name'] == 'generator') {
788 $version_part = explode(" ", $attr['content']);
789 if (count($version_part) == 2) {
790 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
792 $server["platform"] = $version_part[0];
793 $server["version"] = $version_part[1];
794 $server["network"] = NETWORK_DFRN;
801 $list = $xpath->query("//meta[@property]");
803 foreach ($list as $node) {
805 if ($node->attributes->length) {
806 foreach ($node->attributes as $attribute) {
807 $attr[$attribute->name] = $attribute->value;
810 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
812 $server["platform"] = $attr['content'];
813 $server["version"] = "";
814 $server["network"] = NETWORK_DIASPORA;
823 $server["site_name"] = $xpath->evaluate("//head/title/text()")->item(0)->nodeValue;
827 public static function checkServer($server_url, $network = "", $force = false)
829 // Unify the server address
830 $server_url = trim($server_url, "/");
831 $server_url = str_replace("/index.php", "", $server_url);
833 if ($server_url == "") {
837 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
838 if (DBM::is_result($servers)) {
839 if ($servers[0]["created"] <= NULL_DATE) {
841 "UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
842 dbesc(datetime_convert()),
843 dbesc(normalise_link($server_url))
846 $poco = $servers[0]["poco"];
847 $noscrape = $servers[0]["noscrape"];
849 if ($network == "") {
850 $network = $servers[0]["network"];
853 $last_contact = $servers[0]["last_contact"];
854 $last_failure = $servers[0]["last_failure"];
855 $version = $servers[0]["version"];
856 $platform = $servers[0]["platform"];
857 $site_name = $servers[0]["site_name"];
858 $info = $servers[0]["info"];
859 $register_policy = $servers[0]["register_policy"];
860 $registered_users = $servers[0]["registered-users"];
862 if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
863 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
864 return ($last_contact >= $last_failure);
873 $register_policy = -1;
874 $registered_users = 0;
876 $last_contact = NULL_DATE;
877 $last_failure = NULL_DATE;
879 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
882 $possible_failure = false;
883 $orig_last_failure = $last_failure;
884 $orig_last_contact = $last_contact;
886 // Check if the page is accessible via SSL.
887 $orig_server_url = $server_url;
888 $server_url = str_replace("http://", "https://", $server_url);
890 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
891 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
893 // Quit if there is a timeout.
894 // But we want to make sure to only quit if we are mostly sure that this server url fits.
895 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
896 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
897 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
898 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
902 // Maybe the page is unencrypted only?
903 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
904 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
905 $server_url = str_replace("https://", "http://", $server_url);
907 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
908 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
910 // Quit if there is a timeout
911 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
912 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
913 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
917 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
920 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
921 // Workaround for bad configured servers (known nginx problem)
922 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
925 $possible_failure = true;
928 // If the server has no possible failure we reset the cached data
929 if (!$possible_failure) {
934 $register_policy = -1;
938 // This will be too low, but better than no value at all.
939 $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
944 $serverret = z_fetch_url($server_url."/poco");
945 if ($serverret["success"]) {
946 $data = json_decode($serverret["body"]);
947 if (isset($data->totalResults)) {
948 $registered_users = $data->totalResults;
949 $poco = $server_url."/poco";
950 $server = self::detectPocoData($data);
952 $platform = $server['platform'];
953 $network = $server['network'];
962 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
963 $serverret = z_fetch_url($server_url);
965 if (!$serverret["success"] || ($serverret["body"] == "")) {
968 $server = self::detectServerType($serverret["body"]);
970 $platform = $server['platform'];
971 $network = $server['network'];
972 $version = $server['version'];
973 $site_name = $server['site_name'];
976 $lines = explode("\n", $serverret["header"]);
978 foreach ($lines as $line) {
980 if (stristr($line, 'X-Diaspora-Version:')) {
981 $platform = "Diaspora";
982 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
983 $version = trim(str_replace("x-diaspora-version:", "", $version));
984 $network = NETWORK_DIASPORA;
985 $versionparts = explode("-", $version);
986 $version = $versionparts[0];
989 if (stristr($line, 'Server: Mastodon')) {
990 $platform = "Mastodon";
991 $network = NETWORK_OSTATUS;
998 if (!$failure && ($poco == "")) {
999 // Test for Statusnet
1000 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1001 // The "not implemented" is a special treatment for really, really old Friendica versions
1002 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1003 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1004 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1005 $platform = "StatusNet";
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 GNU Social
1013 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1014 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1015 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1016 $platform = "GNU Social";
1017 // Remove junk that some GNU Social servers return
1018 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1019 $version = trim($version, '"');
1020 $network = NETWORK_OSTATUS;
1023 // Test for Mastodon
1024 $orig_version = $version;
1025 $serverret = z_fetch_url($server_url."/api/v1/instance");
1026 if ($serverret["success"] && ($serverret["body"] != '')) {
1027 $data = json_decode($serverret["body"]);
1028 if (isset($data->version)) {
1029 $platform = "Mastodon";
1030 $version = $data->version;
1031 $site_name = $data->title;
1032 $info = $data->description;
1033 $network = NETWORK_OSTATUS;
1035 if (!empty($data->stats->user_count)) {
1036 $registered_users = $data->stats->user_count;
1039 if (strstr($orig_version.$version, 'Pleroma')) {
1040 $platform = 'Pleroma';
1041 $version = trim(str_replace('Pleroma', '', $version));
1046 // Test for Hubzilla and Red
1047 $serverret = z_fetch_url($server_url."/siteinfo.json");
1048 if ($serverret["success"]) {
1049 $data = json_decode($serverret["body"]);
1050 if (isset($data->url)) {
1051 $platform = $data->platform;
1052 $version = $data->version;
1053 $network = NETWORK_DIASPORA;
1055 if (!empty($data->site_name)) {
1056 $site_name = $data->site_name;
1058 if (!empty($data->channels_total)) {
1059 $registered_users = $data->channels_total;
1061 switch ($data->register_policy) {
1062 case "REGISTER_OPEN":
1063 $register_policy = REGISTER_OPEN;
1065 case "REGISTER_APPROVE":
1066 $register_policy = REGISTER_APPROVE;
1068 case "REGISTER_CLOSED":
1070 $register_policy = REGISTER_CLOSED;
1074 // Test for Hubzilla, Redmatrix or Friendica
1075 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1076 if ($serverret["success"]) {
1077 $data = json_decode($serverret["body"]);
1078 if (isset($data->site->server)) {
1079 if (isset($data->site->platform)) {
1080 $platform = $data->site->platform->PLATFORM_NAME;
1081 $version = $data->site->platform->STD_VERSION;
1082 $network = NETWORK_DIASPORA;
1084 if (isset($data->site->BlaBlaNet)) {
1085 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1086 $version = $data->site->BlaBlaNet->STD_VERSION;
1087 $network = NETWORK_DIASPORA;
1089 if (isset($data->site->hubzilla)) {
1090 $platform = $data->site->hubzilla->PLATFORM_NAME;
1091 $version = $data->site->hubzilla->RED_VERSION;
1092 $network = NETWORK_DIASPORA;
1094 if (isset($data->site->redmatrix)) {
1095 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1096 $platform = $data->site->redmatrix->PLATFORM_NAME;
1097 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1098 $platform = $data->site->redmatrix->RED_PLATFORM;
1101 $version = $data->site->redmatrix->RED_VERSION;
1102 $network = NETWORK_DIASPORA;
1104 if (isset($data->site->friendica)) {
1105 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1106 $version = $data->site->friendica->FRIENDICA_VERSION;
1107 $network = NETWORK_DFRN;
1110 $site_name = $data->site->name;
1112 $data->site->closed = self::toBoolean($data->site->closed);
1113 $data->site->private = self::toBoolean($data->site->private);
1114 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1116 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1117 $register_policy = REGISTER_APPROVE;
1118 } elseif (!$data->site->closed && !$data->site->private) {
1119 $register_policy = REGISTER_OPEN;
1121 $register_policy = REGISTER_CLOSED;
1128 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1130 $serverret = z_fetch_url($server_url."/statistics.json");
1131 if ($serverret["success"]) {
1132 $data = json_decode($serverret["body"]);
1133 if (isset($data->version)) {
1134 $version = $data->version;
1135 // Version numbers on statistics.json are presented with additional info, e.g.:
1136 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1137 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1140 if (!empty($data->name)) {
1141 $site_name = $data->name;
1144 if (!empty($data->network)) {
1145 $platform = $data->network;
1148 if ($platform == "Diaspora") {
1149 $network = NETWORK_DIASPORA;
1152 if ($data->registrations_open) {
1153 $register_policy = REGISTER_OPEN;
1155 $register_policy = REGISTER_CLOSED;
1160 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1162 $server = self::fetchNodeinfo($server_url);
1164 $register_policy = $server['register_policy'];
1166 if (isset($server['platform'])) {
1167 $platform = $server['platform'];
1170 if (isset($server['network'])) {
1171 $network = $server['network'];
1174 if (isset($server['version'])) {
1175 $version = $server['version'];
1178 if (isset($server['site_name'])) {
1179 $site_name = $server['site_name'];
1182 if (isset($server['registered-users'])) {
1183 $registered_users = $server['registered-users'];
1188 // Check for noscrape
1189 // Friendica servers could be detected as OStatus servers
1190 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1191 $serverret = z_fetch_url($server_url."/friendica/json");
1193 if (!$serverret["success"]) {
1194 $serverret = z_fetch_url($server_url."/friendika/json");
1197 if ($serverret["success"]) {
1198 $data = json_decode($serverret["body"]);
1200 if (isset($data->version)) {
1201 $network = NETWORK_DFRN;
1203 $noscrape = $data->no_scrape_url;
1204 $version = $data->version;
1205 $site_name = $data->site_name;
1206 $info = $data->info;
1207 $register_policy_str = $data->register_policy;
1208 $platform = $data->platform;
1210 switch ($register_policy_str) {
1211 case "REGISTER_CLOSED":
1212 $register_policy = REGISTER_CLOSED;
1214 case "REGISTER_APPROVE":
1215 $register_policy = REGISTER_APPROVE;
1217 case "REGISTER_OPEN":
1218 $register_policy = REGISTER_OPEN;
1225 if ($possible_failure && !$failure) {
1230 $last_contact = $orig_last_contact;
1231 $last_failure = datetime_convert();
1233 $last_contact = datetime_convert();
1234 $last_failure = $orig_last_failure;
1237 if (($last_contact <= $last_failure) && !$failure) {
1238 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1239 } elseif (($last_contact >= $last_failure) && $failure) {
1240 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1243 // Check again if the server exists
1244 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1246 $version = strip_tags($version);
1247 $site_name = strip_tags($site_name);
1248 $info = strip_tags($info);
1249 $platform = strip_tags($platform);
1252 $fields = ['url' => $server_url, 'version' => $version,
1253 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1254 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1255 'platform' => $platform, 'registered-users' => $registered_users,
1256 'last_contact' => $last_contact, 'last_failure' => last_failure];
1257 dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1258 } elseif (!$failure) {
1259 $fields = ['url' => $server_url, 'nurl' => normalise_link($server_url), 'version' => $version,
1260 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1261 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1262 'platform' => $platform, 'registered-users' => $registered_users,
1263 'created' => datetime_convert(),
1264 'last_contact' => $last_contact, 'last_failure' => last_failure];
1265 dba::insert('gserver', $fields);
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);