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\Strings;
27 use Friendica\Util\XML;
29 require_once 'include/dba.php';
34 * @brief Fetch POCO data
36 * @param integer $cid Contact ID
37 * @param integer $uid User ID
38 * @param integer $zcid Global Contact ID
39 * @param integer $url POCO address that should be polled
41 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
42 * and add the entries to the gcontact (Global Contact) table, or update existing entries
43 * if anything (name or photo) has changed.
44 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
46 * Once the global contact is stored add (if necessary) the contact linkage which associates
47 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
48 * pointing to the same global contact id.
51 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
53 // Call the function "load" via the worker
54 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
58 * @brief Fetch POCO data from the worker
60 * @param integer $cid Contact ID
61 * @param integer $uid User ID
62 * @param integer $zcid Global Contact ID
63 * @param integer $url POCO address that should be polled
66 public static function load($cid, $uid, $zcid, $url)
72 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
73 if (DBA::isResult($contact)) {
74 $url = $contact['poco'];
75 $uid = $contact['uid'];
87 $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') ;
89 Logger::log('load: ' . $url, Logger::DEBUG);
91 $fetchresult = Network::fetchUrlFull($url);
92 $s = $fetchresult->getBody();
94 Logger::log('load: returns ' . $s, Logger::DATA);
96 Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
98 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
102 $j = json_decode($s, true);
104 Logger::log('load: json: ' . print_r($j, true), Logger::DATA);
106 if (!isset($j['entry'])) {
111 foreach ($j['entry'] as $entry) {
118 $updated = DBA::NULL_DATETIME;
126 if (!empty($entry['displayName'])) {
127 $name = $entry['displayName'];
130 if (isset($entry['urls'])) {
131 foreach ($entry['urls'] as $url) {
132 if ($url['type'] == 'profile') {
133 $profile_url = $url['value'];
136 if ($url['type'] == 'webfinger') {
137 $connect_url = str_replace('acct:', '', $url['value']);
142 if (isset($entry['photos'])) {
143 foreach ($entry['photos'] as $photo) {
144 if ($photo['type'] == 'profile') {
145 $profile_photo = $photo['value'];
151 if (isset($entry['updated'])) {
152 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
155 if (isset($entry['network'])) {
156 $network = $entry['network'];
159 if (isset($entry['currentLocation'])) {
160 $location = $entry['currentLocation'];
163 if (isset($entry['aboutMe'])) {
164 $about = HTML::toBBCode($entry['aboutMe']);
167 if (isset($entry['gender'])) {
168 $gender = $entry['gender'];
171 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
172 $generation = ++$entry['generation'];
175 if (isset($entry['tags'])) {
176 foreach ($entry['tags'] as $tag) {
177 $keywords = implode(", ", $tag);
181 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
182 $contact_type = $entry['contactType'];
185 $gcontact = ["url" => $profile_url,
187 "network" => $network,
188 "photo" => $profile_photo,
190 "location" => $location,
192 "keywords" => $keywords,
193 "connect" => $connect_url,
194 "updated" => $updated,
195 "contact-type" => $contact_type,
196 "generation" => $generation];
199 $gcontact = GContact::sanitize($gcontact);
200 $gcid = GContact::update($gcontact);
202 GContact::link($gcid, $uid, $cid, $zcid);
203 } catch (Exception $e) {
204 Logger::log($e->getMessage(), Logger::DEBUG);
207 Logger::log("load: loaded $total entries", Logger::DEBUG);
209 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
210 DBA::delete('glink', $condition);
213 public static function reachable($profile, $server = "", $network = "", $force = false)
216 $server = self::detectServer($profile);
223 return self::checkServer($server, $network, $force);
226 public static function detectServer($profile)
228 // Try to detect the server path based upon some known standard paths
231 if ($server_url == "") {
232 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
233 if ($friendica != $profile) {
234 $server_url = $friendica;
235 $network = Protocol::DFRN;
239 if ($server_url == "") {
240 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
241 if ($diaspora != $profile) {
242 $server_url = $diaspora;
243 $network = Protocol::DIASPORA;
247 if ($server_url == "") {
248 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
249 if ($red != $profile) {
251 $network = Protocol::DIASPORA;
256 if ($server_url == "") {
257 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
258 if ($mastodon != $profile) {
259 $server_url = $mastodon;
260 $network = Protocol::OSTATUS;
264 // Numeric OStatus variant
265 if ($server_url == "") {
266 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
267 if ($ostatus != $profile) {
268 $server_url = $ostatus;
269 $network = Protocol::OSTATUS;
274 if ($server_url == "") {
275 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
276 if ($base != $profile) {
278 $network = Protocol::PHANTOM;
282 if ($server_url == "") {
287 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
288 DBA::escape(Strings::normaliseLink($server_url))
291 if (DBA::isResult($r)) {
295 // Fetch the host-meta to check if this really is a server
296 $curlResult = Network::curl($server_url."/.well-known/host-meta");
297 if (!$curlResult->isSuccess()) {
304 public static function alternateOStatusUrl($url)
306 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
309 public static function lastUpdated($profile, $force = false)
312 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
313 DBA::escape(Strings::normaliseLink($profile))
316 if (!DBA::isResult($gcontacts)) {
320 $contact = ["url" => $profile];
322 if ($gcontacts[0]["created"] <= DBA::NULL_DATETIME) {
323 $contact['created'] = DateTimeFormat::utcNow();
328 $server_url = Strings::normaliseLink(self::detectServer($profile));
331 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
332 $server_url = $gcontacts[0]["server_url"];
335 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
336 $server_url = Strings::normaliseLink(self::detectServer($profile));
339 if (!in_array($gcontacts[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
340 Logger::log("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", Logger::DEBUG);
344 if ($server_url != "") {
345 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
347 $fields = ['last_failure' => DateTimeFormat::utcNow()];
348 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
351 Logger::log("Profile ".$profile.": Server ".$server_url." wasn't reachable.", Logger::DEBUG);
354 $contact['server_url'] = $server_url;
357 if (in_array($gcontacts[0]["network"], ["", Protocol::FEED])) {
359 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
360 DBA::escape(Strings::normaliseLink($server_url))
364 $contact['network'] = $server[0]["network"];
370 // noscrape is really fast so we don't cache the call.
371 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
372 // Use noscrape if possible
373 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(Strings::normaliseLink($server_url)));
376 $curlResult = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
378 if ($curlResult->isSuccess() && ($curlResult->getBody() != "")) {
379 $noscrape = json_decode($curlResult->getBody(), true);
381 if (is_array($noscrape)) {
382 $contact["network"] = $server[0]["network"];
384 if (isset($noscrape["fn"])) {
385 $contact["name"] = $noscrape["fn"];
387 if (isset($noscrape["comm"])) {
388 $contact["community"] = $noscrape["comm"];
390 if (isset($noscrape["tags"])) {
391 $keywords = implode(" ", $noscrape["tags"]);
392 if ($keywords != "") {
393 $contact["keywords"] = $keywords;
397 $location = Profile::formatLocation($noscrape);
399 $contact["location"] = $location;
401 if (isset($noscrape["dfrn-notify"])) {
402 $contact["notify"] = $noscrape["dfrn-notify"];
404 // Remove all fields that are not present in the gcontact table
405 unset($noscrape["fn"]);
406 unset($noscrape["key"]);
407 unset($noscrape["homepage"]);
408 unset($noscrape["comm"]);
409 unset($noscrape["tags"]);
410 unset($noscrape["locality"]);
411 unset($noscrape["region"]);
412 unset($noscrape["country-name"]);
413 unset($noscrape["contacts"]);
414 unset($noscrape["dfrn-request"]);
415 unset($noscrape["dfrn-confirm"]);
416 unset($noscrape["dfrn-notify"]);
417 unset($noscrape["dfrn-poll"]);
419 // Set the date of the last contact
420 /// @todo By now the function "update_gcontact" doesn't work with this field
421 //$contact["last_contact"] = DateTimeFormat::utcNow();
423 $contact = array_merge($contact, $noscrape);
425 GContact::update($contact);
427 if (!empty($noscrape["updated"])) {
428 $fields = ['last_contact' => DateTimeFormat::utcNow()];
429 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
431 Logger::log("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", Logger::DEBUG);
433 return $noscrape["updated"];
440 // If we only can poll the feed, then we only do this once a while
441 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
442 Logger::log("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", Logger::DEBUG);
444 GContact::update($contact);
445 return $gcontacts[0]["updated"];
448 $data = Probe::uri($profile);
450 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
451 // Then check the other link and delete this one
452 if (($data["network"] == Protocol::OSTATUS) && self::alternateOStatusUrl($profile)
453 && (Strings::normaliseLink($profile) == Strings::normaliseLink($data["alias"]))
454 && (Strings::normaliseLink($profile) != Strings::normaliseLink($data["url"]))
456 // Delete the old entry
457 DBA::delete('gcontact', ['nurl' => Strings::normaliseLink($profile)]);
459 $gcontact = array_merge($gcontacts[0], $data);
461 $gcontact["server_url"] = $data["baseurl"];
464 $gcontact = GContact::sanitize($gcontact);
465 GContact::update($gcontact);
467 self::lastUpdated($data["url"], $force);
468 } catch (Exception $e) {
469 Logger::log($e->getMessage(), Logger::DEBUG);
472 Logger::log("Profile ".$profile." was deleted", Logger::DEBUG);
476 if (($data["poll"] == "") || (in_array($data["network"], [Protocol::FEED, Protocol::PHANTOM]))) {
477 $fields = ['last_failure' => DateTimeFormat::utcNow()];
478 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
480 Logger::log("Profile ".$profile." wasn't reachable (profile)", Logger::DEBUG);
484 $contact = array_merge($contact, $data);
486 $contact["server_url"] = $data["baseurl"];
488 GContact::update($contact);
490 $curlResult = Network::curl($data["poll"]);
492 if (!$curlResult->isSuccess()) {
493 $fields = ['last_failure' => DateTimeFormat::utcNow()];
494 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
496 Logger::log("Profile ".$profile." wasn't reachable (no feed)", Logger::DEBUG);
500 $doc = new DOMDocument();
501 /// @TODO Avoid error supression here
502 @$doc->loadXML($curlResult->getBody());
504 $xpath = new DOMXPath($doc);
505 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
507 $entries = $xpath->query('/atom:feed/atom:entry');
511 foreach ($entries as $entry) {
512 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
513 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
515 if ($last_updated < $published) {
516 $last_updated = $published;
519 if ($last_updated < $updated) {
520 $last_updated = $updated;
524 // Maybe there aren't any entries. Then check if it is a valid feed
525 if ($last_updated == "") {
526 if ($xpath->query('/atom:feed')->length > 0) {
527 $last_updated = DBA::NULL_DATETIME;
531 $fields = ['last_contact' => DateTimeFormat::utcNow()];
533 if (!empty($last_updated)) {
534 $fields['updated'] = $last_updated;
537 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
539 if (($gcontacts[0]["generation"] == 0)) {
540 $fields = ['generation' => 9];
541 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
544 Logger::log("Profile ".$profile." was last updated at ".$last_updated, Logger::DEBUG);
546 return $last_updated;
549 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
551 $now = strtotime(DateTimeFormat::utcNow());
553 if ($updated > $last_contact) {
554 $contact_time = strtotime($updated);
556 $contact_time = strtotime($last_contact);
559 $failure_time = strtotime($last_failure);
560 $created_time = strtotime($created);
562 // If there is no "created" time then use the current time
563 if ($created_time <= 0) {
564 $created_time = $now;
567 // If the last contact was less than 24 hours then don't update
568 if (($now - $contact_time) < (60 * 60 * 24)) {
572 // If the last failure was less than 24 hours then don't update
573 if (($now - $failure_time) < (60 * 60 * 24)) {
577 // If the last contact was less than a week ago and the last failure is older than a week then don't update
578 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
581 // 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
582 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
586 // 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
587 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
594 /// @TODO Maybe move this out to an utilities class?
595 private static function toBoolean($val)
597 if (($val == "true") || ($val == 1)) {
599 } elseif (($val == "false") || ($val == 0)) {
607 * @brief Detect server type (Hubzilla or Friendica) via the poco data
609 * @param array $data POCO data
610 * @return array Server data
612 private static function detectPocoData(array $data)
616 if (!isset($data['entry'])) {
620 if (count($data['entry']) == 0) {
624 if (!isset($data['entry'][0]['urls'])) {
628 if (count($data['entry'][0]['urls']) == 0) {
632 foreach ($data['entry'][0]['urls'] as $url) {
633 if ($url['type'] == 'zot') {
635 $server["platform"] = 'Hubzilla';
636 $server["network"] = Protocol::DIASPORA;
644 * @brief Detect server type by using the nodeinfo data
646 * @param string $server_url address of the server
647 * @return array Server data
649 private static function fetchNodeinfo($server_url)
651 $curlResult = Network::curl($server_url."/.well-known/nodeinfo");
652 if (!$curlResult->isSuccess()) {
656 $nodeinfo = json_decode($curlResult->getBody(), true);
658 if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
665 foreach ($nodeinfo['links'] as $link) {
666 if (!is_array($link) || empty($link['rel'])) {
667 Logger::log('Invalid nodeinfo format for ' . $server_url, Logger::DEBUG);
670 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
671 $nodeinfo1_url = $link['href'];
672 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
673 $nodeinfo2_url = $link['href'];
677 if ($nodeinfo1_url . $nodeinfo2_url == '') {
683 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
684 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
685 $server = self::parseNodeinfo2($nodeinfo2_url);
688 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
689 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
690 $server = self::parseNodeinfo1($nodeinfo1_url);
697 * @brief Parses Nodeinfo 1
699 * @param string $nodeinfo_url address of the nodeinfo path
700 * @return array Server data
702 private static function parseNodeinfo1($nodeinfo_url)
704 $curlResult = Network::curl($nodeinfo_url);
706 if (!$curlResult->isSuccess()) {
710 $nodeinfo = json_decode($curlResult->getBody(), true);
712 if (!is_array($nodeinfo)) {
718 $server['register_policy'] = REGISTER_CLOSED;
720 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
721 $server['register_policy'] = REGISTER_OPEN;
724 if (is_array($nodeinfo['software'])) {
725 if (isset($nodeinfo['software']['name'])) {
726 $server['platform'] = $nodeinfo['software']['name'];
729 if (isset($nodeinfo['software']['version'])) {
730 $server['version'] = $nodeinfo['software']['version'];
731 // Version numbers on Nodeinfo are presented with additional info, e.g.:
732 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
733 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
737 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
738 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
741 if (!empty($nodeinfo['usage']['users']['total'])) {
742 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
749 if (is_array($nodeinfo['protocols']['inbound'])) {
750 foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
751 if ($inbound == 'diaspora') {
754 if ($inbound == 'friendica') {
757 if ($inbound == 'gnusocial') {
764 $server['network'] = Protocol::OSTATUS;
767 $server['network'] = Protocol::DIASPORA;
770 $server['network'] = Protocol::DFRN;
781 * @brief Parses Nodeinfo 2
783 * @param string $nodeinfo_url address of the nodeinfo path
784 * @return array Server data
786 private static function parseNodeinfo2($nodeinfo_url)
788 $curlResult = Network::curl($nodeinfo_url);
789 if (!$curlResult->isSuccess()) {
793 $nodeinfo = json_decode($curlResult->getBody(), true);
795 if (!is_array($nodeinfo)) {
801 $server['register_policy'] = REGISTER_CLOSED;
803 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
804 $server['register_policy'] = REGISTER_OPEN;
807 if (is_array($nodeinfo['software'])) {
808 if (isset($nodeinfo['software']['name'])) {
809 $server['platform'] = $nodeinfo['software']['name'];
812 if (isset($nodeinfo['software']['version'])) {
813 $server['version'] = $nodeinfo['software']['version'];
814 // Version numbers on Nodeinfo are presented with additional info, e.g.:
815 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
816 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
820 if (is_array($nodeinfo['metadata']) && isset($nodeinfo['metadata']['nodeName'])) {
821 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
824 if (!empty($nodeinfo['usage']['users']['total'])) {
825 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
832 if (!empty($nodeinfo['protocols'])) {
833 foreach ($nodeinfo['protocols'] as $protocol) {
834 if ($protocol == 'diaspora') {
836 } elseif ($protocol == 'friendica') {
838 } elseif ($protocol == 'gnusocial') {
845 $server['network'] = Protocol::OSTATUS;
846 } elseif ($diaspora) {
847 $server['network'] = Protocol::DIASPORA;
848 } elseif ($friendica) {
849 $server['network'] = Protocol::DFRN;
852 if (empty($server)) {
860 * @brief Detect server type (Hubzilla or Friendica) via the front page body
862 * @param string $body Front page of the server
863 * @return array Server data
865 private static function detectServerType($body)
869 $doc = new DOMDocument();
870 /// @TODO Acoid supressing error
871 @$doc->loadHTML($body);
872 $xpath = new DOMXPath($doc);
874 $list = $xpath->query("//meta[@name]");
876 foreach ($list as $node) {
878 if ($node->attributes->length) {
879 foreach ($node->attributes as $attribute) {
880 $attr[$attribute->name] = $attribute->value;
883 if ($attr['name'] == 'generator') {
884 $version_part = explode(" ", $attr['content']);
885 if (count($version_part) == 2) {
886 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
888 $server["platform"] = $version_part[0];
889 $server["version"] = $version_part[1];
890 $server["network"] = Protocol::DFRN;
897 $list = $xpath->query("//meta[@property]");
899 foreach ($list as $node) {
901 if ($node->attributes->length) {
902 foreach ($node->attributes as $attribute) {
903 $attr[$attribute->name] = $attribute->value;
906 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
908 $server["platform"] = $attr['content'];
909 $server["version"] = "";
910 $server["network"] = Protocol::DIASPORA;
919 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
924 public static function checkServer($server_url, $network = "", $force = false)
926 // Unify the server address
927 $server_url = trim($server_url, "/");
928 $server_url = str_replace("/index.php", "", $server_url);
930 if ($server_url == "") {
934 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
935 if (DBA::isResult($gserver)) {
936 if ($gserver["created"] <= DBA::NULL_DATETIME) {
937 $fields = ['created' => DateTimeFormat::utcNow()];
938 $condition = ['nurl' => Strings::normaliseLink($server_url)];
939 DBA::update('gserver', $fields, $condition);
941 $poco = $gserver["poco"];
942 $noscrape = $gserver["noscrape"];
944 if ($network == "") {
945 $network = $gserver["network"];
948 $last_contact = $gserver["last_contact"];
949 $last_failure = $gserver["last_failure"];
950 $version = $gserver["version"];
951 $platform = $gserver["platform"];
952 $site_name = $gserver["site_name"];
953 $info = $gserver["info"];
954 $register_policy = $gserver["register_policy"];
955 $registered_users = $gserver["registered-users"];
957 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
958 // It can happen that a zero date is in the database, but storing it again is forbidden.
959 if ($last_contact < DBA::NULL_DATETIME) {
960 $last_contact = DBA::NULL_DATETIME;
963 if ($last_failure < DBA::NULL_DATETIME) {
964 $last_failure = DBA::NULL_DATETIME;
967 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
968 Logger::log("Use cached data for server ".$server_url, Logger::DEBUG);
969 return ($last_contact >= $last_failure);
978 $register_policy = -1;
979 $registered_users = 0;
981 $last_contact = DBA::NULL_DATETIME;
982 $last_failure = DBA::NULL_DATETIME;
984 Logger::log("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, Logger::DEBUG);
987 $possible_failure = false;
988 $orig_last_failure = $last_failure;
989 $orig_last_contact = $last_contact;
991 // Mastodon uses the "@" for user profiles.
992 // But this can be misunderstood.
993 if (parse_url($server_url, PHP_URL_USER) != '') {
994 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
998 // Check if the page is accessible via SSL.
999 $orig_server_url = $server_url;
1000 $server_url = str_replace("http://", "https://", $server_url);
1002 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1003 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1005 // Quit if there is a timeout.
1006 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1007 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1008 ($curlResult->isTimeout())) {
1009 Logger::log("Connection to server ".$server_url." timed out.", Logger::DEBUG);
1010 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1014 // Maybe the page is unencrypted only?
1015 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1016 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1017 $server_url = str_replace("https://", "http://", $server_url);
1019 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1020 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1022 // Quit if there is a timeout
1023 if ($curlResult->isTimeout()) {
1024 Logger::log("Connection to server " . $server_url . " timed out.", Logger::DEBUG);
1025 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1029 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1032 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1033 // Workaround for bad configured servers (known nginx problem)
1034 if (!empty($curlResult->getInfo()) && !in_array($curlResult->getInfo()["http_code"], ["403", "404"])) {
1038 $possible_failure = true;
1041 // If the server has no possible failure we reset the cached data
1042 if (!$possible_failure) {
1047 $register_policy = -1;
1051 // This will be too low, but better than no value at all.
1052 $registered_users = DBA::count('gcontact', ['server_url' => Strings::normaliseLink($server_url)]);
1057 $curlResult = Network::curl($server_url."/poco");
1059 if ($curlResult->isSuccess()) {
1060 $data = json_decode($curlResult->getBody(), true);
1062 if (isset($data['totalResults'])) {
1063 $registered_users = $data['totalResults'];
1064 $poco = $server_url . "/poco";
1065 $server = self::detectPocoData($data);
1067 if (!empty($server)) {
1068 $platform = $server['platform'];
1069 $network = $server['network'];
1076 * There are servers out there who don't return 404 on a failure
1077 * We have to be sure that don't misunderstand this
1079 if (is_null($data)) {
1088 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1089 $curlResult = Network::curl($server_url);
1091 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "")) {
1094 $server = self::detectServerType($curlResult->getBody());
1096 if (!empty($server)) {
1097 $platform = $server['platform'];
1098 $network = $server['network'];
1099 $version = $server['version'];
1100 $site_name = $server['site_name'];
1103 $lines = explode("\n", $curlResult->getHeader());
1105 if (count($lines)) {
1106 foreach ($lines as $line) {
1107 $line = trim($line);
1109 if (stristr($line, 'X-Diaspora-Version:')) {
1110 $platform = "Diaspora";
1111 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1112 $version = trim(str_replace("x-diaspora-version:", "", $version));
1113 $network = Protocol::DIASPORA;
1114 $versionparts = explode("-", $version);
1115 $version = $versionparts[0];
1118 if (stristr($line, 'Server: Mastodon')) {
1119 $platform = "Mastodon";
1120 $network = Protocol::OSTATUS;
1127 if (!$failure && ($poco == "")) {
1128 // Test for Statusnet
1129 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1130 // The "not implemented" is a special treatment for really, really old Friendica versions
1131 $curlResult = Network::curl($server_url."/api/statusnet/version.json");
1133 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1134 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1135 $platform = "StatusNet";
1136 // Remove junk that some GNU Social servers return
1137 $version = str_replace(chr(239).chr(187).chr(191), "", $curlResult->getBody());
1138 $version = trim($version, '"');
1139 $network = Protocol::OSTATUS;
1142 // Test for GNU Social
1143 $curlResult = Network::curl($server_url."/api/gnusocial/version.json");
1145 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1146 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1147 $platform = "GNU Social";
1148 // Remove junk that some GNU Social servers return
1149 $version = str_replace(chr(239) . chr(187) . chr(191), "", $curlResult->getBody());
1150 $version = trim($version, '"');
1151 $network = Protocol::OSTATUS;
1154 // Test for Mastodon
1155 $orig_version = $version;
1156 $curlResult = Network::curl($server_url . "/api/v1/instance");
1158 if ($curlResult->isSuccess() && ($curlResult->getBody() != '')) {
1159 $data = json_decode($curlResult->getBody(), true);
1161 if (isset($data['version'])) {
1162 $platform = "Mastodon";
1163 $version = defaults($data, 'version', '');
1164 $site_name = defaults($data, 'title', '');
1165 $info = defaults($data, 'description', '');
1166 $network = Protocol::OSTATUS;
1169 if (!empty($data['stats']['user_count'])) {
1170 $registered_users = $data['stats']['user_count'];
1174 if (strstr($orig_version . $version, 'Pleroma')) {
1175 $platform = 'Pleroma';
1176 $version = trim(str_replace('Pleroma', '', $version));
1181 // Test for Hubzilla and Red
1182 $curlResult = Network::curl($server_url . "/siteinfo.json");
1184 if ($curlResult->isSuccess()) {
1185 $data = json_decode($curlResult->getBody(), true);
1187 if (isset($data['url'])) {
1188 $platform = $data['platform'];
1189 $version = $data['version'];
1190 $network = Protocol::DIASPORA;
1193 if (!empty($data['site_name'])) {
1194 $site_name = $data['site_name'];
1197 if (!empty($data['channels_total'])) {
1198 $registered_users = $data['channels_total'];
1201 if (!empty($data['register_policy'])) {
1202 switch ($data['register_policy']) {
1203 case "REGISTER_OPEN":
1204 $register_policy = REGISTER_OPEN;
1207 case "REGISTER_APPROVE":
1208 $register_policy = REGISTER_APPROVE;
1211 case "REGISTER_CLOSED":
1213 $register_policy = REGISTER_CLOSED;
1218 // Test for Hubzilla, Redmatrix or Friendica
1219 $curlResult = Network::curl($server_url."/api/statusnet/config.json");
1221 if ($curlResult->isSuccess()) {
1222 $data = json_decode($curlResult->getBody(), true);
1224 if (isset($data['site']['server'])) {
1225 if (isset($data['site']['platform'])) {
1226 $platform = $data['site']['platform']['PLATFORM_NAME'];
1227 $version = $data['site']['platform']['STD_VERSION'];
1228 $network = Protocol::DIASPORA;
1231 if (isset($data['site']['BlaBlaNet'])) {
1232 $platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
1233 $version = $data['site']['BlaBlaNet']['STD_VERSION'];
1234 $network = Protocol::DIASPORA;
1237 if (isset($data['site']['hubzilla'])) {
1238 $platform = $data['site']['hubzilla']['PLATFORM_NAME'];
1239 $version = $data['site']['hubzilla']['RED_VERSION'];
1240 $network = Protocol::DIASPORA;
1243 if (isset($data['site']['redmatrix'])) {
1244 if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
1245 $platform = $data['site']['redmatrix']['PLATFORM_NAME'];
1246 } elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
1247 $platform = $data['site']['redmatrix']['RED_PLATFORM'];
1250 $version = $data['site']['redmatrix']['RED_VERSION'];
1251 $network = Protocol::DIASPORA;
1254 if (isset($data['site']['friendica'])) {
1255 $platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
1256 $version = $data['site']['friendica']['FRIENDICA_VERSION'];
1257 $network = Protocol::DFRN;
1260 $site_name = $data['site']['name'];
1263 $inviteonly = false;
1266 if (!empty($data['site']['closed'])) {
1267 $closed = self::toBoolean($data['site']['closed']);
1270 if (!empty($data['site']['private'])) {
1271 $private = self::toBoolean($data['site']['private']);
1274 if (!empty($data['site']['inviteonly'])) {
1275 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1278 if (!$closed && !$private and $inviteonly) {
1279 $register_policy = REGISTER_APPROVE;
1280 } elseif (!$closed && !$private) {
1281 $register_policy = REGISTER_OPEN;
1283 $register_policy = REGISTER_CLOSED;
1290 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1292 $curlResult = Network::curl($server_url . "/statistics.json");
1294 if ($curlResult->isSuccess()) {
1295 $data = json_decode($curlResult->getBody(), true);
1297 if (isset($data['version'])) {
1298 $version = $data['version'];
1299 // Version numbers on statistics.json are presented with additional info, e.g.:
1300 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1301 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1304 if (!empty($data['name'])) {
1305 $site_name = $data['name'];
1308 if (!empty($data['network'])) {
1309 $platform = $data['network'];
1312 if ($platform == "Diaspora") {
1313 $network = Protocol::DIASPORA;
1316 if (!empty($data['registrations_open']) && $data['registrations_open']) {
1317 $register_policy = REGISTER_OPEN;
1319 $register_policy = REGISTER_CLOSED;
1324 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1326 $server = self::fetchNodeinfo($server_url);
1328 if (!empty($server)) {
1329 $register_policy = $server['register_policy'];
1331 if (isset($server['platform'])) {
1332 $platform = $server['platform'];
1335 if (isset($server['network'])) {
1336 $network = $server['network'];
1339 if (isset($server['version'])) {
1340 $version = $server['version'];
1343 if (isset($server['site_name'])) {
1344 $site_name = $server['site_name'];
1347 if (isset($server['registered-users'])) {
1348 $registered_users = $server['registered-users'];
1353 // Check for noscrape
1354 // Friendica servers could be detected as OStatus servers
1355 if (!$failure && in_array($network, [Protocol::DFRN, Protocol::OSTATUS])) {
1356 $curlResult = Network::curl($server_url . "/friendica/json");
1358 if (!$curlResult->isSuccess()) {
1359 $curlResult = Network::curl($server_url . "/friendika/json");
1362 if ($curlResult->isSuccess()) {
1363 $data = json_decode($curlResult->getBody(), true);
1365 if (isset($data['version'])) {
1366 $network = Protocol::DFRN;
1368 if (!empty($data['no_scrape_url'])) {
1369 $noscrape = $data['no_scrape_url'];
1372 $version = $data['version'];
1374 if (!empty($data['site_name'])) {
1375 $site_name = $data['site_name'];
1378 $info = $data['info'];
1379 if (in_array($data['register_policy'], ['REGISTER_CLOSED', 'REGISTER_APPROVE', 'REGISTER_OPEN'])) {
1380 $register_policy = constant($data['register_policy']);
1382 Logger::log("Register policy '{$data['register_policy']}' from $server_url is invalid.");
1383 $register_policy = REGISTER_CLOSED; // set a default value
1385 $platform = $data['platform'];
1390 // Every server has got at least an admin account
1391 if (!$failure && ($registered_users == 0)) {
1392 $registered_users = 1;
1395 if ($possible_failure && !$failure) {
1400 $last_contact = $orig_last_contact;
1401 $last_failure = DateTimeFormat::utcNow();
1403 $last_contact = DateTimeFormat::utcNow();
1404 $last_failure = $orig_last_failure;
1407 if (($last_contact <= $last_failure) && !$failure) {
1408 Logger::log("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", Logger::DEBUG);
1409 } elseif (($last_contact >= $last_failure) && $failure) {
1410 Logger::log("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", Logger::DEBUG);
1413 // Check again if the server exists
1414 $found = DBA::exists('gserver', ['nurl' => Strings::normaliseLink($server_url)]);
1416 $version = strip_tags($version);
1417 $site_name = strip_tags($site_name);
1418 $info = strip_tags($info);
1419 $platform = strip_tags($platform);
1421 $fields = ['url' => $server_url, 'version' => $version,
1422 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1423 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1424 'platform' => $platform, 'registered-users' => $registered_users,
1425 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1428 DBA::update('gserver', $fields, ['nurl' => Strings::normaliseLink($server_url)]);
1429 } elseif (!$failure) {
1430 $fields['nurl'] = Strings::normaliseLink($server_url);
1431 $fields['created'] = DateTimeFormat::utcNow();
1432 DBA::insert('gserver', $fields);
1435 if (!$failure && in_array($fields['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1436 self::discoverRelay($server_url);
1439 Logger::log("End discovery for server " . $server_url, Logger::DEBUG);
1445 * @brief Fetch relay data from a given server url
1447 * @param string $server_url address of the server
1449 private static function discoverRelay($server_url)
1451 Logger::log("Discover relay data for server " . $server_url, Logger::DEBUG);
1453 $curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
1455 if (!$curlResult->isSuccess()) {
1459 $data = json_decode($curlResult->getBody(), true);
1461 if (!is_array($data)) {
1465 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
1467 if (!DBA::isResult($gserver)) {
1471 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
1472 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
1473 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1476 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1478 if ($data['scope'] == 'tags') {
1481 foreach ($data['tags'] as $tag) {
1482 $tag = mb_strtolower($tag);
1483 if (strlen($tag) < 100) {
1488 foreach ($tags as $tag) {
1489 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1493 // Create or update the relay contact
1495 if (isset($data['protocols'])) {
1496 if (isset($data['protocols']['diaspora'])) {
1497 $fields['network'] = Protocol::DIASPORA;
1499 if (isset($data['protocols']['diaspora']['receive'])) {
1500 $fields['batch'] = $data['protocols']['diaspora']['receive'];
1501 } elseif (is_string($data['protocols']['diaspora'])) {
1502 $fields['batch'] = $data['protocols']['diaspora'];
1506 if (isset($data['protocols']['dfrn'])) {
1507 $fields['network'] = Protocol::DFRN;
1509 if (isset($data['protocols']['dfrn']['receive'])) {
1510 $fields['batch'] = $data['protocols']['dfrn']['receive'];
1511 } elseif (is_string($data['protocols']['dfrn'])) {
1512 $fields['batch'] = $data['protocols']['dfrn'];
1516 Diaspora::setRelayContact($server_url, $fields);
1520 * @brief Returns a list of all known servers
1521 * @return array List of server urls
1523 public static function serverlist()
1526 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1527 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1528 ORDER BY `last_contact`
1530 DBA::escape(Protocol::DFRN),
1531 DBA::escape(Protocol::DIASPORA),
1532 DBA::escape(Protocol::OSTATUS)
1535 if (!DBA::isResult($r)) {
1543 * @brief Fetch server list from remote servers and adds them when they are new.
1545 * @param string $poco URL to the POCO endpoint
1547 private static function fetchServerlist($poco)
1549 $curlResult = Network::curl($poco . "/@server");
1551 if (!$curlResult->isSuccess()) {
1555 $serverlist = json_decode($curlResult->getBody(), true);
1557 if (!is_array($serverlist)) {
1561 foreach ($serverlist as $server) {
1562 $server_url = str_replace("/index.php", "", $server['url']);
1564 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(Strings::normaliseLink($server_url)));
1566 if (!DBA::isResult($r)) {
1567 Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
1568 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1573 private static function discoverFederation()
1575 $last = Config::get('poco', 'last_federation_discovery');
1578 $next = $last + (24 * 60 * 60);
1580 if ($next > time()) {
1585 // Discover Friendica, Hubzilla and Diaspora servers
1586 $curlResult = Network::fetchUrl("http://the-federation.info/pods.json");
1588 if (!empty($curlResult)) {
1589 $servers = json_decode($curlResult, true);
1591 if (!empty($servers['pods'])) {
1592 foreach ($servers['pods'] as $server) {
1593 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://" . $server['host']);
1598 // Disvover Mastodon servers
1599 if (!Config::get('system', 'ostatus_disabled')) {
1600 $accesstoken = Config::get('system', 'instances_social_key');
1602 if (!empty($accesstoken)) {
1603 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1604 $header = ['Authorization: Bearer '.$accesstoken];
1605 $curlResult = Network::curl($api, false, $redirects, ['headers' => $header]);
1607 if ($curlResult->isSuccess()) {
1608 $servers = json_decode($curlResult->getBody(), true);
1610 foreach ($servers['instances'] as $server) {
1611 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1612 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1618 // Currently disabled, since the service isn't available anymore.
1619 // It is not removed since I hope that there will be a successor.
1620 // Discover GNU Social Servers.
1621 //if (!Config::get('system','ostatus_disabled')) {
1622 // $serverdata = "http://gstools.org/api/get_open_instances/";
1624 // $curlResult = Network::curl($serverdata);
1625 // if ($curlResult->isSuccess()) {
1626 // $servers = json_decode($result->getBody(), true);
1628 // foreach($servers['data'] as $server)
1629 // self::checkServer($server['instance_address']);
1633 Config::set('poco', 'last_federation_discovery', time());
1636 public static function discoverSingleServer($id)
1638 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1640 if (!DBA::isResult($r)) {
1646 // Discover new servers out there (Works from Friendica version 3.5.2)
1647 self::fetchServerlist($server["poco"]);
1649 // Fetch all users from the other server
1650 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1652 Logger::log("Fetch all users from the server " . $server["url"], Logger::DEBUG);
1654 $curlResult = Network::curl($url);
1656 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1657 $data = json_decode($curlResult->getBody(), true);
1659 if (!empty($data)) {
1660 self::discoverServer($data, 2);
1663 if (Config::get('system', 'poco_discovery') > 1) {
1664 $timeframe = Config::get('system', 'poco_discovery_since');
1666 if ($timeframe == 0) {
1670 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1672 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1673 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1677 $curlResult = Network::curl($url);
1679 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1680 Logger::log("Fetch all global contacts from the server " . $server["nurl"], Logger::DEBUG);
1681 $data = json_decode($curlResult->getBody(), true);
1683 if (!empty($data)) {
1684 $success = self::discoverServer($data);
1688 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1689 Logger::log("Fetch contacts from users of the server " . $server["nurl"], Logger::DEBUG);
1690 self::discoverServerUsers($data, $server);
1694 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1695 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1699 // If the server hadn't replied correctly, then force a sanity check
1700 self::checkServer($server["url"], $server["network"], true);
1702 // If we couldn't reach the server, we will try it some time later
1703 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1704 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1710 public static function discover($complete = false)
1712 // Update the server list
1713 self::discoverFederation();
1717 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1719 if ($requery_days == 0) {
1723 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1725 $gservers = q("SELECT `id`, `url`, `nurl`, `network`
1727 WHERE `last_contact` >= `last_failure`
1729 AND `last_poco_query` < '%s'
1730 ORDER BY RAND()", DBA::escape($last_update)
1733 if (DBA::isResult($gservers)) {
1734 foreach ($gservers as $gserver) {
1735 if (!self::checkServer($gserver['url'], $gserver['network'])) {
1736 // The server is not reachable? Okay, then we will try it later
1737 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1738 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1742 Logger::log('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], Logger::DEBUG);
1743 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
1745 if (!$complete && ( --$no_of_queries == 0)) {
1752 private static function discoverServerUsers(array $data, array $server)
1754 if (!isset($data['entry'])) {
1758 foreach ($data['entry'] as $entry) {
1761 if (isset($entry['urls'])) {
1762 foreach ($entry['urls'] as $url) {
1763 if ($url['type'] == 'profile') {
1764 $profile_url = $url['value'];
1765 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1766 $username = end($path_array);
1771 if ($username != '') {
1772 Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
1774 // Fetch all contacts from a given user from the other server
1775 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1777 $curlResult = Network::curl($url);
1779 if ($curlResult->isSuccess()) {
1780 $data = json_decode($curlResult["body"], true);
1782 if (!empty($data)) {
1783 self::discoverServer($data, 3);
1790 private static function discoverServer(array $data, $default_generation = 0)
1792 if (empty($data['entry'])) {
1798 foreach ($data['entry'] as $entry) {
1800 $profile_photo = '';
1804 $updated = DBA::NULL_DATETIME;
1810 $generation = $default_generation;
1812 if (!empty($entry['displayName'])) {
1813 $name = $entry['displayName'];
1816 if (isset($entry['urls'])) {
1817 foreach ($entry['urls'] as $url) {
1818 if ($url['type'] == 'profile') {
1819 $profile_url = $url['value'];
1822 if ($url['type'] == 'webfinger') {
1823 $connect_url = str_replace('acct:' , '', $url['value']);
1829 if (isset($entry['photos'])) {
1830 foreach ($entry['photos'] as $photo) {
1831 if ($photo['type'] == 'profile') {
1832 $profile_photo = $photo['value'];
1838 if (isset($entry['updated'])) {
1839 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
1842 if (isset($entry['network'])) {
1843 $network = $entry['network'];
1846 if (isset($entry['currentLocation'])) {
1847 $location = $entry['currentLocation'];
1850 if (isset($entry['aboutMe'])) {
1851 $about = HTML::toBBCode($entry['aboutMe']);
1854 if (isset($entry['gender'])) {
1855 $gender = $entry['gender'];
1858 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
1859 $generation = ++$entry['generation'];
1862 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
1863 $contact_type = $entry['contactType'];
1866 if (isset($entry['tags'])) {
1867 foreach ($entry['tags'] as $tag) {
1868 $keywords = implode(", ", $tag);
1872 if ($generation > 0) {
1875 Logger::log("Store profile ".$profile_url, Logger::DEBUG);
1877 $gcontact = ["url" => $profile_url,
1879 "network" => $network,
1880 "photo" => $profile_photo,
1882 "location" => $location,
1883 "gender" => $gender,
1884 "keywords" => $keywords,
1885 "connect" => $connect_url,
1886 "updated" => $updated,
1887 "contact-type" => $contact_type,
1888 "generation" => $generation];
1891 $gcontact = GContact::sanitize($gcontact);
1892 GContact::update($gcontact);
1893 } catch (Exception $e) {
1894 Logger::log($e->getMessage(), Logger::DEBUG);
1897 Logger::log("Done for profile ".$profile_url, Logger::DEBUG);