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\Worker;
18 use Friendica\Database\dba;
19 use Friendica\Database\DBM;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Profile;
22 use Friendica\Network\Probe;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use Friendica\Util\XML;
27 require_once 'include/dba.php';
32 * @brief Fetch POCO data
34 * @param integer $cid Contact ID
35 * @param integer $uid User ID
36 * @param integer $zcid Global Contact ID
37 * @param integer $url POCO address that should be polled
39 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
40 * and add the entries to the gcontact (Global Contact) table, or update existing entries
41 * if anything (name or photo) has changed.
42 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
44 * Once the global contact is stored add (if necessary) the contact linkage which associates
45 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
46 * pointing to the same global contact id.
49 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
51 // Call the function "load" via the worker
52 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
56 * @brief Fetch POCO data from the worker
58 * @param integer $cid Contact ID
59 * @param integer $uid User ID
60 * @param integer $zcid Global Contact ID
61 * @param integer $url POCO address that should be polled
64 public static function load($cid, $uid, $zcid, $url)
70 $contact = dba::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
71 if (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 if (!empty($entry->displayName)) {
124 $name = $entry->displayName;
127 if (isset($entry->urls)) {
128 foreach ($entry->urls as $url) {
129 if ($url->type == 'profile') {
130 $profile_url = $url->value;
133 if ($url->type == 'webfinger') {
134 $connect_url = str_replace('acct:', '', $url->value);
139 if (isset($entry->photos)) {
140 foreach ($entry->photos as $photo) {
141 if ($photo->type == 'profile') {
142 $profile_photo = $photo->value;
148 if (isset($entry->updated)) {
149 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
152 if (isset($entry->network)) {
153 $network = $entry->network;
156 if (isset($entry->currentLocation)) {
157 $location = $entry->currentLocation;
160 if (isset($entry->aboutMe)) {
161 $about = HTML::toBBCode($entry->aboutMe);
164 if (isset($entry->gender)) {
165 $gender = $entry->gender;
168 if (isset($entry->generation) && ($entry->generation > 0)) {
169 $generation = ++$entry->generation;
172 if (isset($entry->tags)) {
173 foreach ($entry->tags as $tag) {
174 $keywords = implode(", ", $tag);
178 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
179 $contact_type = $entry->contactType;
182 $gcontact = ["url" => $profile_url,
184 "network" => $network,
185 "photo" => $profile_photo,
187 "location" => $location,
189 "keywords" => $keywords,
190 "connect" => $connect_url,
191 "updated" => $updated,
192 "contact-type" => $contact_type,
193 "generation" => $generation];
196 $gcontact = GContact::sanitize($gcontact);
197 $gcid = GContact::update($gcontact);
199 GContact::link($gcid, $uid, $cid, $zcid);
200 } catch (Exception $e) {
201 logger($e->getMessage(), LOGGER_DEBUG);
204 logger("load: loaded $total entries", LOGGER_DEBUG);
206 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
207 dba::delete('glink', $condition);
210 public static function reachable($profile, $server = "", $network = "", $force = false)
213 $server = self::detectServer($profile);
220 return self::checkServer($server, $network, $force);
223 public static function detectServer($profile)
225 // Try to detect the server path based upon some known standard paths
228 if ($server_url == "") {
229 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
230 if ($friendica != $profile) {
231 $server_url = $friendica;
232 $network = NETWORK_DFRN;
236 if ($server_url == "") {
237 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
238 if ($diaspora != $profile) {
239 $server_url = $diaspora;
240 $network = NETWORK_DIASPORA;
244 if ($server_url == "") {
245 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
246 if ($red != $profile) {
248 $network = NETWORK_DIASPORA;
253 if ($server_url == "") {
254 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
255 if ($mastodon != $profile) {
256 $server_url = $mastodon;
257 $network = NETWORK_OSTATUS;
261 // Numeric OStatus variant
262 if ($server_url == "") {
263 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
264 if ($ostatus != $profile) {
265 $server_url = $ostatus;
266 $network = NETWORK_OSTATUS;
271 if ($server_url == "") {
272 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
273 if ($base != $profile) {
275 $network = NETWORK_PHANTOM;
279 if ($server_url == "") {
284 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
285 dbesc(normalise_link($server_url))
288 if (DBM::is_result($r)) {
292 // Fetch the host-meta to check if this really is a server
293 $serverret = Network::curl($server_url."/.well-known/host-meta");
294 if (!$serverret["success"]) {
301 public static function alternateOStatusUrl($url)
303 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
306 public static function lastUpdated($profile, $force = false)
309 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
310 dbesc(normalise_link($profile))
313 if (!DBM::is_result($gcontacts)) {
317 $contact = ["url" => $profile];
319 if ($gcontacts[0]["created"] <= NULL_DATE) {
320 $contact['created'] = DateTimeFormat::utcNow();
325 $server_url = normalise_link(self::detectServer($profile));
328 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
329 $server_url = $gcontacts[0]["server_url"];
332 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
333 $server_url = normalise_link(self::detectServer($profile));
336 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
337 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
341 if ($server_url != "") {
342 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
344 $fields = ['last_failure' => DateTimeFormat::utcNow()];
345 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
348 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
351 $contact['server_url'] = $server_url;
354 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
356 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
357 dbesc(normalise_link($server_url))
361 $contact['network'] = $server[0]["network"];
367 // noscrape is really fast so we don't cache the call.
368 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
369 // Use noscrape if possible
370 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
373 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
375 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
376 $noscrape = json_decode($noscraperet["body"], true);
378 if (is_array($noscrape)) {
379 $contact["network"] = $server[0]["network"];
381 if (isset($noscrape["fn"])) {
382 $contact["name"] = $noscrape["fn"];
384 if (isset($noscrape["comm"])) {
385 $contact["community"] = $noscrape["comm"];
387 if (isset($noscrape["tags"])) {
388 $keywords = implode(" ", $noscrape["tags"]);
389 if ($keywords != "") {
390 $contact["keywords"] = $keywords;
394 $location = Profile::formatLocation($noscrape);
396 $contact["location"] = $location;
398 if (isset($noscrape["dfrn-notify"])) {
399 $contact["notify"] = $noscrape["dfrn-notify"];
401 // Remove all fields that are not present in the gcontact table
402 unset($noscrape["fn"]);
403 unset($noscrape["key"]);
404 unset($noscrape["homepage"]);
405 unset($noscrape["comm"]);
406 unset($noscrape["tags"]);
407 unset($noscrape["locality"]);
408 unset($noscrape["region"]);
409 unset($noscrape["country-name"]);
410 unset($noscrape["contacts"]);
411 unset($noscrape["dfrn-request"]);
412 unset($noscrape["dfrn-confirm"]);
413 unset($noscrape["dfrn-notify"]);
414 unset($noscrape["dfrn-poll"]);
416 // Set the date of the last contact
417 /// @todo By now the function "update_gcontact" doesn't work with this field
418 //$contact["last_contact"] = DateTimeFormat::utcNow();
420 $contact = array_merge($contact, $noscrape);
422 GContact::update($contact);
424 if (!empty($noscrape["updated"])) {
425 $fields = ['last_contact' => DateTimeFormat::utcNow()];
426 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
428 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
430 return $noscrape["updated"];
437 // If we only can poll the feed, then we only do this once a while
438 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
439 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
441 GContact::update($contact);
442 return $gcontacts[0]["updated"];
445 $data = Probe::uri($profile);
447 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
448 // Then check the other link and delete this one
449 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
450 && (normalise_link($profile) == normalise_link($data["alias"]))
451 && (normalise_link($profile) != normalise_link($data["url"]))
453 // Delete the old entry
454 dba::delete('gcontact', ['nurl' => normalise_link($profile)]);
456 $gcontact = array_merge($gcontacts[0], $data);
458 $gcontact["server_url"] = $data["baseurl"];
461 $gcontact = GContact::sanitize($gcontact);
462 GContact::update($gcontact);
464 self::lastUpdated($data["url"], $force);
465 } catch (Exception $e) {
466 logger($e->getMessage(), LOGGER_DEBUG);
469 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
473 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
474 $fields = ['last_failure' => DateTimeFormat::utcNow()];
475 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
477 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
481 $contact = array_merge($contact, $data);
483 $contact["server_url"] = $data["baseurl"];
485 GContact::update($contact);
487 $feedret = Network::curl($data["poll"]);
489 if (!$feedret["success"]) {
490 $fields = ['last_failure' => DateTimeFormat::utcNow()];
491 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
493 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
497 $doc = new DOMDocument();
498 @$doc->loadXML($feedret["body"]);
500 $xpath = new DOMXPath($doc);
501 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
503 $entries = $xpath->query('/atom:feed/atom:entry');
507 foreach ($entries as $entry) {
508 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
509 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
511 if ($last_updated < $published) {
512 $last_updated = $published;
515 if ($last_updated < $updated) {
516 $last_updated = $updated;
520 // Maybe there aren't any entries. Then check if it is a valid feed
521 if ($last_updated == "") {
522 if ($xpath->query('/atom:feed')->length > 0) {
523 $last_updated = NULL_DATE;
527 $fields = ['last_contact' => DateTimeFormat::utcNow()];
529 if (!empty($last_updated)) {
530 $fields['updated'] = $last_updated;
533 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
535 if (($gcontacts[0]["generation"] == 0)) {
536 $fields = ['generation' => 9];
537 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
540 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
542 return $last_updated;
545 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
547 $now = strtotime(DateTimeFormat::utcNow());
549 if ($updated > $last_contact) {
550 $contact_time = strtotime($updated);
552 $contact_time = strtotime($last_contact);
555 $failure_time = strtotime($last_failure);
556 $created_time = strtotime($created);
558 // If there is no "created" time then use the current time
559 if ($created_time <= 0) {
560 $created_time = $now;
563 // If the last contact was less than 24 hours then don't update
564 if (($now - $contact_time) < (60 * 60 * 24)) {
568 // If the last failure was less than 24 hours then don't update
569 if (($now - $failure_time) < (60 * 60 * 24)) {
573 // If the last contact was less than a week ago and the last failure is older than a week then don't update
574 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
577 // 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
578 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
582 // 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
583 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
590 private static function toBoolean($val)
592 if (($val == "true") || ($val == 1)) {
594 } elseif (($val == "false") || ($val == 0)) {
602 * @brief Detect server type (Hubzilla or Friendica) via the poco data
604 * @param object $data POCO data
605 * @return array Server data
607 private static function detectPocoData($data)
611 if (!isset($data->entry)) {
615 if (count($data->entry) == 0) {
619 if (!isset($data->entry[0]->urls)) {
623 if (count($data->entry[0]->urls) == 0) {
627 foreach ($data->entry[0]->urls as $url) {
628 if ($url->type == 'zot') {
630 $server["platform"] = 'Hubzilla';
631 $server["network"] = NETWORK_DIASPORA;
639 * @brief Detect server type by using the nodeinfo data
641 * @param string $server_url address of the server
642 * @return array Server data
644 private static function fetchNodeinfo($server_url)
646 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
647 if (!$serverret["success"]) {
651 $nodeinfo = json_decode($serverret['body']);
653 if (!is_object($nodeinfo)) {
657 if (!is_array($nodeinfo->links)) {
664 foreach ($nodeinfo->links as $link) {
665 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
666 $nodeinfo1_url = $link->href;
668 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
669 $nodeinfo2_url = $link->href;
673 if ($nodeinfo1_url . $nodeinfo2_url == '') {
679 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
680 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
681 $server = self::parseNodeinfo2($nodeinfo2_url);
684 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
685 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
686 $server = self::parseNodeinfo1($nodeinfo1_url);
693 * @brief Parses Nodeinfo 1
695 * @param string $nodeinfo_url address of the nodeinfo path
696 * @return array Server data
698 private static function parseNodeinfo1($nodeinfo_url)
700 $serverret = Network::curl($nodeinfo_url);
701 if (!$serverret["success"]) {
705 $nodeinfo = json_decode($serverret['body']);
706 if (!is_object($nodeinfo)) {
712 $server['register_policy'] = REGISTER_CLOSED;
714 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
715 $server['register_policy'] = REGISTER_OPEN;
718 if (is_object($nodeinfo->software)) {
719 if (isset($nodeinfo->software->name)) {
720 $server['platform'] = $nodeinfo->software->name;
723 if (isset($nodeinfo->software->version)) {
724 $server['version'] = $nodeinfo->software->version;
725 // Version numbers on Nodeinfo are presented with additional info, e.g.:
726 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
727 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
731 if (is_object($nodeinfo->metadata)) {
732 if (isset($nodeinfo->metadata->nodeName)) {
733 $server['site_name'] = $nodeinfo->metadata->nodeName;
737 if (!empty($nodeinfo->usage->users->total)) {
738 $server['registered-users'] = $nodeinfo->usage->users->total;
745 if (is_array($nodeinfo->protocols->inbound)) {
746 foreach ($nodeinfo->protocols->inbound as $inbound) {
747 if ($inbound == 'diaspora') {
750 if ($inbound == 'friendica') {
753 if ($inbound == 'gnusocial') {
760 $server['network'] = NETWORK_OSTATUS;
763 $server['network'] = NETWORK_DIASPORA;
766 $server['network'] = NETWORK_DFRN;
777 * @brief Parses Nodeinfo 2
779 * @param string $nodeinfo_url address of the nodeinfo path
780 * @return array Server data
782 private static function parseNodeinfo2($nodeinfo_url)
784 $serverret = Network::curl($nodeinfo_url);
785 if (!$serverret["success"]) {
789 $nodeinfo = json_decode($serverret['body']);
790 if (!is_object($nodeinfo)) {
796 $server['register_policy'] = REGISTER_CLOSED;
798 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
799 $server['register_policy'] = REGISTER_OPEN;
802 if (is_object($nodeinfo->software)) {
803 if (isset($nodeinfo->software->name)) {
804 $server['platform'] = $nodeinfo->software->name;
807 if (isset($nodeinfo->software->version)) {
808 $server['version'] = $nodeinfo->software->version;
809 // Version numbers on Nodeinfo are presented with additional info, e.g.:
810 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
811 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
815 if (is_object($nodeinfo->metadata)) {
816 if (isset($nodeinfo->metadata->nodeName)) {
817 $server['site_name'] = $nodeinfo->metadata->nodeName;
821 if (!empty($nodeinfo->usage->users->total)) {
822 $server['registered-users'] = $nodeinfo->usage->users->total;
829 if (is_array($nodeinfo->protocols)) {
830 foreach ($nodeinfo->protocols as $protocol) {
831 if ($protocol == 'diaspora') {
834 if ($protocol == 'friendica') {
837 if ($protocol == 'gnusocial') {
844 $server['network'] = NETWORK_OSTATUS;
847 $server['network'] = NETWORK_DIASPORA;
850 $server['network'] = NETWORK_DFRN;
861 * @brief Detect server type (Hubzilla or Friendica) via the front page body
863 * @param string $body Front page of the server
864 * @return array Server data
866 private static function detectServerType($body)
870 $doc = new DOMDocument();
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"] = NETWORK_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"] = NETWORK_DIASPORA;
919 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
923 public static function checkServer($server_url, $network = "", $force = false)
925 // Unify the server address
926 $server_url = trim($server_url, "/");
927 $server_url = str_replace("/index.php", "", $server_url);
929 if ($server_url == "") {
933 $gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
934 if (DBM::is_result($gserver)) {
935 if ($gserver["created"] <= NULL_DATE) {
936 $fields = ['created' => DateTimeFormat::utcNow()];
937 $condition = ['nurl' => normalise_link($server_url)];
938 dba::update('gserver', $fields, $condition);
940 $poco = $gserver["poco"];
941 $noscrape = $gserver["noscrape"];
943 if ($network == "") {
944 $network = $gserver["network"];
947 $last_contact = $gserver["last_contact"];
948 $last_failure = $gserver["last_failure"];
949 $version = $gserver["version"];
950 $platform = $gserver["platform"];
951 $site_name = $gserver["site_name"];
952 $info = $gserver["info"];
953 $register_policy = $gserver["register_policy"];
954 $registered_users = $gserver["registered-users"];
956 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
957 // It can happen that a zero date is in the database, but storing it again is forbidden.
958 if ($last_contact < NULL_DATE) {
959 $last_contact = NULL_DATE;
961 if ($last_failure < NULL_DATE) {
962 $last_failure = NULL_DATE;
965 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
966 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
967 return ($last_contact >= $last_failure);
976 $register_policy = -1;
977 $registered_users = 0;
979 $last_contact = NULL_DATE;
980 $last_failure = NULL_DATE;
982 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
985 $possible_failure = false;
986 $orig_last_failure = $last_failure;
987 $orig_last_contact = $last_contact;
989 // Mastodon uses the "@" for user profiles.
990 // But this can be misunderstood.
991 if (parse_url($server_url, PHP_URL_USER) != '') {
992 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
996 // Check if the page is accessible via SSL.
997 $orig_server_url = $server_url;
998 $server_url = str_replace("http://", "https://", $server_url);
1000 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1001 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1003 // Quit if there is a timeout.
1004 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1005 if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
1006 (!$serverret["success"] && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT))) {
1007 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1008 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1012 // Maybe the page is unencrypted only?
1013 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1014 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1015 $server_url = str_replace("https://", "http://", $server_url);
1017 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1018 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1020 // Quit if there is a timeout
1021 if (!$serverret["success"] && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1022 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1023 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1027 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1030 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1031 // Workaround for bad configured servers (known nginx problem)
1032 if (!empty($serverret["debug"]) && !in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1035 $possible_failure = true;
1038 // If the server has no possible failure we reset the cached data
1039 if (!$possible_failure) {
1044 $register_policy = -1;
1048 // This will be too low, but better than no value at all.
1049 $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
1054 $serverret = Network::curl($server_url."/poco");
1055 if ($serverret["success"]) {
1056 $data = json_decode($serverret["body"]);
1057 if (isset($data->totalResults)) {
1058 $registered_users = $data->totalResults;
1059 $poco = $server_url."/poco";
1060 $server = self::detectPocoData($data);
1062 $platform = $server['platform'];
1063 $network = $server['network'];
1068 // There are servers out there who don't return 404 on a failure
1069 // We have to be sure that don't misunderstand this
1070 if (is_null($data)) {
1079 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1080 $serverret = Network::curl($server_url);
1082 if (!$serverret["success"] || ($serverret["body"] == "")) {
1085 $server = self::detectServerType($serverret["body"]);
1087 $platform = $server['platform'];
1088 $network = $server['network'];
1089 $version = $server['version'];
1090 $site_name = $server['site_name'];
1093 $lines = explode("\n", $serverret["header"]);
1094 if (count($lines)) {
1095 foreach ($lines as $line) {
1096 $line = trim($line);
1097 if (stristr($line, 'X-Diaspora-Version:')) {
1098 $platform = "Diaspora";
1099 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1100 $version = trim(str_replace("x-diaspora-version:", "", $version));
1101 $network = NETWORK_DIASPORA;
1102 $versionparts = explode("-", $version);
1103 $version = $versionparts[0];
1106 if (stristr($line, 'Server: Mastodon')) {
1107 $platform = "Mastodon";
1108 $network = NETWORK_OSTATUS;
1115 if (!$failure && ($poco == "")) {
1116 // Test for Statusnet
1117 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1118 // The "not implemented" is a special treatment for really, really old Friendica versions
1119 $serverret = Network::curl($server_url."/api/statusnet/version.json");
1120 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1121 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1122 $platform = "StatusNet";
1123 // Remove junk that some GNU Social servers return
1124 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1125 $version = trim($version, '"');
1126 $network = NETWORK_OSTATUS;
1129 // Test for GNU Social
1130 $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1131 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1132 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1133 $platform = "GNU Social";
1134 // Remove junk that some GNU Social servers return
1135 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1136 $version = trim($version, '"');
1137 $network = NETWORK_OSTATUS;
1140 // Test for Mastodon
1141 $orig_version = $version;
1142 $serverret = Network::curl($server_url."/api/v1/instance");
1143 if ($serverret["success"] && ($serverret["body"] != '')) {
1144 $data = json_decode($serverret["body"]);
1146 if (isset($data->version)) {
1147 $platform = "Mastodon";
1148 $version = $data->version;
1149 $site_name = $data->title;
1150 $info = $data->description;
1151 $network = NETWORK_OSTATUS;
1153 if (!empty($data->stats->user_count)) {
1154 $registered_users = $data->stats->user_count;
1157 if (strstr($orig_version.$version, 'Pleroma')) {
1158 $platform = 'Pleroma';
1159 $version = trim(str_replace('Pleroma', '', $version));
1164 // Test for Hubzilla and Red
1165 $serverret = Network::curl($server_url."/siteinfo.json");
1166 if ($serverret["success"]) {
1167 $data = json_decode($serverret["body"]);
1168 if (isset($data->url)) {
1169 $platform = $data->platform;
1170 $version = $data->version;
1171 $network = NETWORK_DIASPORA;
1173 if (!empty($data->site_name)) {
1174 $site_name = $data->site_name;
1176 if (!empty($data->channels_total)) {
1177 $registered_users = $data->channels_total;
1179 if (!empty($data->register_policy)) {
1180 switch ($data->register_policy) {
1181 case "REGISTER_OPEN":
1182 $register_policy = REGISTER_OPEN;
1184 case "REGISTER_APPROVE":
1185 $register_policy = REGISTER_APPROVE;
1187 case "REGISTER_CLOSED":
1189 $register_policy = REGISTER_CLOSED;
1194 // Test for Hubzilla, Redmatrix or Friendica
1195 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1196 if ($serverret["success"]) {
1197 $data = json_decode($serverret["body"]);
1198 if (isset($data->site->server)) {
1199 if (isset($data->site->platform)) {
1200 $platform = $data->site->platform->PLATFORM_NAME;
1201 $version = $data->site->platform->STD_VERSION;
1202 $network = NETWORK_DIASPORA;
1204 if (isset($data->site->BlaBlaNet)) {
1205 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1206 $version = $data->site->BlaBlaNet->STD_VERSION;
1207 $network = NETWORK_DIASPORA;
1209 if (isset($data->site->hubzilla)) {
1210 $platform = $data->site->hubzilla->PLATFORM_NAME;
1211 $version = $data->site->hubzilla->RED_VERSION;
1212 $network = NETWORK_DIASPORA;
1214 if (isset($data->site->redmatrix)) {
1215 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1216 $platform = $data->site->redmatrix->PLATFORM_NAME;
1217 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1218 $platform = $data->site->redmatrix->RED_PLATFORM;
1221 $version = $data->site->redmatrix->RED_VERSION;
1222 $network = NETWORK_DIASPORA;
1224 if (isset($data->site->friendica)) {
1225 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1226 $version = $data->site->friendica->FRIENDICA_VERSION;
1227 $network = NETWORK_DFRN;
1230 $site_name = $data->site->name;
1232 $data->site->closed = self::toBoolean($data->site->closed);
1234 if (!empty($data->site->private)) {
1235 $data->site->private = self::toBoolean($data->site->private);
1238 if (!empty($data->site->inviteonly)) {
1239 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1242 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1243 $register_policy = REGISTER_APPROVE;
1244 } elseif (!$data->site->closed && !$data->site->private) {
1245 $register_policy = REGISTER_OPEN;
1247 $register_policy = REGISTER_CLOSED;
1254 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1256 $serverret = Network::curl($server_url."/statistics.json");
1257 if ($serverret["success"]) {
1258 $data = json_decode($serverret["body"]);
1260 if (isset($data->version)) {
1261 $version = $data->version;
1262 // Version numbers on statistics.json are presented with additional info, e.g.:
1263 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1264 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1267 if (!empty($data->name)) {
1268 $site_name = $data->name;
1271 if (!empty($data->network)) {
1272 $platform = $data->network;
1275 if ($platform == "Diaspora") {
1276 $network = NETWORK_DIASPORA;
1279 if (!empty($data->registrations_open) && $data->registrations_open) {
1280 $register_policy = REGISTER_OPEN;
1282 $register_policy = REGISTER_CLOSED;
1287 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1289 $server = self::fetchNodeinfo($server_url);
1291 $register_policy = $server['register_policy'];
1293 if (isset($server['platform'])) {
1294 $platform = $server['platform'];
1297 if (isset($server['network'])) {
1298 $network = $server['network'];
1301 if (isset($server['version'])) {
1302 $version = $server['version'];
1305 if (isset($server['site_name'])) {
1306 $site_name = $server['site_name'];
1309 if (isset($server['registered-users'])) {
1310 $registered_users = $server['registered-users'];
1315 // Check for noscrape
1316 // Friendica servers could be detected as OStatus servers
1317 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1318 $serverret = Network::curl($server_url."/friendica/json");
1320 if (!$serverret["success"]) {
1321 $serverret = Network::curl($server_url."/friendika/json");
1324 if ($serverret["success"]) {
1325 $data = json_decode($serverret["body"]);
1327 if (isset($data->version)) {
1328 $network = NETWORK_DFRN;
1330 if (!empty($data->no_scrape_url)) {
1331 $noscrape = $data->no_scrape_url;
1333 $version = $data->version;
1334 if (!empty($data->site_name)) {
1335 $site_name = $data->site_name;
1337 $info = $data->info;
1338 $register_policy = constant($data->register_policy);
1339 $platform = $data->platform;
1344 // Every server has got at least an admin account
1345 if (!$failure && ($registered_users == 0)) {
1346 $registered_users = 1;
1349 if ($possible_failure && !$failure) {
1354 $last_contact = $orig_last_contact;
1355 $last_failure = DateTimeFormat::utcNow();
1357 $last_contact = DateTimeFormat::utcNow();
1358 $last_failure = $orig_last_failure;
1361 if (($last_contact <= $last_failure) && !$failure) {
1362 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1363 } elseif (($last_contact >= $last_failure) && $failure) {
1364 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1367 // Check again if the server exists
1368 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1370 $version = strip_tags($version);
1371 $site_name = strip_tags($site_name);
1372 $info = strip_tags($info);
1373 $platform = strip_tags($platform);
1375 $fields = ['url' => $server_url, 'version' => $version,
1376 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1377 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1378 'platform' => $platform, 'registered-users' => $registered_users,
1379 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1382 dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1383 } elseif (!$failure) {
1384 $fields['nurl'] = normalise_link($server_url);
1385 $fields['created'] = DateTimeFormat::utcNow();
1386 dba::insert('gserver', $fields);
1389 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1390 self::discoverRelay($server_url);
1393 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1399 * @brief Fetch relay data from a given server url
1401 * @param string $server_url address of the server
1403 private static function discoverRelay($server_url)
1405 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1407 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1408 if (!$serverret["success"]) {
1412 $data = json_decode($serverret['body']);
1413 if (!is_object($data)) {
1417 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1418 if (!DBM::is_result($gserver)) {
1422 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1423 $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1424 dba::update('gserver', $fields, ['id' => $gserver['id']]);
1427 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1428 if ($data->scope == 'tags') {
1431 foreach ($data->tags as $tag) {
1432 $tag = mb_strtolower($tag);
1436 foreach ($tags as $tag) {
1437 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1441 // Create or update the relay contact
1443 if (isset($data->protocols)) {
1444 if (isset($data->protocols->diaspora)) {
1445 $fields['network'] = NETWORK_DIASPORA;
1446 if (isset($data->protocols->diaspora->receive)) {
1447 $fields['batch'] = $data->protocols->diaspora->receive;
1448 } elseif (is_string($data->protocols->diaspora)) {
1449 $fields['batch'] = $data->protocols->diaspora;
1452 if (isset($data->protocols->dfrn)) {
1453 $fields['network'] = NETWORK_DFRN;
1454 if (isset($data->protocols->dfrn->receive)) {
1455 $fields['batch'] = $data->protocols->dfrn->receive;
1456 } elseif (is_string($data->protocols->dfrn)) {
1457 $fields['batch'] = $data->protocols->dfrn;
1461 Diaspora::setRelayContact($server_url, $fields);
1465 * @brief Returns a list of all known servers
1466 * @return array List of server urls
1468 public static function serverlist()
1471 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1472 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1473 ORDER BY `last_contact`
1475 dbesc(NETWORK_DFRN),
1476 dbesc(NETWORK_DIASPORA),
1477 dbesc(NETWORK_OSTATUS)
1480 if (!DBM::is_result($r)) {
1488 * @brief Fetch server list from remote servers and adds them when they are new.
1490 * @param string $poco URL to the POCO endpoint
1492 private static function fetchServerlist($poco)
1494 $serverret = Network::curl($poco."/@server");
1495 if (!$serverret["success"]) {
1498 $serverlist = json_decode($serverret['body']);
1500 if (!is_array($serverlist)) {
1504 foreach ($serverlist as $server) {
1505 $server_url = str_replace("/index.php", "", $server->url);
1507 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1508 if (!DBM::is_result($r)) {
1509 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1510 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1515 private static function discoverFederation()
1517 $last = Config::get('poco', 'last_federation_discovery');
1520 $next = $last + (24 * 60 * 60);
1521 if ($next > time()) {
1526 // Discover Friendica, Hubzilla and Diaspora servers
1527 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1530 $servers = json_decode($serverdata);
1532 if (!empty($servers->pods)) {
1533 foreach ($servers->pods as $server) {
1534 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1539 // Disvover Mastodon servers
1540 if (!Config::get('system', 'ostatus_disabled')) {
1541 $accesstoken = Config::get('system', 'instances_social_key');
1542 if (!empty($accesstoken)) {
1543 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1544 $header = ['Authorization: Bearer '.$accesstoken];
1545 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1546 if ($serverdata['success']) {
1547 $servers = json_decode($serverdata['body']);
1548 foreach ($servers->instances as $server) {
1549 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1550 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1556 // Currently disabled, since the service isn't available anymore.
1557 // It is not removed since I hope that there will be a successor.
1558 // Discover GNU Social Servers.
1559 //if (!Config::get('system','ostatus_disabled')) {
1560 // $serverdata = "http://gstools.org/api/get_open_instances/";
1562 // $result = Network::curl($serverdata);
1563 // if ($result["success"]) {
1564 // $servers = json_decode($result["body"]);
1566 // foreach($servers->data as $server)
1567 // self::checkServer($server->instance_address);
1571 Config::set('poco', 'last_federation_discovery', time());
1574 public static function discoverSingleServer($id)
1576 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1577 if (!DBM::is_result($r)) {
1583 // Discover new servers out there (Works from Friendica version 3.5.2)
1584 self::fetchServerlist($server["poco"]);
1586 // Fetch all users from the other server
1587 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1589 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1591 $retdata = Network::curl($url);
1592 if ($retdata["success"]) {
1593 $data = json_decode($retdata["body"]);
1595 self::discoverServer($data, 2);
1597 if (Config::get('system', 'poco_discovery') > 1) {
1598 $timeframe = Config::get('system', 'poco_discovery_since');
1599 if ($timeframe == 0) {
1603 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1605 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1606 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1610 $retdata = Network::curl($url);
1611 if ($retdata["success"]) {
1612 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1613 $success = self::discoverServer(json_decode($retdata["body"]));
1616 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1617 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1618 self::discoverServerUsers($data, $server);
1622 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1623 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1627 // If the server hadn't replied correctly, then force a sanity check
1628 self::checkServer($server["url"], $server["network"], true);
1630 // If we couldn't reach the server, we will try it some time later
1631 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1632 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1638 public static function discover($complete = false)
1640 // Update the server list
1641 self::discoverFederation();
1645 $requery_days = intval(Config::get("system", "poco_requery_days"));
1647 if ($requery_days == 0) {
1650 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1652 $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));
1653 if (DBM::is_result($r)) {
1654 foreach ($r as $server) {
1655 if (!self::checkServer($server["url"], $server["network"])) {
1656 // The server is not reachable? Okay, then we will try it later
1657 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1658 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1662 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1663 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1665 if (!$complete && (--$no_of_queries == 0)) {
1672 private static function discoverServerUsers($data, $server)
1674 if (!isset($data->entry)) {
1678 foreach ($data->entry as $entry) {
1680 if (isset($entry->urls)) {
1681 foreach ($entry->urls as $url) {
1682 if ($url->type == 'profile') {
1683 $profile_url = $url->value;
1684 $urlparts = parse_url($profile_url);
1685 $username = end(explode("/", $urlparts["path"]));
1689 if ($username != "") {
1690 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1692 // Fetch all contacts from a given user from the other server
1693 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1695 $retdata = Network::curl($url);
1696 if ($retdata["success"]) {
1697 self::discoverServer(json_decode($retdata["body"]), 3);
1703 private static function discoverServer($data, $default_generation = 0)
1705 if (!isset($data->entry) || !count($data->entry)) {
1711 foreach ($data->entry as $entry) {
1713 $profile_photo = '';
1717 $updated = NULL_DATE;
1723 $generation = $default_generation;
1725 if (!empty($entry->displayName)) {
1726 $name = $entry->displayName;
1729 if (isset($entry->urls)) {
1730 foreach ($entry->urls as $url) {
1731 if ($url->type == 'profile') {
1732 $profile_url = $url->value;
1735 if ($url->type == 'webfinger') {
1736 $connect_url = str_replace('acct:' , '', $url->value);
1742 if (isset($entry->photos)) {
1743 foreach ($entry->photos as $photo) {
1744 if ($photo->type == 'profile') {
1745 $profile_photo = $photo->value;
1751 if (isset($entry->updated)) {
1752 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1755 if (isset($entry->network)) {
1756 $network = $entry->network;
1759 if (isset($entry->currentLocation)) {
1760 $location = $entry->currentLocation;
1763 if (isset($entry->aboutMe)) {
1764 $about = HTML::toBBCode($entry->aboutMe);
1767 if (isset($entry->gender)) {
1768 $gender = $entry->gender;
1771 if (isset($entry->generation) && ($entry->generation > 0)) {
1772 $generation = ++$entry->generation;
1775 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1776 $contact_type = $entry->contactType;
1779 if (isset($entry->tags)) {
1780 foreach ($entry->tags as $tag) {
1781 $keywords = implode(", ", $tag);
1785 if ($generation > 0) {
1788 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1790 $gcontact = ["url" => $profile_url,
1792 "network" => $network,
1793 "photo" => $profile_photo,
1795 "location" => $location,
1796 "gender" => $gender,
1797 "keywords" => $keywords,
1798 "connect" => $connect_url,
1799 "updated" => $updated,
1800 "contact-type" => $contact_type,
1801 "generation" => $generation];
1804 $gcontact = GContact::sanitize($gcontact);
1805 GContact::update($gcontact);
1806 } catch (Exception $e) {
1807 logger($e->getMessage(), LOGGER_DEBUG);
1810 logger("Done for profile ".$profile_url, LOGGER_DEBUG);