3 * @file src/Protocol/PortableContact.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 namespace Friendica\Protocol;
12 use Friendica\Content\Text\HTML;
13 use Friendica\Core\Config;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Profile;
18 use Friendica\Network\Probe;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Util\XML;
28 require_once 'include/dba.php';
33 * @brief Fetch POCO data
35 * @param integer $cid Contact ID
36 * @param integer $uid User ID
37 * @param integer $zcid Global Contact ID
38 * @param integer $url POCO address that should be polled
40 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
41 * and add the entries to the gcontact (Global Contact) table, or update existing entries
42 * if anything (name or photo) has changed.
43 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
45 * Once the global contact is stored add (if necessary) the contact linkage which associates
46 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
47 * pointing to the same global contact id.
50 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
52 // Call the function "load" via the worker
53 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
57 * @brief Fetch POCO data from the worker
59 * @param integer $cid Contact ID
60 * @param integer $uid User ID
61 * @param integer $zcid Global Contact ID
62 * @param integer $url POCO address that should be polled
65 public static function load($cid, $uid, $zcid, $url)
71 $contact = dba::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
72 if (DBM::is_result($contact)) {
73 $url = $contact['poco'];
74 $uid = $contact['uid'];
86 $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') ;
88 logger('load: ' . $url, LOGGER_DEBUG);
90 $s = Network::fetchUrl($url);
92 logger('load: returns ' . $s, LOGGER_DATA);
94 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
96 if (($a->get_curl_code() > 299) || (! $s)) {
100 $j = json_decode($s);
102 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
104 if (! isset($j->entry)) {
109 foreach ($j->entry as $entry) {
116 $updated = NULL_DATE;
124 if (!empty($entry->displayName)) {
125 $name = $entry->displayName;
128 if (isset($entry->urls)) {
129 foreach ($entry->urls as $url) {
130 if ($url->type == 'profile') {
131 $profile_url = $url->value;
134 if ($url->type == 'webfinger') {
135 $connect_url = str_replace('acct:', '', $url->value);
140 if (isset($entry->photos)) {
141 foreach ($entry->photos as $photo) {
142 if ($photo->type == 'profile') {
143 $profile_photo = $photo->value;
149 if (isset($entry->updated)) {
150 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
153 if (isset($entry->network)) {
154 $network = $entry->network;
157 if (isset($entry->currentLocation)) {
158 $location = $entry->currentLocation;
161 if (isset($entry->aboutMe)) {
162 $about = HTML::toBBCode($entry->aboutMe);
165 if (isset($entry->gender)) {
166 $gender = $entry->gender;
169 if (isset($entry->generation) && ($entry->generation > 0)) {
170 $generation = ++$entry->generation;
173 if (isset($entry->tags)) {
174 foreach ($entry->tags as $tag) {
175 $keywords = implode(", ", $tag);
179 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
180 $contact_type = $entry->contactType;
183 $gcontact = ["url" => $profile_url,
185 "network" => $network,
186 "photo" => $profile_photo,
188 "location" => $location,
190 "keywords" => $keywords,
191 "connect" => $connect_url,
192 "updated" => $updated,
193 "contact-type" => $contact_type,
194 "generation" => $generation];
197 $gcontact = GContact::sanitize($gcontact);
198 $gcid = GContact::update($gcontact);
200 GContact::link($gcid, $uid, $cid, $zcid);
201 } catch (Exception $e) {
202 logger($e->getMessage(), LOGGER_DEBUG);
205 logger("load: loaded $total entries", LOGGER_DEBUG);
207 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
208 dba::delete('glink', $condition);
211 public static function reachable($profile, $server = "", $network = "", $force = false)
214 $server = self::detectServer($profile);
221 return self::checkServer($server, $network, $force);
224 public static function detectServer($profile)
226 // Try to detect the server path based upon some known standard paths
229 if ($server_url == "") {
230 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
231 if ($friendica != $profile) {
232 $server_url = $friendica;
233 $network = NETWORK_DFRN;
237 if ($server_url == "") {
238 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
239 if ($diaspora != $profile) {
240 $server_url = $diaspora;
241 $network = NETWORK_DIASPORA;
245 if ($server_url == "") {
246 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
247 if ($red != $profile) {
249 $network = NETWORK_DIASPORA;
254 if ($server_url == "") {
255 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
256 if ($mastodon != $profile) {
257 $server_url = $mastodon;
258 $network = NETWORK_OSTATUS;
262 // Numeric OStatus variant
263 if ($server_url == "") {
264 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
265 if ($ostatus != $profile) {
266 $server_url = $ostatus;
267 $network = NETWORK_OSTATUS;
272 if ($server_url == "") {
273 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
274 if ($base != $profile) {
276 $network = NETWORK_PHANTOM;
280 if ($server_url == "") {
285 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
286 dbesc(normalise_link($server_url))
289 if (DBM::is_result($r)) {
293 // Fetch the host-meta to check if this really is a server
294 $serverret = Network::curl($server_url."/.well-known/host-meta");
295 if (!$serverret["success"]) {
302 public static function alternateOStatusUrl($url)
304 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
307 public static function lastUpdated($profile, $force = false)
310 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
311 dbesc(normalise_link($profile))
314 if (!DBM::is_result($gcontacts)) {
318 $contact = ["url" => $profile];
320 if ($gcontacts[0]["created"] <= NULL_DATE) {
321 $contact['created'] = DateTimeFormat::utcNow();
326 $server_url = normalise_link(self::detectServer($profile));
329 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
330 $server_url = $gcontacts[0]["server_url"];
333 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
334 $server_url = normalise_link(self::detectServer($profile));
337 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
338 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
342 if ($server_url != "") {
343 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
345 $fields = ['last_failure' => DateTimeFormat::utcNow()];
346 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
349 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
352 $contact['server_url'] = $server_url;
355 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
357 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
358 dbesc(normalise_link($server_url))
362 $contact['network'] = $server[0]["network"];
368 // noscrape is really fast so we don't cache the call.
369 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
370 // Use noscrape if possible
371 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
374 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
376 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
377 $noscrape = json_decode($noscraperet["body"], true);
379 if (is_array($noscrape)) {
380 $contact["network"] = $server[0]["network"];
382 if (isset($noscrape["fn"])) {
383 $contact["name"] = $noscrape["fn"];
385 if (isset($noscrape["comm"])) {
386 $contact["community"] = $noscrape["comm"];
388 if (isset($noscrape["tags"])) {
389 $keywords = implode(" ", $noscrape["tags"]);
390 if ($keywords != "") {
391 $contact["keywords"] = $keywords;
395 $location = Profile::formatLocation($noscrape);
397 $contact["location"] = $location;
399 if (isset($noscrape["dfrn-notify"])) {
400 $contact["notify"] = $noscrape["dfrn-notify"];
402 // Remove all fields that are not present in the gcontact table
403 unset($noscrape["fn"]);
404 unset($noscrape["key"]);
405 unset($noscrape["homepage"]);
406 unset($noscrape["comm"]);
407 unset($noscrape["tags"]);
408 unset($noscrape["locality"]);
409 unset($noscrape["region"]);
410 unset($noscrape["country-name"]);
411 unset($noscrape["contacts"]);
412 unset($noscrape["dfrn-request"]);
413 unset($noscrape["dfrn-confirm"]);
414 unset($noscrape["dfrn-notify"]);
415 unset($noscrape["dfrn-poll"]);
417 // Set the date of the last contact
418 /// @todo By now the function "update_gcontact" doesn't work with this field
419 //$contact["last_contact"] = DateTimeFormat::utcNow();
421 $contact = array_merge($contact, $noscrape);
423 GContact::update($contact);
425 if (!empty($noscrape["updated"])) {
426 $fields = ['last_contact' => DateTimeFormat::utcNow()];
427 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
429 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
431 return $noscrape["updated"];
438 // If we only can poll the feed, then we only do this once a while
439 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
440 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
442 GContact::update($contact);
443 return $gcontacts[0]["updated"];
446 $data = Probe::uri($profile);
448 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
449 // Then check the other link and delete this one
450 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
451 && (normalise_link($profile) == normalise_link($data["alias"]))
452 && (normalise_link($profile) != normalise_link($data["url"]))
454 // Delete the old entry
455 dba::delete('gcontact', ['nurl' => normalise_link($profile)]);
457 $gcontact = array_merge($gcontacts[0], $data);
459 $gcontact["server_url"] = $data["baseurl"];
462 $gcontact = GContact::sanitize($gcontact);
463 GContact::update($gcontact);
465 self::lastUpdated($data["url"], $force);
466 } catch (Exception $e) {
467 logger($e->getMessage(), LOGGER_DEBUG);
470 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
474 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
475 $fields = ['last_failure' => DateTimeFormat::utcNow()];
476 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
478 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
482 $contact = array_merge($contact, $data);
484 $contact["server_url"] = $data["baseurl"];
486 GContact::update($contact);
488 $feedret = Network::curl($data["poll"]);
490 if (!$feedret["success"]) {
491 $fields = ['last_failure' => DateTimeFormat::utcNow()];
492 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
494 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
498 $doc = new DOMDocument();
499 @$doc->loadXML($feedret["body"]);
501 $xpath = new DOMXPath($doc);
502 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
504 $entries = $xpath->query('/atom:feed/atom:entry');
508 foreach ($entries as $entry) {
509 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
510 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
512 if ($last_updated < $published) {
513 $last_updated = $published;
516 if ($last_updated < $updated) {
517 $last_updated = $updated;
521 // Maybe there aren't any entries. Then check if it is a valid feed
522 if ($last_updated == "") {
523 if ($xpath->query('/atom:feed')->length > 0) {
524 $last_updated = NULL_DATE;
528 $fields = ['last_contact' => DateTimeFormat::utcNow()];
530 if (!empty($last_updated)) {
531 $fields['updated'] = $last_updated;
534 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
536 if (($gcontacts[0]["generation"] == 0)) {
537 $fields = ['generation' => 9];
538 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
541 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
543 return $last_updated;
546 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
548 $now = strtotime(DateTimeFormat::utcNow());
550 if ($updated > $last_contact) {
551 $contact_time = strtotime($updated);
553 $contact_time = strtotime($last_contact);
556 $failure_time = strtotime($last_failure);
557 $created_time = strtotime($created);
559 // If there is no "created" time then use the current time
560 if ($created_time <= 0) {
561 $created_time = $now;
564 // If the last contact was less than 24 hours then don't update
565 if (($now - $contact_time) < (60 * 60 * 24)) {
569 // If the last failure was less than 24 hours then don't update
570 if (($now - $failure_time) < (60 * 60 * 24)) {
574 // If the last contact was less than a week ago and the last failure is older than a week then don't update
575 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
578 // 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
579 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
583 // 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
584 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
591 private static function toBoolean($val)
593 if (($val == "true") || ($val == 1)) {
595 } elseif (($val == "false") || ($val == 0)) {
603 * @brief Detect server type (Hubzilla or Friendica) via the poco data
605 * @param object $data POCO data
606 * @return array Server data
608 private static function detectPocoData($data)
612 if (!isset($data->entry)) {
616 if (count($data->entry) == 0) {
620 if (!isset($data->entry[0]->urls)) {
624 if (count($data->entry[0]->urls) == 0) {
628 foreach ($data->entry[0]->urls as $url) {
629 if ($url->type == 'zot') {
631 $server["platform"] = 'Hubzilla';
632 $server["network"] = NETWORK_DIASPORA;
640 * @brief Detect server type by using the nodeinfo data
642 * @param string $server_url address of the server
643 * @return array Server data
645 private static function fetchNodeinfo($server_url)
647 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
648 if (!$serverret["success"]) {
652 $nodeinfo = json_decode($serverret['body']);
654 if (!is_object($nodeinfo)) {
658 if (!is_array($nodeinfo->links)) {
665 foreach ($nodeinfo->links as $link) {
666 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
667 $nodeinfo1_url = $link->href;
669 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
670 $nodeinfo2_url = $link->href;
674 if ($nodeinfo1_url . $nodeinfo2_url == '') {
680 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
681 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
682 $server = self::parseNodeinfo2($nodeinfo2_url);
685 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
686 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
687 $server = self::parseNodeinfo1($nodeinfo1_url);
694 * @brief Parses Nodeinfo 1
696 * @param string $nodeinfo_url address of the nodeinfo path
697 * @return array Server data
699 private static function parseNodeinfo1($nodeinfo_url)
701 $serverret = Network::curl($nodeinfo_url);
702 if (!$serverret["success"]) {
706 $nodeinfo = json_decode($serverret['body']);
707 if (!is_object($nodeinfo)) {
713 $server['register_policy'] = REGISTER_CLOSED;
715 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
716 $server['register_policy'] = REGISTER_OPEN;
719 if (is_object($nodeinfo->software)) {
720 if (isset($nodeinfo->software->name)) {
721 $server['platform'] = $nodeinfo->software->name;
724 if (isset($nodeinfo->software->version)) {
725 $server['version'] = $nodeinfo->software->version;
726 // Version numbers on Nodeinfo are presented with additional info, e.g.:
727 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
728 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
732 if (is_object($nodeinfo->metadata)) {
733 if (isset($nodeinfo->metadata->nodeName)) {
734 $server['site_name'] = $nodeinfo->metadata->nodeName;
738 if (!empty($nodeinfo->usage->users->total)) {
739 $server['registered-users'] = $nodeinfo->usage->users->total;
746 if (is_array($nodeinfo->protocols->inbound)) {
747 foreach ($nodeinfo->protocols->inbound as $inbound) {
748 if ($inbound == 'diaspora') {
751 if ($inbound == 'friendica') {
754 if ($inbound == 'gnusocial') {
761 $server['network'] = NETWORK_OSTATUS;
764 $server['network'] = NETWORK_DIASPORA;
767 $server['network'] = NETWORK_DFRN;
778 * @brief Parses Nodeinfo 2
780 * @param string $nodeinfo_url address of the nodeinfo path
781 * @return array Server data
783 private static function parseNodeinfo2($nodeinfo_url)
785 $serverret = Network::curl($nodeinfo_url);
786 if (!$serverret["success"]) {
790 $nodeinfo = json_decode($serverret['body']);
791 if (!is_object($nodeinfo)) {
797 $server['register_policy'] = REGISTER_CLOSED;
799 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
800 $server['register_policy'] = REGISTER_OPEN;
803 if (is_object($nodeinfo->software)) {
804 if (isset($nodeinfo->software->name)) {
805 $server['platform'] = $nodeinfo->software->name;
808 if (isset($nodeinfo->software->version)) {
809 $server['version'] = $nodeinfo->software->version;
810 // Version numbers on Nodeinfo are presented with additional info, e.g.:
811 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
812 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
816 if (is_object($nodeinfo->metadata)) {
817 if (isset($nodeinfo->metadata->nodeName)) {
818 $server['site_name'] = $nodeinfo->metadata->nodeName;
822 if (!empty($nodeinfo->usage->users->total)) {
823 $server['registered-users'] = $nodeinfo->usage->users->total;
830 if (is_array($nodeinfo->protocols)) {
831 foreach ($nodeinfo->protocols as $protocol) {
832 if ($protocol == 'diaspora') {
835 if ($protocol == 'friendica') {
838 if ($protocol == 'gnusocial') {
845 $server['network'] = NETWORK_OSTATUS;
848 $server['network'] = NETWORK_DIASPORA;
851 $server['network'] = NETWORK_DFRN;
862 * @brief Detect server type (Hubzilla or Friendica) via the front page body
864 * @param string $body Front page of the server
865 * @return array Server data
867 private static function detectServerType($body)
871 $doc = new DOMDocument();
872 @$doc->loadHTML($body);
873 $xpath = new DOMXPath($doc);
875 $list = $xpath->query("//meta[@name]");
877 foreach ($list as $node) {
879 if ($node->attributes->length) {
880 foreach ($node->attributes as $attribute) {
881 $attr[$attribute->name] = $attribute->value;
884 if ($attr['name'] == 'generator') {
885 $version_part = explode(" ", $attr['content']);
886 if (count($version_part) == 2) {
887 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
889 $server["platform"] = $version_part[0];
890 $server["version"] = $version_part[1];
891 $server["network"] = NETWORK_DFRN;
898 $list = $xpath->query("//meta[@property]");
900 foreach ($list as $node) {
902 if ($node->attributes->length) {
903 foreach ($node->attributes as $attribute) {
904 $attr[$attribute->name] = $attribute->value;
907 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
909 $server["platform"] = $attr['content'];
910 $server["version"] = "";
911 $server["network"] = NETWORK_DIASPORA;
920 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
924 public static function checkServer($server_url, $network = "", $force = false)
926 // Unify the server address
927 $server_url = trim($server_url, "/");
928 $server_url = str_replace("/index.php", "", $server_url);
930 if ($server_url == "") {
934 $gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
935 if (DBM::is_result($gserver)) {
936 if ($gserver["created"] <= NULL_DATE) {
937 $fields = ['created' => DateTimeFormat::utcNow()];
938 $condition = ['nurl' => normalise_link($server_url)];
939 dba::update('gserver', $fields, $condition);
941 $poco = $gserver["poco"];
942 $noscrape = $gserver["noscrape"];
944 if ($network == "") {
945 $network = $gserver["network"];
948 $last_contact = $gserver["last_contact"];
949 $last_failure = $gserver["last_failure"];
950 $version = $gserver["version"];
951 $platform = $gserver["platform"];
952 $site_name = $gserver["site_name"];
953 $info = $gserver["info"];
954 $register_policy = $gserver["register_policy"];
955 $registered_users = $gserver["registered-users"];
957 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
958 // It can happen that a zero date is in the database, but storing it again is forbidden.
959 if ($last_contact < NULL_DATE) {
960 $last_contact = NULL_DATE;
962 if ($last_failure < NULL_DATE) {
963 $last_failure = NULL_DATE;
966 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
967 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
968 return ($last_contact >= $last_failure);
977 $register_policy = -1;
978 $registered_users = 0;
980 $last_contact = NULL_DATE;
981 $last_failure = NULL_DATE;
983 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
986 $possible_failure = false;
987 $orig_last_failure = $last_failure;
988 $orig_last_contact = $last_contact;
990 // Mastodon uses the "@" for user profiles.
991 // But this can be misunderstood.
992 if (parse_url($server_url, PHP_URL_USER) != '') {
993 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
997 // Check if the page is accessible via SSL.
998 $orig_server_url = $server_url;
999 $server_url = str_replace("http://", "https://", $server_url);
1001 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1002 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1004 // Quit if there is a timeout.
1005 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1006 if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
1007 (!$serverret["success"] && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT))) {
1008 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1009 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1013 // Maybe the page is unencrypted only?
1014 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1015 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1016 $server_url = str_replace("https://", "http://", $server_url);
1018 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1019 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1021 // Quit if there is a timeout
1022 if (!$serverret["success"] && ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1023 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1024 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1028 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1031 if (!$serverret["success"] || ($serverret["body"] == "") || empty($xmlobj) || !is_object($xmlobj)) {
1032 // Workaround for bad configured servers (known nginx problem)
1033 if (!empty($serverret["debug"]) && !in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1036 $possible_failure = true;
1039 // If the server has no possible failure we reset the cached data
1040 if (!$possible_failure) {
1045 $register_policy = -1;
1049 // This will be too low, but better than no value at all.
1050 $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
1055 $serverret = Network::curl($server_url."/poco");
1056 if ($serverret["success"]) {
1057 $data = json_decode($serverret["body"]);
1058 if (isset($data->totalResults)) {
1059 $registered_users = $data->totalResults;
1060 $poco = $server_url."/poco";
1061 $server = self::detectPocoData($data);
1063 $platform = $server['platform'];
1064 $network = $server['network'];
1069 // There are servers out there who don't return 404 on a failure
1070 // We have to be sure that don't misunderstand this
1071 if (is_null($data)) {
1080 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1081 $serverret = Network::curl($server_url);
1083 if (!$serverret["success"] || ($serverret["body"] == "")) {
1086 $server = self::detectServerType($serverret["body"]);
1088 $platform = $server['platform'];
1089 $network = $server['network'];
1090 $version = $server['version'];
1091 $site_name = $server['site_name'];
1094 $lines = explode("\n", $serverret["header"]);
1095 if (count($lines)) {
1096 foreach ($lines as $line) {
1097 $line = trim($line);
1098 if (stristr($line, 'X-Diaspora-Version:')) {
1099 $platform = "Diaspora";
1100 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1101 $version = trim(str_replace("x-diaspora-version:", "", $version));
1102 $network = NETWORK_DIASPORA;
1103 $versionparts = explode("-", $version);
1104 $version = $versionparts[0];
1107 if (stristr($line, 'Server: Mastodon')) {
1108 $platform = "Mastodon";
1109 $network = NETWORK_OSTATUS;
1116 if (!$failure && ($poco == "")) {
1117 // Test for Statusnet
1118 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1119 // The "not implemented" is a special treatment for really, really old Friendica versions
1120 $serverret = Network::curl($server_url."/api/statusnet/version.json");
1121 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1122 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1123 $platform = "StatusNet";
1124 // Remove junk that some GNU Social servers return
1125 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1126 $version = trim($version, '"');
1127 $network = NETWORK_OSTATUS;
1130 // Test for GNU Social
1131 $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1132 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1133 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1134 $platform = "GNU Social";
1135 // Remove junk that some GNU Social servers return
1136 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1137 $version = trim($version, '"');
1138 $network = NETWORK_OSTATUS;
1141 // Test for Mastodon
1142 $orig_version = $version;
1143 $serverret = Network::curl($server_url."/api/v1/instance");
1144 if ($serverret["success"] && ($serverret["body"] != '')) {
1145 $data = json_decode($serverret["body"]);
1147 if (isset($data->version)) {
1148 $platform = "Mastodon";
1149 $version = $data->version;
1150 $site_name = $data->title;
1151 $info = $data->description;
1152 $network = NETWORK_OSTATUS;
1154 if (!empty($data->stats->user_count)) {
1155 $registered_users = $data->stats->user_count;
1158 if (strstr($orig_version.$version, 'Pleroma')) {
1159 $platform = 'Pleroma';
1160 $version = trim(str_replace('Pleroma', '', $version));
1165 // Test for Hubzilla and Red
1166 $serverret = Network::curl($server_url."/siteinfo.json");
1167 if ($serverret["success"]) {
1168 $data = json_decode($serverret["body"]);
1169 if (isset($data->url)) {
1170 $platform = $data->platform;
1171 $version = $data->version;
1172 $network = NETWORK_DIASPORA;
1174 if (!empty($data->site_name)) {
1175 $site_name = $data->site_name;
1177 if (!empty($data->channels_total)) {
1178 $registered_users = $data->channels_total;
1180 if (!empty($data->register_policy)) {
1181 switch ($data->register_policy) {
1182 case "REGISTER_OPEN":
1183 $register_policy = REGISTER_OPEN;
1185 case "REGISTER_APPROVE":
1186 $register_policy = REGISTER_APPROVE;
1188 case "REGISTER_CLOSED":
1190 $register_policy = REGISTER_CLOSED;
1195 // Test for Hubzilla, Redmatrix or Friendica
1196 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1197 if ($serverret["success"]) {
1198 $data = json_decode($serverret["body"]);
1199 if (isset($data->site->server)) {
1200 if (isset($data->site->platform)) {
1201 $platform = $data->site->platform->PLATFORM_NAME;
1202 $version = $data->site->platform->STD_VERSION;
1203 $network = NETWORK_DIASPORA;
1205 if (isset($data->site->BlaBlaNet)) {
1206 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1207 $version = $data->site->BlaBlaNet->STD_VERSION;
1208 $network = NETWORK_DIASPORA;
1210 if (isset($data->site->hubzilla)) {
1211 $platform = $data->site->hubzilla->PLATFORM_NAME;
1212 $version = $data->site->hubzilla->RED_VERSION;
1213 $network = NETWORK_DIASPORA;
1215 if (isset($data->site->redmatrix)) {
1216 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1217 $platform = $data->site->redmatrix->PLATFORM_NAME;
1218 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1219 $platform = $data->site->redmatrix->RED_PLATFORM;
1222 $version = $data->site->redmatrix->RED_VERSION;
1223 $network = NETWORK_DIASPORA;
1225 if (isset($data->site->friendica)) {
1226 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1227 $version = $data->site->friendica->FRIENDICA_VERSION;
1228 $network = NETWORK_DFRN;
1231 $site_name = $data->site->name;
1233 $data->site->closed = self::toBoolean($data->site->closed);
1235 if (!empty($data->site->private)) {
1236 $data->site->private = self::toBoolean($data->site->private);
1239 if (!empty($data->site->inviteonly)) {
1240 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1243 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1244 $register_policy = REGISTER_APPROVE;
1245 } elseif (!$data->site->closed && !$data->site->private) {
1246 $register_policy = REGISTER_OPEN;
1248 $register_policy = REGISTER_CLOSED;
1255 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1257 $serverret = Network::curl($server_url."/statistics.json");
1258 if ($serverret["success"]) {
1259 $data = json_decode($serverret["body"]);
1261 if (isset($data->version)) {
1262 $version = $data->version;
1263 // Version numbers on statistics.json are presented with additional info, e.g.:
1264 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1265 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1268 if (!empty($data->name)) {
1269 $site_name = $data->name;
1272 if (!empty($data->network)) {
1273 $platform = $data->network;
1276 if ($platform == "Diaspora") {
1277 $network = NETWORK_DIASPORA;
1280 if (!empty($data->registrations_open) && $data->registrations_open) {
1281 $register_policy = REGISTER_OPEN;
1283 $register_policy = REGISTER_CLOSED;
1288 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1290 $server = self::fetchNodeinfo($server_url);
1292 $register_policy = $server['register_policy'];
1294 if (isset($server['platform'])) {
1295 $platform = $server['platform'];
1298 if (isset($server['network'])) {
1299 $network = $server['network'];
1302 if (isset($server['version'])) {
1303 $version = $server['version'];
1306 if (isset($server['site_name'])) {
1307 $site_name = $server['site_name'];
1310 if (isset($server['registered-users'])) {
1311 $registered_users = $server['registered-users'];
1316 // Check for noscrape
1317 // Friendica servers could be detected as OStatus servers
1318 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1319 $serverret = Network::curl($server_url."/friendica/json");
1321 if (!$serverret["success"]) {
1322 $serverret = Network::curl($server_url."/friendika/json");
1325 if ($serverret["success"]) {
1326 $data = json_decode($serverret["body"]);
1328 if (isset($data->version)) {
1329 $network = NETWORK_DFRN;
1331 if (!empty($data->no_scrape_url)) {
1332 $noscrape = $data->no_scrape_url;
1334 $version = $data->version;
1335 if (!empty($data->site_name)) {
1336 $site_name = $data->site_name;
1338 $info = $data->info;
1339 $register_policy = constant($data->register_policy);
1340 $platform = $data->platform;
1345 // Every server has got at least an admin account
1346 if (!$failure && ($registered_users == 0)) {
1347 $registered_users = 1;
1350 if ($possible_failure && !$failure) {
1355 $last_contact = $orig_last_contact;
1356 $last_failure = DateTimeFormat::utcNow();
1358 $last_contact = DateTimeFormat::utcNow();
1359 $last_failure = $orig_last_failure;
1362 if (($last_contact <= $last_failure) && !$failure) {
1363 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1364 } elseif (($last_contact >= $last_failure) && $failure) {
1365 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1368 // Check again if the server exists
1369 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1371 $version = strip_tags($version);
1372 $site_name = strip_tags($site_name);
1373 $info = strip_tags($info);
1374 $platform = strip_tags($platform);
1376 $fields = ['url' => $server_url, 'version' => $version,
1377 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1378 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1379 'platform' => $platform, 'registered-users' => $registered_users,
1380 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1383 dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1384 } elseif (!$failure) {
1385 $fields['nurl'] = normalise_link($server_url);
1386 $fields['created'] = DateTimeFormat::utcNow();
1387 dba::insert('gserver', $fields);
1390 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1391 self::discoverRelay($server_url);
1394 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1400 * @brief Fetch relay data from a given server url
1402 * @param string $server_url address of the server
1404 private static function discoverRelay($server_url)
1406 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1408 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1409 if (!$serverret["success"]) {
1413 $data = json_decode($serverret['body']);
1414 if (!is_object($data)) {
1418 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1419 if (!DBM::is_result($gserver)) {
1423 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1424 $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1425 dba::update('gserver', $fields, ['id' => $gserver['id']]);
1428 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1429 if ($data->scope == 'tags') {
1432 foreach ($data->tags as $tag) {
1433 $tag = mb_strtolower($tag);
1437 foreach ($tags as $tag) {
1438 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1442 // Create or update the relay contact
1444 if (isset($data->protocols)) {
1445 if (isset($data->protocols->diaspora)) {
1446 $fields['network'] = NETWORK_DIASPORA;
1447 if (isset($data->protocols->diaspora->receive)) {
1448 $fields['batch'] = $data->protocols->diaspora->receive;
1449 } elseif (is_string($data->protocols->diaspora)) {
1450 $fields['batch'] = $data->protocols->diaspora;
1453 if (isset($data->protocols->dfrn)) {
1454 $fields['network'] = NETWORK_DFRN;
1455 if (isset($data->protocols->dfrn->receive)) {
1456 $fields['batch'] = $data->protocols->dfrn->receive;
1457 } elseif (is_string($data->protocols->dfrn)) {
1458 $fields['batch'] = $data->protocols->dfrn;
1462 Diaspora::setRelayContact($server_url, $fields);
1466 * @brief Returns a list of all known servers
1467 * @return array List of server urls
1469 public static function serverlist()
1472 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1473 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1474 ORDER BY `last_contact`
1476 dbesc(NETWORK_DFRN),
1477 dbesc(NETWORK_DIASPORA),
1478 dbesc(NETWORK_OSTATUS)
1481 if (!DBM::is_result($r)) {
1489 * @brief Fetch server list from remote servers and adds them when they are new.
1491 * @param string $poco URL to the POCO endpoint
1493 private static function fetchServerlist($poco)
1495 $serverret = Network::curl($poco."/@server");
1496 if (!$serverret["success"]) {
1499 $serverlist = json_decode($serverret['body']);
1501 if (!is_array($serverlist)) {
1505 foreach ($serverlist as $server) {
1506 $server_url = str_replace("/index.php", "", $server->url);
1508 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1509 if (!DBM::is_result($r)) {
1510 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1511 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1516 private static function discoverFederation()
1518 $last = Config::get('poco', 'last_federation_discovery');
1521 $next = $last + (24 * 60 * 60);
1522 if ($next > time()) {
1527 // Discover Friendica, Hubzilla and Diaspora servers
1528 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1531 $servers = json_decode($serverdata);
1533 if (!empty($servers->pods)) {
1534 foreach ($servers->pods as $server) {
1535 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1540 // Disvover Mastodon servers
1541 if (!Config::get('system', 'ostatus_disabled')) {
1542 $accesstoken = Config::get('system', 'instances_social_key');
1543 if (!empty($accesstoken)) {
1544 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1545 $header = ['Authorization: Bearer '.$accesstoken];
1546 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1547 if ($serverdata['success']) {
1548 $servers = json_decode($serverdata['body']);
1549 foreach ($servers->instances as $server) {
1550 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1551 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1557 // Currently disabled, since the service isn't available anymore.
1558 // It is not removed since I hope that there will be a successor.
1559 // Discover GNU Social Servers.
1560 //if (!Config::get('system','ostatus_disabled')) {
1561 // $serverdata = "http://gstools.org/api/get_open_instances/";
1563 // $result = Network::curl($serverdata);
1564 // if ($result["success"]) {
1565 // $servers = json_decode($result["body"]);
1567 // foreach($servers->data as $server)
1568 // self::checkServer($server->instance_address);
1572 Config::set('poco', 'last_federation_discovery', time());
1575 public static function discoverSingleServer($id)
1577 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1578 if (!DBM::is_result($r)) {
1584 // Discover new servers out there (Works from Friendica version 3.5.2)
1585 self::fetchServerlist($server["poco"]);
1587 // Fetch all users from the other server
1588 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1590 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1592 $retdata = Network::curl($url);
1593 if ($retdata["success"]) {
1594 $data = json_decode($retdata["body"]);
1596 self::discoverServer($data, 2);
1598 if (Config::get('system', 'poco_discovery') > 1) {
1599 $timeframe = Config::get('system', 'poco_discovery_since');
1600 if ($timeframe == 0) {
1604 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1606 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1607 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1611 $retdata = Network::curl($url);
1612 if ($retdata["success"]) {
1613 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1614 $success = self::discoverServer(json_decode($retdata["body"]));
1617 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1618 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1619 self::discoverServerUsers($data, $server);
1623 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1624 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1628 // If the server hadn't replied correctly, then force a sanity check
1629 self::checkServer($server["url"], $server["network"], true);
1631 // If we couldn't reach the server, we will try it some time later
1632 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1633 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1639 public static function discover($complete = false)
1641 // Update the server list
1642 self::discoverFederation();
1646 $requery_days = intval(Config::get("system", "poco_requery_days"));
1648 if ($requery_days == 0) {
1651 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1653 $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));
1654 if (DBM::is_result($r)) {
1655 foreach ($r as $server) {
1656 if (!self::checkServer($server["url"], $server["network"])) {
1657 // The server is not reachable? Okay, then we will try it later
1658 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1659 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1663 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1664 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1666 if (!$complete && (--$no_of_queries == 0)) {
1673 private static function discoverServerUsers($data, $server)
1675 if (!isset($data->entry)) {
1679 foreach ($data->entry as $entry) {
1681 if (isset($entry->urls)) {
1682 foreach ($entry->urls as $url) {
1683 if ($url->type == 'profile') {
1684 $profile_url = $url->value;
1685 $urlparts = parse_url($profile_url);
1686 $username = end(explode("/", $urlparts["path"]));
1690 if ($username != "") {
1691 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1693 // Fetch all contacts from a given user from the other server
1694 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1696 $retdata = Network::curl($url);
1697 if ($retdata["success"]) {
1698 self::discoverServer(json_decode($retdata["body"]), 3);
1704 private static function discoverServer($data, $default_generation = 0)
1706 if (!isset($data->entry) || !count($data->entry)) {
1712 foreach ($data->entry as $entry) {
1714 $profile_photo = '';
1718 $updated = NULL_DATE;
1724 $generation = $default_generation;
1726 if (!empty($entry->displayName)) {
1727 $name = $entry->displayName;
1730 if (isset($entry->urls)) {
1731 foreach ($entry->urls as $url) {
1732 if ($url->type == 'profile') {
1733 $profile_url = $url->value;
1736 if ($url->type == 'webfinger') {
1737 $connect_url = str_replace('acct:' , '', $url->value);
1743 if (isset($entry->photos)) {
1744 foreach ($entry->photos as $photo) {
1745 if ($photo->type == 'profile') {
1746 $profile_photo = $photo->value;
1752 if (isset($entry->updated)) {
1753 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1756 if (isset($entry->network)) {
1757 $network = $entry->network;
1760 if (isset($entry->currentLocation)) {
1761 $location = $entry->currentLocation;
1764 if (isset($entry->aboutMe)) {
1765 $about = HTML::toBBCode($entry->aboutMe);
1768 if (isset($entry->gender)) {
1769 $gender = $entry->gender;
1772 if (isset($entry->generation) && ($entry->generation > 0)) {
1773 $generation = ++$entry->generation;
1776 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1777 $contact_type = $entry->contactType;
1780 if (isset($entry->tags)) {
1781 foreach ($entry->tags as $tag) {
1782 $keywords = implode(", ", $tag);
1786 if ($generation > 0) {
1789 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1791 $gcontact = ["url" => $profile_url,
1793 "network" => $network,
1794 "photo" => $profile_photo,
1796 "location" => $location,
1797 "gender" => $gender,
1798 "keywords" => $keywords,
1799 "connect" => $connect_url,
1800 "updated" => $updated,
1801 "contact-type" => $contact_type,
1802 "generation" => $generation];
1805 $gcontact = GContact::sanitize($gcontact);
1806 GContact::update($gcontact);
1807 } catch (Exception $e) {
1808 logger($e->getMessage(), LOGGER_DEBUG);
1811 logger("Done for profile ".$profile_url, LOGGER_DEBUG);