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\Protocol;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Profile;
22 use Friendica\Network\Probe;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use Friendica\Util\XML;
27 require_once 'include/dba.php';
32 * @brief Fetch POCO data
34 * @param integer $cid Contact ID
35 * @param integer $uid User ID
36 * @param integer $zcid Global Contact ID
37 * @param integer $url POCO address that should be polled
39 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
40 * and add the entries to the gcontact (Global Contact) table, or update existing entries
41 * if anything (name or photo) has changed.
42 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
44 * Once the global contact is stored add (if necessary) the contact linkage which associates
45 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
46 * pointing to the same global contact id.
49 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
51 // Call the function "load" via the worker
52 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
56 * @brief Fetch POCO data from the worker
58 * @param integer $cid Contact ID
59 * @param integer $uid User ID
60 * @param integer $zcid Global Contact ID
61 * @param integer $url POCO address that should be polled
64 public static function load($cid, $uid, $zcid, $url)
70 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
71 if (DBA::isResult($contact)) {
72 $url = $contact['poco'];
73 $uid = $contact['uid'];
85 $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') ;
87 logger('load: ' . $url, LOGGER_DEBUG);
89 $fetchresult = Network::fetchUrlFull($url);
90 $s = $fetchresult->getBody();
92 logger('load: returns ' . $s, LOGGER_DATA);
94 logger('load: return code: ' . $fetchresult->getReturnCode(), LOGGER_DEBUG);
96 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
100 $j = json_decode($s, true);
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 if (!empty($entry['displayName'])) {
125 $name = $entry['displayName'];
128 if (isset($entry['urls'])) {
129 foreach ($entry['urls'] as $url) {
130 if ($url['type'] == 'profile') {
131 $profile_url = $url['value'];
134 if ($url['type'] == 'webfinger') {
135 $connect_url = str_replace('acct:', '', $url['value']);
140 if (isset($entry['photos'])) {
141 foreach ($entry['photos'] as $photo) {
142 if ($photo['type'] == 'profile') {
143 $profile_photo = $photo['value'];
149 if (isset($entry['updated'])) {
150 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
153 if (isset($entry['network'])) {
154 $network = $entry['network'];
157 if (isset($entry['currentLocation'])) {
158 $location = $entry['currentLocation'];
161 if (isset($entry['aboutMe'])) {
162 $about = HTML::toBBCode($entry['aboutMe']);
165 if (isset($entry['gender'])) {
166 $gender = $entry['gender'];
169 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
170 $generation = ++$entry['generation'];
173 if (isset($entry['tags'])) {
174 foreach ($entry['tags'] as $tag) {
175 $keywords = implode(", ", $tag);
179 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
180 $contact_type = $entry['contactType'];
183 $gcontact = ["url" => $profile_url,
185 "network" => $network,
186 "photo" => $profile_photo,
188 "location" => $location,
190 "keywords" => $keywords,
191 "connect" => $connect_url,
192 "updated" => $updated,
193 "contact-type" => $contact_type,
194 "generation" => $generation];
197 $gcontact = GContact::sanitize($gcontact);
198 $gcid = GContact::update($gcontact);
200 GContact::link($gcid, $uid, $cid, $zcid);
201 } catch (Exception $e) {
202 logger($e->getMessage(), LOGGER_DEBUG);
205 logger("load: loaded $total entries", LOGGER_DEBUG);
207 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
208 DBA::delete('glink', $condition);
211 public static function reachable($profile, $server = "", $network = "", $force = false)
214 $server = self::detectServer($profile);
221 return self::checkServer($server, $network, $force);
224 public static function detectServer($profile)
226 // Try to detect the server path based upon some known standard paths
229 if ($server_url == "") {
230 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
231 if ($friendica != $profile) {
232 $server_url = $friendica;
233 $network = Protocol::DFRN;
237 if ($server_url == "") {
238 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
239 if ($diaspora != $profile) {
240 $server_url = $diaspora;
241 $network = Protocol::DIASPORA;
245 if ($server_url == "") {
246 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
247 if ($red != $profile) {
249 $network = Protocol::DIASPORA;
254 if ($server_url == "") {
255 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
256 if ($mastodon != $profile) {
257 $server_url = $mastodon;
258 $network = Protocol::OSTATUS;
262 // Numeric OStatus variant
263 if ($server_url == "") {
264 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
265 if ($ostatus != $profile) {
266 $server_url = $ostatus;
267 $network = Protocol::OSTATUS;
272 if ($server_url == "") {
273 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
274 if ($base != $profile) {
276 $network = Protocol::PHANTOM;
280 if ($server_url == "") {
285 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
286 DBA::escape(normalise_link($server_url))
289 if (DBA::isResult($r)) {
293 // Fetch the host-meta to check if this really is a server
294 $curlResult = Network::curl($server_url."/.well-known/host-meta");
295 if (!$curlResult->isSuccess()) {
302 public static function alternateOStatusUrl($url)
304 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
307 public static function lastUpdated($profile, $force = false)
310 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
311 DBA::escape(normalise_link($profile))
314 if (!DBA::isResult($gcontacts)) {
318 $contact = ["url" => $profile];
320 if ($gcontacts[0]["created"] <= NULL_DATE) {
321 $contact['created'] = DateTimeFormat::utcNow();
326 $server_url = normalise_link(self::detectServer($profile));
329 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
330 $server_url = $gcontacts[0]["server_url"];
333 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
334 $server_url = normalise_link(self::detectServer($profile));
337 if (!in_array($gcontacts[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
338 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
342 if ($server_url != "") {
343 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
345 $fields = ['last_failure' => DateTimeFormat::utcNow()];
346 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
349 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
352 $contact['server_url'] = $server_url;
355 if (in_array($gcontacts[0]["network"], ["", Protocol::FEED])) {
357 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
358 DBA::escape(normalise_link($server_url))
362 $contact['network'] = $server[0]["network"];
368 // noscrape is really fast so we don't cache the call.
369 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
370 // Use noscrape if possible
371 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(normalise_link($server_url)));
374 $curlResult = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
376 if ($curlResult->isSuccess() && ($curlResult->getBody() != "")) {
377 $noscrape = json_decode($curlResult->getBody(), true);
379 if (is_array($noscrape)) {
380 $contact["network"] = $server[0]["network"];
382 if (isset($noscrape["fn"])) {
383 $contact["name"] = $noscrape["fn"];
385 if (isset($noscrape["comm"])) {
386 $contact["community"] = $noscrape["comm"];
388 if (isset($noscrape["tags"])) {
389 $keywords = implode(" ", $noscrape["tags"]);
390 if ($keywords != "") {
391 $contact["keywords"] = $keywords;
395 $location = Profile::formatLocation($noscrape);
397 $contact["location"] = $location;
399 if (isset($noscrape["dfrn-notify"])) {
400 $contact["notify"] = $noscrape["dfrn-notify"];
402 // Remove all fields that are not present in the gcontact table
403 unset($noscrape["fn"]);
404 unset($noscrape["key"]);
405 unset($noscrape["homepage"]);
406 unset($noscrape["comm"]);
407 unset($noscrape["tags"]);
408 unset($noscrape["locality"]);
409 unset($noscrape["region"]);
410 unset($noscrape["country-name"]);
411 unset($noscrape["contacts"]);
412 unset($noscrape["dfrn-request"]);
413 unset($noscrape["dfrn-confirm"]);
414 unset($noscrape["dfrn-notify"]);
415 unset($noscrape["dfrn-poll"]);
417 // Set the date of the last contact
418 /// @todo By now the function "update_gcontact" doesn't work with this field
419 //$contact["last_contact"] = DateTimeFormat::utcNow();
421 $contact = array_merge($contact, $noscrape);
423 GContact::update($contact);
425 if (!empty($noscrape["updated"])) {
426 $fields = ['last_contact' => DateTimeFormat::utcNow()];
427 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
429 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
431 return $noscrape["updated"];
438 // If we only can poll the feed, then we only do this once a while
439 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
440 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
442 GContact::update($contact);
443 return $gcontacts[0]["updated"];
446 $data = Probe::uri($profile);
448 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
449 // Then check the other link and delete this one
450 if (($data["network"] == Protocol::OSTATUS) && self::alternateOStatusUrl($profile)
451 && (normalise_link($profile) == normalise_link($data["alias"]))
452 && (normalise_link($profile) != normalise_link($data["url"]))
454 // Delete the old entry
455 DBA::delete('gcontact', ['nurl' => normalise_link($profile)]);
457 $gcontact = array_merge($gcontacts[0], $data);
459 $gcontact["server_url"] = $data["baseurl"];
462 $gcontact = GContact::sanitize($gcontact);
463 GContact::update($gcontact);
465 self::lastUpdated($data["url"], $force);
466 } catch (Exception $e) {
467 logger($e->getMessage(), LOGGER_DEBUG);
470 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
474 if (($data["poll"] == "") || (in_array($data["network"], [Protocol::FEED, Protocol::PHANTOM]))) {
475 $fields = ['last_failure' => DateTimeFormat::utcNow()];
476 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
478 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
482 $contact = array_merge($contact, $data);
484 $contact["server_url"] = $data["baseurl"];
486 GContact::update($contact);
488 $curlResult = Network::curl($data["poll"]);
490 if (!$curlResult->isSuccess()) {
491 $fields = ['last_failure' => DateTimeFormat::utcNow()];
492 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
494 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
498 $doc = new DOMDocument();
499 /// @TODO Avoid error supression here
500 @$doc->loadXML($curlResult->getBody());
502 $xpath = new DOMXPath($doc);
503 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
505 $entries = $xpath->query('/atom:feed/atom:entry');
509 foreach ($entries as $entry) {
510 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
511 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
513 if ($last_updated < $published) {
514 $last_updated = $published;
517 if ($last_updated < $updated) {
518 $last_updated = $updated;
522 // Maybe there aren't any entries. Then check if it is a valid feed
523 if ($last_updated == "") {
524 if ($xpath->query('/atom:feed')->length > 0) {
525 $last_updated = NULL_DATE;
529 $fields = ['last_contact' => DateTimeFormat::utcNow()];
531 if (!empty($last_updated)) {
532 $fields['updated'] = $last_updated;
535 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
537 if (($gcontacts[0]["generation"] == 0)) {
538 $fields = ['generation' => 9];
539 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
542 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
544 return $last_updated;
547 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
549 $now = strtotime(DateTimeFormat::utcNow());
551 if ($updated > $last_contact) {
552 $contact_time = strtotime($updated);
554 $contact_time = strtotime($last_contact);
557 $failure_time = strtotime($last_failure);
558 $created_time = strtotime($created);
560 // If there is no "created" time then use the current time
561 if ($created_time <= 0) {
562 $created_time = $now;
565 // If the last contact was less than 24 hours then don't update
566 if (($now - $contact_time) < (60 * 60 * 24)) {
570 // If the last failure was less than 24 hours then don't update
571 if (($now - $failure_time) < (60 * 60 * 24)) {
575 // If the last contact was less than a week ago and the last failure is older than a week then don't update
576 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
579 // 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
580 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
584 // 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
585 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
592 /// @TODO Maybe move this out to an utilities class?
593 private static function toBoolean($val)
595 if (($val == "true") || ($val == 1)) {
597 } elseif (($val == "false") || ($val == 0)) {
605 * @brief Detect server type (Hubzilla or Friendica) via the poco data
607 * @param array $data POCO data
608 * @return array Server data
610 private static function detectPocoData(array $data)
614 if (!isset($data['entry'])) {
618 if (count($data['entry']) == 0) {
622 if (!isset($data['entry'][0]['urls'])) {
626 if (count($data['entry'][0]['urls']) == 0) {
630 foreach ($data['entry'][0]['urls'] as $url) {
631 if ($url['type'] == 'zot') {
633 $server["platform"] = 'Hubzilla';
634 $server["network"] = Protocol::DIASPORA;
642 * @brief Detect server type by using the nodeinfo data
644 * @param string $server_url address of the server
645 * @return array Server data
647 private static function fetchNodeinfo($server_url)
649 $curlResult = Network::curl($server_url."/.well-known/nodeinfo");
650 if (!$curlResult->isSuccess()) {
654 $nodeinfo = json_decode($curlResult->getBody(), true);
656 if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
663 foreach ($nodeinfo['links'] as $link) {
664 if (!is_array($link) || empty($link['rel'])) {
665 logger('Invalid nodeinfo format for ' . $server_url, LOGGER_DEBUG);
668 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
669 $nodeinfo1_url = $link['href'];
670 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
671 $nodeinfo2_url = $link['href'];
675 if ($nodeinfo1_url . $nodeinfo2_url == '') {
681 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
682 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
683 $server = self::parseNodeinfo2($nodeinfo2_url);
686 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
687 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
688 $server = self::parseNodeinfo1($nodeinfo1_url);
695 * @brief Parses Nodeinfo 1
697 * @param string $nodeinfo_url address of the nodeinfo path
698 * @return array Server data
700 private static function parseNodeinfo1($nodeinfo_url)
702 $curlResult = Network::curl($nodeinfo_url);
704 if (!$curlResult->isSuccess()) {
708 $nodeinfo = json_decode($curlResult->getBody(), true);
710 if (!is_array($nodeinfo)) {
716 $server['register_policy'] = REGISTER_CLOSED;
718 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
719 $server['register_policy'] = REGISTER_OPEN;
722 if (is_array($nodeinfo['software'])) {
723 if (isset($nodeinfo['software']['name'])) {
724 $server['platform'] = $nodeinfo['software']['name'];
727 if (isset($nodeinfo['software']['version'])) {
728 $server['version'] = $nodeinfo['software']['version'];
729 // Version numbers on Nodeinfo are presented with additional info, e.g.:
730 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
731 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
735 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
736 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
739 if (!empty($nodeinfo['usage']['users']['total'])) {
740 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
747 if (is_array($nodeinfo['protocols']['inbound'])) {
748 foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
749 if ($inbound == 'diaspora') {
752 if ($inbound == 'friendica') {
755 if ($inbound == 'gnusocial') {
762 $server['network'] = Protocol::OSTATUS;
765 $server['network'] = Protocol::DIASPORA;
768 $server['network'] = Protocol::DFRN;
779 * @brief Parses Nodeinfo 2
781 * @param string $nodeinfo_url address of the nodeinfo path
782 * @return array Server data
784 private static function parseNodeinfo2($nodeinfo_url)
786 $curlResult = Network::curl($nodeinfo_url);
787 if (!$curlResult->isSuccess()) {
791 $nodeinfo = json_decode($curlResult->getBody(), true);
793 if (!is_array($nodeinfo)) {
799 $server['register_policy'] = REGISTER_CLOSED;
801 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
802 $server['register_policy'] = REGISTER_OPEN;
805 if (is_array($nodeinfo['software'])) {
806 if (isset($nodeinfo['software']['name'])) {
807 $server['platform'] = $nodeinfo['software']['name'];
810 if (isset($nodeinfo['software']['version'])) {
811 $server['version'] = $nodeinfo['software']['version'];
812 // Version numbers on Nodeinfo are presented with additional info, e.g.:
813 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
814 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
818 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
819 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
822 if (!empty($nodeinfo['usage']['users']['total'])) {
823 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
830 if (!empty($nodeinfo['protocols'])) {
831 foreach ($nodeinfo['protocols'] as $protocol) {
832 if ($protocol == 'diaspora') {
834 } elseif ($protocol == 'friendica') {
836 } elseif ($protocol == 'gnusocial') {
843 $server['network'] = Protocol::OSTATUS;
844 } elseif ($diaspora) {
845 $server['network'] = Protocol::DIASPORA;
846 } elseif ($friendica) {
847 $server['network'] = Protocol::DFRN;
850 if (empty($server)) {
858 * @brief Detect server type (Hubzilla or Friendica) via the front page body
860 * @param string $body Front page of the server
861 * @return array Server data
863 private static function detectServerType($body)
867 $doc = new DOMDocument();
868 /// @TODO Acoid supressing error
869 @$doc->loadHTML($body);
870 $xpath = new DOMXPath($doc);
872 $list = $xpath->query("//meta[@name]");
874 foreach ($list as $node) {
876 if ($node->attributes->length) {
877 foreach ($node->attributes as $attribute) {
878 $attr[$attribute->name] = $attribute->value;
881 if ($attr['name'] == 'generator') {
882 $version_part = explode(" ", $attr['content']);
883 if (count($version_part) == 2) {
884 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
886 $server["platform"] = $version_part[0];
887 $server["version"] = $version_part[1];
888 $server["network"] = Protocol::DFRN;
895 $list = $xpath->query("//meta[@property]");
897 foreach ($list as $node) {
899 if ($node->attributes->length) {
900 foreach ($node->attributes as $attribute) {
901 $attr[$attribute->name] = $attribute->value;
904 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
906 $server["platform"] = $attr['content'];
907 $server["version"] = "";
908 $server["network"] = Protocol::DIASPORA;
917 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
922 public static function checkServer($server_url, $network = "", $force = false)
924 // Unify the server address
925 $server_url = trim($server_url, "/");
926 $server_url = str_replace("/index.php", "", $server_url);
928 if ($server_url == "") {
932 $gserver = DBA::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
933 if (DBA::isResult($gserver)) {
934 if ($gserver["created"] <= NULL_DATE) {
935 $fields = ['created' => DateTimeFormat::utcNow()];
936 $condition = ['nurl' => normalise_link($server_url)];
937 DBA::update('gserver', $fields, $condition);
939 $poco = $gserver["poco"];
940 $noscrape = $gserver["noscrape"];
942 if ($network == "") {
943 $network = $gserver["network"];
946 $last_contact = $gserver["last_contact"];
947 $last_failure = $gserver["last_failure"];
948 $version = $gserver["version"];
949 $platform = $gserver["platform"];
950 $site_name = $gserver["site_name"];
951 $info = $gserver["info"];
952 $register_policy = $gserver["register_policy"];
953 $registered_users = $gserver["registered-users"];
955 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
956 // It can happen that a zero date is in the database, but storing it again is forbidden.
957 if ($last_contact < NULL_DATE) {
958 $last_contact = NULL_DATE;
961 if ($last_failure < NULL_DATE) {
962 $last_failure = NULL_DATE;
965 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
966 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
967 return ($last_contact >= $last_failure);
976 $register_policy = -1;
977 $registered_users = 0;
979 $last_contact = NULL_DATE;
980 $last_failure = NULL_DATE;
982 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
985 $possible_failure = false;
986 $orig_last_failure = $last_failure;
987 $orig_last_contact = $last_contact;
989 // Mastodon uses the "@" for user profiles.
990 // But this can be misunderstood.
991 if (parse_url($server_url, PHP_URL_USER) != '') {
992 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
996 // Check if the page is accessible via SSL.
997 $orig_server_url = $server_url;
998 $server_url = str_replace("http://", "https://", $server_url);
1000 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1001 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1003 // Quit if there is a timeout.
1004 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1005 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1006 ($curlResult->isTimeout())) {
1007 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1008 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1012 // Maybe the page is unencrypted only?
1013 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1014 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1015 $server_url = str_replace("https://", "http://", $server_url);
1017 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1018 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1020 // Quit if there is a timeout
1021 if ($curlResult->isTimeout()) {
1022 logger("Connection to server " . $server_url . " timed out.", LOGGER_DEBUG);
1023 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1027 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1030 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1031 // Workaround for bad configured servers (known nginx problem)
1032 if (!empty($curlResult->getInfo()) && !in_array($curlResult->getInfo()["http_code"], ["403", "404"])) {
1036 $possible_failure = true;
1039 // If the server has no possible failure we reset the cached data
1040 if (!$possible_failure) {
1045 $register_policy = -1;
1049 // This will be too low, but better than no value at all.
1050 $registered_users = DBA::count('gcontact', ['server_url' => normalise_link($server_url)]);
1055 $curlResult = Network::curl($server_url."/poco");
1057 if ($curlResult->isSuccess()) {
1058 $data = json_decode($curlResult->getBody(), true);
1060 if (isset($data['totalResults'])) {
1061 $registered_users = $data['totalResults'];
1062 $poco = $server_url . "/poco";
1063 $server = self::detectPocoData($data);
1065 if (!empty($server)) {
1066 $platform = $server['platform'];
1067 $network = $server['network'];
1074 * There are servers out there who don't return 404 on a failure
1075 * We have to be sure that don't misunderstand this
1077 if (is_null($data)) {
1086 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1087 $curlResult = Network::curl($server_url);
1089 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "")) {
1092 $server = self::detectServerType($curlResult->getBody());
1094 if (!empty($server)) {
1095 $platform = $server['platform'];
1096 $network = $server['network'];
1097 $version = $server['version'];
1098 $site_name = $server['site_name'];
1101 $lines = explode("\n", $curlResult->getHeader());
1103 if (count($lines)) {
1104 foreach ($lines as $line) {
1105 $line = trim($line);
1107 if (stristr($line, 'X-Diaspora-Version:')) {
1108 $platform = "Diaspora";
1109 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1110 $version = trim(str_replace("x-diaspora-version:", "", $version));
1111 $network = Protocol::DIASPORA;
1112 $versionparts = explode("-", $version);
1113 $version = $versionparts[0];
1116 if (stristr($line, 'Server: Mastodon')) {
1117 $platform = "Mastodon";
1118 $network = Protocol::OSTATUS;
1125 if (!$failure && ($poco == "")) {
1126 // Test for Statusnet
1127 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1128 // The "not implemented" is a special treatment for really, really old Friendica versions
1129 $curlResult = Network::curl($server_url."/api/statusnet/version.json");
1131 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1132 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1133 $platform = "StatusNet";
1134 // Remove junk that some GNU Social servers return
1135 $version = str_replace(chr(239).chr(187).chr(191), "", $curlResult->getBody());
1136 $version = trim($version, '"');
1137 $network = Protocol::OSTATUS;
1140 // Test for GNU Social
1141 $curlResult = Network::curl($server_url."/api/gnusocial/version.json");
1143 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1144 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1145 $platform = "GNU Social";
1146 // Remove junk that some GNU Social servers return
1147 $version = str_replace(chr(239) . chr(187) . chr(191), "", $curlResult->getBody());
1148 $version = trim($version, '"');
1149 $network = Protocol::OSTATUS;
1152 // Test for Mastodon
1153 $orig_version = $version;
1154 $curlResult = Network::curl($server_url . "/api/v1/instance");
1156 if ($curlResult->isSuccess() && ($curlResult->getBody() != '')) {
1157 $data = json_decode($curlResult->getBody(), true);
1159 if (isset($data['version'])) {
1160 $platform = "Mastodon";
1161 $version = defaults($data, 'version', '');
1162 $site_name = defaults($data, 'title', '');
1163 $info = defaults($data, 'description', '');
1164 $network = Protocol::OSTATUS;
1167 if (!empty($data['stats']['user_count'])) {
1168 $registered_users = $data['stats']['user_count'];
1172 if (strstr($orig_version . $version, 'Pleroma')) {
1173 $platform = 'Pleroma';
1174 $version = trim(str_replace('Pleroma', '', $version));
1179 // Test for Hubzilla and Red
1180 $curlResult = Network::curl($server_url . "/siteinfo.json");
1182 if ($curlResult->isSuccess()) {
1183 $data = json_decode($curlResult->getBody(), true);
1185 if (isset($data['url'])) {
1186 $platform = $data['platform'];
1187 $version = $data['version'];
1188 $network = Protocol::DIASPORA;
1191 if (!empty($data['site_name'])) {
1192 $site_name = $data['site_name'];
1195 if (!empty($data['channels_total'])) {
1196 $registered_users = $data['channels_total'];
1199 if (!empty($data['register_policy'])) {
1200 switch ($data['register_policy']) {
1201 case "REGISTER_OPEN":
1202 $register_policy = REGISTER_OPEN;
1205 case "REGISTER_APPROVE":
1206 $register_policy = REGISTER_APPROVE;
1209 case "REGISTER_CLOSED":
1211 $register_policy = REGISTER_CLOSED;
1216 // Test for Hubzilla, Redmatrix or Friendica
1217 $curlResult = Network::curl($server_url."/api/statusnet/config.json");
1219 if ($curlResult->isSuccess()) {
1220 $data = json_decode($curlResult->getBody(), true);
1222 if (isset($data['site']['server'])) {
1223 if (isset($data['site']['platform'])) {
1224 $platform = $data['site']['platform']['PLATFORM_NAME'];
1225 $version = $data['site']['platform']['STD_VERSION'];
1226 $network = Protocol::DIASPORA;
1229 if (isset($data['site']['BlaBlaNet'])) {
1230 $platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
1231 $version = $data['site']['BlaBlaNet']['STD_VERSION'];
1232 $network = Protocol::DIASPORA;
1235 if (isset($data['site']['hubzilla'])) {
1236 $platform = $data['site']['hubzilla']['PLATFORM_NAME'];
1237 $version = $data['site']['hubzilla']['RED_VERSION'];
1238 $network = Protocol::DIASPORA;
1241 if (isset($data['site']['redmatrix'])) {
1242 if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
1243 $platform = $data['site']['redmatrix']['PLATFORM_NAME'];
1244 } elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
1245 $platform = $data['site']['redmatrix']['RED_PLATFORM'];
1248 $version = $data['site']['redmatrix']['RED_VERSION'];
1249 $network = Protocol::DIASPORA;
1252 if (isset($data['site']['friendica'])) {
1253 $platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
1254 $version = $data['site']['friendica']['FRIENDICA_VERSION'];
1255 $network = Protocol::DFRN;
1258 $site_name = $data['site']['name'];
1261 $inviteonly = false;
1264 if (!empty($data['site']['closed'])) {
1265 $closed = self::toBoolean($data['site']['closed']);
1268 if (!empty($data['site']['private'])) {
1269 $private = self::toBoolean($data['site']['private']);
1272 if (!empty($data['site']['inviteonly'])) {
1273 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1276 if (!$closed && !$private and $inviteonly) {
1277 $register_policy = REGISTER_APPROVE;
1278 } elseif (!$closed && !$private) {
1279 $register_policy = REGISTER_OPEN;
1281 $register_policy = REGISTER_CLOSED;
1288 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1290 $curlResult = Network::curl($server_url . "/statistics.json");
1292 if ($curlResult->isSuccess()) {
1293 $data = json_decode($curlResult->getBody(), true);
1295 if (isset($data['version'])) {
1296 $version = $data['version'];
1297 // Version numbers on statistics.json are presented with additional info, e.g.:
1298 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1299 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1302 if (!empty($data['name'])) {
1303 $site_name = $data['name'];
1306 if (!empty($data['network'])) {
1307 $platform = $data['network'];
1310 if ($platform == "Diaspora") {
1311 $network = Protocol::DIASPORA;
1314 if (!empty($data['registrations_open']) && $data['registrations_open']) {
1315 $register_policy = REGISTER_OPEN;
1317 $register_policy = REGISTER_CLOSED;
1322 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1324 $server = self::fetchNodeinfo($server_url);
1326 if (!empty($server)) {
1327 $register_policy = $server['register_policy'];
1329 if (isset($server['platform'])) {
1330 $platform = $server['platform'];
1333 if (isset($server['network'])) {
1334 $network = $server['network'];
1337 if (isset($server['version'])) {
1338 $version = $server['version'];
1341 if (isset($server['site_name'])) {
1342 $site_name = $server['site_name'];
1345 if (isset($server['registered-users'])) {
1346 $registered_users = $server['registered-users'];
1351 // Check for noscrape
1352 // Friendica servers could be detected as OStatus servers
1353 if (!$failure && in_array($network, [Protocol::DFRN, Protocol::OSTATUS])) {
1354 $curlResult = Network::curl($server_url . "/friendica/json");
1356 if (!$curlResult->isSuccess()) {
1357 $curlResult = Network::curl($server_url . "/friendika/json");
1360 if ($curlResult->isSuccess()) {
1361 $data = json_decode($curlResult->getBody(), true);
1363 if (isset($data['version'])) {
1364 $network = Protocol::DFRN;
1366 if (!empty($data['no_scrape_url'])) {
1367 $noscrape = $data['no_scrape_url'];
1370 $version = $data['version'];
1372 if (!empty($data['site_name'])) {
1373 $site_name = $data['site_name'];
1376 $info = $data['info'];
1377 $register_policy = constant($data['register_policy']);
1378 $platform = $data['platform'];
1383 // Every server has got at least an admin account
1384 if (!$failure && ($registered_users == 0)) {
1385 $registered_users = 1;
1388 if ($possible_failure && !$failure) {
1393 $last_contact = $orig_last_contact;
1394 $last_failure = DateTimeFormat::utcNow();
1396 $last_contact = DateTimeFormat::utcNow();
1397 $last_failure = $orig_last_failure;
1400 if (($last_contact <= $last_failure) && !$failure) {
1401 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1402 } elseif (($last_contact >= $last_failure) && $failure) {
1403 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1406 // Check again if the server exists
1407 $found = DBA::exists('gserver', ['nurl' => normalise_link($server_url)]);
1409 $version = strip_tags($version);
1410 $site_name = strip_tags($site_name);
1411 $info = strip_tags($info);
1412 $platform = strip_tags($platform);
1414 $fields = ['url' => $server_url, 'version' => $version,
1415 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1416 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1417 'platform' => $platform, 'registered-users' => $registered_users,
1418 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1421 DBA::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1422 } elseif (!$failure) {
1423 $fields['nurl'] = normalise_link($server_url);
1424 $fields['created'] = DateTimeFormat::utcNow();
1425 DBA::insert('gserver', $fields);
1428 if (!$failure && in_array($fields['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1429 self::discoverRelay($server_url);
1432 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1438 * @brief Fetch relay data from a given server url
1440 * @param string $server_url address of the server
1442 private static function discoverRelay($server_url)
1444 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1446 $curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
1448 if (!$curlResult->isSuccess()) {
1452 $data = json_decode($curlResult->getBody(), true);
1454 if (!is_array($data)) {
1458 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1460 if (!DBA::isResult($gserver)) {
1464 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
1465 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
1466 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1469 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1471 if ($data['scope'] == 'tags') {
1474 foreach ($data['tags'] as $tag) {
1475 $tag = mb_strtolower($tag);
1476 if (strlen($tag) < 100) {
1481 foreach ($tags as $tag) {
1482 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1486 // Create or update the relay contact
1488 if (isset($data['protocols'])) {
1489 if (isset($data['protocols']['diaspora'])) {
1490 $fields['network'] = Protocol::DIASPORA;
1492 if (isset($data['protocols']['diaspora']['receive'])) {
1493 $fields['batch'] = $data['protocols']['diaspora']['receive'];
1494 } elseif (is_string($data['protocols']['diaspora'])) {
1495 $fields['batch'] = $data['protocols']['diaspora'];
1499 if (isset($data['protocols']['dfrn'])) {
1500 $fields['network'] = Protocol::DFRN;
1502 if (isset($data['protocols']['dfrn']['receive'])) {
1503 $fields['batch'] = $data['protocols']['dfrn']['receive'];
1504 } elseif (is_string($data['protocols']['dfrn'])) {
1505 $fields['batch'] = $data['protocols']['dfrn'];
1509 Diaspora::setRelayContact($server_url, $fields);
1513 * @brief Returns a list of all known servers
1514 * @return array List of server urls
1516 public static function serverlist()
1519 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1520 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1521 ORDER BY `last_contact`
1523 DBA::escape(Protocol::DFRN),
1524 DBA::escape(Protocol::DIASPORA),
1525 DBA::escape(Protocol::OSTATUS)
1528 if (!DBA::isResult($r)) {
1536 * @brief Fetch server list from remote servers and adds them when they are new.
1538 * @param string $poco URL to the POCO endpoint
1540 private static function fetchServerlist($poco)
1542 $curlResult = Network::curl($poco . "/@server");
1544 if (!$curlResult->isSuccess()) {
1548 $serverlist = json_decode($curlResult->getBody(), true);
1550 if (!is_array($serverlist)) {
1554 foreach ($serverlist as $server) {
1555 $server_url = str_replace("/index.php", "", $server['url']);
1557 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(normalise_link($server_url)));
1559 if (!DBA::isResult($r)) {
1560 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1561 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1566 private static function discoverFederation()
1568 $last = Config::get('poco', 'last_federation_discovery');
1571 $next = $last + (24 * 60 * 60);
1573 if ($next > time()) {
1578 // Discover Friendica, Hubzilla and Diaspora servers
1579 $curlResult = Network::fetchUrl("http://the-federation.info/pods.json");
1581 if (!empty($curlResult)) {
1582 $servers = json_decode($curlResult, true);
1584 if (!empty($servers['pods'])) {
1585 foreach ($servers['pods'] as $server) {
1586 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://" . $server['host']);
1591 // Disvover Mastodon servers
1592 if (!Config::get('system', 'ostatus_disabled')) {
1593 $accesstoken = Config::get('system', 'instances_social_key');
1595 if (!empty($accesstoken)) {
1596 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1597 $header = ['Authorization: Bearer '.$accesstoken];
1598 $curlResult = Network::curl($api, false, $redirects, ['headers' => $header]);
1600 if ($curlResult->isSuccess()) {
1601 $servers = json_decode($curlResult->getBody(), true);
1603 foreach ($servers['instances'] as $server) {
1604 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1605 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1611 // Currently disabled, since the service isn't available anymore.
1612 // It is not removed since I hope that there will be a successor.
1613 // Discover GNU Social Servers.
1614 //if (!Config::get('system','ostatus_disabled')) {
1615 // $serverdata = "http://gstools.org/api/get_open_instances/";
1617 // $curlResult = Network::curl($serverdata);
1618 // if ($curlResult->isSuccess()) {
1619 // $servers = json_decode($result->getBody(), true);
1621 // foreach($servers['data'] as $server)
1622 // self::checkServer($server['instance_address']);
1626 Config::set('poco', 'last_federation_discovery', time());
1629 public static function discoverSingleServer($id)
1631 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1633 if (!DBA::isResult($r)) {
1639 // Discover new servers out there (Works from Friendica version 3.5.2)
1640 self::fetchServerlist($server["poco"]);
1642 // Fetch all users from the other server
1643 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1645 logger("Fetch all users from the server " . $server["url"], LOGGER_DEBUG);
1647 $curlResult = Network::curl($url);
1649 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1650 $data = json_decode($curlResult->getBody(), true);
1652 if (!empty($data)) {
1653 self::discoverServer($data, 2);
1656 if (Config::get('system', 'poco_discovery') > 1) {
1657 $timeframe = Config::get('system', 'poco_discovery_since');
1659 if ($timeframe == 0) {
1663 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1665 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1666 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1670 $curlResult = Network::curl($url);
1672 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1673 logger("Fetch all global contacts from the server " . $server["nurl"], LOGGER_DEBUG);
1674 $data = json_decode($curlResult->getBody(), true);
1676 if (!empty($data)) {
1677 $success = self::discoverServer($data);
1681 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1682 logger("Fetch contacts from users of the server " . $server["nurl"], LOGGER_DEBUG);
1683 self::discoverServerUsers($data, $server);
1687 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1688 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1692 // If the server hadn't replied correctly, then force a sanity check
1693 self::checkServer($server["url"], $server["network"], true);
1695 // If we couldn't reach the server, we will try it some time later
1696 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1697 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1703 public static function discover($complete = false)
1705 // Update the server list
1706 self::discoverFederation();
1710 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1712 if ($requery_days == 0) {
1716 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1718 $gservers = q("SELECT `id`, `url`, `nurl`, `network`
1720 WHERE `last_contact` >= `last_failure`
1722 AND `last_poco_query` < '%s'
1723 ORDER BY RAND()", DBA::escape($last_update)
1726 if (DBA::isResult($gservers)) {
1727 foreach ($gservers as $gserver) {
1728 if (!self::checkServer($gserver['url'], $gserver['network'])) {
1729 // The server is not reachable? Okay, then we will try it later
1730 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1731 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1735 logger('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], LOGGER_DEBUG);
1736 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
1738 if (!$complete && ( --$no_of_queries == 0)) {
1745 private static function discoverServerUsers(array $data, array $server)
1747 if (!isset($data['entry'])) {
1751 foreach ($data['entry'] as $entry) {
1754 if (isset($entry['urls'])) {
1755 foreach ($entry['urls'] as $url) {
1756 if ($url['type'] == 'profile') {
1757 $profile_url = $url['value'];
1758 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1759 $username = end($path_array);
1764 if ($username != '') {
1765 logger('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], LOGGER_DEBUG);
1767 // Fetch all contacts from a given user from the other server
1768 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1770 $curlResult = Network::curl($url);
1772 if ($curlResult->isSuccess()) {
1773 $data = json_decode($curlResult["body"], true);
1775 if (!empty($data)) {
1776 self::discoverServer($data, 3);
1783 private static function discoverServer(array $data, $default_generation = 0)
1785 if (empty($data['entry'])) {
1791 foreach ($data['entry'] as $entry) {
1793 $profile_photo = '';
1797 $updated = NULL_DATE;
1803 $generation = $default_generation;
1805 if (!empty($entry['displayName'])) {
1806 $name = $entry['displayName'];
1809 if (isset($entry['urls'])) {
1810 foreach ($entry['urls'] as $url) {
1811 if ($url['type'] == 'profile') {
1812 $profile_url = $url['value'];
1815 if ($url['type'] == 'webfinger') {
1816 $connect_url = str_replace('acct:' , '', $url['value']);
1822 if (isset($entry['photos'])) {
1823 foreach ($entry['photos'] as $photo) {
1824 if ($photo['type'] == 'profile') {
1825 $profile_photo = $photo['value'];
1831 if (isset($entry['updated'])) {
1832 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
1835 if (isset($entry['network'])) {
1836 $network = $entry['network'];
1839 if (isset($entry['currentLocation'])) {
1840 $location = $entry['currentLocation'];
1843 if (isset($entry['aboutMe'])) {
1844 $about = HTML::toBBCode($entry['aboutMe']);
1847 if (isset($entry['gender'])) {
1848 $gender = $entry['gender'];
1851 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
1852 $generation = ++$entry['generation'];
1855 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
1856 $contact_type = $entry['contactType'];
1859 if (isset($entry['tags'])) {
1860 foreach ($entry['tags'] as $tag) {
1861 $keywords = implode(", ", $tag);
1865 if ($generation > 0) {
1868 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1870 $gcontact = ["url" => $profile_url,
1872 "network" => $network,
1873 "photo" => $profile_photo,
1875 "location" => $location,
1876 "gender" => $gender,
1877 "keywords" => $keywords,
1878 "connect" => $connect_url,
1879 "updated" => $updated,
1880 "contact-type" => $contact_type,
1881 "generation" => $generation];
1884 $gcontact = GContact::sanitize($gcontact);
1885 GContact::update($gcontact);
1886 } catch (Exception $e) {
1887 logger($e->getMessage(), LOGGER_DEBUG);
1890 logger("Done for profile ".$profile_url, LOGGER_DEBUG);