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)
69 $r = dba::select('contact', ['poco', 'uid'], ['id' => $cid], ['limit' => 1]);
70 if (DBM::is_result($r)) {
84 $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') ;
86 logger('load: ' . $url, LOGGER_DEBUG);
90 logger('load: returns ' . $s, LOGGER_DATA);
92 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
94 if (($a->get_curl_code() > 299) || (! $s)) {
100 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
102 if (! isset($j->entry)) {
107 foreach ($j->entry as $entry) {
114 $updated = NULL_DATE;
122 $name = $entry->displayName;
124 if (isset($entry->urls)) {
125 foreach ($entry->urls as $url) {
126 if ($url->type == 'profile') {
127 $profile_url = $url->value;
130 if ($url->type == 'webfinger') {
131 $connect_url = str_replace('acct:', '', $url->value);
136 if (isset($entry->photos)) {
137 foreach ($entry->photos as $photo) {
138 if ($photo->type == 'profile') {
139 $profile_photo = $photo->value;
145 if (isset($entry->updated)) {
146 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
149 if (isset($entry->network)) {
150 $network = $entry->network;
153 if (isset($entry->currentLocation)) {
154 $location = $entry->currentLocation;
157 if (isset($entry->aboutMe)) {
158 $about = html2bbcode($entry->aboutMe);
161 if (isset($entry->gender)) {
162 $gender = $entry->gender;
165 if (isset($entry->generation) && ($entry->generation > 0)) {
166 $generation = ++$entry->generation;
169 if (isset($entry->tags)) {
170 foreach ($entry->tags as $tag) {
171 $keywords = implode(", ", $tag);
175 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
176 $contact_type = $entry->contactType;
179 $gcontact = array("url" => $profile_url,
181 "network" => $network,
182 "photo" => $profile_photo,
184 "location" => $location,
186 "keywords" => $keywords,
187 "connect" => $connect_url,
188 "updated" => $updated,
189 "contact-type" => $contact_type,
190 "generation" => $generation);
193 $gcontact = GContact::sanitize($gcontact);
194 $gcid = GContact::update($gcontact);
196 GContact::link($gcid, $uid, $cid, $zcid);
197 } catch (Exception $e) {
198 logger($e->getMessage(), LOGGER_DEBUG);
201 logger("load: loaded $total entries", LOGGER_DEBUG);
203 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
204 dba::delete('glink', $condition);
207 public static function reachable($profile, $server = "", $network = "", $force = false)
210 $server = self::detectServer($profile);
217 return self::checkServer($server, $network, $force);
220 public static function detectServer($profile)
222 // Try to detect the server path based upon some known standard paths
225 if ($server_url == "") {
226 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
227 if ($friendica != $profile) {
228 $server_url = $friendica;
229 $network = NETWORK_DFRN;
233 if ($server_url == "") {
234 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
235 if ($diaspora != $profile) {
236 $server_url = $diaspora;
237 $network = NETWORK_DIASPORA;
241 if ($server_url == "") {
242 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
243 if ($red != $profile) {
245 $network = NETWORK_DIASPORA;
250 if ($server_url == "") {
251 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
252 if ($mastodon != $profile) {
253 $server_url = $mastodon;
254 $network = NETWORK_OSTATUS;
258 // Numeric OStatus variant
259 if ($server_url == "") {
260 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
261 if ($ostatus != $profile) {
262 $server_url = $ostatus;
263 $network = NETWORK_OSTATUS;
268 if ($server_url == "") {
269 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
270 if ($base != $profile) {
272 $network = NETWORK_PHANTOM;
276 if ($server_url == "") {
281 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
282 dbesc(normalise_link($server_url))
285 if (DBM::is_result($r)) {
289 // Fetch the host-meta to check if this really is a server
290 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
291 if (!$serverret["success"]) {
298 public static function alternateOStatusUrl($url)
300 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
303 public static function lastUpdated($profile, $force = false)
306 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
307 dbesc(normalise_link($profile))
310 if (!DBM::is_result($gcontacts)) {
314 $contact = array("url" => $profile);
316 if ($gcontacts[0]["created"] <= NULL_DATE) {
317 $contact['created'] = datetime_convert();
321 $server_url = normalise_link(self::detectServer($profile));
324 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
325 $server_url = $gcontacts[0]["server_url"];
328 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
329 $server_url = normalise_link(self::detectServer($profile));
332 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
333 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
337 if ($server_url != "") {
338 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
340 $fields = ['last_failure' => datetime_convert()];
341 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
344 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
347 $contact['server_url'] = $server_url;
350 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
352 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
353 dbesc(normalise_link($server_url))
357 $contact['network'] = $server[0]["network"];
363 // noscrape is really fast so we don't cache the call.
364 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
365 // Use noscrape if possible
366 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
369 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
371 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
372 $noscrape = json_decode($noscraperet["body"], true);
374 if (is_array($noscrape)) {
375 $contact["network"] = $server[0]["network"];
377 if (isset($noscrape["fn"])) {
378 $contact["name"] = $noscrape["fn"];
380 if (isset($noscrape["comm"])) {
381 $contact["community"] = $noscrape["comm"];
383 if (isset($noscrape["tags"])) {
384 $keywords = implode(" ", $noscrape["tags"]);
385 if ($keywords != "") {
386 $contact["keywords"] = $keywords;
390 $location = Profile::formatLocation($noscrape);
392 $contact["location"] = $location;
394 if (isset($noscrape["dfrn-notify"])) {
395 $contact["notify"] = $noscrape["dfrn-notify"];
397 // Remove all fields that are not present in the gcontact table
398 unset($noscrape["fn"]);
399 unset($noscrape["key"]);
400 unset($noscrape["homepage"]);
401 unset($noscrape["comm"]);
402 unset($noscrape["tags"]);
403 unset($noscrape["locality"]);
404 unset($noscrape["region"]);
405 unset($noscrape["country-name"]);
406 unset($noscrape["contacts"]);
407 unset($noscrape["dfrn-request"]);
408 unset($noscrape["dfrn-confirm"]);
409 unset($noscrape["dfrn-notify"]);
410 unset($noscrape["dfrn-poll"]);
412 // Set the date of the last contact
413 /// @todo By now the function "update_gcontact" doesn't work with this field
414 //$contact["last_contact"] = datetime_convert();
416 $contact = array_merge($contact, $noscrape);
418 GContact::update($contact);
420 if (trim($noscrape["updated"]) != "") {
421 $fields = ['last_contact' => datetime_convert()];
422 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
424 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
426 return $noscrape["updated"];
433 // If we only can poll the feed, then we only do this once a while
434 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
435 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
437 GContact::update($contact);
438 return $gcontacts[0]["updated"];
441 $data = Probe::uri($profile);
443 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
444 // Then check the other link and delete this one
445 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
446 && (normalise_link($profile) == normalise_link($data["alias"]))
447 && (normalise_link($profile) != normalise_link($data["url"]))
449 // Delete the old entry
450 dba::delete('gcontact', ['nurl' => normalise_link($profile)]);
452 $gcontact = array_merge($gcontacts[0], $data);
454 $gcontact["server_url"] = $data["baseurl"];
457 $gcontact = GContact::sanitize($gcontact);
458 GContact::update($gcontact);
460 self::lastUpdated($data["url"], $force);
461 } catch (Exception $e) {
462 logger($e->getMessage(), LOGGER_DEBUG);
465 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
469 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
470 $fields = ['last_failure' => datetime_convert()];
471 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
473 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
477 $contact = array_merge($contact, $data);
479 $contact["server_url"] = $data["baseurl"];
481 GContact::update($contact);
483 $feedret = z_fetch_url($data["poll"]);
485 if (!$feedret["success"]) {
486 $fields = ['last_failure' => datetime_convert()];
487 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
489 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
493 $doc = new DOMDocument();
494 @$doc->loadXML($feedret["body"]);
496 $xpath = new DOMXPath($doc);
497 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
499 $entries = $xpath->query('/atom:feed/atom:entry');
503 foreach ($entries as $entry) {
504 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
505 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
507 if ($last_updated < $published)
508 $last_updated = $published;
510 if ($last_updated < $updated)
511 $last_updated = $updated;
514 // Maybe there aren't any entries. Then check if it is a valid feed
515 if ($last_updated == "") {
516 if ($xpath->query('/atom:feed')->length > 0) {
517 $last_updated = NULL_DATE;
520 $fields = ['updated' => DBM::date($last_updated), 'last_contact' => DBM::date()];
521 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
523 if (($gcontacts[0]["generation"] == 0)) {
524 $fields = ['generation' => 9];
525 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
528 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
530 return($last_updated);
533 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
535 $now = strtotime(datetime_convert());
537 if ($updated > $last_contact) {
538 $contact_time = strtotime($updated);
540 $contact_time = strtotime($last_contact);
543 $failure_time = strtotime($last_failure);
544 $created_time = strtotime($created);
546 // If there is no "created" time then use the current time
547 if ($created_time <= 0) {
548 $created_time = $now;
551 // If the last contact was less than 24 hours then don't update
552 if (($now - $contact_time) < (60 * 60 * 24)) {
556 // If the last failure was less than 24 hours then don't update
557 if (($now - $failure_time) < (60 * 60 * 24)) {
561 // If the last contact was less than a week ago and the last failure is older than a week then don't update
562 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
565 // 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
566 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
570 // 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
571 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
578 public static function toBoolean($val)
580 if (($val == "true") || ($val == 1)) {
582 } elseif (($val == "false") || ($val == 0)) {
590 * @brief Detect server type (Hubzilla or Friendica) via the poco data
592 * @param object $data POCO data
593 * @return array Server data
595 public static function detectPocoData($data)
599 if (!isset($data->entry)) {
603 if (count($data->entry) == 0) {
607 if (!isset($data->entry[0]->urls)) {
611 if (count($data->entry[0]->urls) == 0) {
615 foreach ($data->entry[0]->urls as $url) {
616 if ($url->type == 'zot') {
618 $server["platform"] = 'Hubzilla';
619 $server["network"] = NETWORK_DIASPORA;
627 * @brief Detect server type by using the nodeinfo data
629 * @param string $server_url address of the server
630 * @return array Server data
632 public static function fetchNodeinfo($server_url)
634 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
635 if (!$serverret["success"]) {
639 $nodeinfo = json_decode($serverret['body']);
641 if (!is_object($nodeinfo)) {
645 if (!is_array($nodeinfo->links)) {
651 foreach ($nodeinfo->links as $link) {
652 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
653 $nodeinfo_url = $link->href;
657 if ($nodeinfo_url == '') {
661 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
662 if (parse_url($server_url, PHP_URL_HOST) != parse_url($nodeinfo_url, PHP_URL_HOST)) {
666 $serverret = z_fetch_url($nodeinfo_url);
667 if (!$serverret["success"]) {
671 $nodeinfo = json_decode($serverret['body']);
673 if (!is_object($nodeinfo)) {
679 $server['register_policy'] = REGISTER_CLOSED;
681 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
682 $server['register_policy'] = REGISTER_OPEN;
685 if (is_object($nodeinfo->software)) {
686 if (isset($nodeinfo->software->name)) {
687 $server['platform'] = $nodeinfo->software->name;
690 if (isset($nodeinfo->software->version)) {
691 $server['version'] = $nodeinfo->software->version;
692 // Version numbers on Nodeinfo are presented with additional info, e.g.:
693 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
694 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
698 if (is_object($nodeinfo->metadata)) {
699 if (isset($nodeinfo->metadata->nodeName)) {
700 $server['site_name'] = $nodeinfo->metadata->nodeName;
704 if (!empty($nodeinfo->usage->users->total)) {
705 $server['registered-users'] = $nodeinfo->usage->users->total;
712 if (is_array($nodeinfo->protocols->inbound)) {
713 foreach ($nodeinfo->protocols->inbound as $inbound) {
714 if ($inbound == 'diaspora') {
717 if ($inbound == 'friendica') {
720 if ($inbound == 'gnusocial') {
727 $server['network'] = NETWORK_OSTATUS;
730 $server['network'] = NETWORK_DIASPORA;
733 $server['network'] = NETWORK_DFRN;
744 * @brief Detect server type (Hubzilla or Friendica) via the front page body
746 * @param string $body Front page of the server
747 * @return array Server data
749 public static function detectServerType($body)
753 $doc = new DOMDocument();
754 @$doc->loadHTML($body);
755 $xpath = new DOMXPath($doc);
757 $list = $xpath->query("//meta[@name]");
759 foreach ($list as $node) {
761 if ($node->attributes->length) {
762 foreach ($node->attributes as $attribute) {
763 $attr[$attribute->name] = $attribute->value;
766 if ($attr['name'] == 'generator') {
767 $version_part = explode(" ", $attr['content']);
768 if (count($version_part) == 2) {
769 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
771 $server["platform"] = $version_part[0];
772 $server["version"] = $version_part[1];
773 $server["network"] = NETWORK_DFRN;
780 $list = $xpath->query("//meta[@property]");
782 foreach ($list as $node) {
784 if ($node->attributes->length) {
785 foreach ($node->attributes as $attribute) {
786 $attr[$attribute->name] = $attribute->value;
789 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
791 $server["platform"] = $attr['content'];
792 $server["version"] = "";
793 $server["network"] = NETWORK_DIASPORA;
802 $server["site_name"] = $xpath->evaluate("//head/title/text()")->item(0)->nodeValue;
806 public static function checkServer($server_url, $network = "", $force = false)
808 // Unify the server address
809 $server_url = trim($server_url, "/");
810 $server_url = str_replace("/index.php", "", $server_url);
812 if ($server_url == "") {
816 $servers = dba::select('gserver', [], ['nurl' => normalise_link($server_url)], ['limit' => 1]);
817 if (DBM::is_result($servers)) {
818 if ($servers["created"] <= NULL_DATE) {
819 $fields = ['created' => datetime_convert()];
820 $condition = ['nurl' => normalise_link($server_url)];
821 dba::update('gserver', $fields, $condition);
823 $poco = $servers["poco"];
824 $noscrape = $servers["noscrape"];
826 if ($network == "") {
827 $network = $servers["network"];
830 $last_contact = $servers["last_contact"];
831 $last_failure = $servers["last_failure"];
832 $version = $servers["version"];
833 $platform = $servers["platform"];
834 $site_name = $servers["site_name"];
835 $info = $servers["info"];
836 $register_policy = $servers["register_policy"];
837 $registered_users = $servers["registered-users"];
839 if (!$force && !self::updateNeeded($servers["created"], "", $last_failure, $last_contact)) {
840 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
841 return ($last_contact >= $last_failure);
850 $register_policy = -1;
851 $registered_users = 0;
853 $last_contact = NULL_DATE;
854 $last_failure = NULL_DATE;
856 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
859 $possible_failure = false;
860 $orig_last_failure = $last_failure;
861 $orig_last_contact = $last_contact;
863 // Check if the page is accessible via SSL.
864 $orig_server_url = $server_url;
865 $server_url = str_replace("http://", "https://", $server_url);
867 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
868 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
870 // Quit if there is a timeout.
871 // But we want to make sure to only quit if we are mostly sure that this server url fits.
872 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
873 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
874 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
875 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
879 // Maybe the page is unencrypted only?
880 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
881 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
882 $server_url = str_replace("https://", "http://", $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 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
889 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
890 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
894 $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 // Workaround for bad configured servers (known nginx problem)
899 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
902 $possible_failure = true;
905 // If the server has no possible failure we reset the cached data
906 if (!$possible_failure) {
911 $register_policy = -1;
915 // This will be too low, but better than no value at all.
916 $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
918 // Every server has got an admin account at least
919 if ($registered_users == 0) {
920 $registered_users = 1;
926 $serverret = z_fetch_url($server_url."/poco");
927 if ($serverret["success"]) {
928 $data = json_decode($serverret["body"]);
929 if (isset($data->totalResults)) {
930 $registered_users = $data->totalResults;
931 $poco = $server_url."/poco";
932 $server = self::detectPocoData($data);
934 $platform = $server['platform'];
935 $network = $server['network'];
940 // There are servers out there who don't return 404 on a failure
941 // We have to be sure that don't misunderstand this
942 if (is_null($data)) {
951 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
952 $serverret = z_fetch_url($server_url);
954 if (!$serverret["success"] || ($serverret["body"] == "")) {
957 $server = self::detectServerType($serverret["body"]);
959 $platform = $server['platform'];
960 $network = $server['network'];
961 $version = $server['version'];
962 $site_name = $server['site_name'];
965 $lines = explode("\n", $serverret["header"]);
967 foreach ($lines as $line) {
969 if (stristr($line, 'X-Diaspora-Version:')) {
970 $platform = "Diaspora";
971 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
972 $version = trim(str_replace("x-diaspora-version:", "", $version));
973 $network = NETWORK_DIASPORA;
974 $versionparts = explode("-", $version);
975 $version = $versionparts[0];
978 if (stristr($line, 'Server: Mastodon')) {
979 $platform = "Mastodon";
980 $network = NETWORK_OSTATUS;
987 if (!$failure && ($poco == "")) {
988 // Test for Statusnet
989 // Will also return data for Friendica and GNU Social - but it will be overwritten later
990 // The "not implemented" is a special treatment for really, really old Friendica versions
991 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
992 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
993 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
994 $platform = "StatusNet";
995 // Remove junk that some GNU Social servers return
996 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
997 $version = trim($version, '"');
998 $network = NETWORK_OSTATUS;
1001 // Test for GNU Social
1002 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1003 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1004 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1005 $platform = "GNU Social";
1006 // Remove junk that some GNU Social servers return
1007 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1008 $version = trim($version, '"');
1009 $network = NETWORK_OSTATUS;
1012 // Test for Mastodon
1013 $orig_version = $version;
1014 $serverret = z_fetch_url($server_url."/api/v1/instance");
1015 if ($serverret["success"] && ($serverret["body"] != '')) {
1016 $data = json_decode($serverret["body"]);
1018 if (isset($data->version)) {
1019 $platform = "Mastodon";
1020 $version = $data->version;
1021 $site_name = $data->title;
1022 $info = $data->description;
1023 $network = NETWORK_OSTATUS;
1025 if (!empty($data->stats->user_count)) {
1026 $registered_users = $data->stats->user_count;
1029 if (strstr($orig_version.$version, 'Pleroma')) {
1030 $platform = 'Pleroma';
1031 $version = trim(str_replace('Pleroma', '', $version));
1036 // Test for Hubzilla and Red
1037 $serverret = z_fetch_url($server_url."/siteinfo.json");
1038 if ($serverret["success"]) {
1039 $data = json_decode($serverret["body"]);
1040 if (isset($data->url)) {
1041 $platform = $data->platform;
1042 $version = $data->version;
1043 $network = NETWORK_DIASPORA;
1045 if (!empty($data->site_name)) {
1046 $site_name = $data->site_name;
1048 if (!empty($data->channels_total)) {
1049 $registered_users = $data->channels_total;
1051 switch ($data->register_policy) {
1052 case "REGISTER_OPEN":
1053 $register_policy = REGISTER_OPEN;
1055 case "REGISTER_APPROVE":
1056 $register_policy = REGISTER_APPROVE;
1058 case "REGISTER_CLOSED":
1060 $register_policy = REGISTER_CLOSED;
1064 // Test for Hubzilla, Redmatrix or Friendica
1065 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1066 if ($serverret["success"]) {
1067 $data = json_decode($serverret["body"]);
1068 if (isset($data->site->server)) {
1069 if (isset($data->site->platform)) {
1070 $platform = $data->site->platform->PLATFORM_NAME;
1071 $version = $data->site->platform->STD_VERSION;
1072 $network = NETWORK_DIASPORA;
1074 if (isset($data->site->BlaBlaNet)) {
1075 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1076 $version = $data->site->BlaBlaNet->STD_VERSION;
1077 $network = NETWORK_DIASPORA;
1079 if (isset($data->site->hubzilla)) {
1080 $platform = $data->site->hubzilla->PLATFORM_NAME;
1081 $version = $data->site->hubzilla->RED_VERSION;
1082 $network = NETWORK_DIASPORA;
1084 if (isset($data->site->redmatrix)) {
1085 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1086 $platform = $data->site->redmatrix->PLATFORM_NAME;
1087 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1088 $platform = $data->site->redmatrix->RED_PLATFORM;
1091 $version = $data->site->redmatrix->RED_VERSION;
1092 $network = NETWORK_DIASPORA;
1094 if (isset($data->site->friendica)) {
1095 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1096 $version = $data->site->friendica->FRIENDICA_VERSION;
1097 $network = NETWORK_DFRN;
1100 $site_name = $data->site->name;
1102 $data->site->closed = self::toBoolean($data->site->closed);
1103 $data->site->private = self::toBoolean($data->site->private);
1104 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1106 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1107 $register_policy = REGISTER_APPROVE;
1108 } elseif (!$data->site->closed && !$data->site->private) {
1109 $register_policy = REGISTER_OPEN;
1111 $register_policy = REGISTER_CLOSED;
1118 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1120 $serverret = z_fetch_url($server_url."/statistics.json");
1121 if ($serverret["success"]) {
1122 $data = json_decode($serverret["body"]);
1124 if (isset($data->version)) {
1125 $version = $data->version;
1126 // Version numbers on statistics.json are presented with additional info, e.g.:
1127 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1128 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1131 if (!empty($data->name)) {
1132 $site_name = $data->name;
1135 if (!empty($data->network)) {
1136 $platform = $data->network;
1139 if ($platform == "Diaspora") {
1140 $network = NETWORK_DIASPORA;
1143 if ($data->registrations_open) {
1144 $register_policy = REGISTER_OPEN;
1146 $register_policy = REGISTER_CLOSED;
1151 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1153 $server = self::fetchNodeinfo($server_url);
1155 $register_policy = $server['register_policy'];
1157 if (isset($server['platform'])) {
1158 $platform = $server['platform'];
1161 if (isset($server['network'])) {
1162 $network = $server['network'];
1165 if (isset($server['version'])) {
1166 $version = $server['version'];
1169 if (isset($server['site_name'])) {
1170 $site_name = $server['site_name'];
1173 if (isset($server['registered-users'])) {
1174 $registered_users = $server['registered-users'];
1179 // Check for noscrape
1180 // Friendica servers could be detected as OStatus servers
1181 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1182 $serverret = z_fetch_url($server_url."/friendica/json");
1184 if (!$serverret["success"]) {
1185 $serverret = z_fetch_url($server_url."/friendika/json");
1188 if ($serverret["success"]) {
1189 $data = json_decode($serverret["body"]);
1191 if (isset($data->version)) {
1192 $network = NETWORK_DFRN;
1194 $noscrape = $data->no_scrape_url;
1195 $version = $data->version;
1196 $site_name = $data->site_name;
1197 $info = $data->info;
1198 $register_policy_str = $data->register_policy;
1199 $platform = $data->platform;
1201 switch ($register_policy_str) {
1202 case "REGISTER_CLOSED":
1203 $register_policy = REGISTER_CLOSED;
1205 case "REGISTER_APPROVE":
1206 $register_policy = REGISTER_APPROVE;
1208 case "REGISTER_OPEN":
1209 $register_policy = REGISTER_OPEN;
1216 if ($possible_failure && !$failure) {
1221 $last_contact = $orig_last_contact;
1222 $last_failure = datetime_convert();
1224 $last_contact = datetime_convert();
1225 $last_failure = $orig_last_failure;
1228 if (($last_contact <= $last_failure) && !$failure) {
1229 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1230 } elseif (($last_contact >= $last_failure) && $failure) {
1231 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1234 // Check again if the server exists
1235 $found = dba::exists('gserver', array('nurl' => normalise_link($server_url)));
1237 $version = strip_tags($version);
1238 $site_name = strip_tags($site_name);
1239 $info = strip_tags($info);
1240 $platform = strip_tags($platform);
1242 $fields = ['url' => $server_url, 'version' => $version,
1243 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1244 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1245 'platform' => $platform, 'registered-users' => $registered_users,
1246 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1249 dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1250 } elseif (!$failure) {
1251 $fields['nurl'] = normalise_link($server_url);
1252 $fields['created'] = datetime_convert();
1253 dba::insert('gserver', $fields);
1255 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1261 * @brief Returns a list of all known servers
1262 * @return array List of server urls
1264 public static function serverlist()
1267 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1268 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1269 ORDER BY `last_contact`
1271 dbesc(NETWORK_DFRN),
1272 dbesc(NETWORK_DIASPORA),
1273 dbesc(NETWORK_OSTATUS)
1276 if (!DBM::is_result($r)) {
1284 * @brief Fetch server list from remote servers and adds them when they are new.
1286 * @param string $poco URL to the POCO endpoint
1288 public static function fetchServerlist($poco)
1290 $serverret = z_fetch_url($poco."/@server");
1291 if (!$serverret["success"]) {
1294 $serverlist = json_decode($serverret['body']);
1296 if (!is_array($serverlist)) {
1300 foreach ($serverlist as $server) {
1301 $server_url = str_replace("/index.php", "", $server->url);
1303 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1304 if (!DBM::is_result($r)) {
1305 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1306 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1311 public static function discoverFederation()
1313 $last = Config::get('poco', 'last_federation_discovery');
1316 $next = $last + (24 * 60 * 60);
1317 if ($next > time()) {
1322 // Discover Friendica, Hubzilla and Diaspora servers
1323 $serverdata = fetch_url("http://the-federation.info/pods.json");
1326 $servers = json_decode($serverdata);
1328 foreach ($servers->pods as $server) {
1329 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1333 // Disvover Mastodon servers
1334 if (!Config::get('system', 'ostatus_disabled')) {
1335 $accesstoken = Config::get('system', 'instances_social_key');
1336 if (!empty($accesstoken)) {
1337 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1338 $header = array('Authorization: Bearer '.$accesstoken);
1339 $serverdata = z_fetch_url($api, false, $redirects, ['headers' => $header]);
1340 if ($serverdata['success']) {
1341 $servers = json_decode($serverdata['body']);
1342 foreach ($servers->instances as $server) {
1343 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1344 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1350 // Currently disabled, since the service isn't available anymore.
1351 // It is not removed since I hope that there will be a successor.
1352 // Discover GNU Social Servers.
1353 //if (!Config::get('system','ostatus_disabled')) {
1354 // $serverdata = "http://gstools.org/api/get_open_instances/";
1356 // $result = z_fetch_url($serverdata);
1357 // if ($result["success"]) {
1358 // $servers = json_decode($result["body"]);
1360 // foreach($servers->data as $server)
1361 // self::checkServer($server->instance_address);
1365 Config::set('poco', 'last_federation_discovery', time());
1368 public static function discoverSingleServer($id)
1370 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1371 if (!DBM::is_result($r)) {
1377 // Discover new servers out there (Works from Friendica version 3.5.2)
1378 self::fetchServerlist($server["poco"]);
1380 // Fetch all users from the other server
1381 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1383 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1385 $retdata = z_fetch_url($url);
1386 if ($retdata["success"]) {
1387 $data = json_decode($retdata["body"]);
1389 self::discoverServer($data, 2);
1391 if (Config::get('system', 'poco_discovery') > 1) {
1392 $timeframe = Config::get('system', 'poco_discovery_since');
1393 if ($timeframe == 0) {
1397 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1399 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1400 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1404 $retdata = z_fetch_url($url);
1405 if ($retdata["success"]) {
1406 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1407 $success = self::discoverServer(json_decode($retdata["body"]));
1410 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1411 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1412 self::discoverServerUsers($data, $server);
1416 $fields = ['last_poco_query' => datetime_convert()];
1417 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1421 // If the server hadn't replied correctly, then force a sanity check
1422 self::checkServer($server["url"], $server["network"], true);
1424 // If we couldn't reach the server, we will try it some time later
1425 $fields = ['last_poco_query' => datetime_convert()];
1426 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1432 public static function discover($complete = false)
1434 // Update the server list
1435 self::discoverFederation();
1439 $requery_days = intval(Config::get("system", "poco_requery_days"));
1441 if ($requery_days == 0) {
1444 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1446 $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));
1447 if (DBM::is_result($r)) {
1448 foreach ($r as $server) {
1449 if (!self::checkServer($server["url"], $server["network"])) {
1450 // The server is not reachable? Okay, then we will try it later
1451 $fields = ['last_poco_query' => datetime_convert()];
1452 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1456 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1457 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1459 if (!$complete && (--$no_of_queries == 0)) {
1466 public static function discoverServerUsers($data, $server)
1468 if (!isset($data->entry)) {
1472 foreach ($data->entry as $entry) {
1474 if (isset($entry->urls)) {
1475 foreach ($entry->urls as $url) {
1476 if ($url->type == 'profile') {
1477 $profile_url = $url->value;
1478 $urlparts = parse_url($profile_url);
1479 $username = end(explode("/", $urlparts["path"]));
1483 if ($username != "") {
1484 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1486 // Fetch all contacts from a given user from the other server
1487 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1489 $retdata = z_fetch_url($url);
1490 if ($retdata["success"]) {
1491 self::discoverServer(json_decode($retdata["body"]), 3);
1497 public static function discoverServer($data, $default_generation = 0)
1499 if (!isset($data->entry) || !count($data->entry)) {
1505 foreach ($data->entry as $entry) {
1507 $profile_photo = '';
1511 $updated = NULL_DATE;
1517 $generation = $default_generation;
1519 $name = $entry->displayName;
1521 if (isset($entry->urls)) {
1522 foreach ($entry->urls as $url) {
1523 if ($url->type == 'profile') {
1524 $profile_url = $url->value;
1527 if ($url->type == 'webfinger') {
1528 $connect_url = str_replace('acct:' , '', $url->value);
1534 if (isset($entry->photos)) {
1535 foreach ($entry->photos as $photo) {
1536 if ($photo->type == 'profile') {
1537 $profile_photo = $photo->value;
1543 if (isset($entry->updated)) {
1544 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1547 if (isset($entry->network)) {
1548 $network = $entry->network;
1551 if (isset($entry->currentLocation)) {
1552 $location = $entry->currentLocation;
1555 if (isset($entry->aboutMe)) {
1556 $about = html2bbcode($entry->aboutMe);
1559 if (isset($entry->gender)) {
1560 $gender = $entry->gender;
1563 if (isset($entry->generation) && ($entry->generation > 0)) {
1564 $generation = ++$entry->generation;
1567 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1568 $contact_type = $entry->contactType;
1571 if (isset($entry->tags)) {
1572 foreach ($entry->tags as $tag) {
1573 $keywords = implode(", ", $tag);
1577 if ($generation > 0) {
1580 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1582 $gcontact = array("url" => $profile_url,
1584 "network" => $network,
1585 "photo" => $profile_photo,
1587 "location" => $location,
1588 "gender" => $gender,
1589 "keywords" => $keywords,
1590 "connect" => $connect_url,
1591 "updated" => $updated,
1592 "contact-type" => $contact_type,
1593 "generation" => $generation);
1596 $gcontact = GContact::sanitize($gcontact);
1597 GContact::update($gcontact);
1598 } catch (Exception $e) {
1599 logger($e->getMessage(), LOGGER_DEBUG);
1602 logger("Done for profile ".$profile_url, LOGGER_DEBUG);