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/datetime.php';
24 require_once 'include/network.php';
25 require_once 'include/html2bbcode.php';
30 * @brief Fetch POCO data
32 * @param integer $cid Contact ID
33 * @param integer $uid User ID
34 * @param integer $zcid Global Contact ID
35 * @param integer $url POCO address that should be polled
37 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
38 * and add the entries to the gcontact (Global Contact) table, or update existing entries
39 * if anything (name or photo) has changed.
40 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
42 * Once the global contact is stored add (if necessary) the contact linkage which associates
43 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
44 * pointing to the same global contact id.
47 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
49 // Call the function "load" via the worker
50 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
54 * @brief Fetch POCO data from the worker
56 * @param integer $cid Contact ID
57 * @param integer $uid User ID
58 * @param integer $zcid Global Contact ID
59 * @param integer $url POCO address that should be polled
62 public static function load($cid, $uid, $zcid, $url)
67 if ((! $url) || (! $uid)) {
69 "select `poco`, `uid` from `contact` where `id` = %d limit 1",
72 if (DBM::is_result($r)) {
86 $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') ;
88 logger('load: ' . $url, LOGGER_DEBUG);
92 logger('load: returns ' . $s, LOGGER_DATA);
94 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
96 if (($a->get_curl_code() > 299) || (! $s)) {
100 $j = json_decode($s);
102 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
104 if (! isset($j->entry)) {
109 foreach ($j->entry as $entry) {
116 $updated = NULL_DATE;
124 $name = $entry->displayName;
126 if (isset($entry->urls)) {
127 foreach ($entry->urls as $url) {
128 if ($url->type == 'profile') {
129 $profile_url = $url->value;
132 if ($url->type == 'webfinger') {
133 $connect_url = str_replace('acct:', '', $url->value);
138 if (isset($entry->photos)) {
139 foreach ($entry->photos as $photo) {
140 if ($photo->type == 'profile') {
141 $profile_photo = $photo->value;
147 if (isset($entry->updated)) {
148 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
151 if (isset($entry->network)) {
152 $network = $entry->network;
155 if (isset($entry->currentLocation)) {
156 $location = $entry->currentLocation;
159 if (isset($entry->aboutMe)) {
160 $about = html2bbcode($entry->aboutMe);
163 if (isset($entry->gender)) {
164 $gender = $entry->gender;
167 if (isset($entry->generation) && ($entry->generation > 0)) {
168 $generation = ++$entry->generation;
171 if (isset($entry->tags)) {
172 foreach ($entry->tags as $tag) {
173 $keywords = implode(", ", $tag);
177 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
178 $contact_type = $entry->contactType;
181 $gcontact = array("url" => $profile_url,
183 "network" => $network,
184 "photo" => $profile_photo,
186 "location" => $location,
188 "keywords" => $keywords,
189 "connect" => $connect_url,
190 "updated" => $updated,
191 "contact-type" => $contact_type,
192 "generation" => $generation);
195 $gcontact = GContact::sanitize($gcontact);
196 $gcid = GContact::update($gcontact);
198 GContact::link($gcid, $uid, $cid, $zcid);
199 } catch (Exception $e) {
200 logger($e->getMessage(), LOGGER_DEBUG);
203 logger("load: loaded $total entries", LOGGER_DEBUG);
206 "DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
213 public static function reachable($profile, $server = "", $network = "", $force = false)
216 $server = self::detectServer($profile);
223 return self::checkServer($server, $network, $force);
226 public static function detectServer($profile)
228 // Try to detect the server path based upon some known standard paths
231 if ($server_url == "") {
232 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
233 if ($friendica != $profile) {
234 $server_url = $friendica;
235 $network = NETWORK_DFRN;
239 if ($server_url == "") {
240 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
241 if ($diaspora != $profile) {
242 $server_url = $diaspora;
243 $network = NETWORK_DIASPORA;
247 if ($server_url == "") {
248 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
249 if ($red != $profile) {
251 $network = NETWORK_DIASPORA;
256 if ($server_url == "") {
257 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
258 if ($mastodon != $profile) {
259 $server_url = $mastodon;
260 $network = NETWORK_OSTATUS;
264 // Numeric OStatus variant
265 if ($server_url == "") {
266 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
267 if ($ostatus != $profile) {
268 $server_url = $ostatus;
269 $network = NETWORK_OSTATUS;
274 if ($server_url == "") {
275 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
276 if ($base != $profile) {
278 $network = NETWORK_PHANTOM;
282 if ($server_url == "") {
287 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
288 dbesc(normalise_link($server_url))
291 if (DBM::is_result($r)) {
295 // Fetch the host-meta to check if this really is a server
296 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
297 if (!$serverret["success"]) {
304 public static function alternateOStatusUrl($url)
306 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
309 public static function lastUpdated($profile, $force = false)
312 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
313 dbesc(normalise_link($profile))
316 if (!DBM::is_result($gcontacts)) {
320 $contact = array("url" => $profile);
322 if ($gcontacts[0]["created"] <= NULL_DATE) {
323 $contact['created'] = datetime_convert();
327 $server_url = normalise_link(self::detectServer($profile));
330 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
331 $server_url = $gcontacts[0]["server_url"];
334 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
335 $server_url = normalise_link(self::detectServer($profile));
338 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
339 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
343 if ($server_url != "") {
344 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
347 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
348 dbesc(datetime_convert()),
349 dbesc(normalise_link($profile))
353 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
356 $contact['server_url'] = $server_url;
359 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
361 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
362 dbesc(normalise_link($server_url))
366 $contact['network'] = $server[0]["network"];
372 // noscrape is really fast so we don't cache the call.
373 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
374 // Use noscrape if possible
375 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
378 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
380 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
381 $noscrape = json_decode($noscraperet["body"], true);
383 if (is_array($noscrape)) {
384 $contact["network"] = $server[0]["network"];
386 if (isset($noscrape["fn"])) {
387 $contact["name"] = $noscrape["fn"];
389 if (isset($noscrape["comm"])) {
390 $contact["community"] = $noscrape["comm"];
392 if (isset($noscrape["tags"])) {
393 $keywords = implode(" ", $noscrape["tags"]);
394 if ($keywords != "") {
395 $contact["keywords"] = $keywords;
399 $location = Profile::formatLocation($noscrape);
401 $contact["location"] = $location;
403 if (isset($noscrape["dfrn-notify"])) {
404 $contact["notify"] = $noscrape["dfrn-notify"];
406 // Remove all fields that are not present in the gcontact table
407 unset($noscrape["fn"]);
408 unset($noscrape["key"]);
409 unset($noscrape["homepage"]);
410 unset($noscrape["comm"]);
411 unset($noscrape["tags"]);
412 unset($noscrape["locality"]);
413 unset($noscrape["region"]);
414 unset($noscrape["country-name"]);
415 unset($noscrape["contacts"]);
416 unset($noscrape["dfrn-request"]);
417 unset($noscrape["dfrn-confirm"]);
418 unset($noscrape["dfrn-notify"]);
419 unset($noscrape["dfrn-poll"]);
421 // Set the date of the last contact
422 /// @todo By now the function "update_gcontact" doesn't work with this field
423 //$contact["last_contact"] = datetime_convert();
425 $contact = array_merge($contact, $noscrape);
427 GContact::update($contact);
429 if (trim($noscrape["updated"]) != "") {
431 "UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
432 dbesc(datetime_convert()),
433 dbesc(normalise_link($profile))
436 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
438 return $noscrape["updated"];
445 // If we only can poll the feed, then we only do this once a while
446 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
447 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
449 GContact::update($contact);
450 return $gcontacts[0]["updated"];
453 $data = Probe::uri($profile);
455 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
456 // Then check the other link and delete this one
457 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
458 && (normalise_link($profile) == normalise_link($data["alias"]))
459 && (normalise_link($profile) != normalise_link($data["url"]))
461 // Delete the old entry
462 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
463 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
465 $gcontact = array_merge($gcontacts[0], $data);
467 $gcontact["server_url"] = $data["baseurl"];
470 $gcontact = GContact::sanitize($gcontact);
471 GContact::update($gcontact);
473 self::lastUpdated($data["url"], $force);
474 } catch (Exception $e) {
475 logger($e->getMessage(), LOGGER_DEBUG);
478 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
482 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
484 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
485 dbesc(datetime_convert()),
486 dbesc(normalise_link($profile))
489 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
493 $contact = array_merge($contact, $data);
495 $contact["server_url"] = $data["baseurl"];
497 GContact::update($contact);
499 $feedret = z_fetch_url($data["poll"]);
501 if (!$feedret["success"]) {
503 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
504 dbesc(datetime_convert()),
505 dbesc(normalise_link($profile))
508 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
512 $doc = new DOMDocument();
513 @$doc->loadXML($feedret["body"]);
515 $xpath = new DomXPath($doc);
516 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
518 $entries = $xpath->query('/atom:feed/atom:entry');
522 foreach ($entries as $entry) {
523 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
524 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
526 if ($last_updated < $published)
527 $last_updated = $published;
529 if ($last_updated < $updated)
530 $last_updated = $updated;
533 // Maybe there aren't any entries. Then check if it is a valid feed
534 if ($last_updated == "") {
535 if ($xpath->query('/atom:feed')->length > 0) {
536 $last_updated = NULL_DATE;
540 "UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
541 dbesc(DBM::date($last_updated)),
543 dbesc(normalise_link($profile))
546 if (($gcontacts[0]["generation"] == 0)) {
548 "UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
549 dbesc(normalise_link($profile))
553 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
555 return($last_updated);
558 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
560 $now = strtotime(datetime_convert());
562 if ($updated > $last_contact) {
563 $contact_time = strtotime($updated);
565 $contact_time = strtotime($last_contact);
568 $failure_time = strtotime($last_failure);
569 $created_time = strtotime($created);
571 // If there is no "created" time then use the current time
572 if ($created_time <= 0) {
573 $created_time = $now;
576 // If the last contact was less than 24 hours then don't update
577 if (($now - $contact_time) < (60 * 60 * 24)) {
581 // If the last failure was less than 24 hours then don't update
582 if (($now - $failure_time) < (60 * 60 * 24)) {
586 // If the last contact was less than a week ago and the last failure is older than a week then don't update
587 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
590 // 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
591 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
595 // 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
596 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
603 public static function toBoolean($val)
605 if (($val == "true") || ($val == 1)) {
607 } elseif (($val == "false") || ($val == 0)) {
615 * @brief Detect server type (Hubzilla or Friendica) via the poco data
617 * @param object $data POCO data
618 * @return array Server data
620 public static function detectPocoData($data)
624 if (!isset($data->entry)) {
628 if (count($data->entry) == 0) {
632 if (!isset($data->entry[0]->urls)) {
636 if (count($data->entry[0]->urls) == 0) {
640 foreach ($data->entry[0]->urls as $url) {
641 if ($url->type == 'zot') {
643 $server["platform"] = 'Hubzilla';
644 $server["network"] = NETWORK_DIASPORA;
652 * @brief Detect server type by using the nodeinfo data
654 * @param string $server_url address of the server
655 * @return array Server data
657 public static function fetchNodeinfo($server_url)
659 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
660 if (!$serverret["success"]) {
664 $nodeinfo = json_decode($serverret['body']);
666 if (!is_object($nodeinfo)) {
670 if (!is_array($nodeinfo->links)) {
676 foreach ($nodeinfo->links as $link) {
677 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
678 $nodeinfo_url = $link->href;
682 if ($nodeinfo_url == '') {
686 $serverret = z_fetch_url($nodeinfo_url);
687 if (!$serverret["success"]) {
691 $nodeinfo = json_decode($serverret['body']);
693 if (!is_object($nodeinfo)) {
699 $server['register_policy'] = REGISTER_CLOSED;
701 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
702 $server['register_policy'] = REGISTER_OPEN;
705 if (is_object($nodeinfo->software)) {
706 if (isset($nodeinfo->software->name)) {
707 $server['platform'] = $nodeinfo->software->name;
710 if (isset($nodeinfo->software->version)) {
711 $server['version'] = $nodeinfo->software->version;
712 // Version numbers on Nodeinfo are presented with additional info, e.g.:
713 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
714 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
718 if (is_object($nodeinfo->metadata)) {
719 if (isset($nodeinfo->metadata->nodeName)) {
720 $server['site_name'] = $nodeinfo->metadata->nodeName;
728 if (is_array($nodeinfo->protocols->inbound)) {
729 foreach ($nodeinfo->protocols->inbound as $inbound) {
730 if ($inbound == 'diaspora') {
733 if ($inbound == 'friendica') {
736 if ($inbound == 'gnusocial') {
743 $server['network'] = NETWORK_OSTATUS;
746 $server['network'] = NETWORK_DIASPORA;
749 $server['network'] = NETWORK_DFRN;
760 * @brief Detect server type (Hubzilla or Friendica) via the front page body
762 * @param string $body Front page of the server
763 * @return array Server data
765 public static function detectServerType($body)
769 $doc = new DOMDocument();
770 @$doc->loadHTML($body);
771 $xpath = new DomXPath($doc);
773 $list = $xpath->query("//meta[@name]");
775 foreach ($list as $node) {
777 if ($node->attributes->length) {
778 foreach ($node->attributes as $attribute) {
779 $attr[$attribute->name] = $attribute->value;
782 if ($attr['name'] == 'generator') {
783 $version_part = explode(" ", $attr['content']);
784 if (count($version_part) == 2) {
785 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
787 $server["platform"] = $version_part[0];
788 $server["version"] = $version_part[1];
789 $server["network"] = NETWORK_DFRN;
796 $list = $xpath->query("//meta[@property]");
798 foreach ($list as $node) {
800 if ($node->attributes->length) {
801 foreach ($node->attributes as $attribute) {
802 $attr[$attribute->name] = $attribute->value;
805 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
807 $server["platform"] = $attr['content'];
808 $server["version"] = "";
809 $server["network"] = NETWORK_DIASPORA;
818 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
822 public static function checkServer($server_url, $network = "", $force = false)
824 // Unify the server address
825 $server_url = trim($server_url, "/");
826 $server_url = str_replace("/index.php", "", $server_url);
828 if ($server_url == "") {
832 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
833 if (DBM::is_result($servers)) {
834 if ($servers[0]["created"] <= NULL_DATE) {
836 "UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
837 dbesc(datetime_convert()),
838 dbesc(normalise_link($server_url))
841 $poco = $servers[0]["poco"];
842 $noscrape = $servers[0]["noscrape"];
844 if ($network == "") {
845 $network = $servers[0]["network"];
848 $last_contact = $servers[0]["last_contact"];
849 $last_failure = $servers[0]["last_failure"];
850 $version = $servers[0]["version"];
851 $platform = $servers[0]["platform"];
852 $site_name = $servers[0]["site_name"];
853 $info = $servers[0]["info"];
854 $register_policy = $servers[0]["register_policy"];
856 if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
857 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
858 return ($last_contact >= $last_failure);
867 $register_policy = -1;
869 $last_contact = NULL_DATE;
870 $last_failure = NULL_DATE;
872 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
875 $possible_failure = false;
876 $orig_last_failure = $last_failure;
877 $orig_last_contact = $last_contact;
879 // Check if the page is accessible via SSL.
880 $orig_server_url = $server_url;
881 $server_url = str_replace("http://", "https://", $server_url);
883 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
884 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
886 // Quit if there is a timeout.
887 // But we want to make sure to only quit if we are mostly sure that this server url fits.
888 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
889 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
890 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
891 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
895 // Maybe the page is unencrypted only?
896 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
897 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
898 $server_url = str_replace("https://", "http://", $server_url);
900 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
901 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
903 // Quit if there is a timeout
904 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
905 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
906 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
910 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
913 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
914 // Workaround for bad configured servers (known nginx problem)
915 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
918 $possible_failure = true;
921 // If the server has no possible failure we reset the cached data
922 if (!$possible_failure) {
927 $register_policy = -1;
932 $serverret = z_fetch_url($server_url."/poco");
933 if ($serverret["success"]) {
934 $data = json_decode($serverret["body"]);
935 if (isset($data->totalResults)) {
936 $poco = $server_url."/poco";
937 $server = self::detectPocoData($data);
939 $platform = $server['platform'];
940 $network = $server['network'];
949 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
950 $serverret = z_fetch_url($server_url);
952 if (!$serverret["success"] || ($serverret["body"] == "")) {
955 $server = self::detectServerType($serverret["body"]);
957 $platform = $server['platform'];
958 $network = $server['network'];
959 $version = $server['version'];
960 $site_name = $server['site_name'];
963 $lines = explode("\n", $serverret["header"]);
965 foreach ($lines as $line) {
967 if (stristr($line, 'X-Diaspora-Version:')) {
968 $platform = "Diaspora";
969 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
970 $version = trim(str_replace("x-diaspora-version:", "", $version));
971 $network = NETWORK_DIASPORA;
972 $versionparts = explode("-", $version);
973 $version = $versionparts[0];
976 if (stristr($line, 'Server: Mastodon')) {
977 $platform = "Mastodon";
978 $network = NETWORK_OSTATUS;
985 if (!$failure && ($poco == "")) {
986 // Test for Statusnet
987 // Will also return data for Friendica and GNU Social - but it will be overwritten later
988 // The "not implemented" is a special treatment for really, really old Friendica versions
989 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
990 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
991 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
992 $platform = "StatusNet";
993 // Remove junk that some GNU Social servers return
994 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
995 $version = trim($version, '"');
996 $network = NETWORK_OSTATUS;
999 // Test for GNU Social
1000 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1001 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1002 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1003 $platform = "GNU Social";
1004 // Remove junk that some GNU Social servers return
1005 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1006 $version = trim($version, '"');
1007 $network = NETWORK_OSTATUS;
1010 // Test for Mastodon
1011 $orig_version = $version;
1012 $serverret = z_fetch_url($server_url."/api/v1/instance");
1013 if ($serverret["success"] && ($serverret["body"] != '')) {
1014 $data = json_decode($serverret["body"]);
1015 if (isset($data->version)) {
1016 $platform = "Mastodon";
1017 $version = $data->version;
1018 $site_name = $data->title;
1019 $info = $data->description;
1020 $network = NETWORK_OSTATUS;
1023 if (strstr($orig_version.$version, 'Pleroma')) {
1024 $platform = 'Pleroma';
1025 $version = trim(str_replace('Pleroma', '', $version));
1030 // Test for Hubzilla and Red
1031 $serverret = z_fetch_url($server_url."/siteinfo.json");
1032 if ($serverret["success"]) {
1033 $data = json_decode($serverret["body"]);
1034 if (isset($data->url)) {
1035 $platform = $data->platform;
1036 $version = $data->version;
1037 $network = NETWORK_DIASPORA;
1039 if (!empty($data->site_name)) {
1040 $site_name = $data->site_name;
1042 switch ($data->register_policy) {
1043 case "REGISTER_OPEN":
1044 $register_policy = REGISTER_OPEN;
1046 case "REGISTER_APPROVE":
1047 $register_policy = REGISTER_APPROVE;
1049 case "REGISTER_CLOSED":
1051 $register_policy = REGISTER_CLOSED;
1055 // Test for Hubzilla, Redmatrix or Friendica
1056 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1057 if ($serverret["success"]) {
1058 $data = json_decode($serverret["body"]);
1059 if (isset($data->site->server)) {
1060 if (isset($data->site->platform)) {
1061 $platform = $data->site->platform->PLATFORM_NAME;
1062 $version = $data->site->platform->STD_VERSION;
1063 $network = NETWORK_DIASPORA;
1065 if (isset($data->site->BlaBlaNet)) {
1066 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1067 $version = $data->site->BlaBlaNet->STD_VERSION;
1068 $network = NETWORK_DIASPORA;
1070 if (isset($data->site->hubzilla)) {
1071 $platform = $data->site->hubzilla->PLATFORM_NAME;
1072 $version = $data->site->hubzilla->RED_VERSION;
1073 $network = NETWORK_DIASPORA;
1075 if (isset($data->site->redmatrix)) {
1076 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1077 $platform = $data->site->redmatrix->PLATFORM_NAME;
1078 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1079 $platform = $data->site->redmatrix->RED_PLATFORM;
1082 $version = $data->site->redmatrix->RED_VERSION;
1083 $network = NETWORK_DIASPORA;
1085 if (isset($data->site->friendica)) {
1086 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1087 $version = $data->site->friendica->FRIENDICA_VERSION;
1088 $network = NETWORK_DFRN;
1091 $site_name = $data->site->name;
1093 $data->site->closed = self::toBoolean($data->site->closed);
1094 $data->site->private = self::toBoolean($data->site->private);
1095 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1097 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1098 $register_policy = REGISTER_APPROVE;
1099 } elseif (!$data->site->closed && !$data->site->private) {
1100 $register_policy = REGISTER_OPEN;
1102 $register_policy = REGISTER_CLOSED;
1109 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1111 $serverret = z_fetch_url($server_url."/statistics.json");
1112 if ($serverret["success"]) {
1113 $data = json_decode($serverret["body"]);
1114 if (isset($data->version)) {
1115 $version = $data->version;
1116 // Version numbers on statistics.json are presented with additional info, e.g.:
1117 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1118 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1121 if (!empty($data->name)) {
1122 $site_name = $data->name;
1125 if (!empty($data->network)) {
1126 $platform = $data->network;
1129 if ($platform == "Diaspora") {
1130 $network = NETWORK_DIASPORA;
1133 if ($data->registrations_open) {
1134 $register_policy = REGISTER_OPEN;
1136 $register_policy = REGISTER_CLOSED;
1141 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1143 $server = self::fetchNodeinfo($server_url);
1145 $register_policy = $server['register_policy'];
1147 if (isset($server['platform'])) {
1148 $platform = $server['platform'];
1151 if (isset($server['network'])) {
1152 $network = $server['network'];
1155 if (isset($server['version'])) {
1156 $version = $server['version'];
1159 if (isset($server['site_name'])) {
1160 $site_name = $server['site_name'];
1165 // Check for noscrape
1166 // Friendica servers could be detected as OStatus servers
1167 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1168 $serverret = z_fetch_url($server_url."/friendica/json");
1170 if (!$serverret["success"]) {
1171 $serverret = z_fetch_url($server_url."/friendika/json");
1174 if ($serverret["success"]) {
1175 $data = json_decode($serverret["body"]);
1177 if (isset($data->version)) {
1178 $network = NETWORK_DFRN;
1180 $noscrape = $data->no_scrape_url;
1181 $version = $data->version;
1182 $site_name = $data->site_name;
1183 $info = $data->info;
1184 $register_policy_str = $data->register_policy;
1185 $platform = $data->platform;
1187 switch ($register_policy_str) {
1188 case "REGISTER_CLOSED":
1189 $register_policy = REGISTER_CLOSED;
1191 case "REGISTER_APPROVE":
1192 $register_policy = REGISTER_APPROVE;
1194 case "REGISTER_OPEN":
1195 $register_policy = REGISTER_OPEN;
1202 if ($possible_failure && !$failure) {
1207 $last_contact = $orig_last_contact;
1208 $last_failure = datetime_convert();
1210 $last_contact = datetime_convert();
1211 $last_failure = $orig_last_failure;
1214 if (($last_contact <= $last_failure) && !$failure) {
1215 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1216 } elseif (($last_contact >= $last_failure) && $failure) {
1217 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1220 // Check again if the server exists
1221 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1223 $version = strip_tags($version);
1224 $site_name = strip_tags($site_name);
1225 $info = strip_tags($info);
1226 $platform = strip_tags($platform);
1230 "UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1231 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1236 intval($register_policy),
1241 dbesc($last_contact),
1242 dbesc($last_failure),
1243 dbesc(normalise_link($server_url))
1245 } elseif (!$failure) {
1247 "INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1248 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1250 dbesc(normalise_link($server_url)),
1254 intval($register_policy),
1259 dbesc(datetime_convert()),
1260 dbesc($last_contact),
1261 dbesc($last_failure),
1262 dbesc(datetime_convert())
1265 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1271 * @brief Returns a list of all known servers
1272 * @return array List of server urls
1274 public static function serverlist()
1277 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1278 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1279 ORDER BY `last_contact`
1281 dbesc(NETWORK_DFRN),
1282 dbesc(NETWORK_DIASPORA),
1283 dbesc(NETWORK_OSTATUS)
1286 if (!DBM::is_result($r)) {
1294 * @brief Fetch server list from remote servers and adds them when they are new.
1296 * @param string $poco URL to the POCO endpoint
1298 public static function fetchServerlist($poco)
1300 $serverret = z_fetch_url($poco."/@server");
1301 if (!$serverret["success"]) {
1304 $serverlist = json_decode($serverret['body']);
1306 if (!is_array($serverlist)) {
1310 foreach ($serverlist as $server) {
1311 $server_url = str_replace("/index.php", "", $server->url);
1313 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1314 if (!DBM::is_result($r)) {
1315 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1316 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1321 public static function discoverFederation()
1323 $last = Config::get('poco', 'last_federation_discovery');
1326 $next = $last + (24 * 60 * 60);
1327 if ($next > time()) {
1332 // Discover Friendica, Hubzilla and Diaspora servers
1333 $serverdata = fetch_url("http://the-federation.info/pods.json");
1336 $servers = json_decode($serverdata);
1338 foreach ($servers->pods as $server) {
1339 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1343 // Disvover Mastodon servers
1344 if (!Config::get('system', 'ostatus_disabled')) {
1345 $accesstoken = Config::get('system', 'instances_social_key');
1346 if (!empty($accesstoken)) {
1347 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1348 $header = array('Authorization: Bearer '.$accesstoken);
1349 $serverdata = z_fetch_url($api, false, $redirects, ['headers' => $header]);
1350 if ($serverdata['success']) {
1351 $servers = json_decode($serverdata['body']);
1352 foreach ($servers->instances as $server) {
1353 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1354 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1360 // Currently disabled, since the service isn't available anymore.
1361 // It is not removed since I hope that there will be a successor.
1362 // Discover GNU Social Servers.
1363 //if (!Config::get('system','ostatus_disabled')) {
1364 // $serverdata = "http://gstools.org/api/get_open_instances/";
1366 // $result = z_fetch_url($serverdata);
1367 // if ($result["success"]) {
1368 // $servers = json_decode($result["body"]);
1370 // foreach($servers->data as $server)
1371 // self::checkServer($server->instance_address);
1375 Config::set('poco', 'last_federation_discovery', time());
1378 public static function discoverSingleServer($id)
1380 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1381 if (!DBM::is_result($r)) {
1387 // Discover new servers out there (Works from Friendica version 3.5.2)
1388 self::fetchServerlist($server["poco"]);
1390 // Fetch all users from the other server
1391 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1393 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1395 $retdata = z_fetch_url($url);
1396 if ($retdata["success"]) {
1397 $data = json_decode($retdata["body"]);
1399 self::discoverServer($data, 2);
1401 if (Config::get('system', 'poco_discovery') > 1) {
1402 $timeframe = Config::get('system', 'poco_discovery_since');
1403 if ($timeframe == 0) {
1407 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1409 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1410 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1414 $retdata = z_fetch_url($url);
1415 if ($retdata["success"]) {
1416 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1417 $success = self::discoverServer(json_decode($retdata["body"]));
1420 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1421 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1422 self::discoverServerUsers($data, $server);
1426 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1430 // If the server hadn't replied correctly, then force a sanity check
1431 self::checkServer($server["url"], $server["network"], true);
1433 // If we couldn't reach the server, we will try it some time later
1434 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1440 public static function discover($complete = false)
1442 // Update the server list
1443 self::discoverFederation();
1447 $requery_days = intval(Config::get("system", "poco_requery_days"));
1449 if ($requery_days == 0) {
1452 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1454 $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));
1455 if (DBM::is_result($r)) {
1456 foreach ($r as $server) {
1457 if (!self::checkServer($server["url"], $server["network"])) {
1458 // The server is not reachable? Okay, then we will try it later
1459 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1463 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1464 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1466 if (!$complete && (--$no_of_queries == 0)) {
1473 public static function discoverServerUsers($data, $server)
1475 if (!isset($data->entry)) {
1479 foreach ($data->entry as $entry) {
1481 if (isset($entry->urls)) {
1482 foreach ($entry->urls as $url) {
1483 if ($url->type == 'profile') {
1484 $profile_url = $url->value;
1485 $urlparts = parse_url($profile_url);
1486 $username = end(explode("/", $urlparts["path"]));
1490 if ($username != "") {
1491 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1493 // Fetch all contacts from a given user from the other server
1494 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1496 $retdata = z_fetch_url($url);
1497 if ($retdata["success"]) {
1498 self::discoverServer(json_decode($retdata["body"]), 3);
1504 public static function discoverServer($data, $default_generation = 0)
1506 if (!isset($data->entry) || !count($data->entry)) {
1512 foreach ($data->entry as $entry) {
1514 $profile_photo = '';
1518 $updated = NULL_DATE;
1524 $generation = $default_generation;
1526 $name = $entry->displayName;
1528 if (isset($entry->urls)) {
1529 foreach ($entry->urls as $url) {
1530 if ($url->type == 'profile') {
1531 $profile_url = $url->value;
1534 if ($url->type == 'webfinger') {
1535 $connect_url = str_replace('acct:' , '', $url->value);
1541 if (isset($entry->photos)) {
1542 foreach ($entry->photos as $photo) {
1543 if ($photo->type == 'profile') {
1544 $profile_photo = $photo->value;
1550 if (isset($entry->updated)) {
1551 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1554 if (isset($entry->network)) {
1555 $network = $entry->network;
1558 if (isset($entry->currentLocation)) {
1559 $location = $entry->currentLocation;
1562 if (isset($entry->aboutMe)) {
1563 $about = html2bbcode($entry->aboutMe);
1566 if (isset($entry->gender)) {
1567 $gender = $entry->gender;
1570 if (isset($entry->generation) && ($entry->generation > 0)) {
1571 $generation = ++$entry->generation;
1574 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1575 $contact_type = $entry->contactType;
1578 if (isset($entry->tags)) {
1579 foreach ($entry->tags as $tag) {
1580 $keywords = implode(", ", $tag);
1584 if ($generation > 0) {
1587 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1589 $gcontact = array("url" => $profile_url,
1591 "network" => $network,
1592 "photo" => $profile_photo,
1594 "location" => $location,
1595 "gender" => $gender,
1596 "keywords" => $keywords,
1597 "connect" => $connect_url,
1598 "updated" => $updated,
1599 "contact-type" => $contact_type,
1600 "generation" => $generation);
1603 $gcontact = GContact::sanitize($gcontact);
1604 GContact::update($gcontact);
1605 } catch (Exception $e) {
1606 logger($e->getMessage(), LOGGER_DEBUG);
1609 logger("Done for profile ".$profile_url, LOGGER_DEBUG);