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 $server["site_name"] = $xpath->evaluate($element."//head/title/text()")->item(0)->nodeValue;
823 public static function checkServer($server_url, $network = "", $force = false)
825 // Unify the server address
826 $server_url = trim($server_url, "/");
827 $server_url = str_replace("/index.php", "", $server_url);
829 if ($server_url == "") {
833 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
834 if (DBM::is_result($servers)) {
835 if ($servers[0]["created"] <= NULL_DATE) {
837 "UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
838 dbesc(datetime_convert()),
839 dbesc(normalise_link($server_url))
842 $poco = $servers[0]["poco"];
843 $noscrape = $servers[0]["noscrape"];
845 if ($network == "") {
846 $network = $servers[0]["network"];
849 $last_contact = $servers[0]["last_contact"];
850 $last_failure = $servers[0]["last_failure"];
851 $version = $servers[0]["version"];
852 $platform = $servers[0]["platform"];
853 $site_name = $servers[0]["site_name"];
854 $info = $servers[0]["info"];
855 $register_policy = $servers[0]["register_policy"];
857 if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
858 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
859 return ($last_contact >= $last_failure);
868 $register_policy = -1;
870 $last_contact = NULL_DATE;
871 $last_failure = NULL_DATE;
873 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
876 $possible_failure = false;
877 $orig_last_failure = $last_failure;
878 $orig_last_contact = $last_contact;
880 // Check if the page is accessible via SSL.
881 $orig_server_url = $server_url;
882 $server_url = str_replace("http://", "https://", $server_url);
884 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
885 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
887 // Quit if there is a timeout.
888 // But we want to make sure to only quit if we are mostly sure that this server url fits.
889 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
890 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
891 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
892 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
896 // Maybe the page is unencrypted only?
897 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
898 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
899 $server_url = str_replace("https://", "http://", $server_url);
901 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
902 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
904 // Quit if there is a timeout
905 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
906 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
907 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
911 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
914 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
915 // Workaround for bad configured servers (known nginx problem)
916 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
919 $possible_failure = true;
922 // If the server has no possible failure we reset the cached data
923 if (!$possible_failure) {
928 $register_policy = -1;
933 $serverret = z_fetch_url($server_url."/poco");
934 if ($serverret["success"]) {
935 $data = json_decode($serverret["body"]);
936 if (isset($data->totalResults)) {
937 $poco = $server_url."/poco";
938 $server = self::detectPocoData($data);
940 $platform = $server['platform'];
941 $network = $server['network'];
950 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
951 $serverret = z_fetch_url($server_url);
953 if (!$serverret["success"] || ($serverret["body"] == "")) {
956 $server = self::detectServerType($serverret["body"]);
958 $platform = $server['platform'];
959 $network = $server['network'];
960 $version = $server['version'];
961 $site_name = $server['site_name'];
964 $lines = explode("\n", $serverret["header"]);
966 foreach ($lines as $line) {
968 if (stristr($line, 'X-Diaspora-Version:')) {
969 $platform = "Diaspora";
970 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
971 $version = trim(str_replace("x-diaspora-version:", "", $version));
972 $network = NETWORK_DIASPORA;
973 $versionparts = explode("-", $version);
974 $version = $versionparts[0];
977 if (stristr($line, 'Server: Mastodon')) {
978 $platform = "Mastodon";
979 $network = NETWORK_OSTATUS;
986 if (!$failure && ($poco == "")) {
987 // Test for Statusnet
988 // Will also return data for Friendica and GNU Social - but it will be overwritten later
989 // The "not implemented" is a special treatment for really, really old Friendica versions
990 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
991 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
992 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
993 $platform = "StatusNet";
994 // Remove junk that some GNU Social servers return
995 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
996 $version = trim($version, '"');
997 $network = NETWORK_OSTATUS;
1000 // Test for GNU Social
1001 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1002 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1003 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1004 $platform = "GNU Social";
1005 // Remove junk that some GNU Social servers return
1006 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1007 $version = trim($version, '"');
1008 $network = NETWORK_OSTATUS;
1011 // Test for Mastodon
1012 $orig_version = $version;
1013 $serverret = z_fetch_url($server_url."/api/v1/instance");
1014 if ($serverret["success"] && ($serverret["body"] != '')) {
1015 $data = json_decode($serverret["body"]);
1016 if (isset($data->version)) {
1017 $platform = "Mastodon";
1018 $version = $data->version;
1019 $site_name = $data->title;
1020 $info = $data->description;
1021 $network = NETWORK_OSTATUS;
1024 if (strstr($orig_version.$version, 'Pleroma')) {
1025 $platform = 'Pleroma';
1026 $version = trim(str_replace('Pleroma', '', $version));
1031 // Test for Hubzilla and Red
1032 $serverret = z_fetch_url($server_url."/siteinfo.json");
1033 if ($serverret["success"]) {
1034 $data = json_decode($serverret["body"]);
1035 if (isset($data->url)) {
1036 $platform = $data->platform;
1037 $version = $data->version;
1038 $network = NETWORK_DIASPORA;
1040 if (!empty($data->site_name)) {
1041 $site_name = $data->site_name;
1043 switch ($data->register_policy) {
1044 case "REGISTER_OPEN":
1045 $register_policy = REGISTER_OPEN;
1047 case "REGISTER_APPROVE":
1048 $register_policy = REGISTER_APPROVE;
1050 case "REGISTER_CLOSED":
1052 $register_policy = REGISTER_CLOSED;
1056 // Test for Hubzilla, Redmatrix or Friendica
1057 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1058 if ($serverret["success"]) {
1059 $data = json_decode($serverret["body"]);
1060 if (isset($data->site->server)) {
1061 if (isset($data->site->platform)) {
1062 $platform = $data->site->platform->PLATFORM_NAME;
1063 $version = $data->site->platform->STD_VERSION;
1064 $network = NETWORK_DIASPORA;
1066 if (isset($data->site->BlaBlaNet)) {
1067 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1068 $version = $data->site->BlaBlaNet->STD_VERSION;
1069 $network = NETWORK_DIASPORA;
1071 if (isset($data->site->hubzilla)) {
1072 $platform = $data->site->hubzilla->PLATFORM_NAME;
1073 $version = $data->site->hubzilla->RED_VERSION;
1074 $network = NETWORK_DIASPORA;
1076 if (isset($data->site->redmatrix)) {
1077 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1078 $platform = $data->site->redmatrix->PLATFORM_NAME;
1079 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1080 $platform = $data->site->redmatrix->RED_PLATFORM;
1083 $version = $data->site->redmatrix->RED_VERSION;
1084 $network = NETWORK_DIASPORA;
1086 if (isset($data->site->friendica)) {
1087 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1088 $version = $data->site->friendica->FRIENDICA_VERSION;
1089 $network = NETWORK_DFRN;
1092 $site_name = $data->site->name;
1094 $data->site->closed = self::toBoolean($data->site->closed);
1095 $data->site->private = self::toBoolean($data->site->private);
1096 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1098 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1099 $register_policy = REGISTER_APPROVE;
1100 } elseif (!$data->site->closed && !$data->site->private) {
1101 $register_policy = REGISTER_OPEN;
1103 $register_policy = REGISTER_CLOSED;
1110 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1112 $serverret = z_fetch_url($server_url."/statistics.json");
1113 if ($serverret["success"]) {
1114 $data = json_decode($serverret["body"]);
1115 if (isset($data->version)) {
1116 $version = $data->version;
1117 // Version numbers on statistics.json are presented with additional info, e.g.:
1118 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1119 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1122 if (!empty($data->name)) {
1123 $site_name = $data->name;
1126 if (!empty($data->network)) {
1127 $platform = $data->network;
1130 if ($platform == "Diaspora") {
1131 $network = NETWORK_DIASPORA;
1134 if ($data->registrations_open) {
1135 $register_policy = REGISTER_OPEN;
1137 $register_policy = REGISTER_CLOSED;
1142 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1144 $server = self::fetchNodeinfo($server_url);
1146 $register_policy = $server['register_policy'];
1148 if (isset($server['platform'])) {
1149 $platform = $server['platform'];
1152 if (isset($server['network'])) {
1153 $network = $server['network'];
1156 if (isset($server['version'])) {
1157 $version = $server['version'];
1160 if (isset($server['site_name'])) {
1161 $site_name = $server['site_name'];
1166 // Check for noscrape
1167 // Friendica servers could be detected as OStatus servers
1168 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1169 $serverret = z_fetch_url($server_url."/friendica/json");
1171 if (!$serverret["success"]) {
1172 $serverret = z_fetch_url($server_url."/friendika/json");
1175 if ($serverret["success"]) {
1176 $data = json_decode($serverret["body"]);
1178 if (isset($data->version)) {
1179 $network = NETWORK_DFRN;
1181 $noscrape = $data->no_scrape_url;
1182 $version = $data->version;
1183 $site_name = $data->site_name;
1184 $info = $data->info;
1185 $register_policy_str = $data->register_policy;
1186 $platform = $data->platform;
1188 switch ($register_policy_str) {
1189 case "REGISTER_CLOSED":
1190 $register_policy = REGISTER_CLOSED;
1192 case "REGISTER_APPROVE":
1193 $register_policy = REGISTER_APPROVE;
1195 case "REGISTER_OPEN":
1196 $register_policy = REGISTER_OPEN;
1203 if ($possible_failure && !$failure) {
1208 $last_contact = $orig_last_contact;
1209 $last_failure = datetime_convert();
1211 $last_contact = datetime_convert();
1212 $last_failure = $orig_last_failure;
1215 if (($last_contact <= $last_failure) && !$failure) {
1216 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1217 } elseif (($last_contact >= $last_failure) && $failure) {
1218 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1221 // Check again if the server exists
1222 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1224 $version = strip_tags($version);
1225 $site_name = strip_tags($site_name);
1226 $info = strip_tags($info);
1227 $platform = strip_tags($platform);
1231 "UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1232 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1237 intval($register_policy),
1242 dbesc($last_contact),
1243 dbesc($last_failure),
1244 dbesc(normalise_link($server_url))
1246 } elseif (!$failure) {
1248 "INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1249 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1251 dbesc(normalise_link($server_url)),
1255 intval($register_policy),
1260 dbesc(datetime_convert()),
1261 dbesc($last_contact),
1262 dbesc($last_failure),
1263 dbesc(datetime_convert())
1266 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1272 * @brief Returns a list of all known servers
1273 * @return array List of server urls
1275 public static function serverlist()
1278 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1279 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1280 ORDER BY `last_contact`
1282 dbesc(NETWORK_DFRN),
1283 dbesc(NETWORK_DIASPORA),
1284 dbesc(NETWORK_OSTATUS)
1287 if (!DBM::is_result($r)) {
1295 * @brief Fetch server list from remote servers and adds them when they are new.
1297 * @param string $poco URL to the POCO endpoint
1299 public static function fetchServerlist($poco)
1301 $serverret = z_fetch_url($poco."/@server");
1302 if (!$serverret["success"]) {
1305 $serverlist = json_decode($serverret['body']);
1307 if (!is_array($serverlist)) {
1311 foreach ($serverlist as $server) {
1312 $server_url = str_replace("/index.php", "", $server->url);
1314 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1315 if (!DBM::is_result($r)) {
1316 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1317 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1322 public static function discoverFederation()
1324 $last = Config::get('poco', 'last_federation_discovery');
1327 $next = $last + (24 * 60 * 60);
1328 if ($next > time()) {
1333 // Discover Friendica, Hubzilla and Diaspora servers
1334 $serverdata = fetch_url("http://the-federation.info/pods.json");
1337 $servers = json_decode($serverdata);
1339 foreach ($servers->pods as $server) {
1340 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1344 // Disvover Mastodon servers
1345 if (!Config::get('system', 'ostatus_disabled')) {
1346 $accesstoken = Config::get('system', 'instances_social_key');
1347 if (!empty($accesstoken)) {
1348 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1349 $header = array('Authorization: Bearer '.$accesstoken);
1350 $serverdata = z_fetch_url($api, false, $redirects, ['headers' => $header]);
1351 if ($serverdata['success']) {
1352 $servers = json_decode($serverdata['body']);
1353 foreach ($servers->instances as $server) {
1354 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1355 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 = GContact::sanitize($gcontact);
1605 GContact::update($gcontact);
1606 } catch (Exception $e) {
1607 logger($e->getMessage(), LOGGER_DEBUG);
1610 logger("Done for profile ".$profile_url, LOGGER_DEBUG);