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\Model\GContact;
20 use Friendica\Model\Profile;
21 use Friendica\Network\Probe;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\XML;
26 require_once 'include/dba.php';
31 * @brief Fetch POCO data
33 * @param integer $cid Contact ID
34 * @param integer $uid User ID
35 * @param integer $zcid Global Contact ID
36 * @param integer $url POCO address that should be polled
38 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
39 * and add the entries to the gcontact (Global Contact) table, or update existing entries
40 * if anything (name or photo) has changed.
41 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
43 * Once the global contact is stored add (if necessary) the contact linkage which associates
44 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
45 * pointing to the same global contact id.
48 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
50 // Call the function "load" via the worker
51 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
55 * @brief Fetch POCO data from the worker
57 * @param integer $cid Contact ID
58 * @param integer $uid User ID
59 * @param integer $zcid Global Contact ID
60 * @param integer $url POCO address that should be polled
63 public static function load($cid, $uid, $zcid, $url)
69 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
70 if (DBA::isResult($contact)) {
71 $url = $contact['poco'];
72 $uid = $contact['uid'];
84 $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') ;
86 logger('load: ' . $url, LOGGER_DEBUG);
88 $s = Network::fetchUrl($url);
90 logger('load: returns ' . $s, LOGGER_DATA);
92 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
94 if (($a->get_curl_code() > 299) || (! $s)) {
100 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
102 if (! isset($j->entry)) {
107 foreach ($j->entry as $entry) {
114 $updated = NULL_DATE;
122 if (!empty($entry->displayName)) {
123 $name = $entry->displayName;
126 if (isset($entry->urls)) {
127 foreach ($entry->urls as $url) {
128 if ($url->type == 'profile') {
129 $profile_url = $url->value;
132 if ($url->type == 'webfinger') {
133 $connect_url = str_replace('acct:', '', $url->value);
138 if (isset($entry->photos)) {
139 foreach ($entry->photos as $photo) {
140 if ($photo->type == 'profile') {
141 $profile_photo = $photo->value;
147 if (isset($entry->updated)) {
148 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
151 if (isset($entry->network)) {
152 $network = $entry->network;
155 if (isset($entry->currentLocation)) {
156 $location = $entry->currentLocation;
159 if (isset($entry->aboutMe)) {
160 $about = HTML::toBBCode($entry->aboutMe);
163 if (isset($entry->gender)) {
164 $gender = $entry->gender;
167 if (isset($entry->generation) && ($entry->generation > 0)) {
168 $generation = ++$entry->generation;
171 if (isset($entry->tags)) {
172 foreach ($entry->tags as $tag) {
173 $keywords = implode(", ", $tag);
177 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
178 $contact_type = $entry->contactType;
181 $gcontact = ["url" => $profile_url,
183 "network" => $network,
184 "photo" => $profile_photo,
186 "location" => $location,
188 "keywords" => $keywords,
189 "connect" => $connect_url,
190 "updated" => $updated,
191 "contact-type" => $contact_type,
192 "generation" => $generation];
195 $gcontact = GContact::sanitize($gcontact);
196 $gcid = GContact::update($gcontact);
198 GContact::link($gcid, $uid, $cid, $zcid);
199 } catch (Exception $e) {
200 logger($e->getMessage(), LOGGER_DEBUG);
203 logger("load: loaded $total entries", LOGGER_DEBUG);
205 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
206 DBA::delete('glink', $condition);
209 public static function reachable($profile, $server = "", $network = "", $force = false)
212 $server = self::detectServer($profile);
219 return self::checkServer($server, $network, $force);
222 public static function detectServer($profile)
224 // Try to detect the server path based upon some known standard paths
227 if ($server_url == "") {
228 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
229 if ($friendica != $profile) {
230 $server_url = $friendica;
231 $network = NETWORK_DFRN;
235 if ($server_url == "") {
236 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
237 if ($diaspora != $profile) {
238 $server_url = $diaspora;
239 $network = NETWORK_DIASPORA;
243 if ($server_url == "") {
244 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
245 if ($red != $profile) {
247 $network = NETWORK_DIASPORA;
252 if ($server_url == "") {
253 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
254 if ($mastodon != $profile) {
255 $server_url = $mastodon;
256 $network = NETWORK_OSTATUS;
260 // Numeric OStatus variant
261 if ($server_url == "") {
262 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
263 if ($ostatus != $profile) {
264 $server_url = $ostatus;
265 $network = NETWORK_OSTATUS;
270 if ($server_url == "") {
271 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
272 if ($base != $profile) {
274 $network = NETWORK_PHANTOM;
278 if ($server_url == "") {
283 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
284 DBA::escape(normalise_link($server_url))
287 if (DBA::isResult($r)) {
291 // Fetch the host-meta to check if this really is a server
292 $serverret = Network::curl($server_url."/.well-known/host-meta");
293 if (!$serverret["success"]) {
300 public static function alternateOStatusUrl($url)
302 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
305 public static function lastUpdated($profile, $force = false)
308 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
309 DBA::escape(normalise_link($profile))
312 if (!DBA::isResult($gcontacts)) {
316 $contact = ["url" => $profile];
318 if ($gcontacts[0]["created"] <= NULL_DATE) {
319 $contact['created'] = DateTimeFormat::utcNow();
324 $server_url = normalise_link(self::detectServer($profile));
327 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
328 $server_url = $gcontacts[0]["server_url"];
331 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
332 $server_url = normalise_link(self::detectServer($profile));
335 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
336 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
340 if ($server_url != "") {
341 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
343 $fields = ['last_failure' => DateTimeFormat::utcNow()];
344 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
347 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
350 $contact['server_url'] = $server_url;
353 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
355 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
356 DBA::escape(normalise_link($server_url))
360 $contact['network'] = $server[0]["network"];
366 // noscrape is really fast so we don't cache the call.
367 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
368 // Use noscrape if possible
369 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(normalise_link($server_url)));
372 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
374 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
375 $noscrape = json_decode($noscraperet["body"], true);
377 if (is_array($noscrape)) {
378 $contact["network"] = $server[0]["network"];
380 if (isset($noscrape["fn"])) {
381 $contact["name"] = $noscrape["fn"];
383 if (isset($noscrape["comm"])) {
384 $contact["community"] = $noscrape["comm"];
386 if (isset($noscrape["tags"])) {
387 $keywords = implode(" ", $noscrape["tags"]);
388 if ($keywords != "") {
389 $contact["keywords"] = $keywords;
393 $location = Profile::formatLocation($noscrape);
395 $contact["location"] = $location;
397 if (isset($noscrape["dfrn-notify"])) {
398 $contact["notify"] = $noscrape["dfrn-notify"];
400 // Remove all fields that are not present in the gcontact table
401 unset($noscrape["fn"]);
402 unset($noscrape["key"]);
403 unset($noscrape["homepage"]);
404 unset($noscrape["comm"]);
405 unset($noscrape["tags"]);
406 unset($noscrape["locality"]);
407 unset($noscrape["region"]);
408 unset($noscrape["country-name"]);
409 unset($noscrape["contacts"]);
410 unset($noscrape["dfrn-request"]);
411 unset($noscrape["dfrn-confirm"]);
412 unset($noscrape["dfrn-notify"]);
413 unset($noscrape["dfrn-poll"]);
415 // Set the date of the last contact
416 /// @todo By now the function "update_gcontact" doesn't work with this field
417 //$contact["last_contact"] = DateTimeFormat::utcNow();
419 $contact = array_merge($contact, $noscrape);
421 GContact::update($contact);
423 if (!empty($noscrape["updated"])) {
424 $fields = ['last_contact' => DateTimeFormat::utcNow()];
425 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
427 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
429 return $noscrape["updated"];
436 // If we only can poll the feed, then we only do this once a while
437 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
438 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
440 GContact::update($contact);
441 return $gcontacts[0]["updated"];
444 $data = Probe::uri($profile);
446 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
447 // Then check the other link and delete this one
448 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
449 && (normalise_link($profile) == normalise_link($data["alias"]))
450 && (normalise_link($profile) != normalise_link($data["url"]))
452 // Delete the old entry
453 DBA::delete('gcontact', ['nurl' => normalise_link($profile)]);
455 $gcontact = array_merge($gcontacts[0], $data);
457 $gcontact["server_url"] = $data["baseurl"];
460 $gcontact = GContact::sanitize($gcontact);
461 GContact::update($gcontact);
463 self::lastUpdated($data["url"], $force);
464 } catch (Exception $e) {
465 logger($e->getMessage(), LOGGER_DEBUG);
468 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
472 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
473 $fields = ['last_failure' => DateTimeFormat::utcNow()];
474 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
476 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
480 $contact = array_merge($contact, $data);
482 $contact["server_url"] = $data["baseurl"];
484 GContact::update($contact);
486 $feedret = Network::curl($data["poll"]);
488 if (!$feedret["success"]) {
489 $fields = ['last_failure' => DateTimeFormat::utcNow()];
490 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
492 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
496 $doc = new DOMDocument();
497 @$doc->loadXML($feedret["body"]);
499 $xpath = new DOMXPath($doc);
500 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
502 $entries = $xpath->query('/atom:feed/atom:entry');
506 foreach ($entries as $entry) {
507 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
508 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
510 if ($last_updated < $published) {
511 $last_updated = $published;
514 if ($last_updated < $updated) {
515 $last_updated = $updated;
519 // Maybe there aren't any entries. Then check if it is a valid feed
520 if ($last_updated == "") {
521 if ($xpath->query('/atom:feed')->length > 0) {
522 $last_updated = NULL_DATE;
526 $fields = ['last_contact' => DateTimeFormat::utcNow()];
528 if (!empty($last_updated)) {
529 $fields['updated'] = $last_updated;
532 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
534 if (($gcontacts[0]["generation"] == 0)) {
535 $fields = ['generation' => 9];
536 DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
539 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
541 return $last_updated;
544 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
546 $now = strtotime(DateTimeFormat::utcNow());
548 if ($updated > $last_contact) {
549 $contact_time = strtotime($updated);
551 $contact_time = strtotime($last_contact);
554 $failure_time = strtotime($last_failure);
555 $created_time = strtotime($created);
557 // If there is no "created" time then use the current time
558 if ($created_time <= 0) {
559 $created_time = $now;
562 // If the last contact was less than 24 hours then don't update
563 if (($now - $contact_time) < (60 * 60 * 24)) {
567 // If the last failure was less than 24 hours then don't update
568 if (($now - $failure_time) < (60 * 60 * 24)) {
572 // If the last contact was less than a week ago and the last failure is older than a week then don't update
573 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
576 // 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
577 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
581 // 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
582 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
589 private static function toBoolean($val)
591 if (($val == "true") || ($val == 1)) {
593 } elseif (($val == "false") || ($val == 0)) {
601 * @brief Detect server type (Hubzilla or Friendica) via the poco data
603 * @param object $data POCO data
604 * @return array Server data
606 private static function detectPocoData($data)
610 if (!isset($data->entry)) {
614 if (count($data->entry) == 0) {
618 if (!isset($data->entry[0]->urls)) {
622 if (count($data->entry[0]->urls) == 0) {
626 foreach ($data->entry[0]->urls as $url) {
627 if ($url->type == 'zot') {
629 $server["platform"] = 'Hubzilla';
630 $server["network"] = NETWORK_DIASPORA;
638 * @brief Detect server type by using the nodeinfo data
640 * @param string $server_url address of the server
641 * @return array Server data
643 private static function fetchNodeinfo($server_url)
645 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
646 if (!$serverret["success"]) {
650 $nodeinfo = json_decode($serverret['body']);
652 if (!is_object($nodeinfo)) {
656 if (!is_array($nodeinfo->links)) {
663 foreach ($nodeinfo->links as $link) {
664 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
665 $nodeinfo1_url = $link->href;
667 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
668 $nodeinfo2_url = $link->href;
672 if ($nodeinfo1_url . $nodeinfo2_url == '') {
678 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
679 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
680 $server = self::parseNodeinfo2($nodeinfo2_url);
683 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
684 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
685 $server = self::parseNodeinfo1($nodeinfo1_url);
692 * @brief Parses Nodeinfo 1
694 * @param string $nodeinfo_url address of the nodeinfo path
695 * @return array Server data
697 private static function parseNodeinfo1($nodeinfo_url)
699 $serverret = Network::curl($nodeinfo_url);
700 if (!$serverret["success"]) {
704 $nodeinfo = json_decode($serverret['body']);
705 if (!is_object($nodeinfo)) {
711 $server['register_policy'] = REGISTER_CLOSED;
713 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
714 $server['register_policy'] = REGISTER_OPEN;
717 if (is_object($nodeinfo->software)) {
718 if (isset($nodeinfo->software->name)) {
719 $server['platform'] = $nodeinfo->software->name;
722 if (isset($nodeinfo->software->version)) {
723 $server['version'] = $nodeinfo->software->version;
724 // Version numbers on Nodeinfo are presented with additional info, e.g.:
725 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
726 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
730 if (is_object($nodeinfo->metadata)) {
731 if (isset($nodeinfo->metadata->nodeName)) {
732 $server['site_name'] = $nodeinfo->metadata->nodeName;
736 if (!empty($nodeinfo->usage->users->total)) {
737 $server['registered-users'] = $nodeinfo->usage->users->total;
744 if (is_array($nodeinfo->protocols->inbound)) {
745 foreach ($nodeinfo->protocols->inbound as $inbound) {
746 if ($inbound == 'diaspora') {
749 if ($inbound == 'friendica') {
752 if ($inbound == 'gnusocial') {
759 $server['network'] = NETWORK_OSTATUS;
762 $server['network'] = NETWORK_DIASPORA;
765 $server['network'] = NETWORK_DFRN;
776 * @brief Parses Nodeinfo 2
778 * @param string $nodeinfo_url address of the nodeinfo path
779 * @return array Server data
781 private static function parseNodeinfo2($nodeinfo_url)
783 $serverret = Network::curl($nodeinfo_url);
784 if (!$serverret["success"]) {
788 $nodeinfo = json_decode($serverret['body']);
789 if (!is_object($nodeinfo)) {
795 $server['register_policy'] = REGISTER_CLOSED;
797 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
798 $server['register_policy'] = REGISTER_OPEN;
801 if (is_object($nodeinfo->software)) {
802 if (isset($nodeinfo->software->name)) {
803 $server['platform'] = $nodeinfo->software->name;
806 if (isset($nodeinfo->software->version)) {
807 $server['version'] = $nodeinfo->software->version;
808 // Version numbers on Nodeinfo are presented with additional info, e.g.:
809 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
810 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
814 if (is_object($nodeinfo->metadata)) {
815 if (isset($nodeinfo->metadata->nodeName)) {
816 $server['site_name'] = $nodeinfo->metadata->nodeName;
820 if (!empty($nodeinfo->usage->users->total)) {
821 $server['registered-users'] = $nodeinfo->usage->users->total;
828 if (is_array($nodeinfo->protocols)) {
829 foreach ($nodeinfo->protocols as $protocol) {
830 if ($protocol == 'diaspora') {
833 if ($protocol == 'friendica') {
836 if ($protocol == 'gnusocial') {
843 $server['network'] = NETWORK_OSTATUS;
846 $server['network'] = NETWORK_DIASPORA;
849 $server['network'] = NETWORK_DFRN;
860 * @brief Detect server type (Hubzilla or Friendica) via the front page body
862 * @param string $body Front page of the server
863 * @return array Server data
865 private static function detectServerType($body)
869 $doc = new DOMDocument();
870 @$doc->loadHTML($body);
871 $xpath = new DOMXPath($doc);
873 $list = $xpath->query("//meta[@name]");
875 foreach ($list as $node) {
877 if ($node->attributes->length) {
878 foreach ($node->attributes as $attribute) {
879 $attr[$attribute->name] = $attribute->value;
882 if ($attr['name'] == 'generator') {
883 $version_part = explode(" ", $attr['content']);
884 if (count($version_part) == 2) {
885 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
887 $server["platform"] = $version_part[0];
888 $server["version"] = $version_part[1];
889 $server["network"] = NETWORK_DFRN;
896 $list = $xpath->query("//meta[@property]");
898 foreach ($list as $node) {
900 if ($node->attributes->length) {
901 foreach ($node->attributes as $attribute) {
902 $attr[$attribute->name] = $attribute->value;
905 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
907 $server["platform"] = $attr['content'];
908 $server["version"] = "";
909 $server["network"] = NETWORK_DIASPORA;
918 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
922 public static function checkServer($server_url, $network = "", $force = false)
924 // Unify the server address
925 $server_url = trim($server_url, "/");
926 $server_url = str_replace("/index.php", "", $server_url);
928 if ($server_url == "") {
932 $gserver = DBA::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
933 if (DBA::isResult($gserver)) {
934 if ($gserver["created"] <= NULL_DATE) {
935 $fields = ['created' => DateTimeFormat::utcNow()];
936 $condition = ['nurl' => normalise_link($server_url)];
937 DBA::update('gserver', $fields, $condition);
939 $poco = $gserver["poco"];
940 $noscrape = $gserver["noscrape"];
942 if ($network == "") {
943 $network = $gserver["network"];
946 $last_contact = $gserver["last_contact"];
947 $last_failure = $gserver["last_failure"];
948 $version = $gserver["version"];
949 $platform = $gserver["platform"];
950 $site_name = $gserver["site_name"];
951 $info = $gserver["info"];
952 $register_policy = $gserver["register_policy"];
953 $registered_users = $gserver["registered-users"];
955 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
956 // It can happen that a zero date is in the database, but storing it again is forbidden.
957 if ($last_contact < NULL_DATE) {
958 $last_contact = NULL_DATE;
960 if ($last_failure < NULL_DATE) {
961 $last_failure = NULL_DATE;
964 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
965 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
966 return ($last_contact >= $last_failure);
975 $register_policy = -1;
976 $registered_users = 0;
978 $last_contact = NULL_DATE;
979 $last_failure = NULL_DATE;
981 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
984 $possible_failure = false;
985 $orig_last_failure = $last_failure;
986 $orig_last_contact = $last_contact;
988 // Mastodon uses the "@" for user profiles.
989 // But this can be misunderstood.
990 if (parse_url($server_url, PHP_URL_USER) != '') {
991 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
995 // Check if the page is accessible via SSL.
996 $orig_server_url = $server_url;
997 $server_url = str_replace("http://", "https://", $server_url);
999 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1000 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1002 // Quit if there is a timeout.
1003 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1004 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1005 (!empty($serverret["errno"]) && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT))) {
1006 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1007 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1011 // Maybe the page is unencrypted only?
1012 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1013 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1014 $server_url = str_replace("https://", "http://", $server_url);
1016 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1017 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1019 // Quit if there is a timeout
1020 if (!empty($serverret["errno"]) && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1021 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1022 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1026 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1029 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1030 // Workaround for bad configured servers (known nginx problem)
1031 if (!empty($serverret["debug"]) && !in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1034 $possible_failure = true;
1037 // If the server has no possible failure we reset the cached data
1038 if (!$possible_failure) {
1043 $register_policy = -1;
1047 // This will be too low, but better than no value at all.
1048 $registered_users = DBA::count('gcontact', ['server_url' => normalise_link($server_url)]);
1053 $serverret = Network::curl($server_url."/poco");
1054 if ($serverret["success"]) {
1055 $data = json_decode($serverret["body"]);
1056 if (isset($data->totalResults)) {
1057 $registered_users = $data->totalResults;
1058 $poco = $server_url."/poco";
1059 $server = self::detectPocoData($data);
1061 $platform = $server['platform'];
1062 $network = $server['network'];
1067 // There are servers out there who don't return 404 on a failure
1068 // We have to be sure that don't misunderstand this
1069 if (is_null($data)) {
1078 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1079 $serverret = Network::curl($server_url);
1081 if (!$serverret["success"] || ($serverret["body"] == "")) {
1084 $server = self::detectServerType($serverret["body"]);
1086 $platform = $server['platform'];
1087 $network = $server['network'];
1088 $version = $server['version'];
1089 $site_name = $server['site_name'];
1092 $lines = explode("\n", $serverret["header"]);
1093 if (count($lines)) {
1094 foreach ($lines as $line) {
1095 $line = trim($line);
1096 if (stristr($line, 'X-Diaspora-Version:')) {
1097 $platform = "Diaspora";
1098 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1099 $version = trim(str_replace("x-diaspora-version:", "", $version));
1100 $network = NETWORK_DIASPORA;
1101 $versionparts = explode("-", $version);
1102 $version = $versionparts[0];
1105 if (stristr($line, 'Server: Mastodon')) {
1106 $platform = "Mastodon";
1107 $network = NETWORK_OSTATUS;
1114 if (!$failure && ($poco == "")) {
1115 // Test for Statusnet
1116 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1117 // The "not implemented" is a special treatment for really, really old Friendica versions
1118 $serverret = Network::curl($server_url."/api/statusnet/version.json");
1119 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1120 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1121 $platform = "StatusNet";
1122 // Remove junk that some GNU Social servers return
1123 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1124 $version = trim($version, '"');
1125 $network = NETWORK_OSTATUS;
1128 // Test for GNU Social
1129 $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1130 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1131 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1132 $platform = "GNU Social";
1133 // Remove junk that some GNU Social servers return
1134 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1135 $version = trim($version, '"');
1136 $network = NETWORK_OSTATUS;
1139 // Test for Mastodon
1140 $orig_version = $version;
1141 $serverret = Network::curl($server_url."/api/v1/instance");
1142 if ($serverret["success"] && ($serverret["body"] != '')) {
1143 $data = json_decode($serverret["body"]);
1145 if (isset($data->version)) {
1146 $platform = "Mastodon";
1147 $version = $data->version;
1148 $site_name = $data->title;
1149 $info = $data->description;
1150 $network = NETWORK_OSTATUS;
1152 if (!empty($data->stats->user_count)) {
1153 $registered_users = $data->stats->user_count;
1156 if (strstr($orig_version.$version, 'Pleroma')) {
1157 $platform = 'Pleroma';
1158 $version = trim(str_replace('Pleroma', '', $version));
1163 // Test for Hubzilla and Red
1164 $serverret = Network::curl($server_url."/siteinfo.json");
1165 if ($serverret["success"]) {
1166 $data = json_decode($serverret["body"]);
1167 if (isset($data->url)) {
1168 $platform = $data->platform;
1169 $version = $data->version;
1170 $network = NETWORK_DIASPORA;
1172 if (!empty($data->site_name)) {
1173 $site_name = $data->site_name;
1175 if (!empty($data->channels_total)) {
1176 $registered_users = $data->channels_total;
1178 if (!empty($data->register_policy)) {
1179 switch ($data->register_policy) {
1180 case "REGISTER_OPEN":
1181 $register_policy = REGISTER_OPEN;
1183 case "REGISTER_APPROVE":
1184 $register_policy = REGISTER_APPROVE;
1186 case "REGISTER_CLOSED":
1188 $register_policy = REGISTER_CLOSED;
1193 // Test for Hubzilla, Redmatrix or Friendica
1194 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1195 if ($serverret["success"]) {
1196 $data = json_decode($serverret["body"]);
1197 if (isset($data->site->server)) {
1198 if (isset($data->site->platform)) {
1199 $platform = $data->site->platform->PLATFORM_NAME;
1200 $version = $data->site->platform->STD_VERSION;
1201 $network = NETWORK_DIASPORA;
1203 if (isset($data->site->BlaBlaNet)) {
1204 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1205 $version = $data->site->BlaBlaNet->STD_VERSION;
1206 $network = NETWORK_DIASPORA;
1208 if (isset($data->site->hubzilla)) {
1209 $platform = $data->site->hubzilla->PLATFORM_NAME;
1210 $version = $data->site->hubzilla->RED_VERSION;
1211 $network = NETWORK_DIASPORA;
1213 if (isset($data->site->redmatrix)) {
1214 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1215 $platform = $data->site->redmatrix->PLATFORM_NAME;
1216 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1217 $platform = $data->site->redmatrix->RED_PLATFORM;
1220 $version = $data->site->redmatrix->RED_VERSION;
1221 $network = NETWORK_DIASPORA;
1223 if (isset($data->site->friendica)) {
1224 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1225 $version = $data->site->friendica->FRIENDICA_VERSION;
1226 $network = NETWORK_DFRN;
1229 $site_name = $data->site->name;
1232 $inviteonly = false;
1235 if (!empty($data->site->closed)) {
1236 $closed = self::toBoolean($data->site->closed);
1239 if (!empty($data->site->private)) {
1240 $private = self::toBoolean($data->site->private);
1243 if (!empty($data->site->inviteonly)) {
1244 $inviteonly = self::toBoolean($data->site->inviteonly);
1247 if (!$closed && !$private and $inviteonly) {
1248 $register_policy = REGISTER_APPROVE;
1249 } elseif (!$closed && !$private) {
1250 $register_policy = REGISTER_OPEN;
1252 $register_policy = REGISTER_CLOSED;
1259 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1261 $serverret = Network::curl($server_url."/statistics.json");
1262 if ($serverret["success"]) {
1263 $data = json_decode($serverret["body"]);
1265 if (isset($data->version)) {
1266 $version = $data->version;
1267 // Version numbers on statistics.json are presented with additional info, e.g.:
1268 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1269 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1272 if (!empty($data->name)) {
1273 $site_name = $data->name;
1276 if (!empty($data->network)) {
1277 $platform = $data->network;
1280 if ($platform == "Diaspora") {
1281 $network = NETWORK_DIASPORA;
1284 if (!empty($data->registrations_open) && $data->registrations_open) {
1285 $register_policy = REGISTER_OPEN;
1287 $register_policy = REGISTER_CLOSED;
1292 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1294 $server = self::fetchNodeinfo($server_url);
1296 $register_policy = $server['register_policy'];
1298 if (isset($server['platform'])) {
1299 $platform = $server['platform'];
1302 if (isset($server['network'])) {
1303 $network = $server['network'];
1306 if (isset($server['version'])) {
1307 $version = $server['version'];
1310 if (isset($server['site_name'])) {
1311 $site_name = $server['site_name'];
1314 if (isset($server['registered-users'])) {
1315 $registered_users = $server['registered-users'];
1320 // Check for noscrape
1321 // Friendica servers could be detected as OStatus servers
1322 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1323 $serverret = Network::curl($server_url."/friendica/json");
1325 if (!$serverret["success"]) {
1326 $serverret = Network::curl($server_url."/friendika/json");
1329 if ($serverret["success"]) {
1330 $data = json_decode($serverret["body"]);
1332 if (isset($data->version)) {
1333 $network = NETWORK_DFRN;
1335 if (!empty($data->no_scrape_url)) {
1336 $noscrape = $data->no_scrape_url;
1338 $version = $data->version;
1339 if (!empty($data->site_name)) {
1340 $site_name = $data->site_name;
1342 $info = $data->info;
1343 $register_policy = constant($data->register_policy);
1344 $platform = $data->platform;
1349 // Every server has got at least an admin account
1350 if (!$failure && ($registered_users == 0)) {
1351 $registered_users = 1;
1354 if ($possible_failure && !$failure) {
1359 $last_contact = $orig_last_contact;
1360 $last_failure = DateTimeFormat::utcNow();
1362 $last_contact = DateTimeFormat::utcNow();
1363 $last_failure = $orig_last_failure;
1366 if (($last_contact <= $last_failure) && !$failure) {
1367 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1368 } elseif (($last_contact >= $last_failure) && $failure) {
1369 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1372 // Check again if the server exists
1373 $found = DBA::exists('gserver', ['nurl' => normalise_link($server_url)]);
1375 $version = strip_tags($version);
1376 $site_name = strip_tags($site_name);
1377 $info = strip_tags($info);
1378 $platform = strip_tags($platform);
1380 $fields = ['url' => $server_url, 'version' => $version,
1381 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1382 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1383 'platform' => $platform, 'registered-users' => $registered_users,
1384 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1387 DBA::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1388 } elseif (!$failure) {
1389 $fields['nurl'] = normalise_link($server_url);
1390 $fields['created'] = DateTimeFormat::utcNow();
1391 DBA::insert('gserver', $fields);
1394 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1395 self::discoverRelay($server_url);
1398 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1404 * @brief Fetch relay data from a given server url
1406 * @param string $server_url address of the server
1408 private static function discoverRelay($server_url)
1410 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1412 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1413 if (!$serverret["success"]) {
1417 $data = json_decode($serverret['body']);
1418 if (!is_object($data)) {
1422 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1423 if (!DBA::isResult($gserver)) {
1427 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1428 $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1429 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1432 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1433 if ($data->scope == 'tags') {
1436 foreach ($data->tags as $tag) {
1437 $tag = mb_strtolower($tag);
1441 foreach ($tags as $tag) {
1442 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1446 // Create or update the relay contact
1448 if (isset($data->protocols)) {
1449 if (isset($data->protocols->diaspora)) {
1450 $fields['network'] = NETWORK_DIASPORA;
1451 if (isset($data->protocols->diaspora->receive)) {
1452 $fields['batch'] = $data->protocols->diaspora->receive;
1453 } elseif (is_string($data->protocols->diaspora)) {
1454 $fields['batch'] = $data->protocols->diaspora;
1457 if (isset($data->protocols->dfrn)) {
1458 $fields['network'] = NETWORK_DFRN;
1459 if (isset($data->protocols->dfrn->receive)) {
1460 $fields['batch'] = $data->protocols->dfrn->receive;
1461 } elseif (is_string($data->protocols->dfrn)) {
1462 $fields['batch'] = $data->protocols->dfrn;
1466 Diaspora::setRelayContact($server_url, $fields);
1470 * @brief Returns a list of all known servers
1471 * @return array List of server urls
1473 public static function serverlist()
1476 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1477 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1478 ORDER BY `last_contact`
1480 DBA::escape(NETWORK_DFRN),
1481 DBA::escape(NETWORK_DIASPORA),
1482 DBA::escape(NETWORK_OSTATUS)
1485 if (!DBA::isResult($r)) {
1493 * @brief Fetch server list from remote servers and adds them when they are new.
1495 * @param string $poco URL to the POCO endpoint
1497 private static function fetchServerlist($poco)
1499 $serverret = Network::curl($poco."/@server");
1500 if (!$serverret["success"]) {
1503 $serverlist = json_decode($serverret['body']);
1505 if (!is_array($serverlist)) {
1509 foreach ($serverlist as $server) {
1510 $server_url = str_replace("/index.php", "", $server->url);
1512 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(normalise_link($server_url)));
1513 if (!DBA::isResult($r)) {
1514 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1515 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1520 private static function discoverFederation()
1522 $last = Config::get('poco', 'last_federation_discovery');
1525 $next = $last + (24 * 60 * 60);
1526 if ($next > time()) {
1531 // Discover Friendica, Hubzilla and Diaspora servers
1532 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1535 $servers = json_decode($serverdata);
1537 if (!empty($servers->pods)) {
1538 foreach ($servers->pods as $server) {
1539 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1544 // Disvover Mastodon servers
1545 if (!Config::get('system', 'ostatus_disabled')) {
1546 $accesstoken = Config::get('system', 'instances_social_key');
1547 if (!empty($accesstoken)) {
1548 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1549 $header = ['Authorization: Bearer '.$accesstoken];
1550 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1551 if ($serverdata['success']) {
1552 $servers = json_decode($serverdata['body']);
1553 foreach ($servers->instances as $server) {
1554 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1555 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1561 // Currently disabled, since the service isn't available anymore.
1562 // It is not removed since I hope that there will be a successor.
1563 // Discover GNU Social Servers.
1564 //if (!Config::get('system','ostatus_disabled')) {
1565 // $serverdata = "http://gstools.org/api/get_open_instances/";
1567 // $result = Network::curl($serverdata);
1568 // if ($result["success"]) {
1569 // $servers = json_decode($result["body"]);
1571 // foreach($servers->data as $server)
1572 // self::checkServer($server->instance_address);
1576 Config::set('poco', 'last_federation_discovery', time());
1579 public static function discoverSingleServer($id)
1581 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1582 if (!DBA::isResult($r)) {
1588 // Discover new servers out there (Works from Friendica version 3.5.2)
1589 self::fetchServerlist($server["poco"]);
1591 // Fetch all users from the other server
1592 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1594 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1596 $retdata = Network::curl($url);
1597 if ($retdata["success"]) {
1598 $data = json_decode($retdata["body"]);
1600 self::discoverServer($data, 2);
1602 if (Config::get('system', 'poco_discovery') > 1) {
1603 $timeframe = Config::get('system', 'poco_discovery_since');
1604 if ($timeframe == 0) {
1608 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1610 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1611 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1615 $retdata = Network::curl($url);
1616 if ($retdata["success"]) {
1617 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1618 $success = self::discoverServer(json_decode($retdata["body"]));
1621 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1622 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1623 self::discoverServerUsers($data, $server);
1627 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1628 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1632 // If the server hadn't replied correctly, then force a sanity check
1633 self::checkServer($server["url"], $server["network"], true);
1635 // If we couldn't reach the server, we will try it some time later
1636 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1637 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1643 public static function discover($complete = false)
1645 // Update the server list
1646 self::discoverFederation();
1650 $requery_days = intval(Config::get("system", "poco_requery_days"));
1652 if ($requery_days == 0) {
1655 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1657 $r = q("SELECT `id`, `url`, `nurl`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", DBA::escape($last_update));
1658 if (DBA::isResult($r)) {
1659 foreach ($r as $server) {
1660 if (!self::checkServer($server["url"], $server["network"])) {
1661 // The server is not reachable? Okay, then we will try it later
1662 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1663 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1667 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1668 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1670 if (!$complete && (--$no_of_queries == 0)) {
1677 private static function discoverServerUsers($data, $server)
1679 if (!isset($data->entry)) {
1683 foreach ($data->entry as $entry) {
1685 if (isset($entry->urls)) {
1686 foreach ($entry->urls as $url) {
1687 if ($url->type == 'profile') {
1688 $profile_url = $url->value;
1689 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1690 $username = end($path_array);
1694 if ($username != '') {
1695 logger('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], LOGGER_DEBUG);
1697 // Fetch all contacts from a given user from the other server
1698 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1700 $retdata = Network::curl($url);
1701 if ($retdata['success']) {
1702 self::discoverServer(json_decode($retdata['body']), 3);
1708 private static function discoverServer($data, $default_generation = 0)
1710 if (!isset($data->entry) || !count($data->entry)) {
1716 foreach ($data->entry as $entry) {
1718 $profile_photo = '';
1722 $updated = NULL_DATE;
1728 $generation = $default_generation;
1730 if (!empty($entry->displayName)) {
1731 $name = $entry->displayName;
1734 if (isset($entry->urls)) {
1735 foreach ($entry->urls as $url) {
1736 if ($url->type == 'profile') {
1737 $profile_url = $url->value;
1740 if ($url->type == 'webfinger') {
1741 $connect_url = str_replace('acct:' , '', $url->value);
1747 if (isset($entry->photos)) {
1748 foreach ($entry->photos as $photo) {
1749 if ($photo->type == 'profile') {
1750 $profile_photo = $photo->value;
1756 if (isset($entry->updated)) {
1757 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1760 if (isset($entry->network)) {
1761 $network = $entry->network;
1764 if (isset($entry->currentLocation)) {
1765 $location = $entry->currentLocation;
1768 if (isset($entry->aboutMe)) {
1769 $about = HTML::toBBCode($entry->aboutMe);
1772 if (isset($entry->gender)) {
1773 $gender = $entry->gender;
1776 if (isset($entry->generation) && ($entry->generation > 0)) {
1777 $generation = ++$entry->generation;
1780 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1781 $contact_type = $entry->contactType;
1784 if (isset($entry->tags)) {
1785 foreach ($entry->tags as $tag) {
1786 $keywords = implode(", ", $tag);
1790 if ($generation > 0) {
1793 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1795 $gcontact = ["url" => $profile_url,
1797 "network" => $network,
1798 "photo" => $profile_photo,
1800 "location" => $location,
1801 "gender" => $gender,
1802 "keywords" => $keywords,
1803 "connect" => $connect_url,
1804 "updated" => $updated,
1805 "contact-type" => $contact_type,
1806 "generation" => $generation];
1809 $gcontact = GContact::sanitize($gcontact);
1810 GContact::update($gcontact);
1811 } catch (Exception $e) {
1812 logger($e->getMessage(), LOGGER_DEBUG);
1815 logger("Done for profile ".$profile_url, LOGGER_DEBUG);