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/html2bbcode.php");
13 require_once("include/Contact.php");
14 require_once("include/Photo.php");
19 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
20 * and add the entries to the gcontact (Global Contact) table, or update existing entries
21 * if anything (name or photo) has changed.
22 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
24 * Once the global contact is stored add (if necessary) the contact linkage which associates
25 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
26 * pointing to the same global contact id.
33 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
38 if((! $url) || (! $uid)) {
39 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
54 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation') ;
56 logger('poco_load: ' . $url, LOGGER_DEBUG);
60 logger('poco_load: returns ' . $s, LOGGER_DATA);
62 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
64 if(($a->get_curl_code() > 299) || (! $s))
69 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
71 if(! isset($j->entry))
75 foreach($j->entry as $entry) {
83 $updated = '0000-00-00 00:00:00';
90 $name = $entry->displayName;
92 if(isset($entry->urls)) {
93 foreach($entry->urls as $url) {
94 if($url->type == 'profile') {
95 $profile_url = $url->value;
98 if($url->type == 'webfinger') {
99 $connect_url = str_replace('acct:' , '', $url->value);
104 if(isset($entry->photos)) {
105 foreach($entry->photos as $photo) {
106 if($photo->type == 'profile') {
107 $profile_photo = $photo->value;
113 if(isset($entry->updated))
114 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
116 if(isset($entry->network))
117 $network = $entry->network;
119 if(isset($entry->currentLocation))
120 $location = $entry->currentLocation;
122 if(isset($entry->aboutMe))
123 $about = html2bbcode($entry->aboutMe);
125 if(isset($entry->gender))
126 $gender = $entry->gender;
128 if(isset($entry->generation) AND ($entry->generation > 0))
129 $generation = ++$entry->generation;
131 if(isset($entry->tags))
132 foreach($entry->tags as $tag)
133 $keywords = implode(", ", $tag);
135 // If you query a Friendica server for its profiles, the network has to be Friendica
136 /// TODO It could also be a Redmatrix server
138 // $network = NETWORK_DFRN;
140 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
142 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
143 // Deactivated because we now update Friendica contacts in dfrn.php
144 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
145 // q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
146 // WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
151 // dbesc(normalise_link($profile_url)),
152 // dbesc(NETWORK_DFRN));
154 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
156 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
164 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
170 // 1: Profiles on this server
171 // 2: Contacts of profiles on this server
172 // 3: Contacts of contacts of profiles on this server
177 $alternate = poco_alternate_ostatus_url($profile_url);
179 if ($profile_url == "")
182 $urlparts = parse_url($profile_url);
183 if (!isset($urlparts["scheme"]))
186 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
187 "identi.ca", "alpha.app.net")))
190 $orig_updated = $updated;
192 // Don't store the statusnet connector as network
193 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
194 if ($network == NETWORK_STATUSNET)
197 // The global contacts should contain the original picture, not the cached one
198 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
201 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
202 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
205 $network = $r[0]["network"];
207 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
208 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
209 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
212 $network = $r[0]["network"];
213 //$profile_url = $r[0]["url"];
217 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
218 dbesc(normalise_link($profile_url))
222 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
223 $network = $x[0]["network"];
225 if ($updated == "0000-00-00 00:00:00")
226 $updated = $x[0]["updated"];
228 $created = $x[0]["created"];
229 $server_url = $x[0]["server_url"];
230 $nick = $x[0]["nick"];
231 $addr = $x[0]["addr"];
232 $alias = $x[0]["alias"];
233 $notify = $x[0]["notify"];
235 $created = "0000-00-00 00:00:00";
238 $urlparts = parse_url($profile_url);
239 $nick = end(explode("/", $urlparts["path"]));
245 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
246 AND poco_reachable($profile_url, $server_url, $network, false)) {
247 $data = probe_url($profile_url);
249 $orig_profile = $profile_url;
251 $network = $data["network"];
252 $name = $data["name"];
253 $nick = $data["nick"];
254 $addr = $data["addr"];
255 $alias = $data["alias"];
256 $notify = $data["notify"];
257 $profile_url = $data["url"];
258 $profile_photo = $data["photo"];
259 $server_url = $data["baseurl"];
261 if ($alternate AND ($network == NETWORK_OSTATUS)) {
262 // Delete the old entry - if it exists
263 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
265 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
266 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
269 // possibly create a new entry
270 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
274 if ($alternate AND ($network == NETWORK_OSTATUS))
277 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
278 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
280 dbesc(normalise_link($profile_url))
284 if (($name == "") OR ($profile_photo == ""))
287 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
290 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
292 poco_check_server($server_url, $network);
294 $gcontact = array("url" => $profile_url,
298 "network" => $network,
299 "photo" => $profile_photo,
301 "location" => $location,
303 "keywords" => $keywords,
304 "server_url" => $server_url,
305 "connect" => $connect_url,
307 "updated" => $updated,
308 "generation" => $generation);
310 $gcid = update_gcontact($gcontact);
315 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
322 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
327 dbesc(datetime_convert())
330 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
331 dbesc(datetime_convert()),
342 function poco_reachable($profile, $server = "", $network = "", $force = false) {
345 $server = poco_detect_server($profile);
350 return poco_check_server($server, $network, $force);
353 function poco_detect_server($profile) {
355 // Try to detect the server path based upon some known standard paths
358 if ($server_url == "") {
359 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
360 if ($friendica != $profile) {
361 $server_url = $friendica;
362 $network = NETWORK_DFRN;
366 if ($server_url == "") {
367 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
368 if ($diaspora != $profile) {
369 $server_url = $diaspora;
370 $network = NETWORK_DIASPORA;
374 if ($server_url == "") {
375 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
376 if ($red != $profile) {
378 $network = NETWORK_DIASPORA;
385 function poco_alternate_ostatus_url($url) {
386 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
389 function poco_last_updated($profile, $force = false) {
391 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
392 dbesc(normalise_link($profile)));
394 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
395 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
396 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
398 if ($gcontacts[0]["server_url"] != "")
399 $server_url = $gcontacts[0]["server_url"];
401 $server_url = poco_detect_server($profile);
403 if ($server_url != "") {
404 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
407 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
408 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
413 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
414 dbesc($server_url), dbesc(normalise_link($profile)));
417 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
418 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
419 dbesc(normalise_link($server_url)));
422 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
423 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
428 // noscrape is really fast so we don't cache the call.
429 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
431 // Use noscrape if possible
432 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
435 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
437 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
439 $noscrape = json_decode($noscraperet["body"], true);
441 $contact = array("url" => $profile,
442 "network" => $server[0]["network"],
443 "generation" => $gcontacts[0]["generation"]);
445 $contact["name"] = $noscrape["fn"];
446 $contact["community"] = $noscrape["comm"];
448 if (isset($noscrape["tags"])) {
449 $keywords = implode(" ", $noscrape["tags"]);
451 $contact["keywords"] = $keywords;
454 $location = formatted_location($noscrape);
456 $contact["location"] = $location;
458 $contact["notify"] = $noscrape["dfrn-notify"];
460 // Remove all fields that are not present in the gcontact table
461 unset($noscrape["fn"]);
462 unset($noscrape["key"]);
463 unset($noscrape["homepage"]);
464 unset($noscrape["comm"]);
465 unset($noscrape["tags"]);
466 unset($noscrape["locality"]);
467 unset($noscrape["region"]);
468 unset($noscrape["country-name"]);
469 unset($noscrape["contacts"]);
470 unset($noscrape["dfrn-request"]);
471 unset($noscrape["dfrn-confirm"]);
472 unset($noscrape["dfrn-notify"]);
473 unset($noscrape["dfrn-poll"]);
475 $contact = array_merge($contact, $noscrape);
476 update_gcontact($contact);
478 return $noscrape["updated"];
483 // If we only can poll the feed, then we only do this once a while
484 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
485 return $gcontacts[0]["updated"];
487 $data = probe_url($profile);
489 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
490 // Then check the other link and delete this one
491 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
492 (normalise_link($profile) == normalise_link($data["alias"])) AND
493 (normalise_link($profile) != normalise_link($data["url"]))) {
495 // Delete the old entry
496 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
497 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
499 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
500 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
502 poco_last_updated($data["url"], $force);
507 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
508 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
509 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
513 $contact = array("generation" => $gcontacts[0]["generation"]);
515 $contact = array_merge($contact, $data);
517 $contact["server_url"] = $data["baseurl"];
519 unset($contact["batch"]);
520 unset($contact["poll"]);
521 unset($contact["request"]);
522 unset($contact["confirm"]);
523 unset($contact["poco"]);
524 unset($contact["priority"]);
525 unset($contact["pubkey"]);
526 unset($contact["baseurl"]);
528 update_gcontact($contact);
530 $feedret = z_fetch_url($data["poll"]);
532 if (!$feedret["success"]) {
533 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
534 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
538 $doc = new DOMDocument();
539 @$doc->loadXML($feedret["body"]);
541 $xpath = new DomXPath($doc);
542 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
544 $entries = $xpath->query('/atom:feed/atom:entry');
548 foreach ($entries AS $entry) {
549 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
550 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
552 if ($last_updated < $published)
553 $last_updated = $published;
555 if ($last_updated < $updated)
556 $last_updated = $updated;
559 // Maybe there aren't any entries. Then check if it is a valid feed
560 if ($last_updated == "")
561 if ($xpath->query('/atom:feed')->length > 0)
562 $last_updated = "0000-00-00 00:00:00";
564 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
565 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
567 if (($gcontacts[0]["generation"] == 0))
568 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
569 dbesc(normalise_link($profile)));
571 return($last_updated);
574 function poco_do_update($created, $updated, $last_failure, $last_contact) {
575 $now = strtotime(datetime_convert());
577 if ($updated > $last_contact)
578 $contact_time = strtotime($updated);
580 $contact_time = strtotime($last_contact);
582 $failure_time = strtotime($last_failure);
583 $created_time = strtotime($created);
585 // If there is no "created" time then use the current time
586 if ($created_time <= 0)
587 $created_time = $now;
589 // If the last contact was less than 24 hours then don't update
590 if (($now - $contact_time) < (60 * 60 * 24))
593 // If the last failure was less than 24 hours then don't update
594 if (($now - $failure_time) < (60 * 60 * 24))
597 // If the last contact was less than a week ago and the last failure is older than a week then don't update
598 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
601 // 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
602 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
605 // 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
606 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
612 function poco_to_boolean($val) {
613 if (($val == "true") OR ($val == 1))
615 if (($val == "false") OR ($val == 0))
621 function poco_check_server($server_url, $network = "", $force = false) {
623 // Unify the server address
624 $server_url = trim($server_url, "/");
625 $server_url = str_replace("/index.php", "", $server_url);
627 if ($server_url == "")
630 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
633 if ($servers[0]["created"] == "0000-00-00 00:00:00")
634 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
635 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
637 $poco = $servers[0]["poco"];
638 $noscrape = $servers[0]["noscrape"];
641 $network = $servers[0]["network"];
643 $last_contact = $servers[0]["last_contact"];
644 $last_failure = $servers[0]["last_failure"];
645 $version = $servers[0]["version"];
646 $platform = $servers[0]["platform"];
647 $site_name = $servers[0]["site_name"];
648 $info = $servers[0]["info"];
649 $register_policy = $servers[0]["register_policy"];
651 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
652 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
653 return ($last_contact >= $last_failure);
662 $register_policy = -1;
664 $last_contact = "0000-00-00 00:00:00";
665 $last_failure = "0000-00-00 00:00:00";
667 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
670 $orig_last_failure = $last_failure;
672 // Check if the page is accessible via SSL.
673 $server_url = str_replace("http://", "https://", $server_url);
674 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
676 // Maybe the page is unencrypted only?
677 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
678 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
679 $server_url = str_replace("https://", "http://", $server_url);
680 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
682 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
685 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
686 // Workaround for bad configured servers (known nginx problem)
687 if ($serverret["debug"]["http_code"] != "403") {
688 $last_failure = datetime_convert();
691 } elseif ($network == NETWORK_DIASPORA)
692 $last_contact = datetime_convert();
696 $serverret = z_fetch_url($server_url);
698 if (!$serverret["success"] OR ($serverret["body"] == ""))
701 $lines = explode("\n",$serverret["header"]);
703 foreach($lines as $line) {
705 if(stristr($line,'X-Diaspora-Version:')) {
706 $platform = "Diaspora";
707 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
708 $version = trim(str_replace("x-diaspora-version:", "", $version));
709 $network = NETWORK_DIASPORA;
710 $versionparts = explode("-", $version);
711 $version = $versionparts[0];
718 // Test for Statusnet
719 // Will also return data for Friendica and GNU Social - but it will be overwritten later
720 // The "not implemented" is a special treatment for really, really old Friendica versions
721 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
722 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
723 $platform = "StatusNet";
724 $version = trim($serverret["body"], '"');
725 $network = NETWORK_OSTATUS;
728 // Test for GNU Social
729 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
730 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
731 $platform = "GNU Social";
732 $version = trim($serverret["body"], '"');
733 $network = NETWORK_OSTATUS;
736 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
737 if ($serverret["success"]) {
738 $data = json_decode($serverret["body"]);
740 if (isset($data->site->server)) {
741 $last_contact = datetime_convert();
743 if (isset($data->site->hubzilla)) {
744 $platform = $data->site->hubzilla->PLATFORM_NAME;
745 $version = $data->site->hubzilla->RED_VERSION;
746 $network = NETWORK_DIASPORA;
748 if (isset($data->site->redmatrix)) {
749 if (isset($data->site->redmatrix->PLATFORM_NAME))
750 $platform = $data->site->redmatrix->PLATFORM_NAME;
751 elseif (isset($data->site->redmatrix->RED_PLATFORM))
752 $platform = $data->site->redmatrix->RED_PLATFORM;
754 $version = $data->site->redmatrix->RED_VERSION;
755 $network = NETWORK_DIASPORA;
757 if (isset($data->site->friendica)) {
758 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
759 $version = $data->site->friendica->FRIENDICA_VERSION;
760 $network = NETWORK_DFRN;
763 $site_name = $data->site->name;
765 $data->site->closed = poco_to_boolean($data->site->closed);
766 $data->site->private = poco_to_boolean($data->site->private);
767 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
769 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
770 $register_policy = REGISTER_APPROVE;
771 elseif (!$data->site->closed AND !$data->site->private)
772 $register_policy = REGISTER_OPEN;
774 $register_policy = REGISTER_CLOSED;
779 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
781 $serverret = z_fetch_url($server_url."/statistics.json");
782 if ($serverret["success"]) {
783 $data = json_decode($serverret["body"]);
785 $version = $data->version;
787 $site_name = $data->name;
789 if (isset($data->network) AND ($platform == ""))
790 $platform = $data->network;
792 if ($platform == "Diaspora")
793 $network = NETWORK_DIASPORA;
795 if ($data->registrations_open)
796 $register_policy = REGISTER_OPEN;
798 $register_policy = REGISTER_CLOSED;
800 if (isset($data->version))
801 $last_contact = datetime_convert();
805 // Check for noscrape
806 // Friendica servers could be detected as OStatus servers
807 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
808 $serverret = z_fetch_url($server_url."/friendica/json");
810 if (!$serverret["success"])
811 $serverret = z_fetch_url($server_url."/friendika/json");
813 if ($serverret["success"]) {
814 $data = json_decode($serverret["body"]);
816 if (isset($data->version)) {
817 $last_contact = datetime_convert();
818 $network = NETWORK_DFRN;
820 $noscrape = $data->no_scrape_url;
821 $version = $data->version;
822 $site_name = $data->site_name;
824 $register_policy_str = $data->register_policy;
825 $platform = $data->platform;
827 switch ($register_policy_str) {
828 case "REGISTER_CLOSED":
829 $register_policy = REGISTER_CLOSED;
831 case "REGISTER_APPROVE":
832 $register_policy = REGISTER_APPROVE;
834 case "REGISTER_OPEN":
835 $register_policy = REGISTER_OPEN;
844 $serverret = z_fetch_url($server_url."/poco");
845 if ($serverret["success"]) {
846 $data = json_decode($serverret["body"]);
847 if (isset($data->totalResults)) {
848 $poco = $server_url."/poco";
849 $last_contact = datetime_convert();
854 // Check again if the server exists
855 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
858 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
859 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
864 intval($register_policy),
869 dbesc($last_contact),
870 dbesc($last_failure),
871 dbesc(normalise_link($server_url))
874 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
875 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
877 dbesc(normalise_link($server_url)),
881 intval($register_policy),
886 dbesc(datetime_convert()),
887 dbesc($last_contact),
888 dbesc($last_failure),
889 dbesc(datetime_convert())
892 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
897 function count_common_friends($uid,$cid) {
899 $r = q("SELECT count(*) as `total`
900 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
901 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
902 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
903 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
910 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
912 return $r[0]['total'];
918 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
921 $sql_extra = " order by rand() ";
923 $sql_extra = " order by `gcontact`.`name` asc ";
925 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
927 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
928 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
929 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
930 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
931 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
932 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
933 $sql_extra LIMIT %d, %d",
947 function count_common_friends_zcid($uid,$zcid) {
949 $r = q("SELECT count(*) as `total`
950 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
951 where `glink`.`zcid` = %d
952 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
958 return $r[0]['total'];
963 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
966 $sql_extra = " order by rand() ";
968 $sql_extra = " order by `gcontact`.`name` asc ";
970 $r = q("SELECT `gcontact`.*
971 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
972 where `glink`.`zcid` = %d
973 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
974 $sql_extra limit %d, %d",
986 function count_all_friends($uid,$cid) {
988 $r = q("SELECT count(*) as `total`
989 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
990 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
991 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
997 return $r[0]['total'];
1003 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1005 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1007 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1008 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1009 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1010 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1011 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1024 function suggestion_query($uid, $start = 0, $limit = 80) {
1029 $network = array(NETWORK_DFRN);
1031 if (get_config('system','diaspora_enabled'))
1032 $network[] = NETWORK_DIASPORA;
1034 if (!get_config('system','ostatus_disabled'))
1035 $network[] = NETWORK_OSTATUS;
1037 $sql_network = implode("', '", $network);
1038 //$sql_network = "'".$sql_network."', ''";
1039 $sql_network = "'".$sql_network."'";
1041 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1042 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1043 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1044 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1045 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1046 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1047 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1048 AND `gcontact`.`network` IN (%s)
1049 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1059 if(count($r) && count($r) >= ($limit -1))
1062 $r2 = q("SELECT gcontact.* FROM gcontact
1063 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1064 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1065 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1066 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1067 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1068 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1069 AND `gcontact`.`network` IN (%s)
1070 ORDER BY rand() LIMIT %d, %d",
1080 foreach ($r2 AS $suggestion)
1081 $list[$suggestion["nurl"]] = $suggestion;
1083 foreach ($r AS $suggestion)
1084 $list[$suggestion["nurl"]] = $suggestion;
1086 while (sizeof($list) > ($limit))
1092 function update_suggestions() {
1098 /// TODO Check if it is really neccessary to poll the own server
1099 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1101 $done[] = $a->get_baseurl() . '/poco';
1103 if(strlen(get_config('system','directory'))) {
1104 $x = fetch_url(get_server()."/pubsites");
1106 $j = json_decode($x);
1108 foreach($j->entries as $entry) {
1110 poco_check_server($entry->url);
1112 $url = $entry->url . '/poco';
1113 if(! in_array($url,$done))
1114 poco_load(0,0,0,$entry->url . '/poco');
1120 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1121 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1122 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1126 foreach($r as $rr) {
1127 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1128 if(! in_array($base,$done))
1129 poco_load(0,0,0,$base);
1134 function poco_discover_federation() {
1135 $last = get_config('poco','last_federation_discovery');
1138 $next = $last + (24 * 60 * 60);
1143 // Discover Friendica, Hubzilla and Diaspora servers
1144 $serverdata = fetch_url("http://the-federation.info/pods.json");
1147 $servers = json_decode($serverdata);
1149 foreach($servers->pods AS $server)
1150 poco_check_server("https://".$server->host);
1153 // Discover GNU Social Servers
1154 if (!get_config('system','ostatus_disabled')) {
1155 $serverdata = "http://gstools.org/api/get_open_instances/";
1157 $result = z_fetch_url($serverdata);
1158 if ($result["success"]) {
1159 $servers = json_decode($result["body"]);
1161 foreach($servers->data AS $server)
1162 poco_check_server($server->instance_address);
1166 set_config('poco','last_federation_discovery', time());
1169 function poco_discover($complete = false) {
1171 // Update the server list
1172 poco_discover_federation();
1176 $requery_days = intval(get_config("system", "poco_requery_days"));
1178 if ($requery_days == 0)
1181 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1183 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1185 foreach ($r AS $server) {
1187 if (!poco_check_server($server["url"], $server["network"])) {
1188 // The server is not reachable? Okay, then we will try it later
1189 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1193 // Fetch all users from the other server
1194 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1196 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1198 $retdata = z_fetch_url($url);
1199 if ($retdata["success"]) {
1200 $data = json_decode($retdata["body"]);
1202 poco_discover_server($data, 2);
1204 if (get_config('system','poco_discovery') > 1) {
1206 $timeframe = get_config('system','poco_discovery_since');
1207 if ($timeframe == 0)
1210 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1212 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1213 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1217 $retdata = z_fetch_url($url);
1218 if ($retdata["success"]) {
1219 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1220 $success = poco_discover_server(json_decode($retdata["body"]));
1223 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1224 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1225 poco_discover_server_users($data, $server);
1229 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1230 if (!$complete AND (--$no_of_queries == 0))
1233 // If the server hadn't replied correctly, then force a sanity check
1234 poco_check_server($server["url"], $server["network"], true);
1236 // If we couldn't reach the server, we will try it some time later
1237 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1242 function poco_discover_server_users($data, $server) {
1244 if (!isset($data->entry))
1247 foreach ($data->entry AS $entry) {
1249 if (isset($entry->urls)) {
1250 foreach($entry->urls as $url)
1251 if($url->type == 'profile') {
1252 $profile_url = $url->value;
1253 $urlparts = parse_url($profile_url);
1254 $username = end(explode("/", $urlparts["path"]));
1257 if ($username != "") {
1258 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1260 // Fetch all contacts from a given user from the other server
1261 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1263 $retdata = z_fetch_url($url);
1264 if ($retdata["success"])
1265 poco_discover_server(json_decode($retdata["body"]), 3);
1270 function poco_discover_server($data, $default_generation = 0) {
1272 if (!isset($data->entry) OR !count($data->entry))
1277 foreach ($data->entry AS $entry) {
1279 $profile_photo = '';
1283 $updated = '0000-00-00 00:00:00';
1288 $generation = $default_generation;
1290 $name = $entry->displayName;
1292 if(isset($entry->urls)) {
1293 foreach($entry->urls as $url) {
1294 if($url->type == 'profile') {
1295 $profile_url = $url->value;
1298 if($url->type == 'webfinger') {
1299 $connect_url = str_replace('acct:' , '', $url->value);
1305 if(isset($entry->photos)) {
1306 foreach($entry->photos as $photo) {
1307 if($photo->type == 'profile') {
1308 $profile_photo = $photo->value;
1314 if(isset($entry->updated))
1315 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1317 if(isset($entry->network))
1318 $network = $entry->network;
1320 if(isset($entry->currentLocation))
1321 $location = $entry->currentLocation;
1323 if(isset($entry->aboutMe))
1324 $about = html2bbcode($entry->aboutMe);
1326 if(isset($entry->gender))
1327 $gender = $entry->gender;
1329 if(isset($entry->generation) AND ($entry->generation > 0))
1330 $generation = ++$entry->generation;
1332 if(isset($entry->tags))
1333 foreach($entry->tags as $tag)
1334 $keywords = implode(", ", $tag);
1336 if ($generation > 0) {
1339 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1340 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1341 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1348 * @brief Fetch the gcontact id, add an entry if not existed
1350 * @param arr $contact contact array
1351 * @return bool|int Returns false if not found, integer if contact was found
1353 function get_gcontact_id($contact) {
1357 if ($contact["network"] == NETWORK_STATUSNET)
1358 $contact["network"] = NETWORK_OSTATUS;
1360 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1361 dbesc(normalise_link($contact["url"])));
1364 $gcontact_id = $r[0]["id"];
1366 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1367 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1368 dbesc($contact["name"]),
1369 dbesc($contact["nick"]),
1370 dbesc($contact["addr"]),
1371 dbesc($contact["network"]),
1372 dbesc($contact["url"]),
1373 dbesc(normalise_link($contact["url"])),
1374 dbesc($contact["photo"]),
1375 dbesc(datetime_convert()),
1376 dbesc(datetime_convert()),
1377 dbesc($contact["location"]),
1378 dbesc($contact["about"]),
1379 intval($contact["generation"])
1382 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1383 dbesc(normalise_link($contact["url"])));
1386 $gcontact_id = $r[0]["id"];
1389 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1390 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1391 dbesc(normalise_link($contact["url"])),
1392 intval($gcontact_id));
1394 return $gcontact_id;
1398 * @brief Updates the gcontact table from a given array
1400 * @param arr $contact contact array
1401 * @return bool|int Returns false if not found, integer if contact was found
1403 function update_gcontact($contact) {
1405 /// @todo update contact table as well
1407 $gcontact_id = get_gcontact_id($contact);
1412 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1413 `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1414 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1415 intval($gcontact_id));
1417 // Get all field names
1419 foreach ($r[0] AS $field => $data)
1420 $fields[$field] = $data;
1422 unset($fields["url"]);
1423 unset($fields["updated"]);
1425 // assign all unassigned fields from the database entry
1426 foreach ($fields AS $field => $data)
1427 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1428 $contact[$field] = $r[0][$field];
1430 if ($contact["network"] == NETWORK_STATUSNET)
1431 $contact["network"] = NETWORK_OSTATUS;
1433 if (!isset($contact["updated"]))
1434 $contact["updated"] = datetime_convert();
1436 // Check if any field changed
1438 unset($fields["generation"]);
1440 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1441 foreach ($fields AS $field => $data)
1442 if ($contact[$field] != $r[0][$field]) {
1443 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1447 if ($contact["generation"] < $r[0]["generation"]) {
1448 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1454 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1456 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1457 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1458 `alias` = '%s', `notify` = '%s', `url` = '%s',
1459 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1460 `server_url` = '%s', `connect` = '%s'
1461 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1462 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1463 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1464 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1465 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1466 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1467 intval($contact["generation"]), dbesc($contact["updated"]),
1468 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1469 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1472 // Now update the contact entry with the user id "0" as well.
1473 // This is used for the shadow copies of public items.
1474 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1475 dbesc(normalise_link($contact["url"])));
1478 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1480 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1482 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1483 `network` = '%s', `bd` = '%s', `gender` = '%s',
1484 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1485 `location` = '%s', `about` = '%s'
1487 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1488 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1489 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1490 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1494 return $gcontact_id;
1498 * @brief Updates the gcontact entry from probe
1500 * @param str $url profile link
1502 function update_gcontact_from_probe($url) {
1503 $data = probe_url($url);
1505 if ($data["network"] == NETWORK_PHANTOM)
1508 update_gcontact($data);
1512 * @brief Fetches users of given GNU Social server
1514 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1516 * @param str $server Server address
1518 function gs_fetch_users($server) {
1520 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1524 $url = $server."/main/statistics";
1526 $result = z_fetch_url($url);
1527 if (!$result["success"])
1530 $statistics = json_decode($result["body"]);
1532 if (is_object($statistics->config)) {
1533 if ($statistics->config->instance_with_ssl)
1534 $server = "https://";
1536 $server = "http://";
1538 $server .= $statistics->config->instance_address;
1540 $hostname = $statistics->config->instance_address;
1542 if ($statistics->instance_with_ssl)
1543 $server = "https://";
1545 $server = "http://";
1547 $server .= $statistics->instance_address;
1549 $hostname = $statistics->instance_address;
1552 if (is_object($statistics->users))
1553 foreach ($statistics->users AS $nick => $user) {
1554 $profile_url = $server."/".$user->nickname;
1556 $contact = array("url" => $profile_url,
1557 "name" => $user->fullname,
1558 "addr" => $user->nickname."@".$hostname,
1559 "nick" => $user->nickname,
1560 "about" => $user->bio,
1561 "network" => NETWORK_OSTATUS,
1562 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1563 get_gcontact_id($contact);
1568 * @brief Asking GNU Social server on a regular base for their user data
1571 function gs_discover() {
1573 $requery_days = intval(get_config("system", "poco_requery_days"));
1575 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1577 $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",
1578 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1583 foreach ($r AS $server) {
1584 gs_fetch_users($server["url"]);
1585 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));