3 * @file src/Protocol/PortableContact.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 namespace Friendica\Protocol;
12 use Friendica\Content\Text\HTML;
13 use Friendica\Core\Config;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Profile;
18 use Friendica\Network\Probe;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Protocol\Diaspora;
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 (DBM::is_result($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 $s = Network::fetchUrl($url);
91 logger('load: returns ' . $s, LOGGER_DATA);
93 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
95 if (($a->get_curl_code() > 299) || (! $s)) {
101 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
103 if (! isset($j->entry)) {
108 foreach ($j->entry as $entry) {
115 $updated = NULL_DATE;
123 $name = $entry->displayName;
125 if (isset($entry->urls)) {
126 foreach ($entry->urls as $url) {
127 if ($url->type == 'profile') {
128 $profile_url = $url->value;
131 if ($url->type == 'webfinger') {
132 $connect_url = str_replace('acct:', '', $url->value);
137 if (isset($entry->photos)) {
138 foreach ($entry->photos as $photo) {
139 if ($photo->type == 'profile') {
140 $profile_photo = $photo->value;
146 if (isset($entry->updated)) {
147 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
150 if (isset($entry->network)) {
151 $network = $entry->network;
154 if (isset($entry->currentLocation)) {
155 $location = $entry->currentLocation;
158 if (isset($entry->aboutMe)) {
159 $about = HTML::toBBCode($entry->aboutMe);
162 if (isset($entry->gender)) {
163 $gender = $entry->gender;
166 if (isset($entry->generation) && ($entry->generation > 0)) {
167 $generation = ++$entry->generation;
170 if (isset($entry->tags)) {
171 foreach ($entry->tags as $tag) {
172 $keywords = implode(", ", $tag);
176 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
177 $contact_type = $entry->contactType;
180 $gcontact = ["url" => $profile_url,
182 "network" => $network,
183 "photo" => $profile_photo,
185 "location" => $location,
187 "keywords" => $keywords,
188 "connect" => $connect_url,
189 "updated" => $updated,
190 "contact-type" => $contact_type,
191 "generation" => $generation];
194 $gcontact = GContact::sanitize($gcontact);
195 $gcid = GContact::update($gcontact);
197 GContact::link($gcid, $uid, $cid, $zcid);
198 } catch (Exception $e) {
199 logger($e->getMessage(), LOGGER_DEBUG);
202 logger("load: loaded $total entries", LOGGER_DEBUG);
204 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
205 dba::delete('glink', $condition);
208 public static function reachable($profile, $server = "", $network = "", $force = false)
211 $server = self::detectServer($profile);
218 return self::checkServer($server, $network, $force);
221 public static function detectServer($profile)
223 // Try to detect the server path based upon some known standard paths
226 if ($server_url == "") {
227 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
228 if ($friendica != $profile) {
229 $server_url = $friendica;
230 $network = NETWORK_DFRN;
234 if ($server_url == "") {
235 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
236 if ($diaspora != $profile) {
237 $server_url = $diaspora;
238 $network = NETWORK_DIASPORA;
242 if ($server_url == "") {
243 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
244 if ($red != $profile) {
246 $network = NETWORK_DIASPORA;
251 if ($server_url == "") {
252 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
253 if ($mastodon != $profile) {
254 $server_url = $mastodon;
255 $network = NETWORK_OSTATUS;
259 // Numeric OStatus variant
260 if ($server_url == "") {
261 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
262 if ($ostatus != $profile) {
263 $server_url = $ostatus;
264 $network = NETWORK_OSTATUS;
269 if ($server_url == "") {
270 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
271 if ($base != $profile) {
273 $network = NETWORK_PHANTOM;
277 if ($server_url == "") {
282 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
283 dbesc(normalise_link($server_url))
286 if (DBM::is_result($r)) {
290 // Fetch the host-meta to check if this really is a server
291 $serverret = Network::curl($server_url."/.well-known/host-meta");
292 if (!$serverret["success"]) {
299 public static function alternateOStatusUrl($url)
301 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
304 public static function lastUpdated($profile, $force = false)
307 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
308 dbesc(normalise_link($profile))
311 if (!DBM::is_result($gcontacts)) {
315 $contact = ["url" => $profile];
317 if ($gcontacts[0]["created"] <= NULL_DATE) {
318 $contact['created'] = DateTimeFormat::utcNow();
323 $server_url = normalise_link(self::detectServer($profile));
326 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
327 $server_url = $gcontacts[0]["server_url"];
330 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
331 $server_url = normalise_link(self::detectServer($profile));
334 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
335 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
339 if ($server_url != "") {
340 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
342 $fields = ['last_failure' => DateTimeFormat::utcNow()];
343 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
346 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
349 $contact['server_url'] = $server_url;
352 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
354 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
355 dbesc(normalise_link($server_url))
359 $contact['network'] = $server[0]["network"];
365 // noscrape is really fast so we don't cache the call.
366 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
367 // Use noscrape if possible
368 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
371 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
373 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
374 $noscrape = json_decode($noscraperet["body"], true);
376 if (is_array($noscrape)) {
377 $contact["network"] = $server[0]["network"];
379 if (isset($noscrape["fn"])) {
380 $contact["name"] = $noscrape["fn"];
382 if (isset($noscrape["comm"])) {
383 $contact["community"] = $noscrape["comm"];
385 if (isset($noscrape["tags"])) {
386 $keywords = implode(" ", $noscrape["tags"]);
387 if ($keywords != "") {
388 $contact["keywords"] = $keywords;
392 $location = Profile::formatLocation($noscrape);
394 $contact["location"] = $location;
396 if (isset($noscrape["dfrn-notify"])) {
397 $contact["notify"] = $noscrape["dfrn-notify"];
399 // Remove all fields that are not present in the gcontact table
400 unset($noscrape["fn"]);
401 unset($noscrape["key"]);
402 unset($noscrape["homepage"]);
403 unset($noscrape["comm"]);
404 unset($noscrape["tags"]);
405 unset($noscrape["locality"]);
406 unset($noscrape["region"]);
407 unset($noscrape["country-name"]);
408 unset($noscrape["contacts"]);
409 unset($noscrape["dfrn-request"]);
410 unset($noscrape["dfrn-confirm"]);
411 unset($noscrape["dfrn-notify"]);
412 unset($noscrape["dfrn-poll"]);
414 // Set the date of the last contact
415 /// @todo By now the function "update_gcontact" doesn't work with this field
416 //$contact["last_contact"] = DateTimeFormat::utcNow();
418 $contact = array_merge($contact, $noscrape);
420 GContact::update($contact);
422 if (trim($noscrape["updated"]) != "") {
423 $fields = ['last_contact' => DateTimeFormat::utcNow()];
424 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
426 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
428 return $noscrape["updated"];
435 // If we only can poll the feed, then we only do this once a while
436 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
437 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
439 GContact::update($contact);
440 return $gcontacts[0]["updated"];
443 $data = Probe::uri($profile);
445 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
446 // Then check the other link and delete this one
447 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
448 && (normalise_link($profile) == normalise_link($data["alias"]))
449 && (normalise_link($profile) != normalise_link($data["url"]))
451 // Delete the old entry
452 dba::delete('gcontact', ['nurl' => normalise_link($profile)]);
454 $gcontact = array_merge($gcontacts[0], $data);
456 $gcontact["server_url"] = $data["baseurl"];
459 $gcontact = GContact::sanitize($gcontact);
460 GContact::update($gcontact);
462 self::lastUpdated($data["url"], $force);
463 } catch (Exception $e) {
464 logger($e->getMessage(), LOGGER_DEBUG);
467 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
471 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
472 $fields = ['last_failure' => DateTimeFormat::utcNow()];
473 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
475 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
479 $contact = array_merge($contact, $data);
481 $contact["server_url"] = $data["baseurl"];
483 GContact::update($contact);
485 $feedret = Network::curl($data["poll"]);
487 if (!$feedret["success"]) {
488 $fields = ['last_failure' => DateTimeFormat::utcNow()];
489 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
491 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
495 $doc = new DOMDocument();
496 @$doc->loadXML($feedret["body"]);
498 $xpath = new DOMXPath($doc);
499 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
501 $entries = $xpath->query('/atom:feed/atom:entry');
505 foreach ($entries as $entry) {
506 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
507 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
509 if ($last_updated < $published) {
510 $last_updated = $published;
513 if ($last_updated < $updated) {
514 $last_updated = $updated;
518 // Maybe there aren't any entries. Then check if it is a valid feed
519 if ($last_updated == "") {
520 if ($xpath->query('/atom:feed')->length > 0) {
521 $last_updated = NULL_DATE;
525 $fields = ['updated' => $last_updated, 'last_contact' => DateTimeFormat::utcNow()];
526 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
528 if (($gcontacts[0]["generation"] == 0)) {
529 $fields = ['generation' => 9];
530 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
533 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
535 return $last_updated;
538 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
540 $now = strtotime(DateTimeFormat::utcNow());
542 if ($updated > $last_contact) {
543 $contact_time = strtotime($updated);
545 $contact_time = strtotime($last_contact);
548 $failure_time = strtotime($last_failure);
549 $created_time = strtotime($created);
551 // If there is no "created" time then use the current time
552 if ($created_time <= 0) {
553 $created_time = $now;
556 // If the last contact was less than 24 hours then don't update
557 if (($now - $contact_time) < (60 * 60 * 24)) {
561 // If the last failure was less than 24 hours then don't update
562 if (($now - $failure_time) < (60 * 60 * 24)) {
566 // If the last contact was less than a week ago and the last failure is older than a week then don't update
567 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
570 // 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
571 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
575 // 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
576 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
583 private static function toBoolean($val)
585 if (($val == "true") || ($val == 1)) {
587 } elseif (($val == "false") || ($val == 0)) {
595 * @brief Detect server type (Hubzilla or Friendica) via the poco data
597 * @param object $data POCO data
598 * @return array Server data
600 private static function detectPocoData($data)
604 if (!isset($data->entry)) {
608 if (count($data->entry) == 0) {
612 if (!isset($data->entry[0]->urls)) {
616 if (count($data->entry[0]->urls) == 0) {
620 foreach ($data->entry[0]->urls as $url) {
621 if ($url->type == 'zot') {
623 $server["platform"] = 'Hubzilla';
624 $server["network"] = NETWORK_DIASPORA;
632 * @brief Detect server type by using the nodeinfo data
634 * @param string $server_url address of the server
635 * @return array Server data
637 private static function fetchNodeinfo($server_url)
639 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
640 if (!$serverret["success"]) {
644 $nodeinfo = json_decode($serverret['body']);
646 if (!is_object($nodeinfo)) {
650 if (!is_array($nodeinfo->links)) {
657 foreach ($nodeinfo->links as $link) {
658 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
659 $nodeinfo1_url = $link->href;
661 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
662 $nodeinfo2_url = $link->href;
666 if ($nodeinfo1_url . $nodeinfo2_url == '') {
672 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
673 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
674 $server = self::parseNodeinfo2($nodeinfo2_url);
677 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
678 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
679 $server = self::parseNodeinfo1($nodeinfo1_url);
686 * @brief Parses Nodeinfo 1
688 * @param string $nodeinfo_url address of the nodeinfo path
689 * @return array Server data
691 private static function parseNodeinfo1($nodeinfo_url)
693 $serverret = Network::curl($nodeinfo_url);
694 if (!$serverret["success"]) {
698 $nodeinfo = json_decode($serverret['body']);
699 if (!is_object($nodeinfo)) {
705 $server['register_policy'] = REGISTER_CLOSED;
707 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
708 $server['register_policy'] = REGISTER_OPEN;
711 if (is_object($nodeinfo->software)) {
712 if (isset($nodeinfo->software->name)) {
713 $server['platform'] = $nodeinfo->software->name;
716 if (isset($nodeinfo->software->version)) {
717 $server['version'] = $nodeinfo->software->version;
718 // Version numbers on Nodeinfo are presented with additional info, e.g.:
719 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
720 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
724 if (is_object($nodeinfo->metadata)) {
725 if (isset($nodeinfo->metadata->nodeName)) {
726 $server['site_name'] = $nodeinfo->metadata->nodeName;
730 if (!empty($nodeinfo->usage->users->total)) {
731 $server['registered-users'] = $nodeinfo->usage->users->total;
738 if (is_array($nodeinfo->protocols->inbound)) {
739 foreach ($nodeinfo->protocols->inbound as $inbound) {
740 if ($inbound == 'diaspora') {
743 if ($inbound == 'friendica') {
746 if ($inbound == 'gnusocial') {
753 $server['network'] = NETWORK_OSTATUS;
756 $server['network'] = NETWORK_DIASPORA;
759 $server['network'] = NETWORK_DFRN;
770 * @brief Parses Nodeinfo 2
772 * @param string $nodeinfo_url address of the nodeinfo path
773 * @return array Server data
775 private static function parseNodeinfo2($nodeinfo_url)
777 $serverret = Network::curl($nodeinfo_url);
778 if (!$serverret["success"]) {
782 $nodeinfo = json_decode($serverret['body']);
783 if (!is_object($nodeinfo)) {
789 $server['register_policy'] = REGISTER_CLOSED;
791 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
792 $server['register_policy'] = REGISTER_OPEN;
795 if (is_object($nodeinfo->software)) {
796 if (isset($nodeinfo->software->name)) {
797 $server['platform'] = $nodeinfo->software->name;
800 if (isset($nodeinfo->software->version)) {
801 $server['version'] = $nodeinfo->software->version;
802 // Version numbers on Nodeinfo are presented with additional info, e.g.:
803 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
804 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
808 if (is_object($nodeinfo->metadata)) {
809 if (isset($nodeinfo->metadata->nodeName)) {
810 $server['site_name'] = $nodeinfo->metadata->nodeName;
814 if (!empty($nodeinfo->usage->users->total)) {
815 $server['registered-users'] = $nodeinfo->usage->users->total;
822 if (is_array($nodeinfo->protocols)) {
823 foreach ($nodeinfo->protocols as $protocol) {
824 if ($protocol == 'diaspora') {
827 if ($protocol == 'friendica') {
830 if ($protocol == 'gnusocial') {
837 $server['network'] = NETWORK_OSTATUS;
840 $server['network'] = NETWORK_DIASPORA;
843 $server['network'] = NETWORK_DFRN;
854 * @brief Detect server type (Hubzilla or Friendica) via the front page body
856 * @param string $body Front page of the server
857 * @return array Server data
859 private static function detectServerType($body)
863 $doc = new DOMDocument();
864 @$doc->loadHTML($body);
865 $xpath = new DOMXPath($doc);
867 $list = $xpath->query("//meta[@name]");
869 foreach ($list as $node) {
871 if ($node->attributes->length) {
872 foreach ($node->attributes as $attribute) {
873 $attr[$attribute->name] = $attribute->value;
876 if ($attr['name'] == 'generator') {
877 $version_part = explode(" ", $attr['content']);
878 if (count($version_part) == 2) {
879 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
881 $server["platform"] = $version_part[0];
882 $server["version"] = $version_part[1];
883 $server["network"] = NETWORK_DFRN;
890 $list = $xpath->query("//meta[@property]");
892 foreach ($list as $node) {
894 if ($node->attributes->length) {
895 foreach ($node->attributes as $attribute) {
896 $attr[$attribute->name] = $attribute->value;
899 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
901 $server["platform"] = $attr['content'];
902 $server["version"] = "";
903 $server["network"] = NETWORK_DIASPORA;
912 $server["site_name"] = $xpath->evaluate("//head/title/text()")->item(0)->nodeValue;
916 public static function checkServer($server_url, $network = "", $force = false)
918 // Unify the server address
919 $server_url = trim($server_url, "/");
920 $server_url = str_replace("/index.php", "", $server_url);
922 if ($server_url == "") {
926 $gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
927 if (DBM::is_result($gserver)) {
928 if ($gserver["created"] <= NULL_DATE) {
929 $fields = ['created' => DateTimeFormat::utcNow()];
930 $condition = ['nurl' => normalise_link($server_url)];
931 dba::update('gserver', $fields, $condition);
933 $poco = $gserver["poco"];
934 $noscrape = $gserver["noscrape"];
936 if ($network == "") {
937 $network = $gserver["network"];
940 $last_contact = $gserver["last_contact"];
941 $last_failure = $gserver["last_failure"];
942 $version = $gserver["version"];
943 $platform = $gserver["platform"];
944 $site_name = $gserver["site_name"];
945 $info = $gserver["info"];
946 $register_policy = $gserver["register_policy"];
947 $registered_users = $gserver["registered-users"];
949 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
950 // It can happen that a zero date is in the database, but storing it again is forbidden.
951 if ($last_contact < NULL_DATE) {
952 $last_contact = NULL_DATE;
954 if ($last_failure < NULL_DATE) {
955 $last_failure = NULL_DATE;
958 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
959 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
960 return ($last_contact >= $last_failure);
969 $register_policy = -1;
970 $registered_users = 0;
972 $last_contact = NULL_DATE;
973 $last_failure = NULL_DATE;
975 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
978 $possible_failure = false;
979 $orig_last_failure = $last_failure;
980 $orig_last_contact = $last_contact;
982 // Mastodon uses the "@" for user profiles.
983 // But this can be misunderstood.
984 if (parse_url($server_url, PHP_URL_USER) != '') {
985 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
989 // Check if the page is accessible via SSL.
990 $orig_server_url = $server_url;
991 $server_url = str_replace("http://", "https://", $server_url);
993 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
994 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
996 // Quit if there is a timeout.
997 // But we want to make sure to only quit if we are mostly sure that this server url fits.
998 if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
999 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1000 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1001 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1005 // Maybe the page is unencrypted only?
1006 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1007 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1008 $server_url = str_replace("https://", "http://", $server_url);
1010 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1011 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1013 // Quit if there is a timeout
1014 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1015 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1016 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1020 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1023 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1024 // Workaround for bad configured servers (known nginx problem)
1025 if (!in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1028 $possible_failure = true;
1031 // If the server has no possible failure we reset the cached data
1032 if (!$possible_failure) {
1037 $register_policy = -1;
1041 // This will be too low, but better than no value at all.
1042 $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
1047 $serverret = Network::curl($server_url."/poco");
1048 if ($serverret["success"]) {
1049 $data = json_decode($serverret["body"]);
1050 if (isset($data->totalResults)) {
1051 $registered_users = $data->totalResults;
1052 $poco = $server_url."/poco";
1053 $server = self::detectPocoData($data);
1055 $platform = $server['platform'];
1056 $network = $server['network'];
1061 // There are servers out there who don't return 404 on a failure
1062 // We have to be sure that don't misunderstand this
1063 if (is_null($data)) {
1072 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1073 $serverret = Network::curl($server_url);
1075 if (!$serverret["success"] || ($serverret["body"] == "")) {
1078 $server = self::detectServerType($serverret["body"]);
1080 $platform = $server['platform'];
1081 $network = $server['network'];
1082 $version = $server['version'];
1083 $site_name = $server['site_name'];
1086 $lines = explode("\n", $serverret["header"]);
1087 if (count($lines)) {
1088 foreach ($lines as $line) {
1089 $line = trim($line);
1090 if (stristr($line, 'X-Diaspora-Version:')) {
1091 $platform = "Diaspora";
1092 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1093 $version = trim(str_replace("x-diaspora-version:", "", $version));
1094 $network = NETWORK_DIASPORA;
1095 $versionparts = explode("-", $version);
1096 $version = $versionparts[0];
1099 if (stristr($line, 'Server: Mastodon')) {
1100 $platform = "Mastodon";
1101 $network = NETWORK_OSTATUS;
1108 if (!$failure && ($poco == "")) {
1109 // Test for Statusnet
1110 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1111 // The "not implemented" is a special treatment for really, really old Friendica versions
1112 $serverret = Network::curl($server_url."/api/statusnet/version.json");
1113 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1114 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1115 $platform = "StatusNet";
1116 // Remove junk that some GNU Social servers return
1117 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1118 $version = trim($version, '"');
1119 $network = NETWORK_OSTATUS;
1122 // Test for GNU Social
1123 $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1124 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1125 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1126 $platform = "GNU Social";
1127 // Remove junk that some GNU Social servers return
1128 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1129 $version = trim($version, '"');
1130 $network = NETWORK_OSTATUS;
1133 // Test for Mastodon
1134 $orig_version = $version;
1135 $serverret = Network::curl($server_url."/api/v1/instance");
1136 if ($serverret["success"] && ($serverret["body"] != '')) {
1137 $data = json_decode($serverret["body"]);
1139 if (isset($data->version)) {
1140 $platform = "Mastodon";
1141 $version = $data->version;
1142 $site_name = $data->title;
1143 $info = $data->description;
1144 $network = NETWORK_OSTATUS;
1146 if (!empty($data->stats->user_count)) {
1147 $registered_users = $data->stats->user_count;
1150 if (strstr($orig_version.$version, 'Pleroma')) {
1151 $platform = 'Pleroma';
1152 $version = trim(str_replace('Pleroma', '', $version));
1157 // Test for Hubzilla and Red
1158 $serverret = Network::curl($server_url."/siteinfo.json");
1159 if ($serverret["success"]) {
1160 $data = json_decode($serverret["body"]);
1161 if (isset($data->url)) {
1162 $platform = $data->platform;
1163 $version = $data->version;
1164 $network = NETWORK_DIASPORA;
1166 if (!empty($data->site_name)) {
1167 $site_name = $data->site_name;
1169 if (!empty($data->channels_total)) {
1170 $registered_users = $data->channels_total;
1172 switch ($data->register_policy) {
1173 case "REGISTER_OPEN":
1174 $register_policy = REGISTER_OPEN;
1176 case "REGISTER_APPROVE":
1177 $register_policy = REGISTER_APPROVE;
1179 case "REGISTER_CLOSED":
1181 $register_policy = REGISTER_CLOSED;
1185 // Test for Hubzilla, Redmatrix or Friendica
1186 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1187 if ($serverret["success"]) {
1188 $data = json_decode($serverret["body"]);
1189 if (isset($data->site->server)) {
1190 if (isset($data->site->platform)) {
1191 $platform = $data->site->platform->PLATFORM_NAME;
1192 $version = $data->site->platform->STD_VERSION;
1193 $network = NETWORK_DIASPORA;
1195 if (isset($data->site->BlaBlaNet)) {
1196 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1197 $version = $data->site->BlaBlaNet->STD_VERSION;
1198 $network = NETWORK_DIASPORA;
1200 if (isset($data->site->hubzilla)) {
1201 $platform = $data->site->hubzilla->PLATFORM_NAME;
1202 $version = $data->site->hubzilla->RED_VERSION;
1203 $network = NETWORK_DIASPORA;
1205 if (isset($data->site->redmatrix)) {
1206 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1207 $platform = $data->site->redmatrix->PLATFORM_NAME;
1208 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1209 $platform = $data->site->redmatrix->RED_PLATFORM;
1212 $version = $data->site->redmatrix->RED_VERSION;
1213 $network = NETWORK_DIASPORA;
1215 if (isset($data->site->friendica)) {
1216 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1217 $version = $data->site->friendica->FRIENDICA_VERSION;
1218 $network = NETWORK_DFRN;
1221 $site_name = $data->site->name;
1223 $data->site->closed = self::toBoolean($data->site->closed);
1224 $data->site->private = self::toBoolean($data->site->private);
1225 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1227 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1228 $register_policy = REGISTER_APPROVE;
1229 } elseif (!$data->site->closed && !$data->site->private) {
1230 $register_policy = REGISTER_OPEN;
1232 $register_policy = REGISTER_CLOSED;
1239 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1241 $serverret = Network::curl($server_url."/statistics.json");
1242 if ($serverret["success"]) {
1243 $data = json_decode($serverret["body"]);
1245 if (isset($data->version)) {
1246 $version = $data->version;
1247 // Version numbers on statistics.json are presented with additional info, e.g.:
1248 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1249 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1252 if (!empty($data->name)) {
1253 $site_name = $data->name;
1256 if (!empty($data->network)) {
1257 $platform = $data->network;
1260 if ($platform == "Diaspora") {
1261 $network = NETWORK_DIASPORA;
1264 if ($data->registrations_open) {
1265 $register_policy = REGISTER_OPEN;
1267 $register_policy = REGISTER_CLOSED;
1272 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1274 $server = self::fetchNodeinfo($server_url);
1276 $register_policy = $server['register_policy'];
1278 if (isset($server['platform'])) {
1279 $platform = $server['platform'];
1282 if (isset($server['network'])) {
1283 $network = $server['network'];
1286 if (isset($server['version'])) {
1287 $version = $server['version'];
1290 if (isset($server['site_name'])) {
1291 $site_name = $server['site_name'];
1294 if (isset($server['registered-users'])) {
1295 $registered_users = $server['registered-users'];
1300 // Check for noscrape
1301 // Friendica servers could be detected as OStatus servers
1302 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1303 $serverret = Network::curl($server_url."/friendica/json");
1305 if (!$serverret["success"]) {
1306 $serverret = Network::curl($server_url."/friendika/json");
1309 if ($serverret["success"]) {
1310 $data = json_decode($serverret["body"]);
1312 if (isset($data->version)) {
1313 $network = NETWORK_DFRN;
1315 $noscrape = defaults($data->no_scrape_url, '');
1316 $version = $data->version;
1317 $site_name = $data->site_name;
1318 $info = $data->info;
1319 $register_policy_str = $data->register_policy;
1320 $platform = $data->platform;
1322 switch ($register_policy_str) {
1323 case "REGISTER_CLOSED":
1324 $register_policy = REGISTER_CLOSED;
1326 case "REGISTER_APPROVE":
1327 $register_policy = REGISTER_APPROVE;
1329 case "REGISTER_OPEN":
1330 $register_policy = REGISTER_OPEN;
1337 // Every server has got at least an admin account
1338 if (!$failure && ($registered_users == 0)) {
1339 $registered_users = 1;
1342 if ($possible_failure && !$failure) {
1347 $last_contact = $orig_last_contact;
1348 $last_failure = DateTimeFormat::utcNow();
1350 $last_contact = DateTimeFormat::utcNow();
1351 $last_failure = $orig_last_failure;
1354 if (($last_contact <= $last_failure) && !$failure) {
1355 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1356 } elseif (($last_contact >= $last_failure) && $failure) {
1357 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1360 // Check again if the server exists
1361 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1363 $version = strip_tags($version);
1364 $site_name = strip_tags($site_name);
1365 $info = strip_tags($info);
1366 $platform = strip_tags($platform);
1368 $fields = ['url' => $server_url, 'version' => $version,
1369 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1370 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1371 'platform' => $platform, 'registered-users' => $registered_users,
1372 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1375 dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1376 } elseif (!$failure) {
1377 $fields['nurl'] = normalise_link($server_url);
1378 $fields['created'] = DateTimeFormat::utcNow();
1379 dba::insert('gserver', $fields);
1382 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1383 self::discoverRelay($server_url);
1386 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1392 * @brief Fetch relay data from a given server url
1394 * @param string $server_url address of the server
1396 private static function discoverRelay($server_url)
1398 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1400 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1401 if (!$serverret["success"]) {
1405 $data = json_decode($serverret['body']);
1406 if (!is_object($data)) {
1410 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1411 if (!DBM::is_result($gserver)) {
1415 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1416 $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1417 dba::update('gserver', $fields, ['id' => $gserver['id']]);
1420 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1421 if ($data->scope == 'tags') {
1424 foreach ($data->tags as $tag) {
1425 $tag = mb_strtolower($tag);
1429 foreach ($tags as $tag) {
1430 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag]);
1434 // Create or update the relay contact
1436 if (isset($data->protocols)) {
1437 if (isset($data->protocols->diaspora)) {
1438 $fields['network'] = NETWORK_DIASPORA;
1439 if (isset($data->protocols->diaspora->receive)) {
1440 $fields['batch'] = $data->protocols->diaspora->receive;
1441 } elseif (is_string($data->protocols->diaspora)) {
1442 $fields['batch'] = $data->protocols->diaspora;
1445 if (isset($data->protocols->dfrn)) {
1446 $fields['network'] = NETWORK_DFRN;
1447 if (isset($data->protocols->dfrn->receive)) {
1448 $fields['batch'] = $data->protocols->dfrn->receive;
1449 } elseif (is_string($data->protocols->dfrn)) {
1450 $fields['batch'] = $data->protocols->dfrn;
1454 Diaspora::setRelayContact($server_url, $fields);
1458 * @brief Returns a list of all known servers
1459 * @return array List of server urls
1461 public static function serverlist()
1464 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1465 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1466 ORDER BY `last_contact`
1468 dbesc(NETWORK_DFRN),
1469 dbesc(NETWORK_DIASPORA),
1470 dbesc(NETWORK_OSTATUS)
1473 if (!DBM::is_result($r)) {
1481 * @brief Fetch server list from remote servers and adds them when they are new.
1483 * @param string $poco URL to the POCO endpoint
1485 private static function fetchServerlist($poco)
1487 $serverret = Network::curl($poco."/@server");
1488 if (!$serverret["success"]) {
1491 $serverlist = json_decode($serverret['body']);
1493 if (!is_array($serverlist)) {
1497 foreach ($serverlist as $server) {
1498 $server_url = str_replace("/index.php", "", $server->url);
1500 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1501 if (!DBM::is_result($r)) {
1502 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1503 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1508 private static function discoverFederation()
1510 $last = Config::get('poco', 'last_federation_discovery');
1513 $next = $last + (24 * 60 * 60);
1514 if ($next > time()) {
1519 // Discover Friendica, Hubzilla and Diaspora servers
1520 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1523 $servers = json_decode($serverdata);
1525 foreach ($servers->pods as $server) {
1526 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1530 // Disvover Mastodon servers
1531 if (!Config::get('system', 'ostatus_disabled')) {
1532 $accesstoken = Config::get('system', 'instances_social_key');
1533 if (!empty($accesstoken)) {
1534 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1535 $header = ['Authorization: Bearer '.$accesstoken];
1536 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1537 if ($serverdata['success']) {
1538 $servers = json_decode($serverdata['body']);
1539 foreach ($servers->instances as $server) {
1540 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1541 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1547 // Currently disabled, since the service isn't available anymore.
1548 // It is not removed since I hope that there will be a successor.
1549 // Discover GNU Social Servers.
1550 //if (!Config::get('system','ostatus_disabled')) {
1551 // $serverdata = "http://gstools.org/api/get_open_instances/";
1553 // $result = Network::curl($serverdata);
1554 // if ($result["success"]) {
1555 // $servers = json_decode($result["body"]);
1557 // foreach($servers->data as $server)
1558 // self::checkServer($server->instance_address);
1562 Config::set('poco', 'last_federation_discovery', time());
1565 public static function discoverSingleServer($id)
1567 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1568 if (!DBM::is_result($r)) {
1574 // Discover new servers out there (Works from Friendica version 3.5.2)
1575 self::fetchServerlist($server["poco"]);
1577 // Fetch all users from the other server
1578 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1580 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1582 $retdata = Network::curl($url);
1583 if ($retdata["success"]) {
1584 $data = json_decode($retdata["body"]);
1586 self::discoverServer($data, 2);
1588 if (Config::get('system', 'poco_discovery') > 1) {
1589 $timeframe = Config::get('system', 'poco_discovery_since');
1590 if ($timeframe == 0) {
1594 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1596 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1597 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1601 $retdata = Network::curl($url);
1602 if ($retdata["success"]) {
1603 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1604 $success = self::discoverServer(json_decode($retdata["body"]));
1607 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1608 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1609 self::discoverServerUsers($data, $server);
1613 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1614 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1618 // If the server hadn't replied correctly, then force a sanity check
1619 self::checkServer($server["url"], $server["network"], true);
1621 // If we couldn't reach the server, we will try it some time later
1622 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1623 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1629 public static function discover($complete = false)
1631 // Update the server list
1632 self::discoverFederation();
1636 $requery_days = intval(Config::get("system", "poco_requery_days"));
1638 if ($requery_days == 0) {
1641 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1643 $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1644 if (DBM::is_result($r)) {
1645 foreach ($r as $server) {
1646 if (!self::checkServer($server["url"], $server["network"])) {
1647 // The server is not reachable? Okay, then we will try it later
1648 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1649 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1653 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1654 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1656 if (!$complete && (--$no_of_queries == 0)) {
1663 private static function discoverServerUsers($data, $server)
1665 if (!isset($data->entry)) {
1669 foreach ($data->entry as $entry) {
1671 if (isset($entry->urls)) {
1672 foreach ($entry->urls as $url) {
1673 if ($url->type == 'profile') {
1674 $profile_url = $url->value;
1675 $urlparts = parse_url($profile_url);
1676 $username = end(explode("/", $urlparts["path"]));
1680 if ($username != "") {
1681 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1683 // Fetch all contacts from a given user from the other server
1684 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1686 $retdata = Network::curl($url);
1687 if ($retdata["success"]) {
1688 self::discoverServer(json_decode($retdata["body"]), 3);
1694 private static function discoverServer($data, $default_generation = 0)
1696 if (!isset($data->entry) || !count($data->entry)) {
1702 foreach ($data->entry as $entry) {
1704 $profile_photo = '';
1708 $updated = NULL_DATE;
1714 $generation = $default_generation;
1716 $name = $entry->displayName;
1718 if (isset($entry->urls)) {
1719 foreach ($entry->urls as $url) {
1720 if ($url->type == 'profile') {
1721 $profile_url = $url->value;
1724 if ($url->type == 'webfinger') {
1725 $connect_url = str_replace('acct:' , '', $url->value);
1731 if (isset($entry->photos)) {
1732 foreach ($entry->photos as $photo) {
1733 if ($photo->type == 'profile') {
1734 $profile_photo = $photo->value;
1740 if (isset($entry->updated)) {
1741 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1744 if (isset($entry->network)) {
1745 $network = $entry->network;
1748 if (isset($entry->currentLocation)) {
1749 $location = $entry->currentLocation;
1752 if (isset($entry->aboutMe)) {
1753 $about = HTML::toBBCode($entry->aboutMe);
1756 if (isset($entry->gender)) {
1757 $gender = $entry->gender;
1760 if (isset($entry->generation) && ($entry->generation > 0)) {
1761 $generation = ++$entry->generation;
1764 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1765 $contact_type = $entry->contactType;
1768 if (isset($entry->tags)) {
1769 foreach ($entry->tags as $tag) {
1770 $keywords = implode(", ", $tag);
1774 if ($generation > 0) {
1777 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1779 $gcontact = ["url" => $profile_url,
1781 "network" => $network,
1782 "photo" => $profile_photo,
1784 "location" => $location,
1785 "gender" => $gender,
1786 "keywords" => $keywords,
1787 "connect" => $connect_url,
1788 "updated" => $updated,
1789 "contact-type" => $contact_type,
1790 "generation" => $generation];
1793 $gcontact = GContact::sanitize($gcontact);
1794 GContact::update($gcontact);
1795 } catch (Exception $e) {
1796 logger($e->getMessage(), LOGGER_DEBUG);
1799 logger("Done for profile ".$profile_url, LOGGER_DEBUG);