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 if (is_array($noscrape)) {
442 $contact = array("url" => $profile,
443 "network" => $server[0]["network"],
444 "generation" => $gcontacts[0]["generation"]);
446 $contact["name"] = $noscrape["fn"];
447 $contact["community"] = $noscrape["comm"];
449 if (isset($noscrape["tags"])) {
450 $keywords = implode(" ", $noscrape["tags"]);
452 $contact["keywords"] = $keywords;
455 $location = formatted_location($noscrape);
457 $contact["location"] = $location;
459 $contact["notify"] = $noscrape["dfrn-notify"];
461 // Remove all fields that are not present in the gcontact table
462 unset($noscrape["fn"]);
463 unset($noscrape["key"]);
464 unset($noscrape["homepage"]);
465 unset($noscrape["comm"]);
466 unset($noscrape["tags"]);
467 unset($noscrape["locality"]);
468 unset($noscrape["region"]);
469 unset($noscrape["country-name"]);
470 unset($noscrape["contacts"]);
471 unset($noscrape["dfrn-request"]);
472 unset($noscrape["dfrn-confirm"]);
473 unset($noscrape["dfrn-notify"]);
474 unset($noscrape["dfrn-poll"]);
476 $contact = array_merge($contact, $noscrape);
478 update_gcontact($contact);
480 return $noscrape["updated"];
486 // If we only can poll the feed, then we only do this once a while
487 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
488 return $gcontacts[0]["updated"];
490 $data = probe_url($profile);
492 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
493 // Then check the other link and delete this one
494 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
495 (normalise_link($profile) == normalise_link($data["alias"])) AND
496 (normalise_link($profile) != normalise_link($data["url"]))) {
498 // Delete the old entry
499 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
500 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
502 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
503 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
505 poco_last_updated($data["url"], $force);
510 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
511 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
512 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
516 $contact = array("generation" => $gcontacts[0]["generation"]);
518 $contact = array_merge($contact, $data);
520 $contact["server_url"] = $data["baseurl"];
522 unset($contact["batch"]);
523 unset($contact["poll"]);
524 unset($contact["request"]);
525 unset($contact["confirm"]);
526 unset($contact["poco"]);
527 unset($contact["priority"]);
528 unset($contact["pubkey"]);
529 unset($contact["baseurl"]);
531 update_gcontact($contact);
533 $feedret = z_fetch_url($data["poll"]);
535 if (!$feedret["success"]) {
536 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
537 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
541 $doc = new DOMDocument();
542 @$doc->loadXML($feedret["body"]);
544 $xpath = new DomXPath($doc);
545 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
547 $entries = $xpath->query('/atom:feed/atom:entry');
551 foreach ($entries AS $entry) {
552 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
553 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
555 if ($last_updated < $published)
556 $last_updated = $published;
558 if ($last_updated < $updated)
559 $last_updated = $updated;
562 // Maybe there aren't any entries. Then check if it is a valid feed
563 if ($last_updated == "")
564 if ($xpath->query('/atom:feed')->length > 0)
565 $last_updated = "0000-00-00 00:00:00";
567 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
568 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
570 if (($gcontacts[0]["generation"] == 0))
571 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
572 dbesc(normalise_link($profile)));
574 return($last_updated);
577 function poco_do_update($created, $updated, $last_failure, $last_contact) {
578 $now = strtotime(datetime_convert());
580 if ($updated > $last_contact)
581 $contact_time = strtotime($updated);
583 $contact_time = strtotime($last_contact);
585 $failure_time = strtotime($last_failure);
586 $created_time = strtotime($created);
588 // If there is no "created" time then use the current time
589 if ($created_time <= 0)
590 $created_time = $now;
592 // If the last contact was less than 24 hours then don't update
593 if (($now - $contact_time) < (60 * 60 * 24))
596 // If the last failure was less than 24 hours then don't update
597 if (($now - $failure_time) < (60 * 60 * 24))
600 // If the last contact was less than a week ago and the last failure is older than a week then don't update
601 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
604 // 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
605 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
608 // 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
609 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
615 function poco_to_boolean($val) {
616 if (($val == "true") OR ($val == 1))
618 if (($val == "false") OR ($val == 0))
624 function poco_check_server($server_url, $network = "", $force = false) {
626 // Unify the server address
627 $server_url = trim($server_url, "/");
628 $server_url = str_replace("/index.php", "", $server_url);
630 if ($server_url == "")
633 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
636 if ($servers[0]["created"] == "0000-00-00 00:00:00")
637 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
638 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
640 $poco = $servers[0]["poco"];
641 $noscrape = $servers[0]["noscrape"];
644 $network = $servers[0]["network"];
646 $last_contact = $servers[0]["last_contact"];
647 $last_failure = $servers[0]["last_failure"];
648 $version = $servers[0]["version"];
649 $platform = $servers[0]["platform"];
650 $site_name = $servers[0]["site_name"];
651 $info = $servers[0]["info"];
652 $register_policy = $servers[0]["register_policy"];
654 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
655 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
656 return ($last_contact >= $last_failure);
665 $register_policy = -1;
667 $last_contact = "0000-00-00 00:00:00";
668 $last_failure = "0000-00-00 00:00:00";
670 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
673 $orig_last_failure = $last_failure;
675 // Check if the page is accessible via SSL.
676 $server_url = str_replace("http://", "https://", $server_url);
677 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
679 // Maybe the page is unencrypted only?
680 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
681 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
682 $server_url = str_replace("https://", "http://", $server_url);
683 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
685 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
688 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
689 // Workaround for bad configured servers (known nginx problem)
690 if ($serverret["debug"]["http_code"] != "403") {
691 $last_failure = datetime_convert();
694 } elseif ($network == NETWORK_DIASPORA)
695 $last_contact = datetime_convert();
699 $serverret = z_fetch_url($server_url);
701 if (!$serverret["success"] OR ($serverret["body"] == ""))
704 $lines = explode("\n",$serverret["header"]);
706 foreach($lines as $line) {
708 if(stristr($line,'X-Diaspora-Version:')) {
709 $platform = "Diaspora";
710 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
711 $version = trim(str_replace("x-diaspora-version:", "", $version));
712 $network = NETWORK_DIASPORA;
713 $versionparts = explode("-", $version);
714 $version = $versionparts[0];
721 // Test for Statusnet
722 // Will also return data for Friendica and GNU Social - but it will be overwritten later
723 // The "not implemented" is a special treatment for really, really old Friendica versions
724 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
725 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
726 $platform = "StatusNet";
727 $version = trim($serverret["body"], '"');
728 $network = NETWORK_OSTATUS;
731 // Test for GNU Social
732 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
733 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
734 $platform = "GNU Social";
735 $version = trim($serverret["body"], '"');
736 $network = NETWORK_OSTATUS;
739 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
740 if ($serverret["success"]) {
741 $data = json_decode($serverret["body"]);
743 if (isset($data->site->server)) {
744 $last_contact = datetime_convert();
746 if (isset($data->site->hubzilla)) {
747 $platform = $data->site->hubzilla->PLATFORM_NAME;
748 $version = $data->site->hubzilla->RED_VERSION;
749 $network = NETWORK_DIASPORA;
751 if (isset($data->site->redmatrix)) {
752 if (isset($data->site->redmatrix->PLATFORM_NAME))
753 $platform = $data->site->redmatrix->PLATFORM_NAME;
754 elseif (isset($data->site->redmatrix->RED_PLATFORM))
755 $platform = $data->site->redmatrix->RED_PLATFORM;
757 $version = $data->site->redmatrix->RED_VERSION;
758 $network = NETWORK_DIASPORA;
760 if (isset($data->site->friendica)) {
761 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
762 $version = $data->site->friendica->FRIENDICA_VERSION;
763 $network = NETWORK_DFRN;
766 $site_name = $data->site->name;
768 $data->site->closed = poco_to_boolean($data->site->closed);
769 $data->site->private = poco_to_boolean($data->site->private);
770 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
772 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
773 $register_policy = REGISTER_APPROVE;
774 elseif (!$data->site->closed AND !$data->site->private)
775 $register_policy = REGISTER_OPEN;
777 $register_policy = REGISTER_CLOSED;
782 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
784 $serverret = z_fetch_url($server_url."/statistics.json");
785 if ($serverret["success"]) {
786 $data = json_decode($serverret["body"]);
788 $version = $data->version;
790 $site_name = $data->name;
792 if (isset($data->network) AND ($platform == ""))
793 $platform = $data->network;
795 if ($platform == "Diaspora")
796 $network = NETWORK_DIASPORA;
798 if ($data->registrations_open)
799 $register_policy = REGISTER_OPEN;
801 $register_policy = REGISTER_CLOSED;
803 if (isset($data->version))
804 $last_contact = datetime_convert();
808 // Check for noscrape
809 // Friendica servers could be detected as OStatus servers
810 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
811 $serverret = z_fetch_url($server_url."/friendica/json");
813 if (!$serverret["success"])
814 $serverret = z_fetch_url($server_url."/friendika/json");
816 if ($serverret["success"]) {
817 $data = json_decode($serverret["body"]);
819 if (isset($data->version)) {
820 $last_contact = datetime_convert();
821 $network = NETWORK_DFRN;
823 $noscrape = $data->no_scrape_url;
824 $version = $data->version;
825 $site_name = $data->site_name;
827 $register_policy_str = $data->register_policy;
828 $platform = $data->platform;
830 switch ($register_policy_str) {
831 case "REGISTER_CLOSED":
832 $register_policy = REGISTER_CLOSED;
834 case "REGISTER_APPROVE":
835 $register_policy = REGISTER_APPROVE;
837 case "REGISTER_OPEN":
838 $register_policy = REGISTER_OPEN;
847 $serverret = z_fetch_url($server_url."/poco");
848 if ($serverret["success"]) {
849 $data = json_decode($serverret["body"]);
850 if (isset($data->totalResults)) {
851 $poco = $server_url."/poco";
852 $last_contact = datetime_convert();
857 // Check again if the server exists
858 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
861 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
862 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
867 intval($register_policy),
872 dbesc($last_contact),
873 dbesc($last_failure),
874 dbesc(normalise_link($server_url))
877 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
878 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
880 dbesc(normalise_link($server_url)),
884 intval($register_policy),
889 dbesc(datetime_convert()),
890 dbesc($last_contact),
891 dbesc($last_failure),
892 dbesc(datetime_convert())
895 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
900 function count_common_friends($uid,$cid) {
902 $r = q("SELECT count(*) as `total`
903 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
904 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
905 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
906 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
913 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
915 return $r[0]['total'];
921 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
924 $sql_extra = " order by rand() ";
926 $sql_extra = " order by `gcontact`.`name` asc ";
928 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
930 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
931 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
932 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
933 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
934 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
935 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
936 $sql_extra LIMIT %d, %d",
950 function count_common_friends_zcid($uid,$zcid) {
952 $r = q("SELECT count(*) as `total`
953 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
954 where `glink`.`zcid` = %d
955 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
961 return $r[0]['total'];
966 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
969 $sql_extra = " order by rand() ";
971 $sql_extra = " order by `gcontact`.`name` asc ";
973 $r = q("SELECT `gcontact`.*
974 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
975 where `glink`.`zcid` = %d
976 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
977 $sql_extra limit %d, %d",
989 function count_all_friends($uid,$cid) {
991 $r = q("SELECT count(*) as `total`
992 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
993 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
994 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1000 return $r[0]['total'];
1006 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1008 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1010 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1011 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1012 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1013 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1014 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1027 function suggestion_query($uid, $start = 0, $limit = 80) {
1032 $network = array(NETWORK_DFRN);
1034 if (get_config('system','diaspora_enabled'))
1035 $network[] = NETWORK_DIASPORA;
1037 if (!get_config('system','ostatus_disabled'))
1038 $network[] = NETWORK_OSTATUS;
1040 $sql_network = implode("', '", $network);
1041 //$sql_network = "'".$sql_network."', ''";
1042 $sql_network = "'".$sql_network."'";
1044 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1045 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1046 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1047 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1048 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1049 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1050 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1051 AND `gcontact`.`network` IN (%s)
1052 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1062 if(count($r) && count($r) >= ($limit -1))
1065 $r2 = q("SELECT gcontact.* FROM gcontact
1066 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1067 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1068 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1069 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1070 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1071 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1072 AND `gcontact`.`network` IN (%s)
1073 ORDER BY rand() LIMIT %d, %d",
1083 foreach ($r2 AS $suggestion)
1084 $list[$suggestion["nurl"]] = $suggestion;
1086 foreach ($r AS $suggestion)
1087 $list[$suggestion["nurl"]] = $suggestion;
1089 while (sizeof($list) > ($limit))
1095 function update_suggestions() {
1101 /// TODO Check if it is really neccessary to poll the own server
1102 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1104 $done[] = $a->get_baseurl() . '/poco';
1106 if(strlen(get_config('system','directory'))) {
1107 $x = fetch_url(get_server()."/pubsites");
1109 $j = json_decode($x);
1111 foreach($j->entries as $entry) {
1113 poco_check_server($entry->url);
1115 $url = $entry->url . '/poco';
1116 if(! in_array($url,$done))
1117 poco_load(0,0,0,$entry->url . '/poco');
1123 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1124 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1125 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1129 foreach($r as $rr) {
1130 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1131 if(! in_array($base,$done))
1132 poco_load(0,0,0,$base);
1137 function poco_discover_federation() {
1138 $last = get_config('poco','last_federation_discovery');
1141 $next = $last + (24 * 60 * 60);
1146 // Discover Friendica, Hubzilla and Diaspora servers
1147 $serverdata = fetch_url("http://the-federation.info/pods.json");
1150 $servers = json_decode($serverdata);
1152 foreach($servers->pods AS $server)
1153 poco_check_server("https://".$server->host);
1156 // Discover GNU Social Servers
1157 if (!get_config('system','ostatus_disabled')) {
1158 $serverdata = "http://gstools.org/api/get_open_instances/";
1160 $result = z_fetch_url($serverdata);
1161 if ($result["success"]) {
1162 $servers = json_decode($result["body"]);
1164 foreach($servers->data AS $server)
1165 poco_check_server($server->instance_address);
1169 set_config('poco','last_federation_discovery', time());
1172 function poco_discover($complete = false) {
1174 // Update the server list
1175 poco_discover_federation();
1179 $requery_days = intval(get_config("system", "poco_requery_days"));
1181 if ($requery_days == 0)
1184 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1186 $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));
1188 foreach ($r AS $server) {
1190 if (!poco_check_server($server["url"], $server["network"])) {
1191 // The server is not reachable? Okay, then we will try it later
1192 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1196 // Fetch all users from the other server
1197 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1199 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1201 $retdata = z_fetch_url($url);
1202 if ($retdata["success"]) {
1203 $data = json_decode($retdata["body"]);
1205 poco_discover_server($data, 2);
1207 if (get_config('system','poco_discovery') > 1) {
1209 $timeframe = get_config('system','poco_discovery_since');
1210 if ($timeframe == 0)
1213 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1215 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1216 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1220 $retdata = z_fetch_url($url);
1221 if ($retdata["success"]) {
1222 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1223 $success = poco_discover_server(json_decode($retdata["body"]));
1226 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1227 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1228 poco_discover_server_users($data, $server);
1232 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1233 if (!$complete AND (--$no_of_queries == 0))
1236 // If the server hadn't replied correctly, then force a sanity check
1237 poco_check_server($server["url"], $server["network"], true);
1239 // If we couldn't reach the server, we will try it some time later
1240 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1245 function poco_discover_server_users($data, $server) {
1247 if (!isset($data->entry))
1250 foreach ($data->entry AS $entry) {
1252 if (isset($entry->urls)) {
1253 foreach($entry->urls as $url)
1254 if($url->type == 'profile') {
1255 $profile_url = $url->value;
1256 $urlparts = parse_url($profile_url);
1257 $username = end(explode("/", $urlparts["path"]));
1260 if ($username != "") {
1261 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1263 // Fetch all contacts from a given user from the other server
1264 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1266 $retdata = z_fetch_url($url);
1267 if ($retdata["success"])
1268 poco_discover_server(json_decode($retdata["body"]), 3);
1273 function poco_discover_server($data, $default_generation = 0) {
1275 if (!isset($data->entry) OR !count($data->entry))
1280 foreach ($data->entry AS $entry) {
1282 $profile_photo = '';
1286 $updated = '0000-00-00 00:00:00';
1291 $generation = $default_generation;
1293 $name = $entry->displayName;
1295 if(isset($entry->urls)) {
1296 foreach($entry->urls as $url) {
1297 if($url->type == 'profile') {
1298 $profile_url = $url->value;
1301 if($url->type == 'webfinger') {
1302 $connect_url = str_replace('acct:' , '', $url->value);
1308 if(isset($entry->photos)) {
1309 foreach($entry->photos as $photo) {
1310 if($photo->type == 'profile') {
1311 $profile_photo = $photo->value;
1317 if(isset($entry->updated))
1318 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1320 if(isset($entry->network))
1321 $network = $entry->network;
1323 if(isset($entry->currentLocation))
1324 $location = $entry->currentLocation;
1326 if(isset($entry->aboutMe))
1327 $about = html2bbcode($entry->aboutMe);
1329 if(isset($entry->gender))
1330 $gender = $entry->gender;
1332 if(isset($entry->generation) AND ($entry->generation > 0))
1333 $generation = ++$entry->generation;
1335 if(isset($entry->tags))
1336 foreach($entry->tags as $tag)
1337 $keywords = implode(", ", $tag);
1339 if ($generation > 0) {
1342 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1343 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1344 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1351 * @brief Fetch the gcontact id, add an entry if not existed
1353 * @param arr $contact contact array
1354 * @return bool|int Returns false if not found, integer if contact was found
1356 function get_gcontact_id($contact) {
1360 if ($contact["network"] == NETWORK_STATUSNET)
1361 $contact["network"] = NETWORK_OSTATUS;
1363 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1364 dbesc(normalise_link($contact["url"])));
1367 $gcontact_id = $r[0]["id"];
1369 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1370 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1371 dbesc($contact["name"]),
1372 dbesc($contact["nick"]),
1373 dbesc($contact["addr"]),
1374 dbesc($contact["network"]),
1375 dbesc($contact["url"]),
1376 dbesc(normalise_link($contact["url"])),
1377 dbesc($contact["photo"]),
1378 dbesc(datetime_convert()),
1379 dbesc(datetime_convert()),
1380 dbesc($contact["location"]),
1381 dbesc($contact["about"]),
1382 intval($contact["generation"])
1385 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1386 dbesc(normalise_link($contact["url"])));
1389 $gcontact_id = $r[0]["id"];
1392 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1393 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1394 dbesc(normalise_link($contact["url"])),
1395 intval($gcontact_id));
1397 return $gcontact_id;
1401 * @brief Updates the gcontact table from a given array
1403 * @param arr $contact contact array
1404 * @return bool|int Returns false if not found, integer if contact was found
1406 function update_gcontact($contact) {
1408 /// @todo update contact table as well
1410 $gcontact_id = get_gcontact_id($contact);
1415 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1416 `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1417 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1418 intval($gcontact_id));
1420 // Get all field names
1422 foreach ($r[0] AS $field => $data)
1423 $fields[$field] = $data;
1425 unset($fields["url"]);
1426 unset($fields["updated"]);
1428 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1429 // This value is still transmitted via poco.
1430 if ($contact["keywords"] == "0")
1431 unset($contact["keywords"]);
1433 if ($r[0]["keywords"] == "0")
1434 $r[0]["keywords"] = "";
1436 // assign all unassigned fields from the database entry
1437 foreach ($fields AS $field => $data)
1438 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1439 $contact[$field] = $r[0][$field];
1441 if ($contact["network"] == NETWORK_STATUSNET)
1442 $contact["network"] = NETWORK_OSTATUS;
1444 if (!isset($contact["updated"]))
1445 $contact["updated"] = datetime_convert();
1447 if ($contact["server_url"] == "") {
1448 $server_url = $contact["url"];
1450 $server_url = matching_url($server_url, $contact["alias"]);
1451 if ($server_url != "")
1452 $contact["server_url"] = $server_url;
1454 $server_url = matching_url($server_url, $contact["photo"]);
1455 if ($server_url != "")
1456 $contact["server_url"] = $server_url;
1458 $server_url = matching_url($server_url, $contact["notify"]);
1459 if ($server_url != "")
1460 $contact["server_url"] = $server_url;
1462 $contact["server_url"] = normalise_link($contact["server_url"]);
1464 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1465 $hostname = str_replace("http://", "", $contact["server_url"]);
1466 $contact["addr"] = $contact["nick"]."@".$hostname;
1469 // Check if any field changed
1471 unset($fields["generation"]);
1473 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1474 foreach ($fields AS $field => $data)
1475 if ($contact[$field] != $r[0][$field]) {
1476 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1480 if ($contact["generation"] < $r[0]["generation"]) {
1481 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1487 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1489 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1490 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1491 `alias` = '%s', `notify` = '%s', `url` = '%s',
1492 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1493 `server_url` = '%s', `connect` = '%s'
1494 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1495 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1496 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1497 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1498 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1499 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1500 intval($contact["generation"]), dbesc($contact["updated"]),
1501 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1502 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1505 // Now update the contact entry with the user id "0" as well.
1506 // This is used for the shadow copies of public items.
1507 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1508 dbesc(normalise_link($contact["url"])));
1511 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1513 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1515 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1516 `network` = '%s', `bd` = '%s', `gender` = '%s',
1517 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1518 `location` = '%s', `about` = '%s'
1520 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1521 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1522 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1523 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1527 return $gcontact_id;
1531 * @brief Updates the gcontact entry from probe
1533 * @param str $url profile link
1535 function update_gcontact_from_probe($url) {
1536 $data = probe_url($url);
1538 if ($data["network"] == NETWORK_PHANTOM)
1541 update_gcontact($data);
1545 * @brief Fetches users of given GNU Social server
1547 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1549 * @param str $server Server address
1551 function gs_fetch_users($server) {
1553 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1557 $url = $server."/main/statistics";
1559 $result = z_fetch_url($url);
1560 if (!$result["success"])
1563 $statistics = json_decode($result["body"]);
1565 if (is_object($statistics->config)) {
1566 if ($statistics->config->instance_with_ssl)
1567 $server = "https://";
1569 $server = "http://";
1571 $server .= $statistics->config->instance_address;
1573 $hostname = $statistics->config->instance_address;
1575 if ($statistics->instance_with_ssl)
1576 $server = "https://";
1578 $server = "http://";
1580 $server .= $statistics->instance_address;
1582 $hostname = $statistics->instance_address;
1585 if (is_object($statistics->users))
1586 foreach ($statistics->users AS $nick => $user) {
1587 $profile_url = $server."/".$user->nickname;
1589 $contact = array("url" => $profile_url,
1590 "name" => $user->fullname,
1591 "addr" => $user->nickname."@".$hostname,
1592 "nick" => $user->nickname,
1593 "about" => $user->bio,
1594 "network" => NETWORK_OSTATUS,
1595 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1596 get_gcontact_id($contact);
1601 * @brief Asking GNU Social server on a regular base for their user data
1604 function gs_discover() {
1606 $requery_days = intval(get_config("system", "poco_requery_days"));
1608 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1610 $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",
1611 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1616 foreach ($r AS $server) {
1617 gs_fetch_users($server["url"]);
1618 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));