3 * @file include/socgraph.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
11 use Friendica\Core\Config;
12 use Friendica\Network\Probe;
14 require_once 'include/datetime.php';
15 require_once 'include/probe.php';
16 require_once 'include/network.php';
17 require_once 'include/html2bbcode.php';
18 require_once 'include/Contact.php';
19 require_once 'include/Photo.php';
22 * @brief Fetch POCO data
24 * @param integer $cid Contact ID
25 * @param integer $uid User ID
26 * @param integer $zcid Global Contact ID
27 * @param integer $url POCO address that should be polled
29 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
30 * and add the entries to the gcontact (Global Contact) table, or update existing entries
31 * if anything (name or photo) has changed.
32 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
34 * Once the global contact is stored add (if necessary) the contact linkage which associates
35 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
36 * pointing to the same global contact id.
39 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
40 // Call the function "poco_load_worker" via the worker
41 proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
45 * @brief Fetch POCO data from the worker
47 * @param integer $cid Contact ID
48 * @param integer $uid User ID
49 * @param integer $zcid Global Contact ID
50 * @param integer $url POCO address that should be polled
53 function poco_load_worker($cid, $uid, $zcid, $url) {
57 if ((! $url) || (! $uid)) {
58 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
61 if (dbm::is_result($r)) {
73 $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') ;
75 logger('poco_load: ' . $url, LOGGER_DEBUG);
79 logger('poco_load: returns ' . $s, LOGGER_DATA);
81 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
83 if (($a->get_curl_code() > 299) || (! $s))
88 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
90 if (! isset($j->entry))
94 foreach ($j->entry as $entry) {
102 $updated = NULL_DATE;
110 $name = $entry->displayName;
112 if (isset($entry->urls)) {
113 foreach ($entry->urls as $url) {
114 if ($url->type == 'profile') {
115 $profile_url = $url->value;
118 if ($url->type == 'webfinger') {
119 $connect_url = str_replace('acct:' , '', $url->value);
124 if (isset($entry->photos)) {
125 foreach ($entry->photos as $photo) {
126 if ($photo->type == 'profile') {
127 $profile_photo = $photo->value;
133 if (isset($entry->updated)) {
134 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
137 if (isset($entry->network)) {
138 $network = $entry->network;
141 if (isset($entry->currentLocation)) {
142 $location = $entry->currentLocation;
145 if (isset($entry->aboutMe)) {
146 $about = html2bbcode($entry->aboutMe);
149 if (isset($entry->gender)) {
150 $gender = $entry->gender;
153 if (isset($entry->generation) AND ($entry->generation > 0)) {
154 $generation = ++$entry->generation;
157 if (isset($entry->tags)) {
158 foreach ($entry->tags as $tag) {
159 $keywords = implode(", ", $tag);
163 if (isset($entry->contactType) AND ($entry->contactType >= 0))
164 $contact_type = $entry->contactType;
166 $gcontact = array("url" => $profile_url,
168 "network" => $network,
169 "photo" => $profile_photo,
171 "location" => $location,
173 "keywords" => $keywords,
174 "connect" => $connect_url,
175 "updated" => $updated,
176 "contact-type" => $contact_type,
177 "generation" => $generation);
180 $gcontact = sanitize_gcontact($gcontact);
181 $gcid = update_gcontact($gcontact);
183 link_gcontact($gcid, $uid, $cid, $zcid);
184 } catch (Exception $e) {
185 logger($e->getMessage(), LOGGER_DEBUG);
188 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
190 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
198 * @brief Sanitize the given gcontact data
200 * @param array $gcontact array with gcontact data
205 * 1: Profiles on this server
206 * 2: Contacts of profiles on this server
207 * 3: Contacts of contacts of profiles on this server
211 function sanitize_gcontact($gcontact) {
213 if ($gcontact['url'] == "") {
214 throw new Exception('URL is empty');
217 $urlparts = parse_url($gcontact['url']);
218 if (!isset($urlparts["scheme"])) {
219 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
222 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
223 "identi.ca", "alpha.app.net"))) {
224 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
227 // Don't store the statusnet connector as network
228 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
229 if ($gcontact['network'] == NETWORK_STATUSNET) {
230 $gcontact['network'] = "";
233 // Assure that there are no parameter fragments in the profile url
234 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
235 $gcontact['url'] = clean_contact_url($gcontact['url']);
238 $alternate = poco_alternate_ostatus_url($gcontact['url']);
240 // The global contacts should contain the original picture, not the cached one
241 if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
242 $gcontact['photo'] = "";
245 if (!isset($gcontact['network'])) {
246 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
247 dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
249 if (dbm::is_result($r)) {
250 $gcontact['network'] = $r[0]["network"];
253 if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
254 $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
255 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
257 if (dbm::is_result($r)) {
258 $gcontact['network'] = $r[0]["network"];
263 $gcontact['server_url'] = '';
264 $gcontact['network'] = '';
266 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
267 dbesc(normalise_link($gcontact['url']))
271 if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
272 $gcontact['network'] = $x[0]["network"];
274 if ($gcontact['updated'] <= NULL_DATE) {
275 $gcontact['updated'] = $x[0]["updated"];
277 if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
278 $gcontact['server_url'] = $x[0]["server_url"];
280 if (!isset($gcontact['addr'])) {
281 $gcontact['addr'] = $x[0]["addr"];
285 if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
286 AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
287 $data = Probe::uri($gcontact['url']);
289 if ($data["network"] == NETWORK_PHANTOM) {
290 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
293 $orig_profile = $gcontact['url'];
295 $gcontact["server_url"] = $data["baseurl"];
297 $gcontact = array_merge($gcontact, $data);
299 if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
300 // Delete the old entry - if it exists
301 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
303 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
304 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
309 if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
310 throw new Exception('No name and photo for URL '.$gcontact['url']);
313 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
314 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
317 if (!isset($gcontact['server_url'])) {
318 // We check the server url to be sure that it is a real one
319 $server_url = poco_detect_server($gcontact['url']);
321 // We are now sure that it is a correct URL. So we use it in the future
322 if ($server_url != "") {
323 $gcontact['server_url'] = $server_url;
327 // The server URL doesn't seem to be valid, so we don't store it.
328 if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
329 $gcontact['server_url'] = "";
336 * @brief Link the gcontact entry with user, contact and global contact
338 * @param integer $gcid Global contact ID
339 * @param integer $cid Contact ID
340 * @param integer $uid User ID
341 * @param integer $zcid Global Contact ID
344 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
350 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
356 if (!dbm::is_result($r)) {
357 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
362 dbesc(datetime_convert())
365 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
366 dbesc(datetime_convert()),
375 function poco_reachable($profile, $server = "", $network = "", $force = false) {
378 $server = poco_detect_server($profile);
385 return poco_check_server($server, $network, $force);
388 function poco_detect_server($profile) {
390 // Try to detect the server path based upon some known standard paths
393 if ($server_url == "") {
394 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
395 if ($friendica != $profile) {
396 $server_url = $friendica;
397 $network = NETWORK_DFRN;
401 if ($server_url == "") {
402 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
403 if ($diaspora != $profile) {
404 $server_url = $diaspora;
405 $network = NETWORK_DIASPORA;
409 if ($server_url == "") {
410 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
411 if ($red != $profile) {
413 $network = NETWORK_DIASPORA;
418 if ($server_url == "") {
419 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
420 if ($mastodon != $profile) {
421 $server_url = $mastodon;
422 $network = NETWORK_OSTATUS;
426 // Numeric OStatus variant
427 if ($server_url == "") {
428 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
429 if ($ostatus != $profile) {
430 $server_url = $ostatus;
431 $network = NETWORK_OSTATUS;
436 if ($server_url == "") {
437 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
438 if ($base != $profile) {
440 $network = NETWORK_PHANTOM;
444 if ($server_url == "") {
448 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
449 dbesc(normalise_link($server_url)));
450 if (dbm::is_result($r)) {
454 // Fetch the host-meta to check if this really is a server
455 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
456 if (!$serverret["success"]) {
463 function poco_alternate_ostatus_url($url) {
464 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
467 function poco_last_updated($profile, $force = false) {
469 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
470 dbesc(normalise_link($profile)));
472 if (!dbm::is_result($gcontacts)) {
476 $contact = array("url" => $profile);
478 if ($gcontacts[0]["created"] <= NULL_DATE) {
479 $contact['created'] = datetime_convert();
483 $server_url = normalise_link(poco_detect_server($profile));
486 if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
487 $server_url = $gcontacts[0]["server_url"];
490 if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
491 $server_url = normalise_link(poco_detect_server($profile));
494 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
495 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
499 if ($server_url != "") {
500 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
502 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
503 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
506 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
509 $contact['server_url'] = $server_url;
512 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
513 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
514 dbesc(normalise_link($server_url)));
517 $contact['network'] = $server[0]["network"];
523 // noscrape is really fast so we don't cache the call.
524 if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
526 // Use noscrape if possible
527 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
530 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
532 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
534 $noscrape = json_decode($noscraperet["body"], true);
536 if (is_array($noscrape)) {
537 $contact["network"] = $server[0]["network"];
539 if (isset($noscrape["fn"])) {
540 $contact["name"] = $noscrape["fn"];
542 if (isset($noscrape["comm"])) {
543 $contact["community"] = $noscrape["comm"];
545 if (isset($noscrape["tags"])) {
546 $keywords = implode(" ", $noscrape["tags"]);
547 if ($keywords != "") {
548 $contact["keywords"] = $keywords;
552 $location = formatted_location($noscrape);
554 $contact["location"] = $location;
556 if (isset($noscrape["dfrn-notify"])) {
557 $contact["notify"] = $noscrape["dfrn-notify"];
559 // Remove all fields that are not present in the gcontact table
560 unset($noscrape["fn"]);
561 unset($noscrape["key"]);
562 unset($noscrape["homepage"]);
563 unset($noscrape["comm"]);
564 unset($noscrape["tags"]);
565 unset($noscrape["locality"]);
566 unset($noscrape["region"]);
567 unset($noscrape["country-name"]);
568 unset($noscrape["contacts"]);
569 unset($noscrape["dfrn-request"]);
570 unset($noscrape["dfrn-confirm"]);
571 unset($noscrape["dfrn-notify"]);
572 unset($noscrape["dfrn-poll"]);
574 // Set the date of the last contact
575 /// @todo By now the function "update_gcontact" doesn't work with this field
576 //$contact["last_contact"] = datetime_convert();
578 $contact = array_merge($contact, $noscrape);
580 update_gcontact($contact);
582 if (trim($noscrape["updated"]) != "") {
583 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
584 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
586 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
588 return $noscrape["updated"];
595 // If we only can poll the feed, then we only do this once a while
596 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
597 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
599 update_gcontact($contact);
600 return $gcontacts[0]["updated"];
603 $data = Probe::uri($profile);
605 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
606 // Then check the other link and delete this one
607 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
608 (normalise_link($profile) == normalise_link($data["alias"])) AND
609 (normalise_link($profile) != normalise_link($data["url"]))) {
611 // Delete the old entry
612 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
613 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
615 $gcontact = array_merge($gcontacts[0], $data);
617 $gcontact["server_url"] = $data["baseurl"];
620 $gcontact = sanitize_gcontact($gcontact);
621 update_gcontact($gcontact);
623 poco_last_updated($data["url"], $force);
624 } catch (Exception $e) {
625 logger($e->getMessage(), LOGGER_DEBUG);
628 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
632 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
633 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
634 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
636 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
640 $contact = array_merge($contact, $data);
642 $contact["server_url"] = $data["baseurl"];
644 update_gcontact($contact);
646 $feedret = z_fetch_url($data["poll"]);
648 if (!$feedret["success"]) {
649 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
650 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
652 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
656 $doc = new DOMDocument();
657 @$doc->loadXML($feedret["body"]);
659 $xpath = new DomXPath($doc);
660 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
662 $entries = $xpath->query('/atom:feed/atom:entry');
666 foreach ($entries AS $entry) {
667 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
668 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
670 if ($last_updated < $published)
671 $last_updated = $published;
673 if ($last_updated < $updated)
674 $last_updated = $updated;
677 // Maybe there aren't any entries. Then check if it is a valid feed
678 if ($last_updated == "") {
679 if ($xpath->query('/atom:feed')->length > 0) {
680 $last_updated = NULL_DATE;
683 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
684 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
686 if (($gcontacts[0]["generation"] == 0)) {
687 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
688 dbesc(normalise_link($profile)));
691 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
693 return($last_updated);
696 function poco_do_update($created, $updated, $last_failure, $last_contact) {
697 $now = strtotime(datetime_convert());
699 if ($updated > $last_contact)
700 $contact_time = strtotime($updated);
702 $contact_time = strtotime($last_contact);
704 $failure_time = strtotime($last_failure);
705 $created_time = strtotime($created);
707 // If there is no "created" time then use the current time
708 if ($created_time <= 0)
709 $created_time = $now;
711 // If the last contact was less than 24 hours then don't update
712 if (($now - $contact_time) < (60 * 60 * 24))
715 // If the last failure was less than 24 hours then don't update
716 if (($now - $failure_time) < (60 * 60 * 24))
719 // If the last contact was less than a week ago and the last failure is older than a week then don't update
720 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
723 // 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
724 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
727 // 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
728 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
734 function poco_to_boolean($val) {
735 if (($val == "true") OR ($val == 1))
737 if (($val == "false") OR ($val == 0))
744 * @brief Detect server type (Hubzilla or Friendica) via the poco data
746 * @param object $data POCO data
747 * @return array Server data
749 function poco_detect_poco_data($data) {
752 if (!isset($data->entry)) {
756 if (count($data->entry) == 0) {
760 if (!isset($data->entry[0]->urls)) {
764 if (count($data->entry[0]->urls) == 0) {
768 foreach ($data->entry[0]->urls AS $url) {
769 if ($url->type == 'zot') {
771 $server["platform"] = 'Hubzilla';
772 $server["network"] = NETWORK_DIASPORA;
780 * @brief Detect server type by using the nodeinfo data
782 * @param string $server_url address of the server
783 * @return array Server data
785 function poco_fetch_nodeinfo($server_url) {
786 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
787 if (!$serverret["success"]) {
791 $nodeinfo = json_decode($serverret['body']);
793 if (!is_object($nodeinfo)) {
797 if (!is_array($nodeinfo->links)) {
803 foreach ($nodeinfo->links AS $link) {
804 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
805 $nodeinfo_url = $link->href;
809 if ($nodeinfo_url == '') {
813 $serverret = z_fetch_url($nodeinfo_url);
814 if (!$serverret["success"]) {
818 $nodeinfo = json_decode($serverret['body']);
820 if (!is_object($nodeinfo)) {
826 $server['register_policy'] = REGISTER_CLOSED;
828 if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
829 $server['register_policy'] = REGISTER_OPEN;
832 if (is_object($nodeinfo->software)) {
833 if (isset($nodeinfo->software->name)) {
834 $server['platform'] = $nodeinfo->software->name;
837 if (isset($nodeinfo->software->version)) {
838 $server['version'] = $nodeinfo->software->version;
839 // Version numbers on Nodeinfo are presented with additional info, e.g.:
840 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
841 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
845 if (is_object($nodeinfo->metadata)) {
846 if (isset($nodeinfo->metadata->nodeName)) {
847 $server['site_name'] = $nodeinfo->metadata->nodeName;
855 if (is_array($nodeinfo->protocols->inbound)) {
856 foreach ($nodeinfo->protocols->inbound AS $inbound) {
857 if ($inbound == 'diaspora') {
860 if ($inbound == 'friendica') {
863 if ($inbound == 'gnusocial') {
870 $server['network'] = NETWORK_OSTATUS;
873 $server['network'] = NETWORK_DIASPORA;
876 $server['network'] = NETWORK_DFRN;
887 * @brief Detect server type (Hubzilla or Friendica) via the front page body
889 * @param string $body Front page of the server
890 * @return array Server data
892 function poco_detect_server_type($body) {
895 $doc = new DOMDocument();
896 @$doc->loadHTML($body);
897 $xpath = new DomXPath($doc);
899 $list = $xpath->query("//meta[@name]");
901 foreach ($list as $node) {
903 if ($node->attributes->length) {
904 foreach ($node->attributes as $attribute) {
905 $attr[$attribute->name] = $attribute->value;
908 if ($attr['name'] == 'generator') {
909 $version_part = explode(" ", $attr['content']);
910 if (count($version_part) == 2) {
911 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
913 $server["platform"] = $version_part[0];
914 $server["version"] = $version_part[1];
915 $server["network"] = NETWORK_DFRN;
922 $list = $xpath->query("//meta[@property]");
924 foreach ($list as $node) {
926 if ($node->attributes->length) {
927 foreach ($node->attributes as $attribute) {
928 $attr[$attribute->name] = $attribute->value;
931 if ($attr['property'] == 'generator') {
932 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
934 $server["platform"] = $attr['content'];
935 $server["version"] = "";
936 $server["network"] = NETWORK_DIASPORA;
946 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
950 function poco_check_server($server_url, $network = "", $force = false) {
952 // Unify the server address
953 $server_url = trim($server_url, "/");
954 $server_url = str_replace("/index.php", "", $server_url);
956 if ($server_url == "")
959 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
960 if (dbm::is_result($servers)) {
962 if ($servers[0]["created"] <= NULL_DATE) {
963 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
964 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
966 $poco = $servers[0]["poco"];
967 $noscrape = $servers[0]["noscrape"];
970 $network = $servers[0]["network"];
972 $last_contact = $servers[0]["last_contact"];
973 $last_failure = $servers[0]["last_failure"];
974 $version = $servers[0]["version"];
975 $platform = $servers[0]["platform"];
976 $site_name = $servers[0]["site_name"];
977 $info = $servers[0]["info"];
978 $register_policy = $servers[0]["register_policy"];
980 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
981 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
982 return ($last_contact >= $last_failure);
991 $register_policy = -1;
993 $last_contact = NULL_DATE;
994 $last_failure = NULL_DATE;
996 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
999 $possible_failure = false;
1000 $orig_last_failure = $last_failure;
1001 $orig_last_contact = $last_contact;
1003 // Check if the page is accessible via SSL.
1004 $orig_server_url = $server_url;
1005 $server_url = str_replace("http://", "https://", $server_url);
1007 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1008 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1010 // Quit if there is a timeout.
1011 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1012 if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1013 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1014 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1015 dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
1019 // Maybe the page is unencrypted only?
1020 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1021 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1022 $server_url = str_replace("https://", "http://", $server_url);
1024 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1025 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1027 // Quit if there is a timeout
1028 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1029 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1030 dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
1034 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1037 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1038 // Workaround for bad configured servers (known nginx problem)
1039 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1042 $possible_failure = true;
1045 // If the server has no possible failure we reset the cached data
1046 if (!$possible_failure) {
1051 $register_policy = -1;
1056 $serverret = z_fetch_url($server_url."/poco");
1057 if ($serverret["success"]) {
1058 $data = json_decode($serverret["body"]);
1059 if (isset($data->totalResults)) {
1060 $poco = $server_url."/poco";
1061 $server = poco_detect_poco_data($data);
1063 $platform = $server['platform'];
1064 $network = $server['network'];
1073 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1074 $serverret = z_fetch_url($server_url);
1076 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1079 $server = poco_detect_server_type($serverret["body"]);
1081 $platform = $server['platform'];
1082 $network = $server['network'];
1083 $version = $server['version'];
1084 $site_name = $server['site_name'];
1087 $lines = explode("\n",$serverret["header"]);
1088 if (count($lines)) {
1089 foreach($lines as $line) {
1090 $line = trim($line);
1091 if (stristr($line,'X-Diaspora-Version:')) {
1092 $platform = "Diaspora";
1093 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1094 $version = trim(str_replace("x-diaspora-version:", "", $version));
1095 $network = NETWORK_DIASPORA;
1096 $versionparts = explode("-", $version);
1097 $version = $versionparts[0];
1100 if (stristr($line,'Server: Mastodon')) {
1101 $platform = "Mastodon";
1102 $network = NETWORK_OSTATUS;
1109 if (!$failure AND ($poco == "")) {
1110 // Test for Statusnet
1111 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1112 // The "not implemented" is a special treatment for really, really old Friendica versions
1113 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1114 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1115 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1116 $platform = "StatusNet";
1117 // Remove junk that some GNU Social servers return
1118 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1119 $version = trim($version, '"');
1120 $network = NETWORK_OSTATUS;
1123 // Test for GNU Social
1124 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1125 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1126 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1127 $platform = "GNU Social";
1128 // Remove junk that some GNU Social servers return
1129 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1130 $version = trim($version, '"');
1131 $network = NETWORK_OSTATUS;
1134 // Test for Mastodon
1135 $serverret = z_fetch_url($server_url."/api/v1/instance");
1136 if ($serverret["success"] AND ($serverret["body"] != '')) {
1137 $data = json_decode($serverret["body"]);
1138 if (isset($data->version)) {
1139 $platform = "Mastodon";
1140 $version = $data->version;
1141 $site_name = $data->title;
1142 $info = $data->description;
1143 $network = NETWORK_OSTATUS;
1149 // Test for Hubzilla, Redmatrix or Friendica
1150 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1151 if ($serverret["success"]) {
1152 $data = json_decode($serverret["body"]);
1153 if (isset($data->site->server)) {
1154 if (isset($data->site->platform)) {
1155 $platform = $data->site->platform->PLATFORM_NAME;
1156 $version = $data->site->platform->STD_VERSION;
1157 $network = NETWORK_DIASPORA;
1159 if (isset($data->site->BlaBlaNet)) {
1160 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1161 $version = $data->site->BlaBlaNet->STD_VERSION;
1162 $network = NETWORK_DIASPORA;
1164 if (isset($data->site->hubzilla)) {
1165 $platform = $data->site->hubzilla->PLATFORM_NAME;
1166 $version = $data->site->hubzilla->RED_VERSION;
1167 $network = NETWORK_DIASPORA;
1169 if (isset($data->site->redmatrix)) {
1170 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1171 $platform = $data->site->redmatrix->PLATFORM_NAME;
1172 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1173 $platform = $data->site->redmatrix->RED_PLATFORM;
1176 $version = $data->site->redmatrix->RED_VERSION;
1177 $network = NETWORK_DIASPORA;
1179 if (isset($data->site->friendica)) {
1180 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1181 $version = $data->site->friendica->FRIENDICA_VERSION;
1182 $network = NETWORK_DFRN;
1185 $site_name = $data->site->name;
1187 $data->site->closed = poco_to_boolean($data->site->closed);
1188 $data->site->private = poco_to_boolean($data->site->private);
1189 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1191 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly) {
1192 $register_policy = REGISTER_APPROVE;
1193 } elseif (!$data->site->closed AND !$data->site->private) {
1194 $register_policy = REGISTER_OPEN;
1196 $register_policy = REGISTER_CLOSED;
1202 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1204 $serverret = z_fetch_url($server_url."/statistics.json");
1205 if ($serverret["success"]) {
1206 $data = json_decode($serverret["body"]);
1207 if (isset($data->version)) {
1208 $version = $data->version;
1209 // Version numbers on statistics.json are presented with additional info, e.g.:
1210 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1211 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1214 $site_name = $data->name;
1216 if (isset($data->network)) {
1217 $platform = $data->network;
1220 if ($platform == "Diaspora") {
1221 $network = NETWORK_DIASPORA;
1224 if ($data->registrations_open) {
1225 $register_policy = REGISTER_OPEN;
1227 $register_policy = REGISTER_CLOSED;
1232 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1234 $server = poco_fetch_nodeinfo($server_url);
1236 $register_policy = $server['register_policy'];
1238 if (isset($server['platform'])) {
1239 $platform = $server['platform'];
1242 if (isset($server['network'])) {
1243 $network = $server['network'];
1246 if (isset($server['version'])) {
1247 $version = $server['version'];
1250 if (isset($server['site_name'])) {
1251 $site_name = $server['site_name'];
1256 // Check for noscrape
1257 // Friendica servers could be detected as OStatus servers
1258 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1259 $serverret = z_fetch_url($server_url."/friendica/json");
1261 if (!$serverret["success"]) {
1262 $serverret = z_fetch_url($server_url."/friendika/json");
1265 if ($serverret["success"]) {
1266 $data = json_decode($serverret["body"]);
1268 if (isset($data->version)) {
1269 $network = NETWORK_DFRN;
1271 $noscrape = $data->no_scrape_url;
1272 $version = $data->version;
1273 $site_name = $data->site_name;
1274 $info = $data->info;
1275 $register_policy_str = $data->register_policy;
1276 $platform = $data->platform;
1278 switch ($register_policy_str) {
1279 case "REGISTER_CLOSED":
1280 $register_policy = REGISTER_CLOSED;
1282 case "REGISTER_APPROVE":
1283 $register_policy = REGISTER_APPROVE;
1285 case "REGISTER_OPEN":
1286 $register_policy = REGISTER_OPEN;
1293 if ($possible_failure AND !$failure) {
1298 $last_contact = $orig_last_contact;
1299 $last_failure = datetime_convert();
1301 $last_contact = datetime_convert();
1302 $last_failure = $orig_last_failure;
1305 if (($last_contact <= $last_failure) AND !$failure) {
1306 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1307 } elseif (($last_contact >= $last_failure) AND $failure) {
1308 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1311 // Check again if the server exists
1312 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1314 $version = strip_tags($version);
1315 $site_name = strip_tags($site_name);
1316 $info = strip_tags($info);
1317 $platform = strip_tags($platform);
1320 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1321 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1326 intval($register_policy),
1331 dbesc($last_contact),
1332 dbesc($last_failure),
1333 dbesc(normalise_link($server_url))
1335 } elseif (!$failure) {
1336 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1337 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1339 dbesc(normalise_link($server_url)),
1343 intval($register_policy),
1348 dbesc(datetime_convert()),
1349 dbesc($last_contact),
1350 dbesc($last_failure),
1351 dbesc(datetime_convert())
1354 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1359 function count_common_friends($uid,$cid) {
1361 $r = q("SELECT count(*) as `total`
1362 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1363 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1364 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1365 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1372 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1373 if (dbm::is_result($r))
1374 return $r[0]['total'];
1380 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1383 $sql_extra = " order by rand() ";
1385 $sql_extra = " order by `gcontact`.`name` asc ";
1388 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1390 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1391 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1392 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1393 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1394 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1395 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1396 $sql_extra LIMIT %d, %d",
1405 /// @TODO Check all calling-findings of this function if they properly use dbm::is_result()
1411 function count_common_friends_zcid($uid,$zcid) {
1413 $r = q("SELECT count(*) as `total`
1414 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1415 where `glink`.`zcid` = %d
1416 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1421 if (dbm::is_result($r))
1422 return $r[0]['total'];
1427 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1430 $sql_extra = " order by rand() ";
1432 $sql_extra = " order by `gcontact`.`name` asc ";
1434 $r = q("SELECT `gcontact`.*
1435 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1436 where `glink`.`zcid` = %d
1437 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1438 $sql_extra limit %d, %d",
1445 /// @TODO Check all calling-findings of this function if they properly use dbm::is_result()
1451 function count_all_friends($uid,$cid) {
1453 $r = q("SELECT count(*) as `total`
1454 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1455 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1456 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1461 if (dbm::is_result($r)) {
1462 return $r[0]['total'];
1469 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1471 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1473 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1474 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1475 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1476 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1477 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1485 /// @TODO Check all calling-findings of this function if they properly use dbm::is_result()
1491 function suggestion_query($uid, $start = 0, $limit = 80) {
1497 // Uncommented because the result of the queries are to big to store it in the cache.
1498 // We need to decide if we want to change the db column type or if we want to delete it.
1499 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1500 // if (!is_null($list)) {
1504 $network = array(NETWORK_DFRN);
1506 if (get_config('system','diaspora_enabled')) {
1507 $network[] = NETWORK_DIASPORA;
1510 if (!get_config('system','ostatus_disabled')) {
1511 $network[] = NETWORK_OSTATUS;
1514 $sql_network = implode("', '", $network);
1515 $sql_network = "'".$sql_network."'";
1517 /// @todo This query is really slow
1518 // By now we cache the data for five minutes
1519 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1520 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1521 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1522 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1523 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1524 AND `gcontact`.`updated` >= '%s'
1525 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1526 AND `gcontact`.`network` IN (%s)
1527 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1538 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1539 // Uncommented because the result of the queries are to big to store it in the cache.
1540 // We need to decide if we want to change the db column type or if we want to delete it.
1541 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1546 $r2 = q("SELECT gcontact.* FROM gcontact
1547 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1548 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1549 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1550 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1551 AND `gcontact`.`updated` >= '%s'
1552 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1553 AND `gcontact`.`network` IN (%s)
1554 ORDER BY rand() LIMIT %d, %d",
1565 foreach ($r2 AS $suggestion) {
1566 $list[$suggestion["nurl"]] = $suggestion;
1569 foreach ($r AS $suggestion) {
1570 $list[$suggestion["nurl"]] = $suggestion;
1573 while (sizeof($list) > ($limit)) {
1577 // Uncommented because the result of the queries are to big to store it in the cache.
1578 // We need to decide if we want to change the db column type or if we want to delete it.
1579 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1583 function update_suggestions() {
1589 /// @TODO Check if it is really neccessary to poll the own server
1590 poco_load(0,0,0,App::get_baseurl() . '/poco');
1592 $done[] = App::get_baseurl() . '/poco';
1594 if (strlen(get_config('system','directory'))) {
1595 $x = fetch_url(get_server()."/pubsites");
1597 $j = json_decode($x);
1599 foreach ($j->entries as $entry) {
1601 poco_check_server($entry->url);
1603 $url = $entry->url . '/poco';
1604 if (! in_array($url,$done)) {
1605 poco_load(0,0,0,$entry->url . '/poco');
1612 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1613 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1614 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1617 if (dbm::is_result($r)) {
1618 foreach ($r as $rr) {
1619 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1620 if (! in_array($base,$done)) {
1621 poco_load(0,0,0,$base);
1628 * @brief Fetch server list from remote servers and adds them when they are new.
1630 * @param string $poco URL to the POCO endpoint
1632 function poco_fetch_serverlist($poco) {
1633 $serverret = z_fetch_url($poco."/@server");
1634 if (!$serverret["success"]) {
1637 $serverlist = json_decode($serverret['body']);
1639 if (!is_array($serverlist)) {
1643 foreach ($serverlist AS $server) {
1644 $server_url = str_replace("/index.php", "", $server->url);
1646 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1647 if (!dbm::is_result($r)) {
1648 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1649 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1654 function poco_discover_federation() {
1655 $last = get_config('poco','last_federation_discovery');
1658 $next = $last + (24 * 60 * 60);
1659 if ($next > time()) {
1664 // Discover Friendica, Hubzilla and Diaspora servers
1665 $serverdata = fetch_url("http://the-federation.info/pods.json");
1668 $servers = json_decode($serverdata);
1670 foreach ($servers->pods AS $server) {
1671 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1675 // Disvover Mastodon servers
1676 if (!Config::get('system','ostatus_disabled')) {
1677 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1680 $servers = json_decode($serverdata);
1682 foreach ($servers AS $server) {
1683 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1684 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($url));
1689 // Currently disabled, since the service isn't available anymore.
1690 // It is not removed since I hope that there will be a successor.
1691 // Discover GNU Social Servers.
1692 //if (!get_config('system','ostatus_disabled')) {
1693 // $serverdata = "http://gstools.org/api/get_open_instances/";
1695 // $result = z_fetch_url($serverdata);
1696 // if ($result["success"]) {
1697 // $servers = json_decode($result["body"]);
1699 // foreach($servers->data AS $server)
1700 // poco_check_server($server->instance_address);
1704 set_config('poco','last_federation_discovery', time());
1707 function poco_discover_single_server($id) {
1708 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1709 if (!dbm::is_result($r)) {
1715 // Discover new servers out there (Works from Friendica version 3.5.2)
1716 poco_fetch_serverlist($server["poco"]);
1718 // Fetch all users from the other server
1719 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1721 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1723 $retdata = z_fetch_url($url);
1724 if ($retdata["success"]) {
1725 $data = json_decode($retdata["body"]);
1727 poco_discover_server($data, 2);
1729 if (get_config('system','poco_discovery') > 1) {
1731 $timeframe = get_config('system','poco_discovery_since');
1732 if ($timeframe == 0) {
1736 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1738 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1739 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1743 $retdata = z_fetch_url($url);
1744 if ($retdata["success"]) {
1745 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1746 $success = poco_discover_server(json_decode($retdata["body"]));
1749 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1750 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1751 poco_discover_server_users($data, $server);
1755 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1759 // If the server hadn't replied correctly, then force a sanity check
1760 poco_check_server($server["url"], $server["network"], true);
1762 // If we couldn't reach the server, we will try it some time later
1763 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1769 function poco_discover($complete = false) {
1771 // Update the server list
1772 poco_discover_federation();
1776 $requery_days = intval(get_config("system", "poco_requery_days"));
1778 if ($requery_days == 0) {
1781 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1783 $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));
1784 if (dbm::is_result($r)) {
1785 foreach ($r AS $server) {
1787 if (!poco_check_server($server["url"], $server["network"])) {
1788 // The server is not reachable? Okay, then we will try it later
1789 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1793 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1794 proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1796 if (!$complete AND (--$no_of_queries == 0)) {
1803 function poco_discover_server_users($data, $server) {
1805 if (!isset($data->entry)) {
1809 foreach ($data->entry AS $entry) {
1811 if (isset($entry->urls)) {
1812 foreach ($entry->urls as $url) {
1813 if ($url->type == 'profile') {
1814 $profile_url = $url->value;
1815 $urlparts = parse_url($profile_url);
1816 $username = end(explode("/", $urlparts["path"]));
1820 if ($username != "") {
1821 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1823 // Fetch all contacts from a given user from the other server
1824 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1826 $retdata = z_fetch_url($url);
1827 if ($retdata["success"]) {
1828 poco_discover_server(json_decode($retdata["body"]), 3);
1834 function poco_discover_server($data, $default_generation = 0) {
1836 if (!isset($data->entry) OR !count($data->entry)) {
1842 foreach ($data->entry AS $entry) {
1844 $profile_photo = '';
1848 $updated = NULL_DATE;
1854 $generation = $default_generation;
1856 $name = $entry->displayName;
1858 if (isset($entry->urls)) {
1859 foreach ($entry->urls as $url) {
1860 if ($url->type == 'profile') {
1861 $profile_url = $url->value;
1864 if ($url->type == 'webfinger') {
1865 $connect_url = str_replace('acct:' , '', $url->value);
1871 if (isset($entry->photos)) {
1872 foreach ($entry->photos as $photo) {
1873 if ($photo->type == 'profile') {
1874 $profile_photo = $photo->value;
1880 if (isset($entry->updated)) {
1881 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1884 if (isset($entry->network)) {
1885 $network = $entry->network;
1888 if (isset($entry->currentLocation)) {
1889 $location = $entry->currentLocation;
1892 if (isset($entry->aboutMe)) {
1893 $about = html2bbcode($entry->aboutMe);
1896 if (isset($entry->gender)) {
1897 $gender = $entry->gender;
1900 if (isset($entry->generation) AND ($entry->generation > 0)) {
1901 $generation = ++$entry->generation;
1904 if (isset($entry->contactType) AND ($entry->contactType >= 0)) {
1905 $contact_type = $entry->contactType;
1908 if (isset($entry->tags)) {
1909 foreach ($entry->tags as $tag) {
1910 $keywords = implode(", ", $tag);
1914 if ($generation > 0) {
1917 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1919 $gcontact = array("url" => $profile_url,
1921 "network" => $network,
1922 "photo" => $profile_photo,
1924 "location" => $location,
1925 "gender" => $gender,
1926 "keywords" => $keywords,
1927 "connect" => $connect_url,
1928 "updated" => $updated,
1929 "contact-type" => $contact_type,
1930 "generation" => $generation);
1933 $gcontact = sanitize_gcontact($gcontact);
1934 update_gcontact($gcontact);
1935 } catch (Exception $e) {
1936 logger($e->getMessage(), LOGGER_DEBUG);
1939 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1946 * @brief Removes unwanted parts from a contact url
1948 * @param string $url Contact url
1949 * @return string Contact url with the wanted parts
1951 function clean_contact_url($url) {
1952 $parts = parse_url($url);
1954 if (!isset($parts["scheme"]) OR !isset($parts["host"])) {
1958 $new_url = $parts["scheme"]."://".$parts["host"];
1960 if (isset($parts["port"])) {
1961 $new_url .= ":".$parts["port"];
1964 if (isset($parts["path"])) {
1965 $new_url .= $parts["path"];
1968 if ($new_url != $url) {
1969 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1976 * @brief Replace alternate OStatus user format with the primary one
1978 * @param arr $contact contact array (called by reference)
1980 function fix_alternate_contact_address(&$contact) {
1981 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1982 $data = probe_url($contact["url"]);
1983 if ($contact["network"] == NETWORK_OSTATUS) {
1984 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1985 $contact["url"] = $data["url"];
1986 $contact["addr"] = $data["addr"];
1987 $contact["alias"] = $data["alias"];
1988 $contact["server_url"] = $data["baseurl"];
1994 * @brief Fetch the gcontact id, add an entry if not existed
1996 * @param arr $contact contact array
1997 * @return bool|int Returns false if not found, integer if contact was found
1999 function get_gcontact_id($contact) {
2004 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
2005 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2009 if ($contact["network"] == NETWORK_STATUSNET) {
2010 $contact["network"] = NETWORK_OSTATUS;
2013 // All new contacts are hidden by default
2014 if (!isset($contact["hide"])) {
2015 $contact["hide"] = true;
2018 // Replace alternate OStatus user format with the primary one
2019 fix_alternate_contact_address($contact);
2021 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
2022 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
2023 $contact["url"] = clean_contact_url($contact["url"]);
2026 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
2027 dbesc(normalise_link($contact["url"])));
2029 if (dbm::is_result($r)) {
2030 $gcontact_id = $r[0]["id"];
2032 // Update every 90 days
2033 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2034 $last_failure_str = $r[0]["last_failure"];
2035 $last_failure = strtotime($r[0]["last_failure"]);
2036 $last_contact_str = $r[0]["last_contact"];
2037 $last_contact = strtotime($r[0]["last_contact"]);
2038 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2041 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2042 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2043 dbesc($contact["name"]),
2044 dbesc($contact["nick"]),
2045 dbesc($contact["addr"]),
2046 dbesc($contact["network"]),
2047 dbesc($contact["url"]),
2048 dbesc(normalise_link($contact["url"])),
2049 dbesc($contact["photo"]),
2050 dbesc(datetime_convert()),
2051 dbesc(datetime_convert()),
2052 dbesc($contact["location"]),
2053 dbesc($contact["about"]),
2054 intval($contact["hide"]),
2055 intval($contact["generation"])
2058 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2059 dbesc(normalise_link($contact["url"])));
2061 if (dbm::is_result($r)) {
2062 $gcontact_id = $r[0]["id"];
2064 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2069 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2070 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2073 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != "")) {
2074 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2075 dbesc(normalise_link($contact["url"])),
2076 intval($gcontact_id));
2079 return $gcontact_id;
2083 * @brief Updates the gcontact table from a given array
2085 * @param arr $contact contact array
2086 * @return bool|int Returns false if not found, integer if contact was found
2088 function update_gcontact($contact) {
2090 // Check for invalid "contact-type" value
2091 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2092 $contact['contact-type'] = 0;
2095 /// @todo update contact table as well
2097 $gcontact_id = get_gcontact_id($contact);
2099 if (!$gcontact_id) {
2103 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2104 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2105 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2106 intval($gcontact_id));
2108 // Get all field names
2110 foreach ($r[0] AS $field => $data) {
2111 $fields[$field] = $data;
2114 unset($fields["url"]);
2115 unset($fields["updated"]);
2116 unset($fields["hide"]);
2118 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2119 // This value is still transmitted via poco.
2120 if ($contact["keywords"] == "0") {
2121 unset($contact["keywords"]);
2124 if ($r[0]["keywords"] == "0") {
2125 $r[0]["keywords"] = "";
2128 // assign all unassigned fields from the database entry
2129 foreach ($fields AS $field => $data) {
2130 if (!isset($contact[$field]) OR ($contact[$field] == "")) {
2131 $contact[$field] = $r[0][$field];
2135 if (!isset($contact["hide"])) {
2136 $contact["hide"] = $r[0]["hide"];
2139 $fields["hide"] = $r[0]["hide"];
2141 if ($contact["network"] == NETWORK_STATUSNET) {
2142 $contact["network"] = NETWORK_OSTATUS;
2145 // Replace alternate OStatus user format with the primary one
2146 fix_alternate_contact_address($contact);
2148 if (!isset($contact["updated"])) {
2149 $contact["updated"] = dbm::date();
2152 if ($contact["server_url"] == "") {
2153 $server_url = $contact["url"];
2155 $server_url = matching_url($server_url, $contact["alias"]);
2156 if ($server_url != "") {
2157 $contact["server_url"] = $server_url;
2160 $server_url = matching_url($server_url, $contact["photo"]);
2161 if ($server_url != "") {
2162 $contact["server_url"] = $server_url;
2165 $server_url = matching_url($server_url, $contact["notify"]);
2166 if ($server_url != "") {
2167 $contact["server_url"] = $server_url;
2170 $contact["server_url"] = normalise_link($contact["server_url"]);
2173 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2174 $hostname = str_replace("http://", "", $contact["server_url"]);
2175 $contact["addr"] = $contact["nick"]."@".$hostname;
2178 // Check if any field changed
2180 unset($fields["generation"]);
2182 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2183 foreach ($fields AS $field => $data) {
2184 if ($contact[$field] != $r[0][$field]) {
2185 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2190 if ($contact["generation"] < $r[0]["generation"]) {
2191 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2197 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2199 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2200 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2201 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2202 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2203 `server_url` = '%s', `connect` = '%s'
2204 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2205 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2206 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2207 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2208 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2209 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2210 dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
2211 dbesc($contact["server_url"]), dbesc($contact["connect"]),
2212 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2215 // Now update the contact entry with the user id "0" as well.
2216 // This is used for the shadow copies of public items.
2217 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2218 dbesc(normalise_link($contact["url"])));
2220 if (dbm::is_result($r)) {
2221 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2223 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2225 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2226 `network` = '%s', `bd` = '%s', `gender` = '%s',
2227 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2228 `url` = '%s', `location` = '%s', `about` = '%s'
2230 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2231 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2232 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2233 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2234 intval($r[0]["id"]));
2238 return $gcontact_id;
2242 * @brief Updates the gcontact entry from probe
2244 * @param str $url profile link
2246 function update_gcontact_from_probe($url) {
2247 $data = probe_url($url);
2249 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2250 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2254 $data["server_url"] = $data["baseurl"];
2256 update_gcontact($data);
2260 * @brief Update the gcontact entry for a given user id
2262 * @param int $uid User ID
2264 function update_gcontact_for_user($uid) {
2265 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2266 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2267 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2268 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2269 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2271 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2272 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2273 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2276 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2277 "country-name" => $r[0]["country-name"]));
2279 // The "addr" field was added in 3.4.3 so it can be empty for older users
2280 if ($r[0]["addr"] != "")
2281 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2283 $addr = $r[0]["addr"];
2285 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2286 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2287 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2288 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2289 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2290 "nick" => $r[0]["nickname"], "addr" => $addr,
2291 "connect" => $addr, "server_url" => App::get_baseurl(),
2292 "generation" => 1, "network" => NETWORK_DFRN);
2294 update_gcontact($gcontact);
2298 * @brief Fetches users of given GNU Social server
2300 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2302 * @param str $server Server address
2304 function gs_fetch_users($server) {
2306 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2308 $url = $server."/main/statistics";
2310 $result = z_fetch_url($url);
2311 if (!$result["success"])
2314 $statistics = json_decode($result["body"]);
2316 if (is_object($statistics->config)) {
2317 if ($statistics->config->instance_with_ssl)
2318 $server = "https://";
2320 $server = "http://";
2322 $server .= $statistics->config->instance_address;
2324 $hostname = $statistics->config->instance_address;
2326 if ($statistics->instance_with_ssl)
2327 $server = "https://";
2329 $server = "http://";
2331 $server .= $statistics->instance_address;
2333 $hostname = $statistics->instance_address;
2336 if (is_object($statistics->users))
2337 foreach ($statistics->users AS $nick => $user) {
2338 $profile_url = $server."/".$user->nickname;
2340 $contact = array("url" => $profile_url,
2341 "name" => $user->fullname,
2342 "addr" => $user->nickname."@".$hostname,
2343 "nick" => $user->nickname,
2344 "about" => $user->bio,
2345 "network" => NETWORK_OSTATUS,
2346 "photo" => App::get_baseurl()."/images/person-175.jpg");
2347 get_gcontact_id($contact);
2352 * @brief Asking GNU Social server on a regular base for their user data
2355 function gs_discover() {
2357 $requery_days = intval(get_config("system", "poco_requery_days"));
2359 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2361 $r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
2362 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2367 foreach ($r AS $server) {
2368 gs_fetch_users($server["url"]);
2369 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2374 * @brief Returns a list of all known servers
2375 * @return array List of server urls
2377 function poco_serverlist() {
2378 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2379 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2380 ORDER BY `last_contact`
2382 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2383 if (!dbm::is_result($r)) {