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;
21 require_once 'include/datetime.php';
22 require_once 'include/network.php';
23 require_once 'include/html2bbcode.php';
24 require_once 'include/Contact.php';
25 require_once 'include/Photo.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, "discover_poco", "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 = GlobalContact::sanitize($gcontact);
196 $gcid = GlobalContact::update($gcontact);
198 GlobalContact::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 function poco_reachable($profile, $server = "", $network = "", $force = false) {
216 $server = poco_detect_server($profile);
223 return poco_check_server($server, $network, $force);
226 function poco_detect_server($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 == "") {
286 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
287 dbesc(normalise_link($server_url)));
288 if (DBM::is_result($r)) {
292 // Fetch the host-meta to check if this really is a server
293 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
294 if (!$serverret["success"]) {
301 function poco_alternate_ostatus_url($url) {
302 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
305 function poco_last_updated($profile, $force = false) {
307 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
308 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(poco_detect_server($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(poco_detect_server($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 (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
340 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
341 dbesc(datetime_convert()), dbesc(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))) {
351 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
352 dbesc(normalise_link($server_url)));
355 $contact['network'] = $server[0]["network"];
361 // noscrape is really fast so we don't cache the call.
362 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
364 // Use noscrape if possible
365 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
368 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
370 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 = formatted_location($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 GlobalContact::update($contact);
420 if (trim($noscrape["updated"]) != "") {
421 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
422 dbesc(datetime_convert()), dbesc(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 && !poco_do_update($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 GlobalContact::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) && poco_alternate_ostatus_url($profile)
446 && (normalise_link($profile) == normalise_link($data["alias"]))
447 && (normalise_link($profile) != normalise_link($data["url"]))
449 // Delete the old entry
450 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
451 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
453 $gcontact = array_merge($gcontacts[0], $data);
455 $gcontact["server_url"] = $data["baseurl"];
458 $gcontact = GlobalContact::sanitize($gcontact);
459 GlobalContact::update($gcontact);
461 poco_last_updated($data["url"], $force);
462 } catch (Exception $e) {
463 logger($e->getMessage(), LOGGER_DEBUG);
466 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
470 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
471 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
472 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
474 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
478 $contact = array_merge($contact, $data);
480 $contact["server_url"] = $data["baseurl"];
482 GlobalContact::update($contact);
484 $feedret = z_fetch_url($data["poll"]);
486 if (!$feedret["success"]) {
487 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
488 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
490 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
494 $doc = new DOMDocument();
495 @$doc->loadXML($feedret["body"]);
497 $xpath = new DomXPath($doc);
498 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
500 $entries = $xpath->query('/atom:feed/atom:entry');
504 foreach ($entries as $entry) {
505 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
506 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
508 if ($last_updated < $published)
509 $last_updated = $published;
511 if ($last_updated < $updated)
512 $last_updated = $updated;
515 // Maybe there aren't any entries. Then check if it is a valid feed
516 if ($last_updated == "") {
517 if ($xpath->query('/atom:feed')->length > 0) {
518 $last_updated = NULL_DATE;
521 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
522 dbesc(DBM::date($last_updated)), dbesc(DBM::date()), dbesc(normalise_link($profile)));
524 if (($gcontacts[0]["generation"] == 0)) {
525 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
526 dbesc(normalise_link($profile)));
529 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
531 return($last_updated);
534 function poco_do_update($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 function poco_to_boolean($val) {
579 if (($val == "true") || ($val == 1)) {
581 } elseif (($val == "false") || ($val == 0)) {
589 * @brief Detect server type (Hubzilla or Friendica) via the poco data
591 * @param object $data POCO data
592 * @return array Server data
594 function poco_detect_poco_data($data) {
597 if (!isset($data->entry)) {
601 if (count($data->entry) == 0) {
605 if (!isset($data->entry[0]->urls)) {
609 if (count($data->entry[0]->urls) == 0) {
613 foreach ($data->entry[0]->urls as $url) {
614 if ($url->type == 'zot') {
616 $server["platform"] = 'Hubzilla';
617 $server["network"] = NETWORK_DIASPORA;
625 * @brief Detect server type by using the nodeinfo data
627 * @param string $server_url address of the server
628 * @return array Server data
630 function poco_fetch_nodeinfo($server_url) {
631 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
632 if (!$serverret["success"]) {
636 $nodeinfo = json_decode($serverret['body']);
638 if (!is_object($nodeinfo)) {
642 if (!is_array($nodeinfo->links)) {
648 foreach ($nodeinfo->links as $link) {
649 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
650 $nodeinfo_url = $link->href;
654 if ($nodeinfo_url == '') {
658 $serverret = z_fetch_url($nodeinfo_url);
659 if (!$serverret["success"]) {
663 $nodeinfo = json_decode($serverret['body']);
665 if (!is_object($nodeinfo)) {
671 $server['register_policy'] = REGISTER_CLOSED;
673 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
674 $server['register_policy'] = REGISTER_OPEN;
677 if (is_object($nodeinfo->software)) {
678 if (isset($nodeinfo->software->name)) {
679 $server['platform'] = $nodeinfo->software->name;
682 if (isset($nodeinfo->software->version)) {
683 $server['version'] = $nodeinfo->software->version;
684 // Version numbers on Nodeinfo are presented with additional info, e.g.:
685 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
686 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
690 if (is_object($nodeinfo->metadata)) {
691 if (isset($nodeinfo->metadata->nodeName)) {
692 $server['site_name'] = $nodeinfo->metadata->nodeName;
700 if (is_array($nodeinfo->protocols->inbound)) {
701 foreach ($nodeinfo->protocols->inbound as $inbound) {
702 if ($inbound == 'diaspora') {
705 if ($inbound == 'friendica') {
708 if ($inbound == 'gnusocial') {
715 $server['network'] = NETWORK_OSTATUS;
718 $server['network'] = NETWORK_DIASPORA;
721 $server['network'] = NETWORK_DFRN;
732 * @brief Detect server type (Hubzilla or Friendica) via the front page body
734 * @param string $body Front page of the server
735 * @return array Server data
737 function poco_detect_server_type($body) {
740 $doc = new DOMDocument();
741 @$doc->loadHTML($body);
742 $xpath = new DomXPath($doc);
744 $list = $xpath->query("//meta[@name]");
746 foreach ($list as $node) {
748 if ($node->attributes->length) {
749 foreach ($node->attributes as $attribute) {
750 $attr[$attribute->name] = $attribute->value;
753 if ($attr['name'] == 'generator') {
754 $version_part = explode(" ", $attr['content']);
755 if (count($version_part) == 2) {
756 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
758 $server["platform"] = $version_part[0];
759 $server["version"] = $version_part[1];
760 $server["network"] = NETWORK_DFRN;
767 $list = $xpath->query("//meta[@property]");
769 foreach ($list as $node) {
771 if ($node->attributes->length) {
772 foreach ($node->attributes as $attribute) {
773 $attr[$attribute->name] = $attribute->value;
776 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
778 $server["platform"] = $attr['content'];
779 $server["version"] = "";
780 $server["network"] = NETWORK_DIASPORA;
789 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
793 function poco_check_server($server_url, $network = "", $force = false) {
795 // Unify the server address
796 $server_url = trim($server_url, "/");
797 $server_url = str_replace("/index.php", "", $server_url);
799 if ($server_url == "") {
803 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
804 if (DBM::is_result($servers)) {
806 if ($servers[0]["created"] <= NULL_DATE) {
807 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
808 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
810 $poco = $servers[0]["poco"];
811 $noscrape = $servers[0]["noscrape"];
813 if ($network == "") {
814 $network = $servers[0]["network"];
817 $last_contact = $servers[0]["last_contact"];
818 $last_failure = $servers[0]["last_failure"];
819 $version = $servers[0]["version"];
820 $platform = $servers[0]["platform"];
821 $site_name = $servers[0]["site_name"];
822 $info = $servers[0]["info"];
823 $register_policy = $servers[0]["register_policy"];
825 if (!$force && !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
826 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
827 return ($last_contact >= $last_failure);
836 $register_policy = -1;
838 $last_contact = NULL_DATE;
839 $last_failure = NULL_DATE;
841 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
844 $possible_failure = false;
845 $orig_last_failure = $last_failure;
846 $orig_last_contact = $last_contact;
848 // Check if the page is accessible via SSL.
849 $orig_server_url = $server_url;
850 $server_url = str_replace("http://", "https://", $server_url);
852 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
853 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
855 // Quit if there is a timeout.
856 // But we want to make sure to only quit if we are mostly sure that this server url fits.
857 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
858 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
859 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
860 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
864 // Maybe the page is unencrypted only?
865 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
866 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
867 $server_url = str_replace("https://", "http://", $server_url);
869 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
870 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
872 // Quit if there is a timeout
873 if ($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 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
882 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
883 // Workaround for bad configured servers (known nginx problem)
884 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
887 $possible_failure = true;
890 // If the server has no possible failure we reset the cached data
891 if (!$possible_failure) {
896 $register_policy = -1;
901 $serverret = z_fetch_url($server_url."/poco");
902 if ($serverret["success"]) {
903 $data = json_decode($serverret["body"]);
904 if (isset($data->totalResults)) {
905 $poco = $server_url."/poco";
906 $server = poco_detect_poco_data($data);
908 $platform = $server['platform'];
909 $network = $server['network'];
918 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
919 $serverret = z_fetch_url($server_url);
921 if (!$serverret["success"] || ($serverret["body"] == "")) {
924 $server = poco_detect_server_type($serverret["body"]);
926 $platform = $server['platform'];
927 $network = $server['network'];
928 $version = $server['version'];
929 $site_name = $server['site_name'];
932 $lines = explode("\n",$serverret["header"]);
934 foreach($lines as $line) {
936 if (stristr($line,'X-Diaspora-Version:')) {
937 $platform = "Diaspora";
938 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
939 $version = trim(str_replace("x-diaspora-version:", "", $version));
940 $network = NETWORK_DIASPORA;
941 $versionparts = explode("-", $version);
942 $version = $versionparts[0];
945 if (stristr($line,'Server: Mastodon')) {
946 $platform = "Mastodon";
947 $network = NETWORK_OSTATUS;
954 if (!$failure && ($poco == "")) {
955 // Test for Statusnet
956 // Will also return data for Friendica and GNU Social - but it will be overwritten later
957 // The "not implemented" is a special treatment for really, really old Friendica versions
958 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
959 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
960 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
961 $platform = "StatusNet";
962 // Remove junk that some GNU Social servers return
963 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
964 $version = trim($version, '"');
965 $network = NETWORK_OSTATUS;
968 // Test for GNU Social
969 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
970 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
971 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
972 $platform = "GNU Social";
973 // Remove junk that some GNU Social servers return
974 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
975 $version = trim($version, '"');
976 $network = NETWORK_OSTATUS;
980 $orig_version = $version;
981 $serverret = z_fetch_url($server_url."/api/v1/instance");
982 if ($serverret["success"] && ($serverret["body"] != '')) {
983 $data = json_decode($serverret["body"]);
984 if (isset($data->version)) {
985 $platform = "Mastodon";
986 $version = $data->version;
987 $site_name = $data->title;
988 $info = $data->description;
989 $network = NETWORK_OSTATUS;
992 if (strstr($orig_version.$version, 'Pleroma')) {
993 $platform = 'Pleroma';
994 $version = trim(str_replace('Pleroma', '', $version));
999 // Test for Hubzilla and Red
1000 $serverret = z_fetch_url($server_url."/siteinfo.json");
1001 if ($serverret["success"]) {
1002 $data = json_decode($serverret["body"]);
1003 if (isset($data->url)) {
1004 $platform = $data->platform;
1005 $version = $data->version;
1006 $network = NETWORK_DIASPORA;
1008 if (!empty($data->site_name)) {
1009 $site_name = $data->site_name;
1011 switch ($data->register_policy) {
1012 case "REGISTER_OPEN":
1013 $register_policy = REGISTER_OPEN;
1015 case "REGISTER_APPROVE":
1016 $register_policy = REGISTER_APPROVE;
1018 case "REGISTER_CLOSED":
1020 $register_policy = REGISTER_CLOSED;
1024 // Test for Hubzilla, Redmatrix or Friendica
1025 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1026 if ($serverret["success"]) {
1027 $data = json_decode($serverret["body"]);
1028 if (isset($data->site->server)) {
1029 if (isset($data->site->platform)) {
1030 $platform = $data->site->platform->PLATFORM_NAME;
1031 $version = $data->site->platform->STD_VERSION;
1032 $network = NETWORK_DIASPORA;
1034 if (isset($data->site->BlaBlaNet)) {
1035 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1036 $version = $data->site->BlaBlaNet->STD_VERSION;
1037 $network = NETWORK_DIASPORA;
1039 if (isset($data->site->hubzilla)) {
1040 $platform = $data->site->hubzilla->PLATFORM_NAME;
1041 $version = $data->site->hubzilla->RED_VERSION;
1042 $network = NETWORK_DIASPORA;
1044 if (isset($data->site->redmatrix)) {
1045 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1046 $platform = $data->site->redmatrix->PLATFORM_NAME;
1047 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1048 $platform = $data->site->redmatrix->RED_PLATFORM;
1051 $version = $data->site->redmatrix->RED_VERSION;
1052 $network = NETWORK_DIASPORA;
1054 if (isset($data->site->friendica)) {
1055 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1056 $version = $data->site->friendica->FRIENDICA_VERSION;
1057 $network = NETWORK_DFRN;
1060 $site_name = $data->site->name;
1062 $data->site->closed = poco_to_boolean($data->site->closed);
1063 $data->site->private = poco_to_boolean($data->site->private);
1064 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1066 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1067 $register_policy = REGISTER_APPROVE;
1068 } elseif (!$data->site->closed && !$data->site->private) {
1069 $register_policy = REGISTER_OPEN;
1071 $register_policy = REGISTER_CLOSED;
1078 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1080 $serverret = z_fetch_url($server_url."/statistics.json");
1081 if ($serverret["success"]) {
1082 $data = json_decode($serverret["body"]);
1083 if (isset($data->version)) {
1084 $version = $data->version;
1085 // Version numbers on statistics.json are presented with additional info, e.g.:
1086 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1087 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1090 if (!empty($data->name)) {
1091 $site_name = $data->name;
1094 if (!empty($data->network)) {
1095 $platform = $data->network;
1098 if ($platform == "Diaspora") {
1099 $network = NETWORK_DIASPORA;
1102 if ($data->registrations_open) {
1103 $register_policy = REGISTER_OPEN;
1105 $register_policy = REGISTER_CLOSED;
1110 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1112 $server = poco_fetch_nodeinfo($server_url);
1114 $register_policy = $server['register_policy'];
1116 if (isset($server['platform'])) {
1117 $platform = $server['platform'];
1120 if (isset($server['network'])) {
1121 $network = $server['network'];
1124 if (isset($server['version'])) {
1125 $version = $server['version'];
1128 if (isset($server['site_name'])) {
1129 $site_name = $server['site_name'];
1134 // Check for noscrape
1135 // Friendica servers could be detected as OStatus servers
1136 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1137 $serverret = z_fetch_url($server_url."/friendica/json");
1139 if (!$serverret["success"]) {
1140 $serverret = z_fetch_url($server_url."/friendika/json");
1143 if ($serverret["success"]) {
1144 $data = json_decode($serverret["body"]);
1146 if (isset($data->version)) {
1147 $network = NETWORK_DFRN;
1149 $noscrape = $data->no_scrape_url;
1150 $version = $data->version;
1151 $site_name = $data->site_name;
1152 $info = $data->info;
1153 $register_policy_str = $data->register_policy;
1154 $platform = $data->platform;
1156 switch ($register_policy_str) {
1157 case "REGISTER_CLOSED":
1158 $register_policy = REGISTER_CLOSED;
1160 case "REGISTER_APPROVE":
1161 $register_policy = REGISTER_APPROVE;
1163 case "REGISTER_OPEN":
1164 $register_policy = REGISTER_OPEN;
1171 if ($possible_failure && !$failure) {
1176 $last_contact = $orig_last_contact;
1177 $last_failure = datetime_convert();
1179 $last_contact = datetime_convert();
1180 $last_failure = $orig_last_failure;
1183 if (($last_contact <= $last_failure) && !$failure) {
1184 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1185 } elseif (($last_contact >= $last_failure) && $failure) {
1186 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1189 // Check again if the server exists
1190 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1192 $version = strip_tags($version);
1193 $site_name = strip_tags($site_name);
1194 $info = strip_tags($info);
1195 $platform = strip_tags($platform);
1198 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1199 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1204 intval($register_policy),
1209 dbesc($last_contact),
1210 dbesc($last_failure),
1211 dbesc(normalise_link($server_url))
1213 } elseif (!$failure) {
1214 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1215 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1217 dbesc(normalise_link($server_url)),
1221 intval($register_policy),
1226 dbesc(datetime_convert()),
1227 dbesc($last_contact),
1228 dbesc($last_failure),
1229 dbesc(datetime_convert())
1232 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1238 * @brief Returns a list of all known servers
1239 * @return array List of server urls
1241 function poco_serverlist() {
1242 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1243 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1244 ORDER BY `last_contact`
1246 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1247 if (!DBM::is_result($r)) {
1255 * @brief Fetch server list from remote servers and adds them when they are new.
1257 * @param string $poco URL to the POCO endpoint
1259 function poco_fetch_serverlist($poco) {
1260 $serverret = z_fetch_url($poco."/@server");
1261 if (!$serverret["success"]) {
1264 $serverlist = json_decode($serverret['body']);
1266 if (!is_array($serverlist)) {
1270 foreach ($serverlist as $server) {
1271 $server_url = str_replace("/index.php", "", $server->url);
1273 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1274 if (!DBM::is_result($r)) {
1275 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1276 Worker::add(PRIORITY_LOW, "discover_poco", "server", $server_url);
1281 function poco_discover_federation() {
1282 $last = Config::get('poco','last_federation_discovery');
1285 $next = $last + (24 * 60 * 60);
1286 if ($next > time()) {
1291 // Discover Friendica, Hubzilla and Diaspora servers
1292 $serverdata = fetch_url("http://the-federation.info/pods.json");
1295 $servers = json_decode($serverdata);
1297 foreach ($servers->pods as $server) {
1298 Worker::add(PRIORITY_LOW, "discover_poco", "server", "https://".$server->host);
1302 // Disvover Mastodon servers
1303 if (!Config::get('system','ostatus_disabled')) {
1304 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1307 $servers = json_decode($serverdata);
1309 foreach ($servers as $server) {
1310 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1311 Worker::add(PRIORITY_LOW, "discover_poco", "server", $url);
1316 // Currently disabled, since the service isn't available anymore.
1317 // It is not removed since I hope that there will be a successor.
1318 // Discover GNU Social Servers.
1319 //if (!Config::get('system','ostatus_disabled')) {
1320 // $serverdata = "http://gstools.org/api/get_open_instances/";
1322 // $result = z_fetch_url($serverdata);
1323 // if ($result["success"]) {
1324 // $servers = json_decode($result["body"]);
1326 // foreach($servers->data as $server)
1327 // poco_check_server($server->instance_address);
1331 Config::set('poco','last_federation_discovery', time());
1334 function poco_discover_single_server($id) {
1335 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1336 if (!DBM::is_result($r)) {
1342 // Discover new servers out there (Works from Friendica version 3.5.2)
1343 poco_fetch_serverlist($server["poco"]);
1345 // Fetch all users from the other server
1346 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1348 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1350 $retdata = z_fetch_url($url);
1351 if ($retdata["success"]) {
1352 $data = json_decode($retdata["body"]);
1354 poco_discover_server($data, 2);
1356 if (Config::get('system','poco_discovery') > 1) {
1358 $timeframe = Config::get('system','poco_discovery_since');
1359 if ($timeframe == 0) {
1363 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1365 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1366 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1370 $retdata = z_fetch_url($url);
1371 if ($retdata["success"]) {
1372 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1373 $success = poco_discover_server(json_decode($retdata["body"]));
1376 if (!$success && (Config::get('system','poco_discovery') > 2)) {
1377 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1378 poco_discover_server_users($data, $server);
1382 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1386 // If the server hadn't replied correctly, then force a sanity check
1387 poco_check_server($server["url"], $server["network"], true);
1389 // If we couldn't reach the server, we will try it some time later
1390 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1396 function poco_discover($complete = false) {
1398 // Update the server list
1399 poco_discover_federation();
1403 $requery_days = intval(Config::get("system", "poco_requery_days"));
1405 if ($requery_days == 0) {
1408 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1410 $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));
1411 if (DBM::is_result($r)) {
1412 foreach ($r as $server) {
1414 if (!poco_check_server($server["url"], $server["network"])) {
1415 // The server is not reachable? Okay, then we will try it later
1416 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1420 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1421 Worker::add(PRIORITY_LOW, "discover_poco", "update_server_directory", (int)$server['id']);
1423 if (!$complete && (--$no_of_queries == 0)) {
1430 function poco_discover_server_users($data, $server) {
1432 if (!isset($data->entry)) {
1436 foreach ($data->entry as $entry) {
1438 if (isset($entry->urls)) {
1439 foreach ($entry->urls as $url) {
1440 if ($url->type == 'profile') {
1441 $profile_url = $url->value;
1442 $urlparts = parse_url($profile_url);
1443 $username = end(explode("/", $urlparts["path"]));
1447 if ($username != "") {
1448 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1450 // Fetch all contacts from a given user from the other server
1451 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1453 $retdata = z_fetch_url($url);
1454 if ($retdata["success"]) {
1455 poco_discover_server(json_decode($retdata["body"]), 3);
1461 function poco_discover_server($data, $default_generation = 0) {
1463 if (!isset($data->entry) || !count($data->entry)) {
1469 foreach ($data->entry as $entry) {
1471 $profile_photo = '';
1475 $updated = NULL_DATE;
1481 $generation = $default_generation;
1483 $name = $entry->displayName;
1485 if (isset($entry->urls)) {
1486 foreach ($entry->urls as $url) {
1487 if ($url->type == 'profile') {
1488 $profile_url = $url->value;
1491 if ($url->type == 'webfinger') {
1492 $connect_url = str_replace('acct:' , '', $url->value);
1498 if (isset($entry->photos)) {
1499 foreach ($entry->photos as $photo) {
1500 if ($photo->type == 'profile') {
1501 $profile_photo = $photo->value;
1507 if (isset($entry->updated)) {
1508 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1511 if (isset($entry->network)) {
1512 $network = $entry->network;
1515 if (isset($entry->currentLocation)) {
1516 $location = $entry->currentLocation;
1519 if (isset($entry->aboutMe)) {
1520 $about = html2bbcode($entry->aboutMe);
1523 if (isset($entry->gender)) {
1524 $gender = $entry->gender;
1527 if(isset($entry->generation) && ($entry->generation > 0)) {
1528 $generation = ++$entry->generation;
1531 if(isset($entry->contactType) && ($entry->contactType >= 0)) {
1532 $contact_type = $entry->contactType;
1535 if (isset($entry->tags)) {
1536 foreach ($entry->tags as $tag) {
1537 $keywords = implode(", ", $tag);
1541 if ($generation > 0) {
1544 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1546 $gcontact = array("url" => $profile_url,
1548 "network" => $network,
1549 "photo" => $profile_photo,
1551 "location" => $location,
1552 "gender" => $gender,
1553 "keywords" => $keywords,
1554 "connect" => $connect_url,
1555 "updated" => $updated,
1556 "contact-type" => $contact_type,
1557 "generation" => $generation);
1560 $gcontact = GlobalContact::sanitize($gcontact);
1561 update_gcontact($gcontact);
1562 } catch (Exception $e) {
1563 logger($e->getMessage(), LOGGER_DEBUG);
1566 logger("Done for profile ".$profile_url, LOGGER_DEBUG);