3 * @file src/Protocol/PortableContact.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 namespace Friendica\Protocol;
12 use Friendica\Content\Text\HTML;
13 use Friendica\Core\Config;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Profile;
18 use Friendica\Network\Probe;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Protocol\Diaspora;
27 require_once 'include/dba.php';
32 * @brief Fetch POCO data
34 * @param integer $cid Contact ID
35 * @param integer $uid User ID
36 * @param integer $zcid Global Contact ID
37 * @param integer $url POCO address that should be polled
39 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
40 * and add the entries to the gcontact (Global Contact) table, or update existing entries
41 * if anything (name or photo) has changed.
42 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
44 * Once the global contact is stored add (if necessary) the contact linkage which associates
45 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
46 * pointing to the same global contact id.
49 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
51 // Call the function "load" via the worker
52 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
56 * @brief Fetch POCO data from the worker
58 * @param integer $cid Contact ID
59 * @param integer $uid User ID
60 * @param integer $zcid Global Contact ID
61 * @param integer $url POCO address that should be polled
64 public static function load($cid, $uid, $zcid, $url)
70 $contact = dba::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
71 if (DBM::is_result($contact)) {
72 $url = $contact['poco'];
73 $uid = $contact['uid'];
85 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
87 logger('load: ' . $url, LOGGER_DEBUG);
89 $s = Network::fetchUrl($url);
91 logger('load: returns ' . $s, LOGGER_DATA);
93 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
95 if (($a->get_curl_code() > 299) || (! $s)) {
101 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
103 if (! isset($j->entry)) {
108 foreach ($j->entry as $entry) {
115 $updated = NULL_DATE;
123 $name = $entry->displayName;
125 if (isset($entry->urls)) {
126 foreach ($entry->urls as $url) {
127 if ($url->type == 'profile') {
128 $profile_url = $url->value;
131 if ($url->type == 'webfinger') {
132 $connect_url = str_replace('acct:', '', $url->value);
137 if (isset($entry->photos)) {
138 foreach ($entry->photos as $photo) {
139 if ($photo->type == 'profile') {
140 $profile_photo = $photo->value;
146 if (isset($entry->updated)) {
147 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
150 if (isset($entry->network)) {
151 $network = $entry->network;
154 if (isset($entry->currentLocation)) {
155 $location = $entry->currentLocation;
158 if (isset($entry->aboutMe)) {
159 $about = HTML::toBBCode($entry->aboutMe);
162 if (isset($entry->gender)) {
163 $gender = $entry->gender;
166 if (isset($entry->generation) && ($entry->generation > 0)) {
167 $generation = ++$entry->generation;
170 if (isset($entry->tags)) {
171 foreach ($entry->tags as $tag) {
172 $keywords = implode(", ", $tag);
176 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
177 $contact_type = $entry->contactType;
180 $gcontact = ["url" => $profile_url,
182 "network" => $network,
183 "photo" => $profile_photo,
185 "location" => $location,
187 "keywords" => $keywords,
188 "connect" => $connect_url,
189 "updated" => $updated,
190 "contact-type" => $contact_type,
191 "generation" => $generation];
194 $gcontact = GContact::sanitize($gcontact);
195 $gcid = GContact::update($gcontact);
197 GContact::link($gcid, $uid, $cid, $zcid);
198 } catch (Exception $e) {
199 logger($e->getMessage(), LOGGER_DEBUG);
202 logger("load: loaded $total entries", LOGGER_DEBUG);
204 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
205 dba::delete('glink', $condition);
208 public static function reachable($profile, $server = "", $network = "", $force = false)
211 $server = self::detectServer($profile);
218 return self::checkServer($server, $network, $force);
221 public static function detectServer($profile)
223 // Try to detect the server path based upon some known standard paths
226 if ($server_url == "") {
227 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
228 if ($friendica != $profile) {
229 $server_url = $friendica;
230 $network = NETWORK_DFRN;
234 if ($server_url == "") {
235 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
236 if ($diaspora != $profile) {
237 $server_url = $diaspora;
238 $network = NETWORK_DIASPORA;
242 if ($server_url == "") {
243 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
244 if ($red != $profile) {
246 $network = NETWORK_DIASPORA;
251 if ($server_url == "") {
252 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
253 if ($mastodon != $profile) {
254 $server_url = $mastodon;
255 $network = NETWORK_OSTATUS;
259 // Numeric OStatus variant
260 if ($server_url == "") {
261 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
262 if ($ostatus != $profile) {
263 $server_url = $ostatus;
264 $network = NETWORK_OSTATUS;
269 if ($server_url == "") {
270 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
271 if ($base != $profile) {
273 $network = NETWORK_PHANTOM;
277 if ($server_url == "") {
282 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
283 dbesc(normalise_link($server_url))
286 if (DBM::is_result($r)) {
290 // Fetch the host-meta to check if this really is a server
291 $serverret = Network::curl($server_url."/.well-known/host-meta");
292 if (!$serverret["success"]) {
299 public static function alternateOStatusUrl($url)
301 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
304 public static function lastUpdated($profile, $force = false)
307 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
308 dbesc(normalise_link($profile))
311 if (!DBM::is_result($gcontacts)) {
315 $contact = ["url" => $profile];
317 if ($gcontacts[0]["created"] <= NULL_DATE) {
318 $contact['created'] = DateTimeFormat::utcNow();
323 $server_url = normalise_link(self::detectServer($profile));
326 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
327 $server_url = $gcontacts[0]["server_url"];
330 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
331 $server_url = normalise_link(self::detectServer($profile));
334 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
335 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
339 if ($server_url != "") {
340 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
342 $fields = ['last_failure' => DateTimeFormat::utcNow()];
343 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
346 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
349 $contact['server_url'] = $server_url;
352 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
354 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
355 dbesc(normalise_link($server_url))
359 $contact['network'] = $server[0]["network"];
365 // noscrape is really fast so we don't cache the call.
366 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
367 // Use noscrape if possible
368 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
371 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
373 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
374 $noscrape = json_decode($noscraperet["body"], true);
376 if (is_array($noscrape)) {
377 $contact["network"] = $server[0]["network"];
379 if (isset($noscrape["fn"])) {
380 $contact["name"] = $noscrape["fn"];
382 if (isset($noscrape["comm"])) {
383 $contact["community"] = $noscrape["comm"];
385 if (isset($noscrape["tags"])) {
386 $keywords = implode(" ", $noscrape["tags"]);
387 if ($keywords != "") {
388 $contact["keywords"] = $keywords;
392 $location = Profile::formatLocation($noscrape);
394 $contact["location"] = $location;
396 if (isset($noscrape["dfrn-notify"])) {
397 $contact["notify"] = $noscrape["dfrn-notify"];
399 // Remove all fields that are not present in the gcontact table
400 unset($noscrape["fn"]);
401 unset($noscrape["key"]);
402 unset($noscrape["homepage"]);
403 unset($noscrape["comm"]);
404 unset($noscrape["tags"]);
405 unset($noscrape["locality"]);
406 unset($noscrape["region"]);
407 unset($noscrape["country-name"]);
408 unset($noscrape["contacts"]);
409 unset($noscrape["dfrn-request"]);
410 unset($noscrape["dfrn-confirm"]);
411 unset($noscrape["dfrn-notify"]);
412 unset($noscrape["dfrn-poll"]);
414 // Set the date of the last contact
415 /// @todo By now the function "update_gcontact" doesn't work with this field
416 //$contact["last_contact"] = DateTimeFormat::utcNow();
418 $contact = array_merge($contact, $noscrape);
420 GContact::update($contact);
422 if (trim($noscrape["updated"]) != "") {
423 $fields = ['last_contact' => DateTimeFormat::utcNow()];
424 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
426 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
428 return $noscrape["updated"];
435 // If we only can poll the feed, then we only do this once a while
436 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
437 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
439 GContact::update($contact);
440 return $gcontacts[0]["updated"];
443 $data = Probe::uri($profile);
445 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
446 // Then check the other link and delete this one
447 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
448 && (normalise_link($profile) == normalise_link($data["alias"]))
449 && (normalise_link($profile) != normalise_link($data["url"]))
451 // Delete the old entry
452 dba::delete('gcontact', ['nurl' => normalise_link($profile)]);
454 $gcontact = array_merge($gcontacts[0], $data);
456 $gcontact["server_url"] = $data["baseurl"];
459 $gcontact = GContact::sanitize($gcontact);
460 GContact::update($gcontact);
462 self::lastUpdated($data["url"], $force);
463 } catch (Exception $e) {
464 logger($e->getMessage(), LOGGER_DEBUG);
467 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
471 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
472 $fields = ['last_failure' => DateTimeFormat::utcNow()];
473 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
475 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
479 $contact = array_merge($contact, $data);
481 $contact["server_url"] = $data["baseurl"];
483 GContact::update($contact);
485 $feedret = Network::curl($data["poll"]);
487 if (!$feedret["success"]) {
488 $fields = ['last_failure' => DateTimeFormat::utcNow()];
489 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
491 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
495 $doc = new DOMDocument();
496 @$doc->loadXML($feedret["body"]);
498 $xpath = new DOMXPath($doc);
499 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
501 $entries = $xpath->query('/atom:feed/atom:entry');
505 foreach ($entries as $entry) {
506 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
507 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
509 if ($last_updated < $published) {
510 $last_updated = $published;
513 if ($last_updated < $updated) {
514 $last_updated = $updated;
518 // Maybe there aren't any entries. Then check if it is a valid feed
519 if ($last_updated == "") {
520 if ($xpath->query('/atom:feed')->length > 0) {
521 $last_updated = NULL_DATE;
525 $fields = ['last_contact' => DateTimeFormat::utcNow()];
527 if (!empty($last_updated)) {
528 $fields['updated'] = $last_updated;
531 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
533 if (($gcontacts[0]["generation"] == 0)) {
534 $fields = ['generation' => 9];
535 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
538 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
540 return $last_updated;
543 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
545 $now = strtotime(DateTimeFormat::utcNow());
547 if ($updated > $last_contact) {
548 $contact_time = strtotime($updated);
550 $contact_time = strtotime($last_contact);
553 $failure_time = strtotime($last_failure);
554 $created_time = strtotime($created);
556 // If there is no "created" time then use the current time
557 if ($created_time <= 0) {
558 $created_time = $now;
561 // If the last contact was less than 24 hours then don't update
562 if (($now - $contact_time) < (60 * 60 * 24)) {
566 // If the last failure was less than 24 hours then don't update
567 if (($now - $failure_time) < (60 * 60 * 24)) {
571 // If the last contact was less than a week ago and the last failure is older than a week then don't update
572 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
575 // 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
576 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
580 // 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
581 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
588 private static function toBoolean($val)
590 if (($val == "true") || ($val == 1)) {
592 } elseif (($val == "false") || ($val == 0)) {
600 * @brief Detect server type (Hubzilla or Friendica) via the poco data
602 * @param object $data POCO data
603 * @return array Server data
605 private static function detectPocoData($data)
609 if (!isset($data->entry)) {
613 if (count($data->entry) == 0) {
617 if (!isset($data->entry[0]->urls)) {
621 if (count($data->entry[0]->urls) == 0) {
625 foreach ($data->entry[0]->urls as $url) {
626 if ($url->type == 'zot') {
628 $server["platform"] = 'Hubzilla';
629 $server["network"] = NETWORK_DIASPORA;
637 * @brief Detect server type by using the nodeinfo data
639 * @param string $server_url address of the server
640 * @return array Server data
642 private static function fetchNodeinfo($server_url)
644 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
645 if (!$serverret["success"]) {
649 $nodeinfo = json_decode($serverret['body']);
651 if (!is_object($nodeinfo)) {
655 if (!is_array($nodeinfo->links)) {
662 foreach ($nodeinfo->links as $link) {
663 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
664 $nodeinfo1_url = $link->href;
666 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
667 $nodeinfo2_url = $link->href;
671 if ($nodeinfo1_url . $nodeinfo2_url == '') {
677 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
678 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
679 $server = self::parseNodeinfo2($nodeinfo2_url);
682 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
683 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
684 $server = self::parseNodeinfo1($nodeinfo1_url);
691 * @brief Parses Nodeinfo 1
693 * @param string $nodeinfo_url address of the nodeinfo path
694 * @return array Server data
696 private static function parseNodeinfo1($nodeinfo_url)
698 $serverret = Network::curl($nodeinfo_url);
699 if (!$serverret["success"]) {
703 $nodeinfo = json_decode($serverret['body']);
704 if (!is_object($nodeinfo)) {
710 $server['register_policy'] = REGISTER_CLOSED;
712 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
713 $server['register_policy'] = REGISTER_OPEN;
716 if (is_object($nodeinfo->software)) {
717 if (isset($nodeinfo->software->name)) {
718 $server['platform'] = $nodeinfo->software->name;
721 if (isset($nodeinfo->software->version)) {
722 $server['version'] = $nodeinfo->software->version;
723 // Version numbers on Nodeinfo are presented with additional info, e.g.:
724 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
725 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
729 if (is_object($nodeinfo->metadata)) {
730 if (isset($nodeinfo->metadata->nodeName)) {
731 $server['site_name'] = $nodeinfo->metadata->nodeName;
735 if (!empty($nodeinfo->usage->users->total)) {
736 $server['registered-users'] = $nodeinfo->usage->users->total;
743 if (is_array($nodeinfo->protocols->inbound)) {
744 foreach ($nodeinfo->protocols->inbound as $inbound) {
745 if ($inbound == 'diaspora') {
748 if ($inbound == 'friendica') {
751 if ($inbound == 'gnusocial') {
758 $server['network'] = NETWORK_OSTATUS;
761 $server['network'] = NETWORK_DIASPORA;
764 $server['network'] = NETWORK_DFRN;
775 * @brief Parses Nodeinfo 2
777 * @param string $nodeinfo_url address of the nodeinfo path
778 * @return array Server data
780 private static function parseNodeinfo2($nodeinfo_url)
782 $serverret = Network::curl($nodeinfo_url);
783 if (!$serverret["success"]) {
787 $nodeinfo = json_decode($serverret['body']);
788 if (!is_object($nodeinfo)) {
794 $server['register_policy'] = REGISTER_CLOSED;
796 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
797 $server['register_policy'] = REGISTER_OPEN;
800 if (is_object($nodeinfo->software)) {
801 if (isset($nodeinfo->software->name)) {
802 $server['platform'] = $nodeinfo->software->name;
805 if (isset($nodeinfo->software->version)) {
806 $server['version'] = $nodeinfo->software->version;
807 // Version numbers on Nodeinfo are presented with additional info, e.g.:
808 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
809 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
813 if (is_object($nodeinfo->metadata)) {
814 if (isset($nodeinfo->metadata->nodeName)) {
815 $server['site_name'] = $nodeinfo->metadata->nodeName;
819 if (!empty($nodeinfo->usage->users->total)) {
820 $server['registered-users'] = $nodeinfo->usage->users->total;
827 if (is_array($nodeinfo->protocols)) {
828 foreach ($nodeinfo->protocols as $protocol) {
829 if ($protocol == 'diaspora') {
832 if ($protocol == 'friendica') {
835 if ($protocol == 'gnusocial') {
842 $server['network'] = NETWORK_OSTATUS;
845 $server['network'] = NETWORK_DIASPORA;
848 $server['network'] = NETWORK_DFRN;
859 * @brief Detect server type (Hubzilla or Friendica) via the front page body
861 * @param string $body Front page of the server
862 * @return array Server data
864 private static function detectServerType($body)
868 $doc = new DOMDocument();
869 @$doc->loadHTML($body);
870 $xpath = new DOMXPath($doc);
872 $list = $xpath->query("//meta[@name]");
874 foreach ($list as $node) {
876 if ($node->attributes->length) {
877 foreach ($node->attributes as $attribute) {
878 $attr[$attribute->name] = $attribute->value;
881 if ($attr['name'] == 'generator') {
882 $version_part = explode(" ", $attr['content']);
883 if (count($version_part) == 2) {
884 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
886 $server["platform"] = $version_part[0];
887 $server["version"] = $version_part[1];
888 $server["network"] = NETWORK_DFRN;
895 $list = $xpath->query("//meta[@property]");
897 foreach ($list as $node) {
899 if ($node->attributes->length) {
900 foreach ($node->attributes as $attribute) {
901 $attr[$attribute->name] = $attribute->value;
904 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
906 $server["platform"] = $attr['content'];
907 $server["version"] = "";
908 $server["network"] = NETWORK_DIASPORA;
917 $server["site_name"] = $xpath->evaluate("//head/title/text()")->item(0)->nodeValue;
921 public static function checkServer($server_url, $network = "", $force = false)
923 // Unify the server address
924 $server_url = trim($server_url, "/");
925 $server_url = str_replace("/index.php", "", $server_url);
927 if ($server_url == "") {
931 $gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
932 if (DBM::is_result($gserver)) {
933 if ($gserver["created"] <= NULL_DATE) {
934 $fields = ['created' => DateTimeFormat::utcNow()];
935 $condition = ['nurl' => normalise_link($server_url)];
936 dba::update('gserver', $fields, $condition);
938 $poco = $gserver["poco"];
939 $noscrape = $gserver["noscrape"];
941 if ($network == "") {
942 $network = $gserver["network"];
945 $last_contact = $gserver["last_contact"];
946 $last_failure = $gserver["last_failure"];
947 $version = $gserver["version"];
948 $platform = $gserver["platform"];
949 $site_name = $gserver["site_name"];
950 $info = $gserver["info"];
951 $register_policy = $gserver["register_policy"];
952 $registered_users = $gserver["registered-users"];
954 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
955 // It can happen that a zero date is in the database, but storing it again is forbidden.
956 if ($last_contact < NULL_DATE) {
957 $last_contact = NULL_DATE;
959 if ($last_failure < NULL_DATE) {
960 $last_failure = NULL_DATE;
963 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
964 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
965 return ($last_contact >= $last_failure);
974 $register_policy = -1;
975 $registered_users = 0;
977 $last_contact = NULL_DATE;
978 $last_failure = NULL_DATE;
980 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
983 $possible_failure = false;
984 $orig_last_failure = $last_failure;
985 $orig_last_contact = $last_contact;
987 // Mastodon uses the "@" for user profiles.
988 // But this can be misunderstood.
989 if (parse_url($server_url, PHP_URL_USER) != '') {
990 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
994 // Check if the page is accessible via SSL.
995 $orig_server_url = $server_url;
996 $server_url = str_replace("http://", "https://", $server_url);
998 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
999 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1001 // Quit if there is a timeout.
1002 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1003 if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
1004 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1005 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1006 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1010 // Maybe the page is unencrypted only?
1011 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1012 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1013 $server_url = str_replace("https://", "http://", $server_url);
1015 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1016 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1018 // Quit if there is a timeout
1019 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1020 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1021 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1025 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1028 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1029 // Workaround for bad configured servers (known nginx problem)
1030 if (!in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1033 $possible_failure = true;
1036 // If the server has no possible failure we reset the cached data
1037 if (!$possible_failure) {
1042 $register_policy = -1;
1046 // This will be too low, but better than no value at all.
1047 $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
1052 $serverret = Network::curl($server_url."/poco");
1053 if ($serverret["success"]) {
1054 $data = json_decode($serverret["body"]);
1055 if (isset($data->totalResults)) {
1056 $registered_users = $data->totalResults;
1057 $poco = $server_url."/poco";
1058 $server = self::detectPocoData($data);
1060 $platform = $server['platform'];
1061 $network = $server['network'];
1066 // There are servers out there who don't return 404 on a failure
1067 // We have to be sure that don't misunderstand this
1068 if (is_null($data)) {
1077 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1078 $serverret = Network::curl($server_url);
1080 if (!$serverret["success"] || ($serverret["body"] == "")) {
1083 $server = self::detectServerType($serverret["body"]);
1085 $platform = $server['platform'];
1086 $network = $server['network'];
1087 $version = $server['version'];
1088 $site_name = $server['site_name'];
1091 $lines = explode("\n", $serverret["header"]);
1092 if (count($lines)) {
1093 foreach ($lines as $line) {
1094 $line = trim($line);
1095 if (stristr($line, 'X-Diaspora-Version:')) {
1096 $platform = "Diaspora";
1097 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1098 $version = trim(str_replace("x-diaspora-version:", "", $version));
1099 $network = NETWORK_DIASPORA;
1100 $versionparts = explode("-", $version);
1101 $version = $versionparts[0];
1104 if (stristr($line, 'Server: Mastodon')) {
1105 $platform = "Mastodon";
1106 $network = NETWORK_OSTATUS;
1113 if (!$failure && ($poco == "")) {
1114 // Test for Statusnet
1115 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1116 // The "not implemented" is a special treatment for really, really old Friendica versions
1117 $serverret = Network::curl($server_url."/api/statusnet/version.json");
1118 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1119 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1120 $platform = "StatusNet";
1121 // Remove junk that some GNU Social servers return
1122 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1123 $version = trim($version, '"');
1124 $network = NETWORK_OSTATUS;
1127 // Test for GNU Social
1128 $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1129 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1130 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1131 $platform = "GNU Social";
1132 // Remove junk that some GNU Social servers return
1133 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1134 $version = trim($version, '"');
1135 $network = NETWORK_OSTATUS;
1138 // Test for Mastodon
1139 $orig_version = $version;
1140 $serverret = Network::curl($server_url."/api/v1/instance");
1141 if ($serverret["success"] && ($serverret["body"] != '')) {
1142 $data = json_decode($serverret["body"]);
1144 if (isset($data->version)) {
1145 $platform = "Mastodon";
1146 $version = $data->version;
1147 $site_name = $data->title;
1148 $info = $data->description;
1149 $network = NETWORK_OSTATUS;
1151 if (!empty($data->stats->user_count)) {
1152 $registered_users = $data->stats->user_count;
1155 if (strstr($orig_version.$version, 'Pleroma')) {
1156 $platform = 'Pleroma';
1157 $version = trim(str_replace('Pleroma', '', $version));
1162 // Test for Hubzilla and Red
1163 $serverret = Network::curl($server_url."/siteinfo.json");
1164 if ($serverret["success"]) {
1165 $data = json_decode($serverret["body"]);
1166 if (isset($data->url)) {
1167 $platform = $data->platform;
1168 $version = $data->version;
1169 $network = NETWORK_DIASPORA;
1171 if (!empty($data->site_name)) {
1172 $site_name = $data->site_name;
1174 if (!empty($data->channels_total)) {
1175 $registered_users = $data->channels_total;
1177 switch ($data->register_policy) {
1178 case "REGISTER_OPEN":
1179 $register_policy = REGISTER_OPEN;
1181 case "REGISTER_APPROVE":
1182 $register_policy = REGISTER_APPROVE;
1184 case "REGISTER_CLOSED":
1186 $register_policy = REGISTER_CLOSED;
1190 // Test for Hubzilla, Redmatrix or Friendica
1191 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1192 if ($serverret["success"]) {
1193 $data = json_decode($serverret["body"]);
1194 if (isset($data->site->server)) {
1195 if (isset($data->site->platform)) {
1196 $platform = $data->site->platform->PLATFORM_NAME;
1197 $version = $data->site->platform->STD_VERSION;
1198 $network = NETWORK_DIASPORA;
1200 if (isset($data->site->BlaBlaNet)) {
1201 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1202 $version = $data->site->BlaBlaNet->STD_VERSION;
1203 $network = NETWORK_DIASPORA;
1205 if (isset($data->site->hubzilla)) {
1206 $platform = $data->site->hubzilla->PLATFORM_NAME;
1207 $version = $data->site->hubzilla->RED_VERSION;
1208 $network = NETWORK_DIASPORA;
1210 if (isset($data->site->redmatrix)) {
1211 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1212 $platform = $data->site->redmatrix->PLATFORM_NAME;
1213 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1214 $platform = $data->site->redmatrix->RED_PLATFORM;
1217 $version = $data->site->redmatrix->RED_VERSION;
1218 $network = NETWORK_DIASPORA;
1220 if (isset($data->site->friendica)) {
1221 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1222 $version = $data->site->friendica->FRIENDICA_VERSION;
1223 $network = NETWORK_DFRN;
1226 $site_name = $data->site->name;
1228 $data->site->closed = self::toBoolean($data->site->closed);
1229 $data->site->private = self::toBoolean($data->site->private);
1230 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1232 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1233 $register_policy = REGISTER_APPROVE;
1234 } elseif (!$data->site->closed && !$data->site->private) {
1235 $register_policy = REGISTER_OPEN;
1237 $register_policy = REGISTER_CLOSED;
1244 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1246 $serverret = Network::curl($server_url."/statistics.json");
1247 if ($serverret["success"]) {
1248 $data = json_decode($serverret["body"]);
1250 if (isset($data->version)) {
1251 $version = $data->version;
1252 // Version numbers on statistics.json are presented with additional info, e.g.:
1253 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1254 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1257 if (!empty($data->name)) {
1258 $site_name = $data->name;
1261 if (!empty($data->network)) {
1262 $platform = $data->network;
1265 if ($platform == "Diaspora") {
1266 $network = NETWORK_DIASPORA;
1269 if ($data->registrations_open) {
1270 $register_policy = REGISTER_OPEN;
1272 $register_policy = REGISTER_CLOSED;
1277 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1279 $server = self::fetchNodeinfo($server_url);
1281 $register_policy = $server['register_policy'];
1283 if (isset($server['platform'])) {
1284 $platform = $server['platform'];
1287 if (isset($server['network'])) {
1288 $network = $server['network'];
1291 if (isset($server['version'])) {
1292 $version = $server['version'];
1295 if (isset($server['site_name'])) {
1296 $site_name = $server['site_name'];
1299 if (isset($server['registered-users'])) {
1300 $registered_users = $server['registered-users'];
1305 // Check for noscrape
1306 // Friendica servers could be detected as OStatus servers
1307 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1308 $serverret = Network::curl($server_url."/friendica/json");
1310 if (!$serverret["success"]) {
1311 $serverret = Network::curl($server_url."/friendika/json");
1314 if ($serverret["success"]) {
1315 $data = json_decode($serverret["body"]);
1317 if (isset($data->version)) {
1318 $network = NETWORK_DFRN;
1320 $noscrape = defaults($data->no_scrape_url, '');
1321 $version = $data->version;
1322 $site_name = $data->site_name;
1323 $info = $data->info;
1324 $register_policy = constant($data->register_policy);
1325 $platform = $data->platform;
1330 // Every server has got at least an admin account
1331 if (!$failure && ($registered_users == 0)) {
1332 $registered_users = 1;
1335 if ($possible_failure && !$failure) {
1340 $last_contact = $orig_last_contact;
1341 $last_failure = DateTimeFormat::utcNow();
1343 $last_contact = DateTimeFormat::utcNow();
1344 $last_failure = $orig_last_failure;
1347 if (($last_contact <= $last_failure) && !$failure) {
1348 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1349 } elseif (($last_contact >= $last_failure) && $failure) {
1350 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1353 // Check again if the server exists
1354 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1356 $version = strip_tags($version);
1357 $site_name = strip_tags($site_name);
1358 $info = strip_tags($info);
1359 $platform = strip_tags($platform);
1361 $fields = ['url' => $server_url, 'version' => $version,
1362 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1363 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1364 'platform' => $platform, 'registered-users' => $registered_users,
1365 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1368 dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1369 } elseif (!$failure) {
1370 $fields['nurl'] = normalise_link($server_url);
1371 $fields['created'] = DateTimeFormat::utcNow();
1372 dba::insert('gserver', $fields);
1375 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1376 self::discoverRelay($server_url);
1379 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1385 * @brief Fetch relay data from a given server url
1387 * @param string $server_url address of the server
1389 private static function discoverRelay($server_url)
1391 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1393 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1394 if (!$serverret["success"]) {
1398 $data = json_decode($serverret['body']);
1399 if (!is_object($data)) {
1403 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1404 if (!DBM::is_result($gserver)) {
1408 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1409 $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1410 dba::update('gserver', $fields, ['id' => $gserver['id']]);
1413 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1414 if ($data->scope == 'tags') {
1417 foreach ($data->tags as $tag) {
1418 $tag = mb_strtolower($tag);
1422 foreach ($tags as $tag) {
1423 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1427 // Create or update the relay contact
1429 if (isset($data->protocols)) {
1430 if (isset($data->protocols->diaspora)) {
1431 $fields['network'] = NETWORK_DIASPORA;
1432 if (isset($data->protocols->diaspora->receive)) {
1433 $fields['batch'] = $data->protocols->diaspora->receive;
1434 } elseif (is_string($data->protocols->diaspora)) {
1435 $fields['batch'] = $data->protocols->diaspora;
1438 if (isset($data->protocols->dfrn)) {
1439 $fields['network'] = NETWORK_DFRN;
1440 if (isset($data->protocols->dfrn->receive)) {
1441 $fields['batch'] = $data->protocols->dfrn->receive;
1442 } elseif (is_string($data->protocols->dfrn)) {
1443 $fields['batch'] = $data->protocols->dfrn;
1447 Diaspora::setRelayContact($server_url, $fields);
1451 * @brief Returns a list of all known servers
1452 * @return array List of server urls
1454 public static function serverlist()
1457 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1458 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1459 ORDER BY `last_contact`
1461 dbesc(NETWORK_DFRN),
1462 dbesc(NETWORK_DIASPORA),
1463 dbesc(NETWORK_OSTATUS)
1466 if (!DBM::is_result($r)) {
1474 * @brief Fetch server list from remote servers and adds them when they are new.
1476 * @param string $poco URL to the POCO endpoint
1478 private static function fetchServerlist($poco)
1480 $serverret = Network::curl($poco."/@server");
1481 if (!$serverret["success"]) {
1484 $serverlist = json_decode($serverret['body']);
1486 if (!is_array($serverlist)) {
1490 foreach ($serverlist as $server) {
1491 $server_url = str_replace("/index.php", "", $server->url);
1493 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1494 if (!DBM::is_result($r)) {
1495 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1496 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1501 private static function discoverFederation()
1503 $last = Config::get('poco', 'last_federation_discovery');
1506 $next = $last + (24 * 60 * 60);
1507 if ($next > time()) {
1512 // Discover Friendica, Hubzilla and Diaspora servers
1513 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1516 $servers = json_decode($serverdata);
1518 if (is_array($servers->pods)) {
1519 foreach ($servers->pods as $server) {
1520 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1525 // Disvover Mastodon servers
1526 if (!Config::get('system', 'ostatus_disabled')) {
1527 $accesstoken = Config::get('system', 'instances_social_key');
1528 if (!empty($accesstoken)) {
1529 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1530 $header = ['Authorization: Bearer '.$accesstoken];
1531 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1532 if ($serverdata['success']) {
1533 $servers = json_decode($serverdata['body']);
1534 foreach ($servers->instances as $server) {
1535 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1536 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1542 // Currently disabled, since the service isn't available anymore.
1543 // It is not removed since I hope that there will be a successor.
1544 // Discover GNU Social Servers.
1545 //if (!Config::get('system','ostatus_disabled')) {
1546 // $serverdata = "http://gstools.org/api/get_open_instances/";
1548 // $result = Network::curl($serverdata);
1549 // if ($result["success"]) {
1550 // $servers = json_decode($result["body"]);
1552 // foreach($servers->data as $server)
1553 // self::checkServer($server->instance_address);
1557 Config::set('poco', 'last_federation_discovery', time());
1560 public static function discoverSingleServer($id)
1562 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1563 if (!DBM::is_result($r)) {
1569 // Discover new servers out there (Works from Friendica version 3.5.2)
1570 self::fetchServerlist($server["poco"]);
1572 // Fetch all users from the other server
1573 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1575 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1577 $retdata = Network::curl($url);
1578 if ($retdata["success"]) {
1579 $data = json_decode($retdata["body"]);
1581 self::discoverServer($data, 2);
1583 if (Config::get('system', 'poco_discovery') > 1) {
1584 $timeframe = Config::get('system', 'poco_discovery_since');
1585 if ($timeframe == 0) {
1589 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1591 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1592 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1596 $retdata = Network::curl($url);
1597 if ($retdata["success"]) {
1598 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1599 $success = self::discoverServer(json_decode($retdata["body"]));
1602 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1603 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1604 self::discoverServerUsers($data, $server);
1608 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1609 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1613 // If the server hadn't replied correctly, then force a sanity check
1614 self::checkServer($server["url"], $server["network"], true);
1616 // If we couldn't reach the server, we will try it some time later
1617 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1618 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1624 public static function discover($complete = false)
1626 // Update the server list
1627 self::discoverFederation();
1631 $requery_days = intval(Config::get("system", "poco_requery_days"));
1633 if ($requery_days == 0) {
1636 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1638 $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));
1639 if (DBM::is_result($r)) {
1640 foreach ($r as $server) {
1641 if (!self::checkServer($server["url"], $server["network"])) {
1642 // The server is not reachable? Okay, then we will try it later
1643 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1644 dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1648 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1649 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1651 if (!$complete && (--$no_of_queries == 0)) {
1658 private static function discoverServerUsers($data, $server)
1660 if (!isset($data->entry)) {
1664 foreach ($data->entry as $entry) {
1666 if (isset($entry->urls)) {
1667 foreach ($entry->urls as $url) {
1668 if ($url->type == 'profile') {
1669 $profile_url = $url->value;
1670 $urlparts = parse_url($profile_url);
1671 $username = end(explode("/", $urlparts["path"]));
1675 if ($username != "") {
1676 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1678 // Fetch all contacts from a given user from the other server
1679 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1681 $retdata = Network::curl($url);
1682 if ($retdata["success"]) {
1683 self::discoverServer(json_decode($retdata["body"]), 3);
1689 private static function discoverServer($data, $default_generation = 0)
1691 if (!isset($data->entry) || !count($data->entry)) {
1697 foreach ($data->entry as $entry) {
1699 $profile_photo = '';
1703 $updated = NULL_DATE;
1709 $generation = $default_generation;
1711 $name = $entry->displayName;
1713 if (isset($entry->urls)) {
1714 foreach ($entry->urls as $url) {
1715 if ($url->type == 'profile') {
1716 $profile_url = $url->value;
1719 if ($url->type == 'webfinger') {
1720 $connect_url = str_replace('acct:' , '', $url->value);
1726 if (isset($entry->photos)) {
1727 foreach ($entry->photos as $photo) {
1728 if ($photo->type == 'profile') {
1729 $profile_photo = $photo->value;
1735 if (isset($entry->updated)) {
1736 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1739 if (isset($entry->network)) {
1740 $network = $entry->network;
1743 if (isset($entry->currentLocation)) {
1744 $location = $entry->currentLocation;
1747 if (isset($entry->aboutMe)) {
1748 $about = HTML::toBBCode($entry->aboutMe);
1751 if (isset($entry->gender)) {
1752 $gender = $entry->gender;
1755 if (isset($entry->generation) && ($entry->generation > 0)) {
1756 $generation = ++$entry->generation;
1759 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1760 $contact_type = $entry->contactType;
1763 if (isset($entry->tags)) {
1764 foreach ($entry->tags as $tag) {
1765 $keywords = implode(", ", $tag);
1769 if ($generation > 0) {
1772 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1774 $gcontact = ["url" => $profile_url,
1776 "network" => $network,
1777 "photo" => $profile_photo,
1779 "location" => $location,
1780 "gender" => $gender,
1781 "keywords" => $keywords,
1782 "connect" => $connect_url,
1783 "updated" => $updated,
1784 "contact-type" => $contact_type,
1785 "generation" => $generation];
1788 $gcontact = GContact::sanitize($gcontact);
1789 GContact::update($gcontact);
1790 } catch (Exception $e) {
1791 logger($e->getMessage(), LOGGER_DEBUG);
1794 logger("Done for profile ".$profile_url, LOGGER_DEBUG);