3 * @file src/Protocol/PortableContact.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 namespace Friendica\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBM;
18 use Friendica\Model\GlobalContact;
19 use Friendica\Network\Probe;
20 use Friendica\Object\Profile;
26 require_once 'include/datetime.php';
27 require_once 'include/network.php';
28 require_once 'include/html2bbcode.php';
29 require_once 'include/Contact.php';
30 require_once 'include/Photo.php';
35 * @brief Fetch POCO data
37 * @param integer $cid Contact ID
38 * @param integer $uid User ID
39 * @param integer $zcid Global Contact ID
40 * @param integer $url POCO address that should be polled
42 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
43 * and add the entries to the gcontact (Global Contact) table, or update existing entries
44 * if anything (name or photo) has changed.
45 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
47 * Once the global contact is stored add (if necessary) the contact linkage which associates
48 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
49 * pointing to the same global contact id.
52 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
54 // Call the function "load" via the worker
55 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
59 * @brief Fetch POCO data from the worker
61 * @param integer $cid Contact ID
62 * @param integer $uid User ID
63 * @param integer $zcid Global Contact ID
64 * @param integer $url POCO address that should be polled
67 public static function load($cid, $uid, $zcid, $url)
72 if ((! $url) || (! $uid)) {
74 "select `poco`, `uid` from `contact` where `id` = %d limit 1",
77 if (DBM::is_result($r)) {
91 $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') ;
93 logger('load: ' . $url, LOGGER_DEBUG);
97 logger('load: returns ' . $s, LOGGER_DATA);
99 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
101 if (($a->get_curl_code() > 299) || (! $s)) {
105 $j = json_decode($s);
107 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
109 if (! isset($j->entry)) {
114 foreach ($j->entry as $entry) {
121 $updated = NULL_DATE;
129 $name = $entry->displayName;
131 if (isset($entry->urls)) {
132 foreach ($entry->urls as $url) {
133 if ($url->type == 'profile') {
134 $profile_url = $url->value;
137 if ($url->type == 'webfinger') {
138 $connect_url = str_replace('acct:', '', $url->value);
143 if (isset($entry->photos)) {
144 foreach ($entry->photos as $photo) {
145 if ($photo->type == 'profile') {
146 $profile_photo = $photo->value;
152 if (isset($entry->updated)) {
153 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
156 if (isset($entry->network)) {
157 $network = $entry->network;
160 if (isset($entry->currentLocation)) {
161 $location = $entry->currentLocation;
164 if (isset($entry->aboutMe)) {
165 $about = html2bbcode($entry->aboutMe);
168 if (isset($entry->gender)) {
169 $gender = $entry->gender;
172 if (isset($entry->generation) && ($entry->generation > 0)) {
173 $generation = ++$entry->generation;
176 if (isset($entry->tags)) {
177 foreach ($entry->tags as $tag) {
178 $keywords = implode(", ", $tag);
182 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
183 $contact_type = $entry->contactType;
186 $gcontact = array("url" => $profile_url,
188 "network" => $network,
189 "photo" => $profile_photo,
191 "location" => $location,
193 "keywords" => $keywords,
194 "connect" => $connect_url,
195 "updated" => $updated,
196 "contact-type" => $contact_type,
197 "generation" => $generation);
200 $gcontact = GlobalContact::sanitize($gcontact);
201 $gcid = GlobalContact::update($gcontact);
203 GlobalContact::link($gcid, $uid, $cid, $zcid);
204 } catch (Exception $e) {
205 logger($e->getMessage(), LOGGER_DEBUG);
208 logger("load: loaded $total entries", LOGGER_DEBUG);
211 "DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
218 public static function reachable($profile, $server = "", $network = "", $force = false)
221 $server = self::detectServer($profile);
228 return self::checkServer($server, $network, $force);
231 public static function detectServer($profile)
233 // Try to detect the server path based upon some known standard paths
236 if ($server_url == "") {
237 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
238 if ($friendica != $profile) {
239 $server_url = $friendica;
240 $network = NETWORK_DFRN;
244 if ($server_url == "") {
245 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
246 if ($diaspora != $profile) {
247 $server_url = $diaspora;
248 $network = NETWORK_DIASPORA;
252 if ($server_url == "") {
253 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
254 if ($red != $profile) {
256 $network = NETWORK_DIASPORA;
261 if ($server_url == "") {
262 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
263 if ($mastodon != $profile) {
264 $server_url = $mastodon;
265 $network = NETWORK_OSTATUS;
269 // Numeric OStatus variant
270 if ($server_url == "") {
271 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
272 if ($ostatus != $profile) {
273 $server_url = $ostatus;
274 $network = NETWORK_OSTATUS;
279 if ($server_url == "") {
280 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
281 if ($base != $profile) {
283 $network = NETWORK_PHANTOM;
287 if ($server_url == "") {
292 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
293 dbesc(normalise_link($server_url))
296 if (DBM::is_result($r)) {
300 // Fetch the host-meta to check if this really is a server
301 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
302 if (!$serverret["success"]) {
309 public static function alternateOStatusUrl($url)
311 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
314 public static function lastUpdated($profile, $force = false)
317 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
318 dbesc(normalise_link($profile))
321 if (!DBM::is_result($gcontacts)) {
325 $contact = array("url" => $profile);
327 if ($gcontacts[0]["created"] <= NULL_DATE) {
328 $contact['created'] = datetime_convert();
332 $server_url = normalise_link(self::detectServer($profile));
335 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
336 $server_url = $gcontacts[0]["server_url"];
339 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
340 $server_url = normalise_link(self::detectServer($profile));
343 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
344 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
348 if ($server_url != "") {
349 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
352 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
353 dbesc(datetime_convert()),
354 dbesc(normalise_link($profile))
358 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
361 $contact['server_url'] = $server_url;
364 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
366 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
367 dbesc(normalise_link($server_url))
371 $contact['network'] = $server[0]["network"];
377 // noscrape is really fast so we don't cache the call.
378 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
379 // Use noscrape if possible
380 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
383 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
385 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
386 $noscrape = json_decode($noscraperet["body"], true);
388 if (is_array($noscrape)) {
389 $contact["network"] = $server[0]["network"];
391 if (isset($noscrape["fn"])) {
392 $contact["name"] = $noscrape["fn"];
394 if (isset($noscrape["comm"])) {
395 $contact["community"] = $noscrape["comm"];
397 if (isset($noscrape["tags"])) {
398 $keywords = implode(" ", $noscrape["tags"]);
399 if ($keywords != "") {
400 $contact["keywords"] = $keywords;
404 $location = Profile::formatLocation($noscrape);
406 $contact["location"] = $location;
408 if (isset($noscrape["dfrn-notify"])) {
409 $contact["notify"] = $noscrape["dfrn-notify"];
411 // Remove all fields that are not present in the gcontact table
412 unset($noscrape["fn"]);
413 unset($noscrape["key"]);
414 unset($noscrape["homepage"]);
415 unset($noscrape["comm"]);
416 unset($noscrape["tags"]);
417 unset($noscrape["locality"]);
418 unset($noscrape["region"]);
419 unset($noscrape["country-name"]);
420 unset($noscrape["contacts"]);
421 unset($noscrape["dfrn-request"]);
422 unset($noscrape["dfrn-confirm"]);
423 unset($noscrape["dfrn-notify"]);
424 unset($noscrape["dfrn-poll"]);
426 // Set the date of the last contact
427 /// @todo By now the function "update_gcontact" doesn't work with this field
428 //$contact["last_contact"] = datetime_convert();
430 $contact = array_merge($contact, $noscrape);
432 GlobalContact::update($contact);
434 if (trim($noscrape["updated"]) != "") {
436 "UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
437 dbesc(datetime_convert()),
438 dbesc(normalise_link($profile))
441 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
443 return $noscrape["updated"];
450 // If we only can poll the feed, then we only do this once a while
451 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
452 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
454 GlobalContact::update($contact);
455 return $gcontacts[0]["updated"];
458 $data = Probe::uri($profile);
460 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
461 // Then check the other link and delete this one
462 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
463 && (normalise_link($profile) == normalise_link($data["alias"]))
464 && (normalise_link($profile) != normalise_link($data["url"]))
466 // Delete the old entry
467 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
468 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
470 $gcontact = array_merge($gcontacts[0], $data);
472 $gcontact["server_url"] = $data["baseurl"];
475 $gcontact = GlobalContact::sanitize($gcontact);
476 GlobalContact::update($gcontact);
478 self::lastUpdated($data["url"], $force);
479 } catch (Exception $e) {
480 logger($e->getMessage(), LOGGER_DEBUG);
483 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
487 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
489 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
490 dbesc(datetime_convert()),
491 dbesc(normalise_link($profile))
494 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
498 $contact = array_merge($contact, $data);
500 $contact["server_url"] = $data["baseurl"];
502 GlobalContact::update($contact);
504 $feedret = z_fetch_url($data["poll"]);
506 if (!$feedret["success"]) {
508 "UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
509 dbesc(datetime_convert()),
510 dbesc(normalise_link($profile))
513 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
517 $doc = new DOMDocument();
518 @$doc->loadXML($feedret["body"]);
520 $xpath = new DomXPath($doc);
521 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
523 $entries = $xpath->query('/atom:feed/atom:entry');
527 foreach ($entries as $entry) {
528 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
529 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
531 if ($last_updated < $published)
532 $last_updated = $published;
534 if ($last_updated < $updated)
535 $last_updated = $updated;
538 // Maybe there aren't any entries. Then check if it is a valid feed
539 if ($last_updated == "") {
540 if ($xpath->query('/atom:feed')->length > 0) {
541 $last_updated = NULL_DATE;
545 "UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
546 dbesc(DBM::date($last_updated)),
548 dbesc(normalise_link($profile))
551 if (($gcontacts[0]["generation"] == 0)) {
553 "UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
554 dbesc(normalise_link($profile))
558 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
560 return($last_updated);
563 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
565 $now = strtotime(datetime_convert());
567 if ($updated > $last_contact) {
568 $contact_time = strtotime($updated);
570 $contact_time = strtotime($last_contact);
573 $failure_time = strtotime($last_failure);
574 $created_time = strtotime($created);
576 // If there is no "created" time then use the current time
577 if ($created_time <= 0) {
578 $created_time = $now;
581 // If the last contact was less than 24 hours then don't update
582 if (($now - $contact_time) < (60 * 60 * 24)) {
586 // If the last failure was less than 24 hours then don't update
587 if (($now - $failure_time) < (60 * 60 * 24)) {
591 // If the last contact was less than a week ago and the last failure is older than a week then don't update
592 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
595 // 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
596 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
600 // 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
601 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
608 public static function toBoolean($val)
610 if (($val == "true") || ($val == 1)) {
612 } elseif (($val == "false") || ($val == 0)) {
620 * @brief Detect server type (Hubzilla or Friendica) via the poco data
622 * @param object $data POCO data
623 * @return array Server data
625 public static function detectPocoData($data)
629 if (!isset($data->entry)) {
633 if (count($data->entry) == 0) {
637 if (!isset($data->entry[0]->urls)) {
641 if (count($data->entry[0]->urls) == 0) {
645 foreach ($data->entry[0]->urls as $url) {
646 if ($url->type == 'zot') {
648 $server["platform"] = 'Hubzilla';
649 $server["network"] = NETWORK_DIASPORA;
657 * @brief Detect server type by using the nodeinfo data
659 * @param string $server_url address of the server
660 * @return array Server data
662 public static function fetchNodeinfo($server_url)
664 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
665 if (!$serverret["success"]) {
669 $nodeinfo = json_decode($serverret['body']);
671 if (!is_object($nodeinfo)) {
675 if (!is_array($nodeinfo->links)) {
681 foreach ($nodeinfo->links as $link) {
682 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
683 $nodeinfo_url = $link->href;
687 if ($nodeinfo_url == '') {
691 $serverret = z_fetch_url($nodeinfo_url);
692 if (!$serverret["success"]) {
696 $nodeinfo = json_decode($serverret['body']);
698 if (!is_object($nodeinfo)) {
704 $server['register_policy'] = REGISTER_CLOSED;
706 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
707 $server['register_policy'] = REGISTER_OPEN;
710 if (is_object($nodeinfo->software)) {
711 if (isset($nodeinfo->software->name)) {
712 $server['platform'] = $nodeinfo->software->name;
715 if (isset($nodeinfo->software->version)) {
716 $server['version'] = $nodeinfo->software->version;
717 // Version numbers on Nodeinfo are presented with additional info, e.g.:
718 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
719 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
723 if (is_object($nodeinfo->metadata)) {
724 if (isset($nodeinfo->metadata->nodeName)) {
725 $server['site_name'] = $nodeinfo->metadata->nodeName;
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($element."//head/title/text()", $context)->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"];
861 if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
862 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
863 return ($last_contact >= $last_failure);
872 $register_policy = -1;
874 $last_contact = NULL_DATE;
875 $last_failure = NULL_DATE;
877 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
880 $possible_failure = false;
881 $orig_last_failure = $last_failure;
882 $orig_last_contact = $last_contact;
884 // Check if the page is accessible via SSL.
885 $orig_server_url = $server_url;
886 $server_url = str_replace("http://", "https://", $server_url);
888 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
889 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
891 // Quit if there is a timeout.
892 // But we want to make sure to only quit if we are mostly sure that this server url fits.
893 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
894 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
895 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
896 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
900 // Maybe the page is unencrypted only?
901 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
902 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
903 $server_url = str_replace("https://", "http://", $server_url);
905 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
906 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
908 // Quit if there is a timeout
909 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
910 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
911 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
915 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
918 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
919 // Workaround for bad configured servers (known nginx problem)
920 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
923 $possible_failure = true;
926 // If the server has no possible failure we reset the cached data
927 if (!$possible_failure) {
932 $register_policy = -1;
937 $serverret = z_fetch_url($server_url."/poco");
938 if ($serverret["success"]) {
939 $data = json_decode($serverret["body"]);
940 if (isset($data->totalResults)) {
941 $poco = $server_url."/poco";
942 $server = self::detectPocoData($data);
944 $platform = $server['platform'];
945 $network = $server['network'];
954 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
955 $serverret = z_fetch_url($server_url);
957 if (!$serverret["success"] || ($serverret["body"] == "")) {
960 $server = self::detectServerType($serverret["body"]);
962 $platform = $server['platform'];
963 $network = $server['network'];
964 $version = $server['version'];
965 $site_name = $server['site_name'];
968 $lines = explode("\n", $serverret["header"]);
970 foreach ($lines as $line) {
972 if (stristr($line, 'X-Diaspora-Version:')) {
973 $platform = "Diaspora";
974 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
975 $version = trim(str_replace("x-diaspora-version:", "", $version));
976 $network = NETWORK_DIASPORA;
977 $versionparts = explode("-", $version);
978 $version = $versionparts[0];
981 if (stristr($line, 'Server: Mastodon')) {
982 $platform = "Mastodon";
983 $network = NETWORK_OSTATUS;
990 if (!$failure && ($poco == "")) {
991 // Test for Statusnet
992 // Will also return data for Friendica and GNU Social - but it will be overwritten later
993 // The "not implemented" is a special treatment for really, really old Friendica versions
994 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
995 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
996 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
997 $platform = "StatusNet";
998 // Remove junk that some GNU Social servers return
999 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1000 $version = trim($version, '"');
1001 $network = NETWORK_OSTATUS;
1004 // Test for GNU Social
1005 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1006 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1007 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1008 $platform = "GNU Social";
1009 // Remove junk that some GNU Social servers return
1010 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1011 $version = trim($version, '"');
1012 $network = NETWORK_OSTATUS;
1015 // Test for Mastodon
1016 $orig_version = $version;
1017 $serverret = z_fetch_url($server_url."/api/v1/instance");
1018 if ($serverret["success"] && ($serverret["body"] != '')) {
1019 $data = json_decode($serverret["body"]);
1020 if (isset($data->version)) {
1021 $platform = "Mastodon";
1022 $version = $data->version;
1023 $site_name = $data->title;
1024 $info = $data->description;
1025 $network = NETWORK_OSTATUS;
1028 if (strstr($orig_version.$version, 'Pleroma')) {
1029 $platform = 'Pleroma';
1030 $version = trim(str_replace('Pleroma', '', $version));
1035 // Test for Hubzilla and Red
1036 $serverret = z_fetch_url($server_url."/siteinfo.json");
1037 if ($serverret["success"]) {
1038 $data = json_decode($serverret["body"]);
1039 if (isset($data->url)) {
1040 $platform = $data->platform;
1041 $version = $data->version;
1042 $network = NETWORK_DIASPORA;
1044 if (!empty($data->site_name)) {
1045 $site_name = $data->site_name;
1047 switch ($data->register_policy) {
1048 case "REGISTER_OPEN":
1049 $register_policy = REGISTER_OPEN;
1051 case "REGISTER_APPROVE":
1052 $register_policy = REGISTER_APPROVE;
1054 case "REGISTER_CLOSED":
1056 $register_policy = REGISTER_CLOSED;
1060 // Test for Hubzilla, Redmatrix or Friendica
1061 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1062 if ($serverret["success"]) {
1063 $data = json_decode($serverret["body"]);
1064 if (isset($data->site->server)) {
1065 if (isset($data->site->platform)) {
1066 $platform = $data->site->platform->PLATFORM_NAME;
1067 $version = $data->site->platform->STD_VERSION;
1068 $network = NETWORK_DIASPORA;
1070 if (isset($data->site->BlaBlaNet)) {
1071 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1072 $version = $data->site->BlaBlaNet->STD_VERSION;
1073 $network = NETWORK_DIASPORA;
1075 if (isset($data->site->hubzilla)) {
1076 $platform = $data->site->hubzilla->PLATFORM_NAME;
1077 $version = $data->site->hubzilla->RED_VERSION;
1078 $network = NETWORK_DIASPORA;
1080 if (isset($data->site->redmatrix)) {
1081 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1082 $platform = $data->site->redmatrix->PLATFORM_NAME;
1083 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1084 $platform = $data->site->redmatrix->RED_PLATFORM;
1087 $version = $data->site->redmatrix->RED_VERSION;
1088 $network = NETWORK_DIASPORA;
1090 if (isset($data->site->friendica)) {
1091 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1092 $version = $data->site->friendica->FRIENDICA_VERSION;
1093 $network = NETWORK_DFRN;
1096 $site_name = $data->site->name;
1098 $data->site->closed = self::toBoolean($data->site->closed);
1099 $data->site->private = self::toBoolean($data->site->private);
1100 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1102 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1103 $register_policy = REGISTER_APPROVE;
1104 } elseif (!$data->site->closed && !$data->site->private) {
1105 $register_policy = REGISTER_OPEN;
1107 $register_policy = REGISTER_CLOSED;
1114 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1116 $serverret = z_fetch_url($server_url."/statistics.json");
1117 if ($serverret["success"]) {
1118 $data = json_decode($serverret["body"]);
1119 if (isset($data->version)) {
1120 $version = $data->version;
1121 // Version numbers on statistics.json are presented with additional info, e.g.:
1122 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1123 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1126 if (!empty($data->name)) {
1127 $site_name = $data->name;
1130 if (!empty($data->network)) {
1131 $platform = $data->network;
1134 if ($platform == "Diaspora") {
1135 $network = NETWORK_DIASPORA;
1138 if ($data->registrations_open) {
1139 $register_policy = REGISTER_OPEN;
1141 $register_policy = REGISTER_CLOSED;
1146 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1148 $server = self::fetchNodeinfo($server_url);
1150 $register_policy = $server['register_policy'];
1152 if (isset($server['platform'])) {
1153 $platform = $server['platform'];
1156 if (isset($server['network'])) {
1157 $network = $server['network'];
1160 if (isset($server['version'])) {
1161 $version = $server['version'];
1164 if (isset($server['site_name'])) {
1165 $site_name = $server['site_name'];
1170 // Check for noscrape
1171 // Friendica servers could be detected as OStatus servers
1172 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1173 $serverret = z_fetch_url($server_url."/friendica/json");
1175 if (!$serverret["success"]) {
1176 $serverret = z_fetch_url($server_url."/friendika/json");
1179 if ($serverret["success"]) {
1180 $data = json_decode($serverret["body"]);
1182 if (isset($data->version)) {
1183 $network = NETWORK_DFRN;
1185 $noscrape = $data->no_scrape_url;
1186 $version = $data->version;
1187 $site_name = $data->site_name;
1188 $info = $data->info;
1189 $register_policy_str = $data->register_policy;
1190 $platform = $data->platform;
1192 switch ($register_policy_str) {
1193 case "REGISTER_CLOSED":
1194 $register_policy = REGISTER_CLOSED;
1196 case "REGISTER_APPROVE":
1197 $register_policy = REGISTER_APPROVE;
1199 case "REGISTER_OPEN":
1200 $register_policy = REGISTER_OPEN;
1207 if ($possible_failure && !$failure) {
1212 $last_contact = $orig_last_contact;
1213 $last_failure = datetime_convert();
1215 $last_contact = datetime_convert();
1216 $last_failure = $orig_last_failure;
1219 if (($last_contact <= $last_failure) && !$failure) {
1220 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1221 } elseif (($last_contact >= $last_failure) && $failure) {
1222 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1225 // Check again if the server exists
1226 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1228 $version = strip_tags($version);
1229 $site_name = strip_tags($site_name);
1230 $info = strip_tags($info);
1231 $platform = strip_tags($platform);
1235 "UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1236 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1241 intval($register_policy),
1246 dbesc($last_contact),
1247 dbesc($last_failure),
1248 dbesc(normalise_link($server_url))
1250 } elseif (!$failure) {
1252 "INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1253 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1255 dbesc(normalise_link($server_url)),
1259 intval($register_policy),
1264 dbesc(datetime_convert()),
1265 dbesc($last_contact),
1266 dbesc($last_failure),
1267 dbesc(datetime_convert())
1270 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1276 * @brief Returns a list of all known servers
1277 * @return array List of server urls
1279 public static function serverlist()
1282 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1283 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1284 ORDER BY `last_contact`
1286 dbesc(NETWORK_DFRN),
1287 dbesc(NETWORK_DIASPORA),
1288 dbesc(NETWORK_OSTATUS)
1291 if (!DBM::is_result($r)) {
1299 * @brief Fetch server list from remote servers and adds them when they are new.
1301 * @param string $poco URL to the POCO endpoint
1303 public static function fetchServerlist($poco)
1305 $serverret = z_fetch_url($poco."/@server");
1306 if (!$serverret["success"]) {
1309 $serverlist = json_decode($serverret['body']);
1311 if (!is_array($serverlist)) {
1315 foreach ($serverlist as $server) {
1316 $server_url = str_replace("/index.php", "", $server->url);
1318 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1319 if (!DBM::is_result($r)) {
1320 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1321 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1326 public static function discoverFederation()
1328 $last = Config::get('poco', 'last_federation_discovery');
1331 $next = $last + (24 * 60 * 60);
1332 if ($next > time()) {
1337 // Discover Friendica, Hubzilla and Diaspora servers
1338 $serverdata = fetch_url("http://the-federation.info/pods.json");
1341 $servers = json_decode($serverdata);
1343 foreach ($servers->pods as $server) {
1344 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1348 // Disvover Mastodon servers
1349 if (!Config::get('system', 'ostatus_disabled')) {
1350 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1353 $servers = json_decode($serverdata);
1355 foreach ($servers as $server) {
1356 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1357 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 = GlobalContact::sanitize($gcontact);
1606 GlobalContact::update($gcontact);
1607 } catch (Exception $e) {
1608 logger($e->getMessage(), LOGGER_DEBUG);
1611 logger("Done for profile ".$profile_url, LOGGER_DEBUG);