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;
15 use Friendica\Content\Text\HTML;
16 use Friendica\Core\Config;
17 use Friendica\Core\Logger;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBA;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Profile;
23 use Friendica\Network\Probe;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Network;
26 use Friendica\Util\XML;
28 require_once 'include/dba.php';
33 * @brief Fetch POCO data
35 * @param integer $cid Contact ID
36 * @param integer $uid User ID
37 * @param integer $zcid Global Contact ID
38 * @param integer $url POCO address that should be polled
40 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
41 * and add the entries to the gcontact (Global Contact) table, or update existing entries
42 * if anything (name or photo) has changed.
43 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
45 * Once the global contact is stored add (if necessary) the contact linkage which associates
46 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
47 * pointing to the same global contact id.
50 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
52 // Call the function "load" via the worker
53 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
57 * @brief Fetch POCO data from the worker
59 * @param integer $cid Contact ID
60 * @param integer $uid User ID
61 * @param integer $zcid Global Contact ID
62 * @param integer $url POCO address that should be polled
65 public static function load($cid, $uid, $zcid, $url)
71 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
72 if (DBA::isResult($contact)) {
73 $url = $contact['poco'];
74 $uid = $contact['uid'];
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::log('load: ' . $url, Logger::DEBUG);
90 $fetchresult = Network::fetchUrlFull($url);
91 $s = $fetchresult->getBody();
93 Logger::log('load: returns ' . $s, Logger::DATA);
95 Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
97 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
101 $j = json_decode($s, true);
103 Logger::log('load: json: ' . print_r($j, true), Logger::DATA);
105 if (!isset($j['entry'])) {
110 foreach ($j['entry'] as $entry) {
117 $updated = DBA::NULL_DATETIME;
125 if (!empty($entry['displayName'])) {
126 $name = $entry['displayName'];
129 if (isset($entry['urls'])) {
130 foreach ($entry['urls'] as $url) {
131 if ($url['type'] == 'profile') {
132 $profile_url = $url['value'];
135 if ($url['type'] == 'webfinger') {
136 $connect_url = str_replace('acct:', '', $url['value']);
141 if (isset($entry['photos'])) {
142 foreach ($entry['photos'] as $photo) {
143 if ($photo['type'] == 'profile') {
144 $profile_photo = $photo['value'];
150 if (isset($entry['updated'])) {
151 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
154 if (isset($entry['network'])) {
155 $network = $entry['network'];
158 if (isset($entry['currentLocation'])) {
159 $location = $entry['currentLocation'];
162 if (isset($entry['aboutMe'])) {
163 $about = HTML::toBBCode($entry['aboutMe']);
166 if (isset($entry['gender'])) {
167 $gender = $entry['gender'];
170 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
171 $generation = ++$entry['generation'];
174 if (isset($entry['tags'])) {
175 foreach ($entry['tags'] as $tag) {
176 $keywords = implode(", ", $tag);
180 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
181 $contact_type = $entry['contactType'];
184 $gcontact = ["url" => $profile_url,
186 "network" => $network,
187 "photo" => $profile_photo,
189 "location" => $location,
191 "keywords" => $keywords,
192 "connect" => $connect_url,
193 "updated" => $updated,
194 "contact-type" => $contact_type,
195 "generation" => $generation];
198 $gcontact = GContact::sanitize($gcontact);
199 $gcid = GContact::update($gcontact);
201 GContact::link($gcid, $uid, $cid, $zcid);
202 } catch (Exception $e) {
203 Logger::log($e->getMessage(), Logger::DEBUG);
206 Logger::log("load: loaded $total entries", Logger::DEBUG);
208 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
209 DBA::delete('glink', $condition);
212 public static function reachable($profile, $server = "", $network = "", $force = false)
215 $server = self::detectServer($profile);
222 return self::checkServer($server, $network, $force);
225 public static function detectServer($profile)
227 // Try to detect the server path based upon some known standard paths
230 if ($server_url == "") {
231 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
232 if ($friendica != $profile) {
233 $server_url = $friendica;
234 $network = Protocol::DFRN;
238 if ($server_url == "") {
239 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
240 if ($diaspora != $profile) {
241 $server_url = $diaspora;
242 $network = Protocol::DIASPORA;
246 if ($server_url == "") {
247 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
248 if ($red != $profile) {
250 $network = Protocol::DIASPORA;
255 if ($server_url == "") {
256 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
257 if ($mastodon != $profile) {
258 $server_url = $mastodon;
259 $network = Protocol::OSTATUS;
263 // Numeric OStatus variant
264 if ($server_url == "") {
265 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
266 if ($ostatus != $profile) {
267 $server_url = $ostatus;
268 $network = Protocol::OSTATUS;
273 if ($server_url == "") {
274 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
275 if ($base != $profile) {
277 $network = Protocol::PHANTOM;
281 if ($server_url == "") {
286 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
287 DBA::escape(normalise_link($server_url))
290 if (DBA::isResult($r)) {
294 // Fetch the host-meta to check if this really is a server
295 $curlResult = Network::curl($server_url."/.well-known/host-meta");
296 if (!$curlResult->isSuccess()) {
303 public static function alternateOStatusUrl($url)
305 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
308 public static function lastUpdated($profile, $force = false)
311 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
312 DBA::escape(normalise_link($profile))
315 if (!DBA::isResult($gcontacts)) {
319 $contact = ["url" => $profile];
321 if ($gcontacts[0]["created"] <= DBA::NULL_DATETIME) {
322 $contact['created'] = DateTimeFormat::utcNow();
327 $server_url = normalise_link(self::detectServer($profile));
330 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
331 $server_url = $gcontacts[0]["server_url"];
334 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
335 $server_url = normalise_link(self::detectServer($profile));
338 if (!in_array($gcontacts[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
339 Logger::log("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", Logger::DEBUG);
343 if ($server_url != "") {
344 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
346 $fields = ['last_failure' => DateTimeFormat::utcNow()];
347 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
350 Logger::log("Profile ".$profile.": Server ".$server_url." wasn't reachable.", Logger::DEBUG);
353 $contact['server_url'] = $server_url;
356 if (in_array($gcontacts[0]["network"], ["", Protocol::FEED])) {
358 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
359 DBA::escape(normalise_link($server_url))
363 $contact['network'] = $server[0]["network"];
369 // noscrape is really fast so we don't cache the call.
370 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
371 // Use noscrape if possible
372 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(normalise_link($server_url)));
375 $curlResult = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
377 if ($curlResult->isSuccess() && ($curlResult->getBody() != "")) {
378 $noscrape = json_decode($curlResult->getBody(), true);
380 if (is_array($noscrape)) {
381 $contact["network"] = $server[0]["network"];
383 if (isset($noscrape["fn"])) {
384 $contact["name"] = $noscrape["fn"];
386 if (isset($noscrape["comm"])) {
387 $contact["community"] = $noscrape["comm"];
389 if (isset($noscrape["tags"])) {
390 $keywords = implode(" ", $noscrape["tags"]);
391 if ($keywords != "") {
392 $contact["keywords"] = $keywords;
396 $location = Profile::formatLocation($noscrape);
398 $contact["location"] = $location;
400 if (isset($noscrape["dfrn-notify"])) {
401 $contact["notify"] = $noscrape["dfrn-notify"];
403 // Remove all fields that are not present in the gcontact table
404 unset($noscrape["fn"]);
405 unset($noscrape["key"]);
406 unset($noscrape["homepage"]);
407 unset($noscrape["comm"]);
408 unset($noscrape["tags"]);
409 unset($noscrape["locality"]);
410 unset($noscrape["region"]);
411 unset($noscrape["country-name"]);
412 unset($noscrape["contacts"]);
413 unset($noscrape["dfrn-request"]);
414 unset($noscrape["dfrn-confirm"]);
415 unset($noscrape["dfrn-notify"]);
416 unset($noscrape["dfrn-poll"]);
418 // Set the date of the last contact
419 /// @todo By now the function "update_gcontact" doesn't work with this field
420 //$contact["last_contact"] = DateTimeFormat::utcNow();
422 $contact = array_merge($contact, $noscrape);
424 GContact::update($contact);
426 if (!empty($noscrape["updated"])) {
427 $fields = ['last_contact' => DateTimeFormat::utcNow()];
428 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
430 Logger::log("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", Logger::DEBUG);
432 return $noscrape["updated"];
439 // If we only can poll the feed, then we only do this once a while
440 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
441 Logger::log("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", Logger::DEBUG);
443 GContact::update($contact);
444 return $gcontacts[0]["updated"];
447 $data = Probe::uri($profile);
449 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
450 // Then check the other link and delete this one
451 if (($data["network"] == Protocol::OSTATUS) && self::alternateOStatusUrl($profile)
452 && (normalise_link($profile) == normalise_link($data["alias"]))
453 && (normalise_link($profile) != normalise_link($data["url"]))
455 // Delete the old entry
456 DBA::delete('gcontact', ['nurl' => normalise_link($profile)]);
458 $gcontact = array_merge($gcontacts[0], $data);
460 $gcontact["server_url"] = $data["baseurl"];
463 $gcontact = GContact::sanitize($gcontact);
464 GContact::update($gcontact);
466 self::lastUpdated($data["url"], $force);
467 } catch (Exception $e) {
468 Logger::log($e->getMessage(), Logger::DEBUG);
471 Logger::log("Profile ".$profile." was deleted", Logger::DEBUG);
475 if (($data["poll"] == "") || (in_array($data["network"], [Protocol::FEED, Protocol::PHANTOM]))) {
476 $fields = ['last_failure' => DateTimeFormat::utcNow()];
477 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
479 Logger::log("Profile ".$profile." wasn't reachable (profile)", Logger::DEBUG);
483 $contact = array_merge($contact, $data);
485 $contact["server_url"] = $data["baseurl"];
487 GContact::update($contact);
489 $curlResult = Network::curl($data["poll"]);
491 if (!$curlResult->isSuccess()) {
492 $fields = ['last_failure' => DateTimeFormat::utcNow()];
493 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
495 Logger::log("Profile ".$profile." wasn't reachable (no feed)", Logger::DEBUG);
499 $doc = new DOMDocument();
500 /// @TODO Avoid error supression here
501 @$doc->loadXML($curlResult->getBody());
503 $xpath = new DOMXPath($doc);
504 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
506 $entries = $xpath->query('/atom:feed/atom:entry');
510 foreach ($entries as $entry) {
511 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
512 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
514 if ($last_updated < $published) {
515 $last_updated = $published;
518 if ($last_updated < $updated) {
519 $last_updated = $updated;
523 // Maybe there aren't any entries. Then check if it is a valid feed
524 if ($last_updated == "") {
525 if ($xpath->query('/atom:feed')->length > 0) {
526 $last_updated = DBA::NULL_DATETIME;
530 $fields = ['last_contact' => DateTimeFormat::utcNow()];
532 if (!empty($last_updated)) {
533 $fields['updated'] = $last_updated;
536 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
538 if (($gcontacts[0]["generation"] == 0)) {
539 $fields = ['generation' => 9];
540 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
543 Logger::log("Profile ".$profile." was last updated at ".$last_updated, Logger::DEBUG);
545 return $last_updated;
548 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
550 $now = strtotime(DateTimeFormat::utcNow());
552 if ($updated > $last_contact) {
553 $contact_time = strtotime($updated);
555 $contact_time = strtotime($last_contact);
558 $failure_time = strtotime($last_failure);
559 $created_time = strtotime($created);
561 // If there is no "created" time then use the current time
562 if ($created_time <= 0) {
563 $created_time = $now;
566 // If the last contact was less than 24 hours then don't update
567 if (($now - $contact_time) < (60 * 60 * 24)) {
571 // If the last failure was less than 24 hours then don't update
572 if (($now - $failure_time) < (60 * 60 * 24)) {
576 // If the last contact was less than a week ago and the last failure is older than a week then don't update
577 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
580 // 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
581 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
585 // 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
586 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
593 /// @TODO Maybe move this out to an utilities class?
594 private static function toBoolean($val)
596 if (($val == "true") || ($val == 1)) {
598 } elseif (($val == "false") || ($val == 0)) {
606 * @brief Detect server type (Hubzilla or Friendica) via the poco data
608 * @param array $data POCO data
609 * @return array Server data
611 private static function detectPocoData(array $data)
615 if (!isset($data['entry'])) {
619 if (count($data['entry']) == 0) {
623 if (!isset($data['entry'][0]['urls'])) {
627 if (count($data['entry'][0]['urls']) == 0) {
631 foreach ($data['entry'][0]['urls'] as $url) {
632 if ($url['type'] == 'zot') {
634 $server["platform"] = 'Hubzilla';
635 $server["network"] = Protocol::DIASPORA;
643 * @brief Detect server type by using the nodeinfo data
645 * @param string $server_url address of the server
646 * @return array Server data
648 private static function fetchNodeinfo($server_url)
650 $curlResult = Network::curl($server_url."/.well-known/nodeinfo");
651 if (!$curlResult->isSuccess()) {
655 $nodeinfo = json_decode($curlResult->getBody(), true);
657 if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
664 foreach ($nodeinfo['links'] as $link) {
665 if (!is_array($link) || empty($link['rel'])) {
666 Logger::log('Invalid nodeinfo format for ' . $server_url, Logger::DEBUG);
669 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
670 $nodeinfo1_url = $link['href'];
671 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
672 $nodeinfo2_url = $link['href'];
676 if ($nodeinfo1_url . $nodeinfo2_url == '') {
682 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
683 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
684 $server = self::parseNodeinfo2($nodeinfo2_url);
687 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
688 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
689 $server = self::parseNodeinfo1($nodeinfo1_url);
696 * @brief Parses Nodeinfo 1
698 * @param string $nodeinfo_url address of the nodeinfo path
699 * @return array Server data
701 private static function parseNodeinfo1($nodeinfo_url)
703 $curlResult = Network::curl($nodeinfo_url);
705 if (!$curlResult->isSuccess()) {
709 $nodeinfo = json_decode($curlResult->getBody(), true);
711 if (!is_array($nodeinfo)) {
717 $server['register_policy'] = REGISTER_CLOSED;
719 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
720 $server['register_policy'] = REGISTER_OPEN;
723 if (is_array($nodeinfo['software'])) {
724 if (isset($nodeinfo['software']['name'])) {
725 $server['platform'] = $nodeinfo['software']['name'];
728 if (isset($nodeinfo['software']['version'])) {
729 $server['version'] = $nodeinfo['software']['version'];
730 // Version numbers on Nodeinfo are presented with additional info, e.g.:
731 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
732 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
736 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
737 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
740 if (!empty($nodeinfo['usage']['users']['total'])) {
741 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
748 if (is_array($nodeinfo['protocols']['inbound'])) {
749 foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
750 if ($inbound == 'diaspora') {
753 if ($inbound == 'friendica') {
756 if ($inbound == 'gnusocial') {
763 $server['network'] = Protocol::OSTATUS;
766 $server['network'] = Protocol::DIASPORA;
769 $server['network'] = Protocol::DFRN;
780 * @brief Parses Nodeinfo 2
782 * @param string $nodeinfo_url address of the nodeinfo path
783 * @return array Server data
785 private static function parseNodeinfo2($nodeinfo_url)
787 $curlResult = Network::curl($nodeinfo_url);
788 if (!$curlResult->isSuccess()) {
792 $nodeinfo = json_decode($curlResult->getBody(), true);
794 if (!is_array($nodeinfo)) {
800 $server['register_policy'] = REGISTER_CLOSED;
802 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
803 $server['register_policy'] = REGISTER_OPEN;
806 if (is_array($nodeinfo['software'])) {
807 if (isset($nodeinfo['software']['name'])) {
808 $server['platform'] = $nodeinfo['software']['name'];
811 if (isset($nodeinfo['software']['version'])) {
812 $server['version'] = $nodeinfo['software']['version'];
813 // Version numbers on Nodeinfo are presented with additional info, e.g.:
814 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
815 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
819 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
820 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
823 if (!empty($nodeinfo['usage']['users']['total'])) {
824 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
831 if (!empty($nodeinfo['protocols'])) {
832 foreach ($nodeinfo['protocols'] as $protocol) {
833 if ($protocol == 'diaspora') {
835 } elseif ($protocol == 'friendica') {
837 } elseif ($protocol == 'gnusocial') {
844 $server['network'] = Protocol::OSTATUS;
845 } elseif ($diaspora) {
846 $server['network'] = Protocol::DIASPORA;
847 } elseif ($friendica) {
848 $server['network'] = Protocol::DFRN;
851 if (empty($server)) {
859 * @brief Detect server type (Hubzilla or Friendica) via the front page body
861 * @param string $body Front page of the server
862 * @return array Server data
864 private static function detectServerType($body)
868 $doc = new DOMDocument();
869 /// @TODO Acoid supressing error
870 @$doc->loadHTML($body);
871 $xpath = new DOMXPath($doc);
873 $list = $xpath->query("//meta[@name]");
875 foreach ($list as $node) {
877 if ($node->attributes->length) {
878 foreach ($node->attributes as $attribute) {
879 $attr[$attribute->name] = $attribute->value;
882 if ($attr['name'] == 'generator') {
883 $version_part = explode(" ", $attr['content']);
884 if (count($version_part) == 2) {
885 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
887 $server["platform"] = $version_part[0];
888 $server["version"] = $version_part[1];
889 $server["network"] = Protocol::DFRN;
896 $list = $xpath->query("//meta[@property]");
898 foreach ($list as $node) {
900 if ($node->attributes->length) {
901 foreach ($node->attributes as $attribute) {
902 $attr[$attribute->name] = $attribute->value;
905 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
907 $server["platform"] = $attr['content'];
908 $server["version"] = "";
909 $server["network"] = Protocol::DIASPORA;
918 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
923 public static function checkServer($server_url, $network = "", $force = false)
925 // Unify the server address
926 $server_url = trim($server_url, "/");
927 $server_url = str_replace("/index.php", "", $server_url);
929 if ($server_url == "") {
933 $gserver = DBA::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
934 if (DBA::isResult($gserver)) {
935 if ($gserver["created"] <= DBA::NULL_DATETIME) {
936 $fields = ['created' => DateTimeFormat::utcNow()];
937 $condition = ['nurl' => normalise_link($server_url)];
938 DBA::update('gserver', $fields, $condition);
940 $poco = $gserver["poco"];
941 $noscrape = $gserver["noscrape"];
943 if ($network == "") {
944 $network = $gserver["network"];
947 $last_contact = $gserver["last_contact"];
948 $last_failure = $gserver["last_failure"];
949 $version = $gserver["version"];
950 $platform = $gserver["platform"];
951 $site_name = $gserver["site_name"];
952 $info = $gserver["info"];
953 $register_policy = $gserver["register_policy"];
954 $registered_users = $gserver["registered-users"];
956 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
957 // It can happen that a zero date is in the database, but storing it again is forbidden.
958 if ($last_contact < DBA::NULL_DATETIME) {
959 $last_contact = DBA::NULL_DATETIME;
962 if ($last_failure < DBA::NULL_DATETIME) {
963 $last_failure = DBA::NULL_DATETIME;
966 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
967 Logger::log("Use cached data for server ".$server_url, Logger::DEBUG);
968 return ($last_contact >= $last_failure);
977 $register_policy = -1;
978 $registered_users = 0;
980 $last_contact = DBA::NULL_DATETIME;
981 $last_failure = DBA::NULL_DATETIME;
983 Logger::log("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, Logger::DEBUG);
986 $possible_failure = false;
987 $orig_last_failure = $last_failure;
988 $orig_last_contact = $last_contact;
990 // Mastodon uses the "@" for user profiles.
991 // But this can be misunderstood.
992 if (parse_url($server_url, PHP_URL_USER) != '') {
993 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
997 // Check if the page is accessible via SSL.
998 $orig_server_url = $server_url;
999 $server_url = str_replace("http://", "https://", $server_url);
1001 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1002 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1004 // Quit if there is a timeout.
1005 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1006 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1007 ($curlResult->isTimeout())) {
1008 Logger::log("Connection to server ".$server_url." timed out.", Logger::DEBUG);
1009 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1013 // Maybe the page is unencrypted only?
1014 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1015 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1016 $server_url = str_replace("https://", "http://", $server_url);
1018 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1019 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1021 // Quit if there is a timeout
1022 if ($curlResult->isTimeout()) {
1023 Logger::log("Connection to server " . $server_url . " timed out.", Logger::DEBUG);
1024 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1028 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1031 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1032 // Workaround for bad configured servers (known nginx problem)
1033 if (!empty($curlResult->getInfo()) && !in_array($curlResult->getInfo()["http_code"], ["403", "404"])) {
1037 $possible_failure = true;
1040 // If the server has no possible failure we reset the cached data
1041 if (!$possible_failure) {
1046 $register_policy = -1;
1050 // This will be too low, but better than no value at all.
1051 $registered_users = DBA::count('gcontact', ['server_url' => normalise_link($server_url)]);
1056 $curlResult = Network::curl($server_url."/poco");
1058 if ($curlResult->isSuccess()) {
1059 $data = json_decode($curlResult->getBody(), true);
1061 if (isset($data['totalResults'])) {
1062 $registered_users = $data['totalResults'];
1063 $poco = $server_url . "/poco";
1064 $server = self::detectPocoData($data);
1066 if (!empty($server)) {
1067 $platform = $server['platform'];
1068 $network = $server['network'];
1075 * There are servers out there who don't return 404 on a failure
1076 * We have to be sure that don't misunderstand this
1078 if (is_null($data)) {
1087 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1088 $curlResult = Network::curl($server_url);
1090 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "")) {
1093 $server = self::detectServerType($curlResult->getBody());
1095 if (!empty($server)) {
1096 $platform = $server['platform'];
1097 $network = $server['network'];
1098 $version = $server['version'];
1099 $site_name = $server['site_name'];
1102 $lines = explode("\n", $curlResult->getHeader());
1104 if (count($lines)) {
1105 foreach ($lines as $line) {
1106 $line = trim($line);
1108 if (stristr($line, 'X-Diaspora-Version:')) {
1109 $platform = "Diaspora";
1110 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1111 $version = trim(str_replace("x-diaspora-version:", "", $version));
1112 $network = Protocol::DIASPORA;
1113 $versionparts = explode("-", $version);
1114 $version = $versionparts[0];
1117 if (stristr($line, 'Server: Mastodon')) {
1118 $platform = "Mastodon";
1119 $network = Protocol::OSTATUS;
1126 if (!$failure && ($poco == "")) {
1127 // Test for Statusnet
1128 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1129 // The "not implemented" is a special treatment for really, really old Friendica versions
1130 $curlResult = Network::curl($server_url."/api/statusnet/version.json");
1132 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1133 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1134 $platform = "StatusNet";
1135 // Remove junk that some GNU Social servers return
1136 $version = str_replace(chr(239).chr(187).chr(191), "", $curlResult->getBody());
1137 $version = trim($version, '"');
1138 $network = Protocol::OSTATUS;
1141 // Test for GNU Social
1142 $curlResult = Network::curl($server_url."/api/gnusocial/version.json");
1144 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1145 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1146 $platform = "GNU Social";
1147 // Remove junk that some GNU Social servers return
1148 $version = str_replace(chr(239) . chr(187) . chr(191), "", $curlResult->getBody());
1149 $version = trim($version, '"');
1150 $network = Protocol::OSTATUS;
1153 // Test for Mastodon
1154 $orig_version = $version;
1155 $curlResult = Network::curl($server_url . "/api/v1/instance");
1157 if ($curlResult->isSuccess() && ($curlResult->getBody() != '')) {
1158 $data = json_decode($curlResult->getBody(), true);
1160 if (isset($data['version'])) {
1161 $platform = "Mastodon";
1162 $version = defaults($data, 'version', '');
1163 $site_name = defaults($data, 'title', '');
1164 $info = defaults($data, 'description', '');
1165 $network = Protocol::OSTATUS;
1168 if (!empty($data['stats']['user_count'])) {
1169 $registered_users = $data['stats']['user_count'];
1173 if (strstr($orig_version . $version, 'Pleroma')) {
1174 $platform = 'Pleroma';
1175 $version = trim(str_replace('Pleroma', '', $version));
1180 // Test for Hubzilla and Red
1181 $curlResult = Network::curl($server_url . "/siteinfo.json");
1183 if ($curlResult->isSuccess()) {
1184 $data = json_decode($curlResult->getBody(), true);
1186 if (isset($data['url'])) {
1187 $platform = $data['platform'];
1188 $version = $data['version'];
1189 $network = Protocol::DIASPORA;
1192 if (!empty($data['site_name'])) {
1193 $site_name = $data['site_name'];
1196 if (!empty($data['channels_total'])) {
1197 $registered_users = $data['channels_total'];
1200 if (!empty($data['register_policy'])) {
1201 switch ($data['register_policy']) {
1202 case "REGISTER_OPEN":
1203 $register_policy = REGISTER_OPEN;
1206 case "REGISTER_APPROVE":
1207 $register_policy = REGISTER_APPROVE;
1210 case "REGISTER_CLOSED":
1212 $register_policy = REGISTER_CLOSED;
1217 // Test for Hubzilla, Redmatrix or Friendica
1218 $curlResult = Network::curl($server_url."/api/statusnet/config.json");
1220 if ($curlResult->isSuccess()) {
1221 $data = json_decode($curlResult->getBody(), true);
1223 if (isset($data['site']['server'])) {
1224 if (isset($data['site']['platform'])) {
1225 $platform = $data['site']['platform']['PLATFORM_NAME'];
1226 $version = $data['site']['platform']['STD_VERSION'];
1227 $network = Protocol::DIASPORA;
1230 if (isset($data['site']['BlaBlaNet'])) {
1231 $platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
1232 $version = $data['site']['BlaBlaNet']['STD_VERSION'];
1233 $network = Protocol::DIASPORA;
1236 if (isset($data['site']['hubzilla'])) {
1237 $platform = $data['site']['hubzilla']['PLATFORM_NAME'];
1238 $version = $data['site']['hubzilla']['RED_VERSION'];
1239 $network = Protocol::DIASPORA;
1242 if (isset($data['site']['redmatrix'])) {
1243 if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
1244 $platform = $data['site']['redmatrix']['PLATFORM_NAME'];
1245 } elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
1246 $platform = $data['site']['redmatrix']['RED_PLATFORM'];
1249 $version = $data['site']['redmatrix']['RED_VERSION'];
1250 $network = Protocol::DIASPORA;
1253 if (isset($data['site']['friendica'])) {
1254 $platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
1255 $version = $data['site']['friendica']['FRIENDICA_VERSION'];
1256 $network = Protocol::DFRN;
1259 $site_name = $data['site']['name'];
1262 $inviteonly = false;
1265 if (!empty($data['site']['closed'])) {
1266 $closed = self::toBoolean($data['site']['closed']);
1269 if (!empty($data['site']['private'])) {
1270 $private = self::toBoolean($data['site']['private']);
1273 if (!empty($data['site']['inviteonly'])) {
1274 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1277 if (!$closed && !$private and $inviteonly) {
1278 $register_policy = REGISTER_APPROVE;
1279 } elseif (!$closed && !$private) {
1280 $register_policy = REGISTER_OPEN;
1282 $register_policy = REGISTER_CLOSED;
1289 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1291 $curlResult = Network::curl($server_url . "/statistics.json");
1293 if ($curlResult->isSuccess()) {
1294 $data = json_decode($curlResult->getBody(), true);
1296 if (isset($data['version'])) {
1297 $version = $data['version'];
1298 // Version numbers on statistics.json are presented with additional info, e.g.:
1299 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1300 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1303 if (!empty($data['name'])) {
1304 $site_name = $data['name'];
1307 if (!empty($data['network'])) {
1308 $platform = $data['network'];
1311 if ($platform == "Diaspora") {
1312 $network = Protocol::DIASPORA;
1315 if (!empty($data['registrations_open']) && $data['registrations_open']) {
1316 $register_policy = REGISTER_OPEN;
1318 $register_policy = REGISTER_CLOSED;
1323 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1325 $server = self::fetchNodeinfo($server_url);
1327 if (!empty($server)) {
1328 $register_policy = $server['register_policy'];
1330 if (isset($server['platform'])) {
1331 $platform = $server['platform'];
1334 if (isset($server['network'])) {
1335 $network = $server['network'];
1338 if (isset($server['version'])) {
1339 $version = $server['version'];
1342 if (isset($server['site_name'])) {
1343 $site_name = $server['site_name'];
1346 if (isset($server['registered-users'])) {
1347 $registered_users = $server['registered-users'];
1352 // Check for noscrape
1353 // Friendica servers could be detected as OStatus servers
1354 if (!$failure && in_array($network, [Protocol::DFRN, Protocol::OSTATUS])) {
1355 $curlResult = Network::curl($server_url . "/friendica/json");
1357 if (!$curlResult->isSuccess()) {
1358 $curlResult = Network::curl($server_url . "/friendika/json");
1361 if ($curlResult->isSuccess()) {
1362 $data = json_decode($curlResult->getBody(), true);
1364 if (isset($data['version'])) {
1365 $network = Protocol::DFRN;
1367 if (!empty($data['no_scrape_url'])) {
1368 $noscrape = $data['no_scrape_url'];
1371 $version = $data['version'];
1373 if (!empty($data['site_name'])) {
1374 $site_name = $data['site_name'];
1377 $info = $data['info'];
1378 if (in_array($data['register_policy'], ['REGISTER_CLOSED', 'REGISTER_APPROVE', 'REGISTER_OPEN'])) {
1379 $register_policy = constant($data['register_policy']);
1381 Logger::log("Register policy '{$data['register_policy']}' from $server_url is invalid.");
1382 $register_policy = REGISTER_CLOSED; // set a default value
1384 $platform = $data['platform'];
1389 // Every server has got at least an admin account
1390 if (!$failure && ($registered_users == 0)) {
1391 $registered_users = 1;
1394 if ($possible_failure && !$failure) {
1399 $last_contact = $orig_last_contact;
1400 $last_failure = DateTimeFormat::utcNow();
1402 $last_contact = DateTimeFormat::utcNow();
1403 $last_failure = $orig_last_failure;
1406 if (($last_contact <= $last_failure) && !$failure) {
1407 Logger::log("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", Logger::DEBUG);
1408 } elseif (($last_contact >= $last_failure) && $failure) {
1409 Logger::log("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", Logger::DEBUG);
1412 // Check again if the server exists
1413 $found = DBA::exists('gserver', ['nurl' => normalise_link($server_url)]);
1415 $version = strip_tags($version);
1416 $site_name = strip_tags($site_name);
1417 $info = strip_tags($info);
1418 $platform = strip_tags($platform);
1420 $fields = ['url' => $server_url, 'version' => $version,
1421 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1422 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1423 'platform' => $platform, 'registered-users' => $registered_users,
1424 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1427 DBA::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1428 } elseif (!$failure) {
1429 $fields['nurl'] = normalise_link($server_url);
1430 $fields['created'] = DateTimeFormat::utcNow();
1431 DBA::insert('gserver', $fields);
1434 if (!$failure && in_array($fields['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1435 self::discoverRelay($server_url);
1438 Logger::log("End discovery for server " . $server_url, Logger::DEBUG);
1444 * @brief Fetch relay data from a given server url
1446 * @param string $server_url address of the server
1448 private static function discoverRelay($server_url)
1450 Logger::log("Discover relay data for server " . $server_url, Logger::DEBUG);
1452 $curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
1454 if (!$curlResult->isSuccess()) {
1458 $data = json_decode($curlResult->getBody(), true);
1460 if (!is_array($data)) {
1464 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1466 if (!DBA::isResult($gserver)) {
1470 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
1471 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
1472 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1475 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1477 if ($data['scope'] == 'tags') {
1480 foreach ($data['tags'] as $tag) {
1481 $tag = mb_strtolower($tag);
1482 if (strlen($tag) < 100) {
1487 foreach ($tags as $tag) {
1488 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1492 // Create or update the relay contact
1494 if (isset($data['protocols'])) {
1495 if (isset($data['protocols']['diaspora'])) {
1496 $fields['network'] = Protocol::DIASPORA;
1498 if (isset($data['protocols']['diaspora']['receive'])) {
1499 $fields['batch'] = $data['protocols']['diaspora']['receive'];
1500 } elseif (is_string($data['protocols']['diaspora'])) {
1501 $fields['batch'] = $data['protocols']['diaspora'];
1505 if (isset($data['protocols']['dfrn'])) {
1506 $fields['network'] = Protocol::DFRN;
1508 if (isset($data['protocols']['dfrn']['receive'])) {
1509 $fields['batch'] = $data['protocols']['dfrn']['receive'];
1510 } elseif (is_string($data['protocols']['dfrn'])) {
1511 $fields['batch'] = $data['protocols']['dfrn'];
1515 Diaspora::setRelayContact($server_url, $fields);
1519 * @brief Returns a list of all known servers
1520 * @return array List of server urls
1522 public static function serverlist()
1525 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1526 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1527 ORDER BY `last_contact`
1529 DBA::escape(Protocol::DFRN),
1530 DBA::escape(Protocol::DIASPORA),
1531 DBA::escape(Protocol::OSTATUS)
1534 if (!DBA::isResult($r)) {
1542 * @brief Fetch server list from remote servers and adds them when they are new.
1544 * @param string $poco URL to the POCO endpoint
1546 private static function fetchServerlist($poco)
1548 $curlResult = Network::curl($poco . "/@server");
1550 if (!$curlResult->isSuccess()) {
1554 $serverlist = json_decode($curlResult->getBody(), true);
1556 if (!is_array($serverlist)) {
1560 foreach ($serverlist as $server) {
1561 $server_url = str_replace("/index.php", "", $server['url']);
1563 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(normalise_link($server_url)));
1565 if (!DBA::isResult($r)) {
1566 Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
1567 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1572 private static function discoverFederation()
1574 $last = Config::get('poco', 'last_federation_discovery');
1577 $next = $last + (24 * 60 * 60);
1579 if ($next > time()) {
1584 // Discover Friendica, Hubzilla and Diaspora servers
1585 $curlResult = Network::fetchUrl("http://the-federation.info/pods.json");
1587 if (!empty($curlResult)) {
1588 $servers = json_decode($curlResult, true);
1590 if (!empty($servers['pods'])) {
1591 foreach ($servers['pods'] as $server) {
1592 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://" . $server['host']);
1597 // Disvover Mastodon servers
1598 if (!Config::get('system', 'ostatus_disabled')) {
1599 $accesstoken = Config::get('system', 'instances_social_key');
1601 if (!empty($accesstoken)) {
1602 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1603 $header = ['Authorization: Bearer '.$accesstoken];
1604 $curlResult = Network::curl($api, false, $redirects, ['headers' => $header]);
1606 if ($curlResult->isSuccess()) {
1607 $servers = json_decode($curlResult->getBody(), true);
1609 foreach ($servers['instances'] as $server) {
1610 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1611 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1617 // Currently disabled, since the service isn't available anymore.
1618 // It is not removed since I hope that there will be a successor.
1619 // Discover GNU Social Servers.
1620 //if (!Config::get('system','ostatus_disabled')) {
1621 // $serverdata = "http://gstools.org/api/get_open_instances/";
1623 // $curlResult = Network::curl($serverdata);
1624 // if ($curlResult->isSuccess()) {
1625 // $servers = json_decode($result->getBody(), true);
1627 // foreach($servers['data'] as $server)
1628 // self::checkServer($server['instance_address']);
1632 Config::set('poco', 'last_federation_discovery', time());
1635 public static function discoverSingleServer($id)
1637 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1639 if (!DBA::isResult($r)) {
1645 // Discover new servers out there (Works from Friendica version 3.5.2)
1646 self::fetchServerlist($server["poco"]);
1648 // Fetch all users from the other server
1649 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1651 Logger::log("Fetch all users from the server " . $server["url"], Logger::DEBUG);
1653 $curlResult = Network::curl($url);
1655 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1656 $data = json_decode($curlResult->getBody(), true);
1658 if (!empty($data)) {
1659 self::discoverServer($data, 2);
1662 if (Config::get('system', 'poco_discovery') > 1) {
1663 $timeframe = Config::get('system', 'poco_discovery_since');
1665 if ($timeframe == 0) {
1669 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1671 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1672 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1676 $curlResult = Network::curl($url);
1678 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1679 Logger::log("Fetch all global contacts from the server " . $server["nurl"], Logger::DEBUG);
1680 $data = json_decode($curlResult->getBody(), true);
1682 if (!empty($data)) {
1683 $success = self::discoverServer($data);
1687 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1688 Logger::log("Fetch contacts from users of the server " . $server["nurl"], Logger::DEBUG);
1689 self::discoverServerUsers($data, $server);
1693 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1694 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1698 // If the server hadn't replied correctly, then force a sanity check
1699 self::checkServer($server["url"], $server["network"], true);
1701 // If we couldn't reach the server, we will try it some time later
1702 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1703 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1709 public static function discover($complete = false)
1711 // Update the server list
1712 self::discoverFederation();
1716 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1718 if ($requery_days == 0) {
1722 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1724 $gservers = q("SELECT `id`, `url`, `nurl`, `network`
1726 WHERE `last_contact` >= `last_failure`
1728 AND `last_poco_query` < '%s'
1729 ORDER BY RAND()", DBA::escape($last_update)
1732 if (DBA::isResult($gservers)) {
1733 foreach ($gservers as $gserver) {
1734 if (!self::checkServer($gserver['url'], $gserver['network'])) {
1735 // The server is not reachable? Okay, then we will try it later
1736 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1737 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1741 Logger::log('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], Logger::DEBUG);
1742 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
1744 if (!$complete && ( --$no_of_queries == 0)) {
1751 private static function discoverServerUsers(array $data, array $server)
1753 if (!isset($data['entry'])) {
1757 foreach ($data['entry'] as $entry) {
1760 if (isset($entry['urls'])) {
1761 foreach ($entry['urls'] as $url) {
1762 if ($url['type'] == 'profile') {
1763 $profile_url = $url['value'];
1764 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1765 $username = end($path_array);
1770 if ($username != '') {
1771 Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
1773 // Fetch all contacts from a given user from the other server
1774 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1776 $curlResult = Network::curl($url);
1778 if ($curlResult->isSuccess()) {
1779 $data = json_decode($curlResult["body"], true);
1781 if (!empty($data)) {
1782 self::discoverServer($data, 3);
1789 private static function discoverServer(array $data, $default_generation = 0)
1791 if (empty($data['entry'])) {
1797 foreach ($data['entry'] as $entry) {
1799 $profile_photo = '';
1803 $updated = DBA::NULL_DATETIME;
1809 $generation = $default_generation;
1811 if (!empty($entry['displayName'])) {
1812 $name = $entry['displayName'];
1815 if (isset($entry['urls'])) {
1816 foreach ($entry['urls'] as $url) {
1817 if ($url['type'] == 'profile') {
1818 $profile_url = $url['value'];
1821 if ($url['type'] == 'webfinger') {
1822 $connect_url = str_replace('acct:' , '', $url['value']);
1828 if (isset($entry['photos'])) {
1829 foreach ($entry['photos'] as $photo) {
1830 if ($photo['type'] == 'profile') {
1831 $profile_photo = $photo['value'];
1837 if (isset($entry['updated'])) {
1838 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
1841 if (isset($entry['network'])) {
1842 $network = $entry['network'];
1845 if (isset($entry['currentLocation'])) {
1846 $location = $entry['currentLocation'];
1849 if (isset($entry['aboutMe'])) {
1850 $about = HTML::toBBCode($entry['aboutMe']);
1853 if (isset($entry['gender'])) {
1854 $gender = $entry['gender'];
1857 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
1858 $generation = ++$entry['generation'];
1861 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
1862 $contact_type = $entry['contactType'];
1865 if (isset($entry['tags'])) {
1866 foreach ($entry['tags'] as $tag) {
1867 $keywords = implode(", ", $tag);
1871 if ($generation > 0) {
1874 Logger::log("Store profile ".$profile_url, Logger::DEBUG);
1876 $gcontact = ["url" => $profile_url,
1878 "network" => $network,
1879 "photo" => $profile_photo,
1881 "location" => $location,
1882 "gender" => $gender,
1883 "keywords" => $keywords,
1884 "connect" => $connect_url,
1885 "updated" => $updated,
1886 "contact-type" => $contact_type,
1887 "generation" => $generation];
1890 $gcontact = GContact::sanitize($gcontact);
1891 GContact::update($gcontact);
1892 } catch (Exception $e) {
1893 Logger::log($e->getMessage(), Logger::DEBUG);
1896 Logger::log("Done for profile ".$profile_url, Logger::DEBUG);