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);
175 if (sanitized_gcontact($gcontact)) {
176 $gcid = update_gcontact($gcontact);
178 link_gcontact($gcid, $uid, $cid, $zcid);
181 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
183 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
191 * @brief Sanitize the given gcontact data
193 * @param array $gcontact array with gcontact data
197 * 1: Profiles on this server
198 * 2: Contacts of profiles on this server
199 * 3: Contacts of contacts of profiles on this server
203 function sanitized_gcontact(&$gcontact) {
205 if ($gcontact['url'] == "") {
209 $urlparts = parse_url($gcontact['url']);
210 if (!isset($urlparts["scheme"])) {
214 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
215 "identi.ca", "alpha.app.net"))) {
219 // Don't store the statusnet connector as network
220 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
221 if ($gcontact['network'] == NETWORK_STATUSNET) {
222 $gcontact['network'] = "";
225 // Assure that there are no parameter fragments in the profile url
226 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
227 $gcontact['url'] = clean_contact_url($gcontact['url']);
230 $alternate = poco_alternate_ostatus_url($gcontact['url']);
232 // The global contacts should contain the original picture, not the cached one
233 if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
234 $gcontact['photo'] = "";
237 if (!isset($gcontact['network'])) {
238 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
239 dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
241 if (dbm::is_result($r)) {
242 $gcontact['network'] = $r[0]["network"];
245 if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
246 $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
247 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
249 if (dbm::is_result($r)) {
250 $gcontact['network'] = $r[0]["network"];
255 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
256 dbesc(normalise_link($gcontact['url']))
260 if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
261 $gcontact['network'] = $x[0]["network"];
263 if ($gcontact['updated'] <= NULL_DATE) {
264 $gcontact['updated'] = $x[0]["updated"];
266 if (!isset($gcontact['server_url'])) {
267 $gcontact['server_url'] = $x[0]["server_url"];
269 if (!isset($gcontact['addr'])) {
270 $gcontact['addr'] = $x[0]["addr"];
273 if (!isset($gcontact['server_url'])) {
274 $gcontact['server_url'] = '';
276 if (!isset($gcontact['network'])) {
277 $gcontact['network'] = '';
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) {
289 $orig_profile = $gcontact['url'];
291 $gcontact["server_url"] = $data["baseurl"];
293 unset($data["guid"]);
294 unset($data["batch"]);
295 unset($data["poll"]);
296 unset($data["request"]);
297 unset($data["confirm"]);
298 unset($data["poco"]);
299 unset($data["priority"]);
300 unset($data["pubkey"]);
301 unset($data["baseurl"]);
303 $gcontact = array_merge($gcontact, $data);
305 if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
306 // Delete the old entry - if it exists
307 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
309 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
310 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
315 if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
319 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
323 if (!isset($gcontact['server_url'])) {
324 // We check the server url to be sure that it is a real one
325 $server_url = poco_detect_server($gcontact['url']);
327 // We are now sure that it is a correct URL. So we use it in the future
328 if ($server_url != "") {
329 $gcontact['server_url'] = $server_url;
333 // The server URL doesn't seem to be valid, so we don't store it.
334 if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
335 $gcontact['server_url'] = "";
342 * @brief Link the gcontact entry with user, contact and global contact
344 * @param integer $gcid Global contact ID
345 * @param integer $cid Contact ID
346 * @param integer $uid User ID
347 * @param integer $zcid Global Contact ID
350 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
356 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
362 if (!dbm::is_result($r)) {
363 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
368 dbesc(datetime_convert())
371 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
372 dbesc(datetime_convert()),
381 function poco_reachable($profile, $server = "", $network = "", $force = false) {
384 $server = poco_detect_server($profile);
389 return poco_check_server($server, $network, $force);
392 function poco_detect_server($profile) {
394 // Try to detect the server path based upon some known standard paths
397 if ($server_url == "") {
398 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
399 if ($friendica != $profile) {
400 $server_url = $friendica;
401 $network = NETWORK_DFRN;
405 if ($server_url == "") {
406 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
407 if ($diaspora != $profile) {
408 $server_url = $diaspora;
409 $network = NETWORK_DIASPORA;
413 if ($server_url == "") {
414 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
415 if ($red != $profile) {
417 $network = NETWORK_DIASPORA;
422 if ($server_url == "") {
423 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
424 if ($mastodon != $profile) {
425 $server_url = $mastodon;
426 $network = NETWORK_OSTATUS;
430 // Numeric OStatus variant
431 if ($server_url == "") {
432 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
433 if ($ostatus != $profile) {
434 $server_url = $ostatus;
435 $network = NETWORK_OSTATUS;
440 if ($server_url == "") {
441 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
442 if ($base != $profile) {
444 $network = NETWORK_PHANTOM;
448 if ($server_url == "") {
452 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
453 dbesc(normalise_link($server_url)));
454 if (dbm::is_result($r)) {
458 // Fetch the host-meta to check if this really is a server
459 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
460 if (!$serverret["success"]) {
467 function poco_alternate_ostatus_url($url) {
468 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
471 function poco_last_updated($profile, $force = false) {
473 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
474 dbesc(normalise_link($profile)));
476 if ($gcontacts[0]["created"] <= NULL_DATE) {
477 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
478 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
480 if ($gcontacts[0]["server_url"] != "") {
481 $server_url = $gcontacts[0]["server_url"];
483 if (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"])) {
484 $server_url = poco_detect_server($profile);
487 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
488 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
492 if ($server_url != "") {
493 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)));
499 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
503 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
504 dbesc($server_url), dbesc(normalise_link($profile)));
507 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
508 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
509 dbesc(normalise_link($server_url)));
512 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
513 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
518 // noscrape is really fast so we don't cache the call.
519 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
521 // Use noscrape if possible
522 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
525 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
527 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
529 $noscrape = json_decode($noscraperet["body"], true);
531 if (is_array($noscrape)) {
532 $contact = array("url" => $profile,
533 "network" => $server[0]["network"],
534 "generation" => $gcontacts[0]["generation"]);
536 if (isset($noscrape["fn"]))
537 $contact["name"] = $noscrape["fn"];
539 if (isset($noscrape["comm"]))
540 $contact["community"] = $noscrape["comm"];
542 if (isset($noscrape["tags"])) {
543 $keywords = implode(" ", $noscrape["tags"]);
545 $contact["keywords"] = $keywords;
548 $location = formatted_location($noscrape);
550 $contact["location"] = $location;
552 if (isset($noscrape["dfrn-notify"]))
553 $contact["notify"] = $noscrape["dfrn-notify"];
555 // Remove all fields that are not present in the gcontact table
556 unset($noscrape["fn"]);
557 unset($noscrape["key"]);
558 unset($noscrape["homepage"]);
559 unset($noscrape["comm"]);
560 unset($noscrape["tags"]);
561 unset($noscrape["locality"]);
562 unset($noscrape["region"]);
563 unset($noscrape["country-name"]);
564 unset($noscrape["contacts"]);
565 unset($noscrape["dfrn-request"]);
566 unset($noscrape["dfrn-confirm"]);
567 unset($noscrape["dfrn-notify"]);
568 unset($noscrape["dfrn-poll"]);
570 // Set the date of the last contact
571 /// @todo By now the function "update_gcontact" doesn't work with this field
572 //$contact["last_contact"] = datetime_convert();
574 $contact = array_merge($contact, $noscrape);
576 update_gcontact($contact);
578 if (trim($noscrape["updated"]) != "") {
579 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
580 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
582 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
584 return $noscrape["updated"];
591 // If we only can poll the feed, then we only do this once a while
592 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
593 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
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 unset($gcontact["guid"]);
612 unset($gcontact["batch"]);
613 unset($gcontact["poll"]);
614 unset($gcontact["request"]);
615 unset($gcontact["confirm"]);
616 unset($gcontact["poco"]);
617 unset($gcontact["priority"]);
618 unset($gcontact["pubkey"]);
619 unset($gcontact["baseurl"]);
621 if (sanitized_gcontact($gcontact)) {
622 update_gcontact($gcontact);
624 poco_last_updated($data["url"], $force);
627 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
631 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
632 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
633 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
635 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
639 $contact = array("generation" => $gcontacts[0]["generation"]);
641 $contact = array_merge($contact, $data);
643 $contact["server_url"] = $data["baseurl"];
645 unset($contact["guid"]);
646 unset($contact["batch"]);
647 unset($contact["poll"]);
648 unset($contact["request"]);
649 unset($contact["confirm"]);
650 unset($contact["poco"]);
651 unset($contact["priority"]);
652 unset($contact["pubkey"]);
653 unset($contact["baseurl"]);
655 update_gcontact($contact);
657 $feedret = z_fetch_url($data["poll"]);
659 if (!$feedret["success"]) {
660 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
661 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
663 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
667 $doc = new DOMDocument();
668 @$doc->loadXML($feedret["body"]);
670 $xpath = new DomXPath($doc);
671 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
673 $entries = $xpath->query('/atom:feed/atom:entry');
677 foreach ($entries AS $entry) {
678 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
679 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
681 if ($last_updated < $published)
682 $last_updated = $published;
684 if ($last_updated < $updated)
685 $last_updated = $updated;
688 // Maybe there aren't any entries. Then check if it is a valid feed
689 if ($last_updated == "") {
690 if ($xpath->query('/atom:feed')->length > 0) {
691 $last_updated = NULL_DATE;
694 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
695 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
697 if (($gcontacts[0]["generation"] == 0))
698 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
699 dbesc(normalise_link($profile)));
701 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
703 return($last_updated);
706 function poco_do_update($created, $updated, $last_failure, $last_contact) {
707 $now = strtotime(datetime_convert());
709 if ($updated > $last_contact)
710 $contact_time = strtotime($updated);
712 $contact_time = strtotime($last_contact);
714 $failure_time = strtotime($last_failure);
715 $created_time = strtotime($created);
717 // If there is no "created" time then use the current time
718 if ($created_time <= 0)
719 $created_time = $now;
721 // If the last contact was less than 24 hours then don't update
722 if (($now - $contact_time) < (60 * 60 * 24))
725 // If the last failure was less than 24 hours then don't update
726 if (($now - $failure_time) < (60 * 60 * 24))
729 // If the last contact was less than a week ago and the last failure is older than a week then don't update
730 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
733 // 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
734 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
737 // 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
738 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
744 function poco_to_boolean($val) {
745 if (($val == "true") OR ($val == 1))
747 if (($val == "false") OR ($val == 0))
754 * @brief Detect server type (Hubzilla or Friendica) via the poco data
756 * @param object $data POCO data
757 * @return array Server data
759 function poco_detect_poco_data($data) {
762 if (!isset($data->entry)) {
766 if (count($data->entry) == 0) {
770 if (!isset($data->entry[0]->urls)) {
774 if (count($data->entry[0]->urls) == 0) {
778 foreach ($data->entry[0]->urls AS $url) {
779 if ($url->type == 'zot') {
781 $server["platform"] = 'Hubzilla';
782 $server["network"] = NETWORK_DIASPORA;
790 * @brief Detect server type by using the nodeinfo data
792 * @param string $server_url address of the server
793 * @return array Server data
795 function poco_fetch_nodeinfo($server_url) {
796 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
797 if (!$serverret["success"]) {
801 $nodeinfo = json_decode($serverret['body']);
803 if (!is_object($nodeinfo)) {
807 if (!is_array($nodeinfo->links)) {
813 foreach ($nodeinfo->links AS $link) {
814 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
815 $nodeinfo_url = $link->href;
819 if ($nodeinfo_url == '') {
823 $serverret = z_fetch_url($nodeinfo_url);
824 if (!$serverret["success"]) {
828 $nodeinfo = json_decode($serverret['body']);
830 if (!is_object($nodeinfo)) {
836 $server['register_policy'] = REGISTER_CLOSED;
838 if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
839 $server['register_policy'] = REGISTER_OPEN;
842 if (is_object($nodeinfo->software)) {
843 if (isset($nodeinfo->software->name)) {
844 $server['platform'] = $nodeinfo->software->name;
847 if (isset($nodeinfo->software->version)) {
848 $server['version'] = $nodeinfo->software->version;
849 // Version numbers on Nodeinfo are presented with additional info, e.g.:
850 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
851 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
855 if (is_object($nodeinfo->metadata)) {
856 if (isset($nodeinfo->metadata->nodeName)) {
857 $server['site_name'] = $nodeinfo->metadata->nodeName;
865 if (is_array($nodeinfo->protocols->inbound)) {
866 foreach ($nodeinfo->protocols->inbound AS $inbound) {
867 if ($inbound == 'diaspora') {
870 if ($inbound == 'friendica') {
873 if ($inbound == 'gnusocial') {
880 $server['network'] = NETWORK_OSTATUS;
883 $server['network'] = NETWORK_DIASPORA;
886 $server['network'] = NETWORK_DFRN;
897 * @brief Detect server type (Hubzilla or Friendica) via the front page body
899 * @param string $body Front page of the server
900 * @return array Server data
902 function poco_detect_server_type($body) {
905 $doc = new \DOMDocument();
906 @$doc->loadHTML($body);
907 $xpath = new \DomXPath($doc);
909 $list = $xpath->query("//meta[@name]");
911 foreach ($list as $node) {
913 if ($node->attributes->length) {
914 foreach ($node->attributes as $attribute) {
915 $attr[$attribute->name] = $attribute->value;
918 if ($attr['name'] == 'generator') {
919 $version_part = explode(" ", $attr['content']);
920 if (count($version_part) == 2) {
921 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
923 $server["platform"] = $version_part[0];
924 $server["version"] = $version_part[1];
925 $server["network"] = NETWORK_DFRN;
932 $list = $xpath->query("//meta[@property]");
934 foreach ($list as $node) {
936 if ($node->attributes->length) {
937 foreach ($node->attributes as $attribute) {
938 $attr[$attribute->name] = $attribute->value;
941 if ($attr['property'] == 'generator') {
942 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
944 $server["platform"] = $attr['content'];
945 $server["version"] = "";
946 $server["network"] = NETWORK_DIASPORA;
956 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
960 function poco_check_server($server_url, $network = "", $force = false) {
962 // Unify the server address
963 $server_url = trim($server_url, "/");
964 $server_url = str_replace("/index.php", "", $server_url);
966 if ($server_url == "")
969 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
970 if (dbm::is_result($servers)) {
972 if ($servers[0]["created"] <= NULL_DATE) {
973 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
974 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
976 $poco = $servers[0]["poco"];
977 $noscrape = $servers[0]["noscrape"];
980 $network = $servers[0]["network"];
982 $last_contact = $servers[0]["last_contact"];
983 $last_failure = $servers[0]["last_failure"];
984 $version = $servers[0]["version"];
985 $platform = $servers[0]["platform"];
986 $site_name = $servers[0]["site_name"];
987 $info = $servers[0]["info"];
988 $register_policy = $servers[0]["register_policy"];
990 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
991 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
992 return ($last_contact >= $last_failure);
1001 $register_policy = -1;
1003 $last_contact = NULL_DATE;
1004 $last_failure = NULL_DATE;
1006 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
1009 $possible_failure = false;
1010 $orig_last_failure = $last_failure;
1011 $orig_last_contact = $last_contact;
1013 // Check if the page is accessible via SSL.
1014 $orig_server_url = $server_url;
1015 $server_url = str_replace("http://", "https://", $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 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1022 if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1023 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1024 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1028 // Maybe the page is unencrypted only?
1029 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1030 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1031 $server_url = str_replace("https://", "http://", $server_url);
1033 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1034 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1036 // Quit if there is a timeout
1037 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1038 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1042 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1045 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1046 // Workaround for bad configured servers (known nginx problem)
1047 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1048 $last_failure = datetime_convert();
1051 $possible_failure = true;
1052 } elseif ($network == NETWORK_DIASPORA)
1053 $last_contact = datetime_convert();
1055 // If the server has no possible failure we reset the cached data
1056 if (!$possible_failure) {
1061 $register_policy = -1;
1066 $serverret = z_fetch_url($server_url."/poco");
1067 if ($serverret["success"]) {
1068 $data = json_decode($serverret["body"]);
1069 if (isset($data->totalResults)) {
1070 $poco = $server_url."/poco";
1071 $last_contact = datetime_convert();
1073 $server = poco_detect_poco_data($data);
1075 $platform = $server['platform'];
1076 $network = $server['network'];
1085 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1086 $serverret = z_fetch_url($server_url);
1088 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1089 $last_failure = datetime_convert();
1092 $server = poco_detect_server_type($serverret["body"]);
1094 $platform = $server['platform'];
1095 $network = $server['network'];
1096 $version = $server['version'];
1097 $site_name = $server['site_name'];
1098 $last_contact = datetime_convert();
1101 $lines = explode("\n",$serverret["header"]);
1103 foreach($lines as $line) {
1104 $line = trim($line);
1105 if(stristr($line,'X-Diaspora-Version:')) {
1106 $platform = "Diaspora";
1107 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1108 $version = trim(str_replace("x-diaspora-version:", "", $version));
1109 $network = NETWORK_DIASPORA;
1110 $versionparts = explode("-", $version);
1111 $version = $versionparts[0];
1112 $last_contact = datetime_convert();
1115 if(stristr($line,'Server: Mastodon')) {
1116 $platform = "Mastodon";
1117 $network = NETWORK_OSTATUS;
1118 // Mastodon doesn't reveal version numbers
1120 $last_contact = datetime_convert();
1127 if (!$failure AND ($poco == "")) {
1128 // Test for Statusnet
1129 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1130 // The "not implemented" is a special treatment for really, really old Friendica versions
1131 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1132 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1133 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1134 $platform = "StatusNet";
1135 // Remove junk that some GNU Social servers return
1136 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1137 $version = trim($version, '"');
1138 $network = NETWORK_OSTATUS;
1139 $last_contact = datetime_convert();
1142 // Test for GNU Social
1143 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1144 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1145 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1146 $platform = "GNU Social";
1147 // Remove junk that some GNU Social servers return
1148 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1149 $version = trim($version, '"');
1150 $network = NETWORK_OSTATUS;
1151 $last_contact = datetime_convert();
1156 // Test for Hubzilla, Redmatrix or Friendica
1157 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1158 if ($serverret["success"]) {
1159 $data = json_decode($serverret["body"]);
1160 if (isset($data->site->server)) {
1161 $last_contact = datetime_convert();
1163 if (isset($data->site->platform)) {
1164 $platform = $data->site->platform->PLATFORM_NAME;
1165 $version = $data->site->platform->STD_VERSION;
1166 $network = NETWORK_DIASPORA;
1168 if (isset($data->site->BlaBlaNet)) {
1169 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1170 $version = $data->site->BlaBlaNet->STD_VERSION;
1171 $network = NETWORK_DIASPORA;
1173 if (isset($data->site->hubzilla)) {
1174 $platform = $data->site->hubzilla->PLATFORM_NAME;
1175 $version = $data->site->hubzilla->RED_VERSION;
1176 $network = NETWORK_DIASPORA;
1178 if (isset($data->site->redmatrix)) {
1179 if (isset($data->site->redmatrix->PLATFORM_NAME))
1180 $platform = $data->site->redmatrix->PLATFORM_NAME;
1181 elseif (isset($data->site->redmatrix->RED_PLATFORM))
1182 $platform = $data->site->redmatrix->RED_PLATFORM;
1184 $version = $data->site->redmatrix->RED_VERSION;
1185 $network = NETWORK_DIASPORA;
1187 if (isset($data->site->friendica)) {
1188 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1189 $version = $data->site->friendica->FRIENDICA_VERSION;
1190 $network = NETWORK_DFRN;
1193 $site_name = $data->site->name;
1195 $data->site->closed = poco_to_boolean($data->site->closed);
1196 $data->site->private = poco_to_boolean($data->site->private);
1197 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1199 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1200 $register_policy = REGISTER_APPROVE;
1201 elseif (!$data->site->closed AND !$data->site->private)
1202 $register_policy = REGISTER_OPEN;
1204 $register_policy = REGISTER_CLOSED;
1210 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1212 $serverret = z_fetch_url($server_url."/statistics.json");
1213 if ($serverret["success"]) {
1214 $data = json_decode($serverret["body"]);
1215 if (isset($data->version)) {
1216 $version = $data->version;
1217 // Version numbers on statistics.json are presented with additional info, e.g.:
1218 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1219 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1222 $site_name = $data->name;
1224 if (isset($data->network)) {
1225 $platform = $data->network;
1228 if ($platform == "Diaspora") {
1229 $network = NETWORK_DIASPORA;
1232 if ($data->registrations_open) {
1233 $register_policy = REGISTER_OPEN;
1235 $register_policy = REGISTER_CLOSED;
1238 if (isset($data->version))
1239 $last_contact = datetime_convert();
1243 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1245 $server = poco_fetch_nodeinfo($server_url);
1247 $register_policy = $server['register_policy'];
1249 if (isset($server['platform'])) {
1250 $platform = $server['platform'];
1253 if (isset($server['network'])) {
1254 $network = $server['network'];
1257 if (isset($server['version'])) {
1258 $version = $server['version'];
1261 if (isset($server['site_name'])) {
1262 $site_name = $server['site_name'];
1265 $last_contact = datetime_convert();
1269 // Check for noscrape
1270 // Friendica servers could be detected as OStatus servers
1271 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1272 $serverret = z_fetch_url($server_url."/friendica/json");
1274 if (!$serverret["success"])
1275 $serverret = z_fetch_url($server_url."/friendika/json");
1277 if ($serverret["success"]) {
1278 $data = json_decode($serverret["body"]);
1280 if (isset($data->version)) {
1281 $last_contact = datetime_convert();
1282 $network = NETWORK_DFRN;
1284 $noscrape = $data->no_scrape_url;
1285 $version = $data->version;
1286 $site_name = $data->site_name;
1287 $info = $data->info;
1288 $register_policy_str = $data->register_policy;
1289 $platform = $data->platform;
1291 switch ($register_policy_str) {
1292 case "REGISTER_CLOSED":
1293 $register_policy = REGISTER_CLOSED;
1295 case "REGISTER_APPROVE":
1296 $register_policy = REGISTER_APPROVE;
1298 case "REGISTER_OPEN":
1299 $register_policy = REGISTER_OPEN;
1306 if ($possible_failure AND !$failure) {
1307 $last_failure = datetime_convert();
1312 $last_contact = $orig_last_contact;
1314 $last_failure = $orig_last_failure;
1317 if (($last_contact <= $last_failure) AND !$failure) {
1318 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1319 } else if (($last_contact >= $last_failure) AND $failure) {
1320 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1323 // Check again if the server exists
1324 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1326 $version = strip_tags($version);
1327 $site_name = strip_tags($site_name);
1328 $info = strip_tags($info);
1329 $platform = strip_tags($platform);
1332 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1333 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1338 intval($register_policy),
1343 dbesc($last_contact),
1344 dbesc($last_failure),
1345 dbesc(normalise_link($server_url))
1347 } elseif (!$failure) {
1348 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1349 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1351 dbesc(normalise_link($server_url)),
1355 intval($register_policy),
1360 dbesc(datetime_convert()),
1361 dbesc($last_contact),
1362 dbesc($last_failure),
1363 dbesc(datetime_convert())
1366 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1371 function count_common_friends($uid,$cid) {
1373 $r = q("SELECT count(*) as `total`
1374 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1375 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1376 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1377 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1384 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1385 if (dbm::is_result($r))
1386 return $r[0]['total'];
1392 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1395 $sql_extra = " order by rand() ";
1397 $sql_extra = " order by `gcontact`.`name` asc ";
1399 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1401 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1402 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1403 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1404 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1405 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1406 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1407 $sql_extra LIMIT %d, %d",
1421 function count_common_friends_zcid($uid,$zcid) {
1423 $r = q("SELECT count(*) as `total`
1424 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1425 where `glink`.`zcid` = %d
1426 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1431 if (dbm::is_result($r))
1432 return $r[0]['total'];
1437 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1440 $sql_extra = " order by rand() ";
1442 $sql_extra = " order by `gcontact`.`name` asc ";
1444 $r = q("SELECT `gcontact`.*
1445 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1446 where `glink`.`zcid` = %d
1447 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1448 $sql_extra limit %d, %d",
1460 function count_all_friends($uid,$cid) {
1462 $r = q("SELECT count(*) as `total`
1463 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1464 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1465 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1470 if (dbm::is_result($r))
1471 return $r[0]['total'];
1477 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1479 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1481 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1482 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1483 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1484 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1485 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1498 function suggestion_query($uid, $start = 0, $limit = 80) {
1504 // Uncommented because the result of the queries are to big to store it in the cache.
1505 // We need to decide if we want to change the db column type or if we want to delete it.
1506 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1507 // if (!is_null($list)) {
1511 $network = array(NETWORK_DFRN);
1513 if (get_config('system','diaspora_enabled'))
1514 $network[] = NETWORK_DIASPORA;
1516 if (!get_config('system','ostatus_disabled'))
1517 $network[] = NETWORK_OSTATUS;
1519 $sql_network = implode("', '", $network);
1520 $sql_network = "'".$sql_network."'";
1522 /// @todo This query is really slow
1523 // By now we cache the data for five minutes
1524 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1525 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1526 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1527 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1528 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1529 AND `gcontact`.`updated` >= '%s'
1530 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1531 AND `gcontact`.`network` IN (%s)
1532 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1543 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1544 // Uncommented because the result of the queries are to big to store it in the cache.
1545 // We need to decide if we want to change the db column type or if we want to delete it.
1546 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1551 $r2 = q("SELECT gcontact.* FROM gcontact
1552 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1553 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1554 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1555 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1556 AND `gcontact`.`updated` >= '%s'
1557 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1558 AND `gcontact`.`network` IN (%s)
1559 ORDER BY rand() LIMIT %d, %d",
1570 foreach ($r2 AS $suggestion)
1571 $list[$suggestion["nurl"]] = $suggestion;
1573 foreach ($r AS $suggestion)
1574 $list[$suggestion["nurl"]] = $suggestion;
1576 while (sizeof($list) > ($limit))
1579 // Uncommented because the result of the queries are to big to store it in the cache.
1580 // We need to decide if we want to change the db column type or if we want to delete it.
1581 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1585 function update_suggestions() {
1591 /// @TODO Check if it is really neccessary to poll the own server
1592 poco_load(0,0,0,App::get_baseurl() . '/poco');
1594 $done[] = App::get_baseurl() . '/poco';
1596 if (strlen(get_config('system','directory'))) {
1597 $x = fetch_url(get_server()."/pubsites");
1599 $j = json_decode($x);
1601 foreach ($j->entries as $entry) {
1603 poco_check_server($entry->url);
1605 $url = $entry->url . '/poco';
1606 if (! in_array($url,$done)) {
1607 poco_load(0,0,0,$entry->url . '/poco');
1614 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1615 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1616 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1619 if (dbm::is_result($r)) {
1620 foreach ($r as $rr) {
1621 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1622 if(! in_array($base,$done))
1623 poco_load(0,0,0,$base);
1629 * @brief Fetch server list from remote servers and adds them when they are new.
1631 * @param string $poco URL to the POCO endpoint
1633 function poco_fetch_serverlist($poco) {
1634 $serverret = z_fetch_url($poco."/@server");
1635 if (!$serverret["success"]) {
1638 $serverlist = json_decode($serverret['body']);
1640 if (!is_array($serverlist)) {
1644 foreach ($serverlist AS $server) {
1645 $server_url = str_replace("/index.php", "", $server->url);
1647 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1648 if (!dbm::is_result($r)) {
1649 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1650 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1655 function poco_discover_federation() {
1656 $last = get_config('poco','last_federation_discovery');
1659 $next = $last + (24 * 60 * 60);
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 // Currently disabled, since the service isn't available anymore.
1676 // It is not removed since I hope that there will be a successor.
1677 // Discover GNU Social Servers.
1678 //if (!get_config('system','ostatus_disabled')) {
1679 // $serverdata = "http://gstools.org/api/get_open_instances/";
1681 // $result = z_fetch_url($serverdata);
1682 // if ($result["success"]) {
1683 // $servers = json_decode($result["body"]);
1685 // foreach($servers->data AS $server)
1686 // poco_check_server($server->instance_address);
1690 set_config('poco','last_federation_discovery', time());
1693 function poco_discover_single_server($id) {
1694 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1695 if (!dbm::is_result($r)) {
1701 // Discover new servers out there (Works from Friendica version 3.5.2)
1702 poco_fetch_serverlist($server["poco"]);
1704 // Fetch all users from the other server
1705 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1707 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1709 $retdata = z_fetch_url($url);
1710 if ($retdata["success"]) {
1711 $data = json_decode($retdata["body"]);
1713 poco_discover_server($data, 2);
1715 if (get_config('system','poco_discovery') > 1) {
1717 $timeframe = get_config('system','poco_discovery_since');
1718 if ($timeframe == 0) {
1722 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1724 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1725 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1729 $retdata = z_fetch_url($url);
1730 if ($retdata["success"]) {
1731 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1732 $success = poco_discover_server(json_decode($retdata["body"]));
1735 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1736 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1737 poco_discover_server_users($data, $server);
1741 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1745 // If the server hadn't replied correctly, then force a sanity check
1746 poco_check_server($server["url"], $server["network"], true);
1748 // If we couldn't reach the server, we will try it some time later
1749 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1755 function poco_discover($complete = false) {
1757 // Update the server list
1758 poco_discover_federation();
1762 $requery_days = intval(get_config("system", "poco_requery_days"));
1764 if ($requery_days == 0) {
1767 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1769 $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));
1770 if (dbm::is_result($r)) {
1771 foreach ($r AS $server) {
1773 if (!poco_check_server($server["url"], $server["network"])) {
1774 // The server is not reachable? Okay, then we will try it later
1775 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1779 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1780 proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1782 if (!$complete AND (--$no_of_queries == 0)) {
1789 function poco_discover_server_users($data, $server) {
1791 if (!isset($data->entry))
1794 foreach ($data->entry AS $entry) {
1796 if (isset($entry->urls)) {
1797 foreach($entry->urls as $url)
1798 if ($url->type == 'profile') {
1799 $profile_url = $url->value;
1800 $urlparts = parse_url($profile_url);
1801 $username = end(explode("/", $urlparts["path"]));
1804 if ($username != "") {
1805 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1807 // Fetch all contacts from a given user from the other server
1808 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1810 $retdata = z_fetch_url($url);
1811 if ($retdata["success"])
1812 poco_discover_server(json_decode($retdata["body"]), 3);
1817 function poco_discover_server($data, $default_generation = 0) {
1819 if (!isset($data->entry) OR !count($data->entry))
1824 foreach ($data->entry AS $entry) {
1826 $profile_photo = '';
1830 $updated = NULL_DATE;
1836 $generation = $default_generation;
1838 $name = $entry->displayName;
1840 if (isset($entry->urls)) {
1841 foreach($entry->urls as $url) {
1842 if ($url->type == 'profile') {
1843 $profile_url = $url->value;
1846 if ($url->type == 'webfinger') {
1847 $connect_url = str_replace('acct:' , '', $url->value);
1853 if (isset($entry->photos)) {
1854 foreach ($entry->photos as $photo) {
1855 if ($photo->type == 'profile') {
1856 $profile_photo = $photo->value;
1862 if (isset($entry->updated)) {
1863 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1866 if(isset($entry->network)) {
1867 $network = $entry->network;
1870 if(isset($entry->currentLocation)) {
1871 $location = $entry->currentLocation;
1874 if(isset($entry->aboutMe)) {
1875 $about = html2bbcode($entry->aboutMe);
1878 if(isset($entry->gender)) {
1879 $gender = $entry->gender;
1882 if(isset($entry->generation) AND ($entry->generation > 0)) {
1883 $generation = ++$entry->generation;
1886 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1887 $contact_type = $entry->contactType;
1890 if(isset($entry->tags)) {
1891 foreach ($entry->tags as $tag) {
1892 $keywords = implode(", ", $tag);
1896 if ($generation > 0) {
1899 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1901 $gcontact = array("url" => $profile_url,
1903 "network" => $network,
1904 "photo" => $profile_photo,
1906 "location" => $location,
1907 "gender" => $gender,
1908 "keywords" => $keywords,
1909 "connect" => $connect_url,
1910 "updated" => $updated,
1911 "contact-type" => $contact_type,
1912 "generation" => $generation);
1914 if (sanitized_gcontact($gcontact)) {
1915 update_gcontact($gcontact);
1918 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1925 * @brief Removes unwanted parts from a contact url
1927 * @param string $url Contact url
1928 * @return string Contact url with the wanted parts
1930 function clean_contact_url($url) {
1931 $parts = parse_url($url);
1933 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1936 $new_url = $parts["scheme"]."://".$parts["host"];
1938 if (isset($parts["port"]))
1939 $new_url .= ":".$parts["port"];
1941 if (isset($parts["path"]))
1942 $new_url .= $parts["path"];
1944 if ($new_url != $url)
1945 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1951 * @brief Replace alternate OStatus user format with the primary one
1953 * @param arr $contact contact array (called by reference)
1955 function fix_alternate_contact_address(&$contact) {
1956 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1957 $data = probe_url($contact["url"]);
1958 if ($contact["network"] == NETWORK_OSTATUS) {
1959 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1960 $contact["url"] = $data["url"];
1961 $contact["addr"] = $data["addr"];
1962 $contact["alias"] = $data["alias"];
1963 $contact["server_url"] = $data["baseurl"];
1969 * @brief Fetch the gcontact id, add an entry if not existed
1971 * @param arr $contact contact array
1972 * @return bool|int Returns false if not found, integer if contact was found
1974 function get_gcontact_id($contact) {
1979 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1980 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1984 if ($contact["network"] == NETWORK_STATUSNET)
1985 $contact["network"] = NETWORK_OSTATUS;
1987 // All new contacts are hidden by default
1988 if (!isset($contact["hide"]))
1989 $contact["hide"] = true;
1991 // Replace alternate OStatus user format with the primary one
1992 fix_alternate_contact_address($contact);
1994 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1995 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1996 $contact["url"] = clean_contact_url($contact["url"]);
1998 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1999 dbesc(normalise_link($contact["url"])));
2002 $gcontact_id = $r[0]["id"];
2004 // Update every 90 days
2005 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2006 $last_failure_str = $r[0]["last_failure"];
2007 $last_failure = strtotime($r[0]["last_failure"]);
2008 $last_contact_str = $r[0]["last_contact"];
2009 $last_contact = strtotime($r[0]["last_contact"]);
2010 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2013 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2014 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2015 dbesc($contact["name"]),
2016 dbesc($contact["nick"]),
2017 dbesc($contact["addr"]),
2018 dbesc($contact["network"]),
2019 dbesc($contact["url"]),
2020 dbesc(normalise_link($contact["url"])),
2021 dbesc($contact["photo"]),
2022 dbesc(datetime_convert()),
2023 dbesc(datetime_convert()),
2024 dbesc($contact["location"]),
2025 dbesc($contact["about"]),
2026 intval($contact["hide"]),
2027 intval($contact["generation"])
2030 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2031 dbesc(normalise_link($contact["url"])));
2034 $gcontact_id = $r[0]["id"];
2036 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2041 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2042 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2045 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2046 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2047 dbesc(normalise_link($contact["url"])),
2048 intval($gcontact_id));
2050 return $gcontact_id;
2054 * @brief Updates the gcontact table from a given array
2056 * @param arr $contact contact array
2057 * @return bool|int Returns false if not found, integer if contact was found
2059 function update_gcontact($contact) {
2061 // Check for invalid "contact-type" value
2062 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2063 $contact['contact-type'] = 0;
2066 /// @todo update contact table as well
2068 $gcontact_id = get_gcontact_id($contact);
2073 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2074 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2075 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2076 intval($gcontact_id));
2078 // Get all field names
2080 foreach ($r[0] AS $field => $data)
2081 $fields[$field] = $data;
2083 unset($fields["url"]);
2084 unset($fields["updated"]);
2085 unset($fields["hide"]);
2087 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2088 // This value is still transmitted via poco.
2089 if ($contact["keywords"] == "0")
2090 unset($contact["keywords"]);
2092 if ($r[0]["keywords"] == "0")
2093 $r[0]["keywords"] = "";
2095 // assign all unassigned fields from the database entry
2096 foreach ($fields AS $field => $data)
2097 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2098 $contact[$field] = $r[0][$field];
2100 if (!isset($contact["hide"]))
2101 $contact["hide"] = $r[0]["hide"];
2103 $fields["hide"] = $r[0]["hide"];
2105 if ($contact["network"] == NETWORK_STATUSNET)
2106 $contact["network"] = NETWORK_OSTATUS;
2108 // Replace alternate OStatus user format with the primary one
2109 fix_alternate_contact_address($contact);
2111 if (!isset($contact["updated"]))
2112 $contact["updated"] = datetime_convert();
2114 if ($contact["server_url"] == "") {
2115 $server_url = $contact["url"];
2117 $server_url = matching_url($server_url, $contact["alias"]);
2118 if ($server_url != "")
2119 $contact["server_url"] = $server_url;
2121 $server_url = matching_url($server_url, $contact["photo"]);
2122 if ($server_url != "")
2123 $contact["server_url"] = $server_url;
2125 $server_url = matching_url($server_url, $contact["notify"]);
2126 if ($server_url != "")
2127 $contact["server_url"] = $server_url;
2129 $contact["server_url"] = normalise_link($contact["server_url"]);
2131 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2132 $hostname = str_replace("http://", "", $contact["server_url"]);
2133 $contact["addr"] = $contact["nick"]."@".$hostname;
2136 // Check if any field changed
2138 unset($fields["generation"]);
2140 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2141 foreach ($fields AS $field => $data)
2142 if ($contact[$field] != $r[0][$field]) {
2143 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2147 if ($contact["generation"] < $r[0]["generation"]) {
2148 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2154 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2156 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2157 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2158 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2159 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2160 `server_url` = '%s', `connect` = '%s'
2161 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2162 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2163 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2164 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2165 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2166 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2167 dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
2168 dbesc($contact["server_url"]), dbesc($contact["connect"]),
2169 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2172 // Now update the contact entry with the user id "0" as well.
2173 // This is used for the shadow copies of public items.
2174 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2175 dbesc(normalise_link($contact["url"])));
2178 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2180 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2182 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2183 `network` = '%s', `bd` = '%s', `gender` = '%s',
2184 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2185 `url` = '%s', `location` = '%s', `about` = '%s'
2187 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2188 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2189 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2190 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2191 intval($r[0]["id"]));
2195 return $gcontact_id;
2199 * @brief Updates the gcontact entry from probe
2201 * @param str $url profile link
2203 function update_gcontact_from_probe($url) {
2204 $data = probe_url($url);
2206 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2207 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2211 update_gcontact($data);
2215 * @brief Update the gcontact entry for a given user id
2217 * @param int $uid User ID
2219 function update_gcontact_for_user($uid) {
2220 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2221 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2222 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2223 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2224 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2226 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2227 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2228 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2231 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2232 "country-name" => $r[0]["country-name"]));
2234 // The "addr" field was added in 3.4.3 so it can be empty for older users
2235 if ($r[0]["addr"] != "")
2236 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2238 $addr = $r[0]["addr"];
2240 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2241 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2242 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2243 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2244 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2245 "nick" => $r[0]["nickname"], "addr" => $addr,
2246 "connect" => $addr, "server_url" => App::get_baseurl(),
2247 "generation" => 1, "network" => NETWORK_DFRN);
2249 update_gcontact($gcontact);
2253 * @brief Fetches users of given GNU Social server
2255 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2257 * @param str $server Server address
2259 function gs_fetch_users($server) {
2261 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2263 $url = $server."/main/statistics";
2265 $result = z_fetch_url($url);
2266 if (!$result["success"])
2269 $statistics = json_decode($result["body"]);
2271 if (is_object($statistics->config)) {
2272 if ($statistics->config->instance_with_ssl)
2273 $server = "https://";
2275 $server = "http://";
2277 $server .= $statistics->config->instance_address;
2279 $hostname = $statistics->config->instance_address;
2281 if ($statistics->instance_with_ssl)
2282 $server = "https://";
2284 $server = "http://";
2286 $server .= $statistics->instance_address;
2288 $hostname = $statistics->instance_address;
2291 if (is_object($statistics->users))
2292 foreach ($statistics->users AS $nick => $user) {
2293 $profile_url = $server."/".$user->nickname;
2295 $contact = array("url" => $profile_url,
2296 "name" => $user->fullname,
2297 "addr" => $user->nickname."@".$hostname,
2298 "nick" => $user->nickname,
2299 "about" => $user->bio,
2300 "network" => NETWORK_OSTATUS,
2301 "photo" => App::get_baseurl()."/images/person-175.jpg");
2302 get_gcontact_id($contact);
2307 * @brief Asking GNU Social server on a regular base for their user data
2310 function gs_discover() {
2312 $requery_days = intval(get_config("system", "poco_requery_days"));
2314 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2316 $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",
2317 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2322 foreach ($r AS $server) {
2323 gs_fetch_users($server["url"]);
2324 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2329 * @brief Returns a list of all known servers
2330 * @return array List of server urls
2332 function poco_serverlist() {
2333 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2334 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2335 ORDER BY `last_contact`
2337 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2338 if (!dbm::is_result($r)) {