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
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/network.php");
13 require_once("include/html2bbcode.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
18 * @brief Fetch POCO data
20 * @param integer $cid Contact ID
21 * @param integer $uid User ID
22 * @param integer $zcid Global Contact ID
23 * @param integer $url POCO address that should be polled
25 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
26 * and add the entries to the gcontact (Global Contact) table, or update existing entries
27 * if anything (name or photo) has changed.
28 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
30 * Once the global contact is stored add (if necessary) the contact linkage which associates
31 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
32 * pointing to the same global contact id.
35 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
36 // Call the function "poco_load_worker" via the worker
37 proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
41 * @brief Fetch POCO data from the worker
43 * @param integer $cid Contact ID
44 * @param integer $uid User ID
45 * @param integer $zcid Global Contact ID
46 * @param integer $url POCO address that should be polled
49 function poco_load_worker($cid, $uid, $zcid, $url) {
53 if((! $url) || (! $uid)) {
54 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
57 if (dbm::is_result($r)) {
69 $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') ;
71 logger('poco_load: ' . $url, LOGGER_DEBUG);
75 logger('poco_load: returns ' . $s, LOGGER_DATA);
77 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
79 if(($a->get_curl_code() > 299) || (! $s))
84 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
86 if(! isset($j->entry))
90 foreach($j->entry as $entry) {
106 $name = $entry->displayName;
108 if (isset($entry->urls)) {
109 foreach ($entry->urls as $url) {
110 if ($url->type == 'profile') {
111 $profile_url = $url->value;
114 if ($url->type == 'webfinger') {
115 $connect_url = str_replace('acct:' , '', $url->value);
120 if (isset($entry->photos)) {
121 foreach ($entry->photos as $photo) {
122 if ($photo->type == 'profile') {
123 $profile_photo = $photo->value;
129 if (isset($entry->updated)) {
130 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
133 if (isset($entry->network)) {
134 $network = $entry->network;
137 if (isset($entry->currentLocation)) {
138 $location = $entry->currentLocation;
141 if (isset($entry->aboutMe)) {
142 $about = html2bbcode($entry->aboutMe);
145 if (isset($entry->gender)) {
146 $gender = $entry->gender;
149 if (isset($entry->generation) AND ($entry->generation > 0)) {
150 $generation = ++$entry->generation;
153 if (isset($entry->tags)) {
154 foreach($entry->tags as $tag) {
155 $keywords = implode(", ", $tag);
159 if (isset($entry->contactType) AND ($entry->contactType >= 0))
160 $contact_type = $entry->contactType;
162 $gcontact = array("url" => $profile_url,
164 "network" => $network,
165 "photo" => $profile_photo,
167 "location" => $location,
169 "keywords" => $keywords,
170 "connect" => $connect_url,
171 "updated" => $updated,
172 "contact-type" => $contact_type,
173 "generation" => $generation);
176 $gcontact = sanitize_gcontact($gcontact);
177 $gcid = update_gcontact($gcontact);
179 link_gcontact($gcid, $uid, $cid, $zcid);
180 } catch (Exception $e) {
181 logger($e->getMessage(), LOGGER_DEBUG);
184 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
186 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
194 * @brief Sanitize the given gcontact data
196 * @param array $gcontact array with gcontact data
201 * 1: Profiles on this server
202 * 2: Contacts of profiles on this server
203 * 3: Contacts of contacts of profiles on this server
207 function sanitize_gcontact($gcontact) {
209 if ($gcontact['url'] == "") {
210 throw new Exception('URL is empty');
213 $urlparts = parse_url($gcontact['url']);
214 if (!isset($urlparts["scheme"])) {
215 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
218 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
219 "identi.ca", "alpha.app.net"))) {
220 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
223 // Don't store the statusnet connector as network
224 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
225 if ($gcontact['network'] == NETWORK_STATUSNET) {
226 $gcontact['network'] = "";
229 // Assure that there are no parameter fragments in the profile url
230 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
231 $gcontact['url'] = clean_contact_url($gcontact['url']);
234 $alternate = poco_alternate_ostatus_url($gcontact['url']);
236 // The global contacts should contain the original picture, not the cached one
237 if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
238 $gcontact['photo'] = "";
241 if (!isset($gcontact['network'])) {
242 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
243 dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
245 if (dbm::is_result($r)) {
246 $gcontact['network'] = $r[0]["network"];
249 if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
250 $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
251 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
253 if (dbm::is_result($r)) {
254 $gcontact['network'] = $r[0]["network"];
259 $gcontact['server_url'] = '';
260 $gcontact['network'] = '';
262 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
263 dbesc(normalise_link($gcontact['url']))
267 if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
268 $gcontact['network'] = $x[0]["network"];
270 if ($gcontact['updated'] <= NULL_DATE) {
271 $gcontact['updated'] = $x[0]["updated"];
273 if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
274 $gcontact['server_url'] = $x[0]["server_url"];
276 if (!isset($gcontact['addr'])) {
277 $gcontact['addr'] = $x[0]["addr"];
281 if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
282 AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
283 $data = Probe::uri($gcontact['url']);
285 if ($data["network"] == NETWORK_PHANTOM) {
286 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
289 $orig_profile = $gcontact['url'];
291 $gcontact["server_url"] = $data["baseurl"];
293 $gcontact = array_merge($gcontact, $data);
295 if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
296 // Delete the old entry - if it exists
297 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
299 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
300 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
305 if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
306 throw new Exception('No name and photo for URL '.$gcontact['url']);
309 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
310 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
313 if (!isset($gcontact['server_url'])) {
314 // We check the server url to be sure that it is a real one
315 $server_url = poco_detect_server($gcontact['url']);
317 // We are now sure that it is a correct URL. So we use it in the future
318 if ($server_url != "") {
319 $gcontact['server_url'] = $server_url;
323 // The server URL doesn't seem to be valid, so we don't store it.
324 if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
325 $gcontact['server_url'] = "";
332 * @brief Link the gcontact entry with user, contact and global contact
334 * @param integer $gcid Global contact ID
335 * @param integer $cid Contact ID
336 * @param integer $uid User ID
337 * @param integer $zcid Global Contact ID
340 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
346 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
352 if (!dbm::is_result($r)) {
353 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
358 dbesc(datetime_convert())
361 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
362 dbesc(datetime_convert()),
371 function poco_reachable($profile, $server = "", $network = "", $force = false) {
374 $server = poco_detect_server($profile);
379 return poco_check_server($server, $network, $force);
382 function poco_detect_server($profile) {
384 // Try to detect the server path based upon some known standard paths
387 if ($server_url == "") {
388 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
389 if ($friendica != $profile) {
390 $server_url = $friendica;
391 $network = NETWORK_DFRN;
395 if ($server_url == "") {
396 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
397 if ($diaspora != $profile) {
398 $server_url = $diaspora;
399 $network = NETWORK_DIASPORA;
403 if ($server_url == "") {
404 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
405 if ($red != $profile) {
407 $network = NETWORK_DIASPORA;
412 if ($server_url == "") {
413 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
414 if ($mastodon != $profile) {
415 $server_url = $mastodon;
416 $network = NETWORK_OSTATUS;
420 // Numeric OStatus variant
421 if ($server_url == "") {
422 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
423 if ($ostatus != $profile) {
424 $server_url = $ostatus;
425 $network = NETWORK_OSTATUS;
430 if ($server_url == "") {
431 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
432 if ($base != $profile) {
434 $network = NETWORK_PHANTOM;
438 if ($server_url == "") {
442 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
443 dbesc(normalise_link($server_url)));
444 if (dbm::is_result($r)) {
448 // Fetch the host-meta to check if this really is a server
449 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
450 if (!$serverret["success"]) {
457 function poco_alternate_ostatus_url($url) {
458 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
461 function poco_last_updated($profile, $force = false) {
463 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
464 dbesc(normalise_link($profile)));
466 if (!dbm::is_result($gcontacts)) {
470 $contact = array("url" => $profile);
472 if ($gcontacts[0]["created"] <= NULL_DATE) {
473 $contact['created'] = datetime_convert();
477 $server_url = normalise_link(poco_detect_server($profile));
480 if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
481 $server_url = $gcontacts[0]["server_url"];
484 if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
485 $server_url = normalise_link(poco_detect_server($profile));
488 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
489 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
493 if ($server_url != "") {
494 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
496 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
497 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
500 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
503 $contact['server_url'] = $server_url;
506 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
507 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
508 dbesc(normalise_link($server_url)));
511 $contact['network'] = $server[0]["network"];
517 // noscrape is really fast so we don't cache the call.
518 if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
520 // Use noscrape if possible
521 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
524 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
526 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
528 $noscrape = json_decode($noscraperet["body"], true);
530 if (is_array($noscrape)) {
531 $contact["network"] = $server[0]["network"];
533 if (isset($noscrape["fn"])) {
534 $contact["name"] = $noscrape["fn"];
536 if (isset($noscrape["comm"])) {
537 $contact["community"] = $noscrape["comm"];
539 if (isset($noscrape["tags"])) {
540 $keywords = implode(" ", $noscrape["tags"]);
541 if ($keywords != "") {
542 $contact["keywords"] = $keywords;
546 $location = formatted_location($noscrape);
548 $contact["location"] = $location;
550 if (isset($noscrape["dfrn-notify"])) {
551 $contact["notify"] = $noscrape["dfrn-notify"];
553 // Remove all fields that are not present in the gcontact table
554 unset($noscrape["fn"]);
555 unset($noscrape["key"]);
556 unset($noscrape["homepage"]);
557 unset($noscrape["comm"]);
558 unset($noscrape["tags"]);
559 unset($noscrape["locality"]);
560 unset($noscrape["region"]);
561 unset($noscrape["country-name"]);
562 unset($noscrape["contacts"]);
563 unset($noscrape["dfrn-request"]);
564 unset($noscrape["dfrn-confirm"]);
565 unset($noscrape["dfrn-notify"]);
566 unset($noscrape["dfrn-poll"]);
568 // Set the date of the last contact
569 /// @todo By now the function "update_gcontact" doesn't work with this field
570 //$contact["last_contact"] = datetime_convert();
572 $contact = array_merge($contact, $noscrape);
574 update_gcontact($contact);
576 if (trim($noscrape["updated"]) != "") {
577 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
578 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
580 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
582 return $noscrape["updated"];
589 // If we only can poll the feed, then we only do this once a while
590 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
591 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
593 update_gcontact($contact);
594 return $gcontacts[0]["updated"];
597 $data = Probe::uri($profile);
599 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
600 // Then check the other link and delete this one
601 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
602 (normalise_link($profile) == normalise_link($data["alias"])) AND
603 (normalise_link($profile) != normalise_link($data["url"]))) {
605 // Delete the old entry
606 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
607 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
609 $gcontact = array_merge($gcontacts[0], $data);
611 $gcontact["server_url"] = $data["baseurl"];
614 $gcontact = sanitize_gcontact($gcontact);
615 update_gcontact($gcontact);
617 poco_last_updated($data["url"], $force);
618 } catch (Exception $e) {
619 logger($e->getMessage(), LOGGER_DEBUG);
622 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
626 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
627 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
628 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
630 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
634 $contact = array_merge($contact, $data);
636 $contact["server_url"] = $data["baseurl"];
638 update_gcontact($contact);
640 $feedret = z_fetch_url($data["poll"]);
642 if (!$feedret["success"]) {
643 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
644 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
646 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
650 $doc = new DOMDocument();
651 @$doc->loadXML($feedret["body"]);
653 $xpath = new DomXPath($doc);
654 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
656 $entries = $xpath->query('/atom:feed/atom:entry');
660 foreach ($entries AS $entry) {
661 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
662 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
664 if ($last_updated < $published)
665 $last_updated = $published;
667 if ($last_updated < $updated)
668 $last_updated = $updated;
671 // Maybe there aren't any entries. Then check if it is a valid feed
672 if ($last_updated == "") {
673 if ($xpath->query('/atom:feed')->length > 0) {
674 $last_updated = NULL_DATE;
677 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
678 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
680 if (($gcontacts[0]["generation"] == 0)) {
681 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
682 dbesc(normalise_link($profile)));
685 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
687 return($last_updated);
690 function poco_do_update($created, $updated, $last_failure, $last_contact) {
691 $now = strtotime(datetime_convert());
693 if ($updated > $last_contact)
694 $contact_time = strtotime($updated);
696 $contact_time = strtotime($last_contact);
698 $failure_time = strtotime($last_failure);
699 $created_time = strtotime($created);
701 // If there is no "created" time then use the current time
702 if ($created_time <= 0)
703 $created_time = $now;
705 // If the last contact was less than 24 hours then don't update
706 if (($now - $contact_time) < (60 * 60 * 24))
709 // If the last failure was less than 24 hours then don't update
710 if (($now - $failure_time) < (60 * 60 * 24))
713 // If the last contact was less than a week ago and the last failure is older than a week then don't update
714 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
717 // 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
718 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
721 // 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
722 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
728 function poco_to_boolean($val) {
729 if (($val == "true") OR ($val == 1))
731 if (($val == "false") OR ($val == 0))
738 * @brief Detect server type (Hubzilla or Friendica) via the poco data
740 * @param object $data POCO data
741 * @return array Server data
743 function poco_detect_poco_data($data) {
746 if (!isset($data->entry)) {
750 if (count($data->entry) == 0) {
754 if (!isset($data->entry[0]->urls)) {
758 if (count($data->entry[0]->urls) == 0) {
762 foreach ($data->entry[0]->urls AS $url) {
763 if ($url->type == 'zot') {
765 $server["platform"] = 'Hubzilla';
766 $server["network"] = NETWORK_DIASPORA;
774 * @brief Detect server type by using the nodeinfo data
776 * @param string $server_url address of the server
777 * @return array Server data
779 function poco_fetch_nodeinfo($server_url) {
780 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
781 if (!$serverret["success"]) {
785 $nodeinfo = json_decode($serverret['body']);
787 if (!is_object($nodeinfo)) {
791 if (!is_array($nodeinfo->links)) {
797 foreach ($nodeinfo->links AS $link) {
798 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
799 $nodeinfo_url = $link->href;
803 if ($nodeinfo_url == '') {
807 $serverret = z_fetch_url($nodeinfo_url);
808 if (!$serverret["success"]) {
812 $nodeinfo = json_decode($serverret['body']);
814 if (!is_object($nodeinfo)) {
820 $server['register_policy'] = REGISTER_CLOSED;
822 if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
823 $server['register_policy'] = REGISTER_OPEN;
826 if (is_object($nodeinfo->software)) {
827 if (isset($nodeinfo->software->name)) {
828 $server['platform'] = $nodeinfo->software->name;
831 if (isset($nodeinfo->software->version)) {
832 $server['version'] = $nodeinfo->software->version;
833 // Version numbers on Nodeinfo are presented with additional info, e.g.:
834 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
835 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
839 if (is_object($nodeinfo->metadata)) {
840 if (isset($nodeinfo->metadata->nodeName)) {
841 $server['site_name'] = $nodeinfo->metadata->nodeName;
849 if (is_array($nodeinfo->protocols->inbound)) {
850 foreach ($nodeinfo->protocols->inbound AS $inbound) {
851 if ($inbound == 'diaspora') {
854 if ($inbound == 'friendica') {
857 if ($inbound == 'gnusocial') {
864 $server['network'] = NETWORK_OSTATUS;
867 $server['network'] = NETWORK_DIASPORA;
870 $server['network'] = NETWORK_DFRN;
881 * @brief Detect server type (Hubzilla or Friendica) via the front page body
883 * @param string $body Front page of the server
884 * @return array Server data
886 function poco_detect_server_type($body) {
889 $doc = new \DOMDocument();
890 @$doc->loadHTML($body);
891 $xpath = new \DomXPath($doc);
893 $list = $xpath->query("//meta[@name]");
895 foreach ($list as $node) {
897 if ($node->attributes->length) {
898 foreach ($node->attributes as $attribute) {
899 $attr[$attribute->name] = $attribute->value;
902 if ($attr['name'] == 'generator') {
903 $version_part = explode(" ", $attr['content']);
904 if (count($version_part) == 2) {
905 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
907 $server["platform"] = $version_part[0];
908 $server["version"] = $version_part[1];
909 $server["network"] = NETWORK_DFRN;
916 $list = $xpath->query("//meta[@property]");
918 foreach ($list as $node) {
920 if ($node->attributes->length) {
921 foreach ($node->attributes as $attribute) {
922 $attr[$attribute->name] = $attribute->value;
925 if ($attr['property'] == 'generator') {
926 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
928 $server["platform"] = $attr['content'];
929 $server["version"] = "";
930 $server["network"] = NETWORK_DIASPORA;
940 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
944 function poco_check_server($server_url, $network = "", $force = false) {
946 // Unify the server address
947 $server_url = trim($server_url, "/");
948 $server_url = str_replace("/index.php", "", $server_url);
950 if ($server_url == "")
953 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
954 if (dbm::is_result($servers)) {
956 if ($servers[0]["created"] <= NULL_DATE) {
957 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
958 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
960 $poco = $servers[0]["poco"];
961 $noscrape = $servers[0]["noscrape"];
964 $network = $servers[0]["network"];
966 $last_contact = $servers[0]["last_contact"];
967 $last_failure = $servers[0]["last_failure"];
968 $version = $servers[0]["version"];
969 $platform = $servers[0]["platform"];
970 $site_name = $servers[0]["site_name"];
971 $info = $servers[0]["info"];
972 $register_policy = $servers[0]["register_policy"];
974 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
975 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
976 return ($last_contact >= $last_failure);
985 $register_policy = -1;
987 $last_contact = NULL_DATE;
988 $last_failure = NULL_DATE;
990 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
993 $possible_failure = false;
994 $orig_last_failure = $last_failure;
995 $orig_last_contact = $last_contact;
997 // Check if the page is accessible via SSL.
998 $orig_server_url = $server_url;
999 $server_url = str_replace("http://", "https://", $server_url);
1001 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1002 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1004 // Quit if there is a timeout.
1005 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1006 if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1007 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1008 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1012 // Maybe the page is unencrypted only?
1013 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1014 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1015 $server_url = str_replace("https://", "http://", $server_url);
1017 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1018 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1020 // Quit if there is a timeout
1021 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1022 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1026 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1029 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1030 // Workaround for bad configured servers (known nginx problem)
1031 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1032 $last_failure = datetime_convert();
1035 $possible_failure = true;
1036 } elseif ($network == NETWORK_DIASPORA)
1037 $last_contact = datetime_convert();
1039 // If the server has no possible failure we reset the cached data
1040 if (!$possible_failure) {
1045 $register_policy = -1;
1050 $serverret = z_fetch_url($server_url."/poco");
1051 if ($serverret["success"]) {
1052 $data = json_decode($serverret["body"]);
1053 if (isset($data->totalResults)) {
1054 $poco = $server_url."/poco";
1055 $last_contact = datetime_convert();
1057 $server = poco_detect_poco_data($data);
1059 $platform = $server['platform'];
1060 $network = $server['network'];
1069 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1070 $serverret = z_fetch_url($server_url);
1072 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1073 $last_failure = datetime_convert();
1076 $server = poco_detect_server_type($serverret["body"]);
1078 $platform = $server['platform'];
1079 $network = $server['network'];
1080 $version = $server['version'];
1081 $site_name = $server['site_name'];
1082 $last_contact = datetime_convert();
1085 $lines = explode("\n",$serverret["header"]);
1087 foreach($lines as $line) {
1088 $line = trim($line);
1089 if(stristr($line,'X-Diaspora-Version:')) {
1090 $platform = "Diaspora";
1091 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1092 $version = trim(str_replace("x-diaspora-version:", "", $version));
1093 $network = NETWORK_DIASPORA;
1094 $versionparts = explode("-", $version);
1095 $version = $versionparts[0];
1096 $last_contact = datetime_convert();
1099 if(stristr($line,'Server: Mastodon')) {
1100 $platform = "Mastodon";
1101 $network = NETWORK_OSTATUS;
1102 // Mastodon doesn't reveal version numbers
1104 $last_contact = datetime_convert();
1111 if (!$failure AND ($poco == "")) {
1112 // Test for Statusnet
1113 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1114 // The "not implemented" is a special treatment for really, really old Friendica versions
1115 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1116 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1117 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1118 $platform = "StatusNet";
1119 // Remove junk that some GNU Social servers return
1120 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1121 $version = trim($version, '"');
1122 $network = NETWORK_OSTATUS;
1123 $last_contact = datetime_convert();
1126 // Test for GNU Social
1127 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1128 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1129 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1130 $platform = "GNU Social";
1131 // Remove junk that some GNU Social servers return
1132 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1133 $version = trim($version, '"');
1134 $network = NETWORK_OSTATUS;
1135 $last_contact = datetime_convert();
1140 // Test for Hubzilla, Redmatrix or Friendica
1141 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1142 if ($serverret["success"]) {
1143 $data = json_decode($serverret["body"]);
1144 if (isset($data->site->server)) {
1145 $last_contact = datetime_convert();
1147 if (isset($data->site->platform)) {
1148 $platform = $data->site->platform->PLATFORM_NAME;
1149 $version = $data->site->platform->STD_VERSION;
1150 $network = NETWORK_DIASPORA;
1152 if (isset($data->site->BlaBlaNet)) {
1153 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1154 $version = $data->site->BlaBlaNet->STD_VERSION;
1155 $network = NETWORK_DIASPORA;
1157 if (isset($data->site->hubzilla)) {
1158 $platform = $data->site->hubzilla->PLATFORM_NAME;
1159 $version = $data->site->hubzilla->RED_VERSION;
1160 $network = NETWORK_DIASPORA;
1162 if (isset($data->site->redmatrix)) {
1163 if (isset($data->site->redmatrix->PLATFORM_NAME))
1164 $platform = $data->site->redmatrix->PLATFORM_NAME;
1165 elseif (isset($data->site->redmatrix->RED_PLATFORM))
1166 $platform = $data->site->redmatrix->RED_PLATFORM;
1168 $version = $data->site->redmatrix->RED_VERSION;
1169 $network = NETWORK_DIASPORA;
1171 if (isset($data->site->friendica)) {
1172 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1173 $version = $data->site->friendica->FRIENDICA_VERSION;
1174 $network = NETWORK_DFRN;
1177 $site_name = $data->site->name;
1179 $data->site->closed = poco_to_boolean($data->site->closed);
1180 $data->site->private = poco_to_boolean($data->site->private);
1181 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1183 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1184 $register_policy = REGISTER_APPROVE;
1185 elseif (!$data->site->closed AND !$data->site->private)
1186 $register_policy = REGISTER_OPEN;
1188 $register_policy = REGISTER_CLOSED;
1194 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1196 $serverret = z_fetch_url($server_url."/statistics.json");
1197 if ($serverret["success"]) {
1198 $data = json_decode($serverret["body"]);
1199 if (isset($data->version)) {
1200 $version = $data->version;
1201 // Version numbers on statistics.json are presented with additional info, e.g.:
1202 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1203 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1206 $site_name = $data->name;
1208 if (isset($data->network)) {
1209 $platform = $data->network;
1212 if ($platform == "Diaspora") {
1213 $network = NETWORK_DIASPORA;
1216 if ($data->registrations_open) {
1217 $register_policy = REGISTER_OPEN;
1219 $register_policy = REGISTER_CLOSED;
1222 if (isset($data->version))
1223 $last_contact = datetime_convert();
1227 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1229 $server = poco_fetch_nodeinfo($server_url);
1231 $register_policy = $server['register_policy'];
1233 if (isset($server['platform'])) {
1234 $platform = $server['platform'];
1237 if (isset($server['network'])) {
1238 $network = $server['network'];
1241 if (isset($server['version'])) {
1242 $version = $server['version'];
1245 if (isset($server['site_name'])) {
1246 $site_name = $server['site_name'];
1249 $last_contact = datetime_convert();
1253 // Check for noscrape
1254 // Friendica servers could be detected as OStatus servers
1255 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1256 $serverret = z_fetch_url($server_url."/friendica/json");
1258 if (!$serverret["success"])
1259 $serverret = z_fetch_url($server_url."/friendika/json");
1261 if ($serverret["success"]) {
1262 $data = json_decode($serverret["body"]);
1264 if (isset($data->version)) {
1265 $last_contact = datetime_convert();
1266 $network = NETWORK_DFRN;
1268 $noscrape = $data->no_scrape_url;
1269 $version = $data->version;
1270 $site_name = $data->site_name;
1271 $info = $data->info;
1272 $register_policy_str = $data->register_policy;
1273 $platform = $data->platform;
1275 switch ($register_policy_str) {
1276 case "REGISTER_CLOSED":
1277 $register_policy = REGISTER_CLOSED;
1279 case "REGISTER_APPROVE":
1280 $register_policy = REGISTER_APPROVE;
1282 case "REGISTER_OPEN":
1283 $register_policy = REGISTER_OPEN;
1290 if ($possible_failure AND !$failure) {
1291 $last_failure = datetime_convert();
1296 $last_contact = $orig_last_contact;
1298 $last_failure = $orig_last_failure;
1301 if (($last_contact <= $last_failure) AND !$failure) {
1302 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1303 } else if (($last_contact >= $last_failure) AND $failure) {
1304 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1307 // Check again if the server exists
1308 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1310 $version = strip_tags($version);
1311 $site_name = strip_tags($site_name);
1312 $info = strip_tags($info);
1313 $platform = strip_tags($platform);
1316 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1317 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1322 intval($register_policy),
1327 dbesc($last_contact),
1328 dbesc($last_failure),
1329 dbesc(normalise_link($server_url))
1331 } elseif (!$failure) {
1332 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1333 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1335 dbesc(normalise_link($server_url)),
1339 intval($register_policy),
1344 dbesc(datetime_convert()),
1345 dbesc($last_contact),
1346 dbesc($last_failure),
1347 dbesc(datetime_convert())
1350 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1355 function count_common_friends($uid,$cid) {
1357 $r = q("SELECT count(*) as `total`
1358 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1359 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1360 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1361 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1368 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1369 if (dbm::is_result($r))
1370 return $r[0]['total'];
1376 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1379 $sql_extra = " order by rand() ";
1381 $sql_extra = " order by `gcontact`.`name` asc ";
1383 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1385 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1386 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1387 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1388 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1389 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1390 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1391 $sql_extra LIMIT %d, %d",
1405 function count_common_friends_zcid($uid,$zcid) {
1407 $r = q("SELECT count(*) as `total`
1408 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1409 where `glink`.`zcid` = %d
1410 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1415 if (dbm::is_result($r))
1416 return $r[0]['total'];
1421 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1424 $sql_extra = " order by rand() ";
1426 $sql_extra = " order by `gcontact`.`name` asc ";
1428 $r = q("SELECT `gcontact`.*
1429 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1430 where `glink`.`zcid` = %d
1431 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1432 $sql_extra limit %d, %d",
1444 function count_all_friends($uid,$cid) {
1446 $r = q("SELECT count(*) as `total`
1447 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1448 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1449 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1454 if (dbm::is_result($r))
1455 return $r[0]['total'];
1461 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1463 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1465 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1466 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1467 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1468 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1469 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1482 function suggestion_query($uid, $start = 0, $limit = 80) {
1488 // Uncommented because the result of the queries are to big to store it in the cache.
1489 // We need to decide if we want to change the db column type or if we want to delete it.
1490 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1491 // if (!is_null($list)) {
1495 $network = array(NETWORK_DFRN);
1497 if (get_config('system','diaspora_enabled'))
1498 $network[] = NETWORK_DIASPORA;
1500 if (!get_config('system','ostatus_disabled'))
1501 $network[] = NETWORK_OSTATUS;
1503 $sql_network = implode("', '", $network);
1504 $sql_network = "'".$sql_network."'";
1506 /// @todo This query is really slow
1507 // By now we cache the data for five minutes
1508 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1509 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1510 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1511 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1512 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1513 AND `gcontact`.`updated` >= '%s'
1514 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1515 AND `gcontact`.`network` IN (%s)
1516 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1527 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1528 // Uncommented because the result of the queries are to big to store it in the cache.
1529 // We need to decide if we want to change the db column type or if we want to delete it.
1530 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1535 $r2 = q("SELECT gcontact.* FROM gcontact
1536 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1537 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1538 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1539 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1540 AND `gcontact`.`updated` >= '%s'
1541 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1542 AND `gcontact`.`network` IN (%s)
1543 ORDER BY rand() LIMIT %d, %d",
1554 foreach ($r2 AS $suggestion)
1555 $list[$suggestion["nurl"]] = $suggestion;
1557 foreach ($r AS $suggestion)
1558 $list[$suggestion["nurl"]] = $suggestion;
1560 while (sizeof($list) > ($limit))
1563 // Uncommented because the result of the queries are to big to store it in the cache.
1564 // We need to decide if we want to change the db column type or if we want to delete it.
1565 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1569 function update_suggestions() {
1575 /// @TODO Check if it is really neccessary to poll the own server
1576 poco_load(0,0,0,App::get_baseurl() . '/poco');
1578 $done[] = App::get_baseurl() . '/poco';
1580 if (strlen(get_config('system','directory'))) {
1581 $x = fetch_url(get_server()."/pubsites");
1583 $j = json_decode($x);
1585 foreach ($j->entries as $entry) {
1587 poco_check_server($entry->url);
1589 $url = $entry->url . '/poco';
1590 if (! in_array($url,$done)) {
1591 poco_load(0,0,0,$entry->url . '/poco');
1598 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1599 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1600 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1603 if (dbm::is_result($r)) {
1604 foreach ($r as $rr) {
1605 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1606 if(! in_array($base,$done))
1607 poco_load(0,0,0,$base);
1613 * @brief Fetch server list from remote servers and adds them when they are new.
1615 * @param string $poco URL to the POCO endpoint
1617 function poco_fetch_serverlist($poco) {
1618 $serverret = z_fetch_url($poco."/@server");
1619 if (!$serverret["success"]) {
1622 $serverlist = json_decode($serverret['body']);
1624 if (!is_array($serverlist)) {
1628 foreach ($serverlist AS $server) {
1629 $server_url = str_replace("/index.php", "", $server->url);
1631 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1632 if (!dbm::is_result($r)) {
1633 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1634 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1639 function poco_discover_federation() {
1640 $last = get_config('poco','last_federation_discovery');
1643 $next = $last + (24 * 60 * 60);
1648 // Discover Friendica, Hubzilla and Diaspora servers
1649 $serverdata = fetch_url("http://the-federation.info/pods.json");
1652 $servers = json_decode($serverdata);
1654 foreach ($servers->pods AS $server) {
1655 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1659 // Currently disabled, since the service isn't available anymore.
1660 // It is not removed since I hope that there will be a successor.
1661 // Discover GNU Social Servers.
1662 //if (!get_config('system','ostatus_disabled')) {
1663 // $serverdata = "http://gstools.org/api/get_open_instances/";
1665 // $result = z_fetch_url($serverdata);
1666 // if ($result["success"]) {
1667 // $servers = json_decode($result["body"]);
1669 // foreach($servers->data AS $server)
1670 // poco_check_server($server->instance_address);
1674 set_config('poco','last_federation_discovery', time());
1677 function poco_discover_single_server($id) {
1678 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1679 if (!dbm::is_result($r)) {
1685 // Discover new servers out there (Works from Friendica version 3.5.2)
1686 poco_fetch_serverlist($server["poco"]);
1688 // Fetch all users from the other server
1689 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1691 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1693 $retdata = z_fetch_url($url);
1694 if ($retdata["success"]) {
1695 $data = json_decode($retdata["body"]);
1697 poco_discover_server($data, 2);
1699 if (get_config('system','poco_discovery') > 1) {
1701 $timeframe = get_config('system','poco_discovery_since');
1702 if ($timeframe == 0) {
1706 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1708 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1709 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1713 $retdata = z_fetch_url($url);
1714 if ($retdata["success"]) {
1715 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1716 $success = poco_discover_server(json_decode($retdata["body"]));
1719 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1720 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1721 poco_discover_server_users($data, $server);
1725 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1729 // If the server hadn't replied correctly, then force a sanity check
1730 poco_check_server($server["url"], $server["network"], true);
1732 // If we couldn't reach the server, we will try it some time later
1733 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1739 function poco_discover($complete = false) {
1741 // Update the server list
1742 poco_discover_federation();
1746 $requery_days = intval(get_config("system", "poco_requery_days"));
1748 if ($requery_days == 0) {
1751 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1753 $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));
1754 if (dbm::is_result($r)) {
1755 foreach ($r AS $server) {
1757 if (!poco_check_server($server["url"], $server["network"])) {
1758 // The server is not reachable? Okay, then we will try it later
1759 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1763 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1764 proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1766 if (!$complete AND (--$no_of_queries == 0)) {
1773 function poco_discover_server_users($data, $server) {
1775 if (!isset($data->entry))
1778 foreach ($data->entry AS $entry) {
1780 if (isset($entry->urls)) {
1781 foreach($entry->urls as $url)
1782 if ($url->type == 'profile') {
1783 $profile_url = $url->value;
1784 $urlparts = parse_url($profile_url);
1785 $username = end(explode("/", $urlparts["path"]));
1788 if ($username != "") {
1789 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1791 // Fetch all contacts from a given user from the other server
1792 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1794 $retdata = z_fetch_url($url);
1795 if ($retdata["success"])
1796 poco_discover_server(json_decode($retdata["body"]), 3);
1801 function poco_discover_server($data, $default_generation = 0) {
1803 if (!isset($data->entry) OR !count($data->entry))
1808 foreach ($data->entry AS $entry) {
1810 $profile_photo = '';
1814 $updated = NULL_DATE;
1820 $generation = $default_generation;
1822 $name = $entry->displayName;
1824 if (isset($entry->urls)) {
1825 foreach($entry->urls as $url) {
1826 if ($url->type == 'profile') {
1827 $profile_url = $url->value;
1830 if ($url->type == 'webfinger') {
1831 $connect_url = str_replace('acct:' , '', $url->value);
1837 if (isset($entry->photos)) {
1838 foreach ($entry->photos as $photo) {
1839 if ($photo->type == 'profile') {
1840 $profile_photo = $photo->value;
1846 if (isset($entry->updated)) {
1847 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1850 if(isset($entry->network)) {
1851 $network = $entry->network;
1854 if(isset($entry->currentLocation)) {
1855 $location = $entry->currentLocation;
1858 if(isset($entry->aboutMe)) {
1859 $about = html2bbcode($entry->aboutMe);
1862 if(isset($entry->gender)) {
1863 $gender = $entry->gender;
1866 if(isset($entry->generation) AND ($entry->generation > 0)) {
1867 $generation = ++$entry->generation;
1870 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1871 $contact_type = $entry->contactType;
1874 if(isset($entry->tags)) {
1875 foreach ($entry->tags as $tag) {
1876 $keywords = implode(", ", $tag);
1880 if ($generation > 0) {
1883 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1885 $gcontact = array("url" => $profile_url,
1887 "network" => $network,
1888 "photo" => $profile_photo,
1890 "location" => $location,
1891 "gender" => $gender,
1892 "keywords" => $keywords,
1893 "connect" => $connect_url,
1894 "updated" => $updated,
1895 "contact-type" => $contact_type,
1896 "generation" => $generation);
1899 $gcontact = sanitize_gcontact($gcontact);
1900 update_gcontact($gcontact);
1901 } catch (Exception $e) {
1902 logger($e->getMessage(), LOGGER_DEBUG);
1905 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1912 * @brief Removes unwanted parts from a contact url
1914 * @param string $url Contact url
1915 * @return string Contact url with the wanted parts
1917 function clean_contact_url($url) {
1918 $parts = parse_url($url);
1920 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1923 $new_url = $parts["scheme"]."://".$parts["host"];
1925 if (isset($parts["port"]))
1926 $new_url .= ":".$parts["port"];
1928 if (isset($parts["path"]))
1929 $new_url .= $parts["path"];
1931 if ($new_url != $url)
1932 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1938 * @brief Replace alternate OStatus user format with the primary one
1940 * @param arr $contact contact array (called by reference)
1942 function fix_alternate_contact_address(&$contact) {
1943 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1944 $data = probe_url($contact["url"]);
1945 if ($contact["network"] == NETWORK_OSTATUS) {
1946 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1947 $contact["url"] = $data["url"];
1948 $contact["addr"] = $data["addr"];
1949 $contact["alias"] = $data["alias"];
1950 $contact["server_url"] = $data["baseurl"];
1956 * @brief Fetch the gcontact id, add an entry if not existed
1958 * @param arr $contact contact array
1959 * @return bool|int Returns false if not found, integer if contact was found
1961 function get_gcontact_id($contact) {
1966 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1967 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1971 if ($contact["network"] == NETWORK_STATUSNET)
1972 $contact["network"] = NETWORK_OSTATUS;
1974 // All new contacts are hidden by default
1975 if (!isset($contact["hide"]))
1976 $contact["hide"] = true;
1978 // Replace alternate OStatus user format with the primary one
1979 fix_alternate_contact_address($contact);
1981 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1982 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1983 $contact["url"] = clean_contact_url($contact["url"]);
1985 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1986 dbesc(normalise_link($contact["url"])));
1989 $gcontact_id = $r[0]["id"];
1991 // Update every 90 days
1992 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1993 $last_failure_str = $r[0]["last_failure"];
1994 $last_failure = strtotime($r[0]["last_failure"]);
1995 $last_contact_str = $r[0]["last_contact"];
1996 $last_contact = strtotime($r[0]["last_contact"]);
1997 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2000 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2001 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2002 dbesc($contact["name"]),
2003 dbesc($contact["nick"]),
2004 dbesc($contact["addr"]),
2005 dbesc($contact["network"]),
2006 dbesc($contact["url"]),
2007 dbesc(normalise_link($contact["url"])),
2008 dbesc($contact["photo"]),
2009 dbesc(datetime_convert()),
2010 dbesc(datetime_convert()),
2011 dbesc($contact["location"]),
2012 dbesc($contact["about"]),
2013 intval($contact["hide"]),
2014 intval($contact["generation"])
2017 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2018 dbesc(normalise_link($contact["url"])));
2021 $gcontact_id = $r[0]["id"];
2023 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2028 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2029 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2032 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2033 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2034 dbesc(normalise_link($contact["url"])),
2035 intval($gcontact_id));
2037 return $gcontact_id;
2041 * @brief Updates the gcontact table from a given array
2043 * @param arr $contact contact array
2044 * @return bool|int Returns false if not found, integer if contact was found
2046 function update_gcontact($contact) {
2048 // Check for invalid "contact-type" value
2049 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2050 $contact['contact-type'] = 0;
2053 /// @todo update contact table as well
2055 $gcontact_id = get_gcontact_id($contact);
2060 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2061 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2062 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2063 intval($gcontact_id));
2065 // Get all field names
2067 foreach ($r[0] AS $field => $data)
2068 $fields[$field] = $data;
2070 unset($fields["url"]);
2071 unset($fields["updated"]);
2072 unset($fields["hide"]);
2074 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2075 // This value is still transmitted via poco.
2076 if ($contact["keywords"] == "0")
2077 unset($contact["keywords"]);
2079 if ($r[0]["keywords"] == "0")
2080 $r[0]["keywords"] = "";
2082 // assign all unassigned fields from the database entry
2083 foreach ($fields AS $field => $data)
2084 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2085 $contact[$field] = $r[0][$field];
2087 if (!isset($contact["hide"]))
2088 $contact["hide"] = $r[0]["hide"];
2090 $fields["hide"] = $r[0]["hide"];
2092 if ($contact["network"] == NETWORK_STATUSNET)
2093 $contact["network"] = NETWORK_OSTATUS;
2095 // Replace alternate OStatus user format with the primary one
2096 fix_alternate_contact_address($contact);
2098 if (!isset($contact["updated"]))
2099 $contact["updated"] = datetime_convert();
2101 if ($contact["server_url"] == "") {
2102 $server_url = $contact["url"];
2104 $server_url = matching_url($server_url, $contact["alias"]);
2105 if ($server_url != "")
2106 $contact["server_url"] = $server_url;
2108 $server_url = matching_url($server_url, $contact["photo"]);
2109 if ($server_url != "")
2110 $contact["server_url"] = $server_url;
2112 $server_url = matching_url($server_url, $contact["notify"]);
2113 if ($server_url != "")
2114 $contact["server_url"] = $server_url;
2116 $contact["server_url"] = normalise_link($contact["server_url"]);
2118 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2119 $hostname = str_replace("http://", "", $contact["server_url"]);
2120 $contact["addr"] = $contact["nick"]."@".$hostname;
2123 // Check if any field changed
2125 unset($fields["generation"]);
2127 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2128 foreach ($fields AS $field => $data)
2129 if ($contact[$field] != $r[0][$field]) {
2130 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2134 if ($contact["generation"] < $r[0]["generation"]) {
2135 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2141 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2143 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2144 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2145 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2146 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2147 `server_url` = '%s', `connect` = '%s'
2148 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2149 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2150 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2151 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2152 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2153 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2154 dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
2155 dbesc($contact["server_url"]), dbesc($contact["connect"]),
2156 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2159 // Now update the contact entry with the user id "0" as well.
2160 // This is used for the shadow copies of public items.
2161 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2162 dbesc(normalise_link($contact["url"])));
2165 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2167 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2169 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2170 `network` = '%s', `bd` = '%s', `gender` = '%s',
2171 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2172 `url` = '%s', `location` = '%s', `about` = '%s'
2174 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2175 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2176 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2177 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2178 intval($r[0]["id"]));
2182 return $gcontact_id;
2186 * @brief Updates the gcontact entry from probe
2188 * @param str $url profile link
2190 function update_gcontact_from_probe($url) {
2191 $data = probe_url($url);
2193 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2194 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2198 $data["server_url"] = $data["baseurl"];
2200 update_gcontact($data);
2204 * @brief Update the gcontact entry for a given user id
2206 * @param int $uid User ID
2208 function update_gcontact_for_user($uid) {
2209 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2210 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2211 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2212 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2213 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2215 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2216 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2217 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2220 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2221 "country-name" => $r[0]["country-name"]));
2223 // The "addr" field was added in 3.4.3 so it can be empty for older users
2224 if ($r[0]["addr"] != "")
2225 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2227 $addr = $r[0]["addr"];
2229 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2230 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2231 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2232 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2233 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2234 "nick" => $r[0]["nickname"], "addr" => $addr,
2235 "connect" => $addr, "server_url" => App::get_baseurl(),
2236 "generation" => 1, "network" => NETWORK_DFRN);
2238 update_gcontact($gcontact);
2242 * @brief Fetches users of given GNU Social server
2244 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2246 * @param str $server Server address
2248 function gs_fetch_users($server) {
2250 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2252 $url = $server."/main/statistics";
2254 $result = z_fetch_url($url);
2255 if (!$result["success"])
2258 $statistics = json_decode($result["body"]);
2260 if (is_object($statistics->config)) {
2261 if ($statistics->config->instance_with_ssl)
2262 $server = "https://";
2264 $server = "http://";
2266 $server .= $statistics->config->instance_address;
2268 $hostname = $statistics->config->instance_address;
2270 if ($statistics->instance_with_ssl)
2271 $server = "https://";
2273 $server = "http://";
2275 $server .= $statistics->instance_address;
2277 $hostname = $statistics->instance_address;
2280 if (is_object($statistics->users))
2281 foreach ($statistics->users AS $nick => $user) {
2282 $profile_url = $server."/".$user->nickname;
2284 $contact = array("url" => $profile_url,
2285 "name" => $user->fullname,
2286 "addr" => $user->nickname."@".$hostname,
2287 "nick" => $user->nickname,
2288 "about" => $user->bio,
2289 "network" => NETWORK_OSTATUS,
2290 "photo" => App::get_baseurl()."/images/person-175.jpg");
2291 get_gcontact_id($contact);
2296 * @brief Asking GNU Social server on a regular base for their user data
2299 function gs_discover() {
2301 $requery_days = intval(get_config("system", "poco_requery_days"));
2303 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2305 $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",
2306 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2311 foreach ($r AS $server) {
2312 gs_fetch_users($server["url"]);
2313 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2318 * @brief Returns a list of all known servers
2319 * @return array List of server urls
2321 function poco_serverlist() {
2322 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2323 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2324 ORDER BY `last_contact`
2326 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2327 if (!dbm::is_result($r)) {