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
726 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
727 $platform = "StatusNet";
728 $version = trim($serverret["body"], '"');
729 $network = NETWORK_OSTATUS;
732 // Test for GNU Social
733 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
734 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
735 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
736 $platform = "GNU Social";
737 $version = trim($serverret["body"], '"');
738 $network = NETWORK_OSTATUS;
741 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
742 if ($serverret["success"]) {
743 $data = json_decode($serverret["body"]);
745 if (isset($data->site->server)) {
746 $last_contact = datetime_convert();
748 if (isset($data->site->hubzilla)) {
749 $platform = $data->site->hubzilla->PLATFORM_NAME;
750 $version = $data->site->hubzilla->RED_VERSION;
751 $network = NETWORK_DIASPORA;
753 if (isset($data->site->redmatrix)) {
754 if (isset($data->site->redmatrix->PLATFORM_NAME))
755 $platform = $data->site->redmatrix->PLATFORM_NAME;
756 elseif (isset($data->site->redmatrix->RED_PLATFORM))
757 $platform = $data->site->redmatrix->RED_PLATFORM;
759 $version = $data->site->redmatrix->RED_VERSION;
760 $network = NETWORK_DIASPORA;
762 if (isset($data->site->friendica)) {
763 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
764 $version = $data->site->friendica->FRIENDICA_VERSION;
765 $network = NETWORK_DFRN;
768 $site_name = $data->site->name;
770 $data->site->closed = poco_to_boolean($data->site->closed);
771 $data->site->private = poco_to_boolean($data->site->private);
772 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
774 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
775 $register_policy = REGISTER_APPROVE;
776 elseif (!$data->site->closed AND !$data->site->private)
777 $register_policy = REGISTER_OPEN;
779 $register_policy = REGISTER_CLOSED;
784 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
786 $serverret = z_fetch_url($server_url."/statistics.json");
787 if ($serverret["success"]) {
788 $data = json_decode($serverret["body"]);
790 $version = $data->version;
792 $site_name = $data->name;
794 if (isset($data->network) AND ($platform == ""))
795 $platform = $data->network;
797 if ($platform == "Diaspora")
798 $network = NETWORK_DIASPORA;
800 if ($data->registrations_open)
801 $register_policy = REGISTER_OPEN;
803 $register_policy = REGISTER_CLOSED;
805 if (isset($data->version))
806 $last_contact = datetime_convert();
810 // Check for noscrape
811 // Friendica servers could be detected as OStatus servers
812 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
813 $serverret = z_fetch_url($server_url."/friendica/json");
815 if (!$serverret["success"])
816 $serverret = z_fetch_url($server_url."/friendika/json");
818 if ($serverret["success"]) {
819 $data = json_decode($serverret["body"]);
821 if (isset($data->version)) {
822 $last_contact = datetime_convert();
823 $network = NETWORK_DFRN;
825 $noscrape = $data->no_scrape_url;
826 $version = $data->version;
827 $site_name = $data->site_name;
829 $register_policy_str = $data->register_policy;
830 $platform = $data->platform;
832 switch ($register_policy_str) {
833 case "REGISTER_CLOSED":
834 $register_policy = REGISTER_CLOSED;
836 case "REGISTER_APPROVE":
837 $register_policy = REGISTER_APPROVE;
839 case "REGISTER_OPEN":
840 $register_policy = REGISTER_OPEN;
849 $serverret = z_fetch_url($server_url."/poco");
850 if ($serverret["success"]) {
851 $data = json_decode($serverret["body"]);
852 if (isset($data->totalResults)) {
853 $poco = $server_url."/poco";
854 $last_contact = datetime_convert();
859 // Check again if the server exists
860 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
862 $version = strip_tags($version);
863 $site_name = strip_tags($site_name);
864 $info = strip_tags($info);
865 $platform = strip_tags($platform);
868 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
869 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
874 intval($register_policy),
879 dbesc($last_contact),
880 dbesc($last_failure),
881 dbesc(normalise_link($server_url))
884 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
885 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
887 dbesc(normalise_link($server_url)),
891 intval($register_policy),
896 dbesc(datetime_convert()),
897 dbesc($last_contact),
898 dbesc($last_failure),
899 dbesc(datetime_convert())
902 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
907 function count_common_friends($uid,$cid) {
909 $r = q("SELECT count(*) as `total`
910 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
911 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
912 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
913 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
920 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
922 return $r[0]['total'];
928 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
931 $sql_extra = " order by rand() ";
933 $sql_extra = " order by `gcontact`.`name` asc ";
935 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
937 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
938 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
939 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
940 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
941 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
942 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
943 $sql_extra LIMIT %d, %d",
957 function count_common_friends_zcid($uid,$zcid) {
959 $r = q("SELECT count(*) as `total`
960 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
961 where `glink`.`zcid` = %d
962 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
968 return $r[0]['total'];
973 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
976 $sql_extra = " order by rand() ";
978 $sql_extra = " order by `gcontact`.`name` asc ";
980 $r = q("SELECT `gcontact`.*
981 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
982 where `glink`.`zcid` = %d
983 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
984 $sql_extra limit %d, %d",
996 function count_all_friends($uid,$cid) {
998 $r = q("SELECT count(*) as `total`
999 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1000 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1001 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1007 return $r[0]['total'];
1013 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1015 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1017 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1018 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1019 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1020 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1021 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1034 function suggestion_query($uid, $start = 0, $limit = 80) {
1039 $network = array(NETWORK_DFRN);
1041 if (get_config('system','diaspora_enabled'))
1042 $network[] = NETWORK_DIASPORA;
1044 if (!get_config('system','ostatus_disabled'))
1045 $network[] = NETWORK_OSTATUS;
1047 $sql_network = implode("', '", $network);
1048 //$sql_network = "'".$sql_network."', ''";
1049 $sql_network = "'".$sql_network."'";
1051 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1052 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1053 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1054 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1055 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1056 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1057 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1058 AND `gcontact`.`network` IN (%s)
1059 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1069 if(count($r) && count($r) >= ($limit -1))
1072 $r2 = q("SELECT gcontact.* FROM gcontact
1073 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1074 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1075 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1076 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1077 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1078 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1079 AND `gcontact`.`network` IN (%s)
1080 ORDER BY rand() LIMIT %d, %d",
1090 foreach ($r2 AS $suggestion)
1091 $list[$suggestion["nurl"]] = $suggestion;
1093 foreach ($r AS $suggestion)
1094 $list[$suggestion["nurl"]] = $suggestion;
1096 while (sizeof($list) > ($limit))
1102 function update_suggestions() {
1108 /// TODO Check if it is really neccessary to poll the own server
1109 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1111 $done[] = $a->get_baseurl() . '/poco';
1113 if(strlen(get_config('system','directory'))) {
1114 $x = fetch_url(get_server()."/pubsites");
1116 $j = json_decode($x);
1118 foreach($j->entries as $entry) {
1120 poco_check_server($entry->url);
1122 $url = $entry->url . '/poco';
1123 if(! in_array($url,$done))
1124 poco_load(0,0,0,$entry->url . '/poco');
1130 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1131 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1132 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1136 foreach($r as $rr) {
1137 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1138 if(! in_array($base,$done))
1139 poco_load(0,0,0,$base);
1144 function poco_discover_federation() {
1145 $last = get_config('poco','last_federation_discovery');
1148 $next = $last + (24 * 60 * 60);
1153 // Discover Friendica, Hubzilla and Diaspora servers
1154 $serverdata = fetch_url("http://the-federation.info/pods.json");
1157 $servers = json_decode($serverdata);
1159 foreach($servers->pods AS $server)
1160 poco_check_server("https://".$server->host);
1163 // Discover GNU Social Servers
1164 if (!get_config('system','ostatus_disabled')) {
1165 $serverdata = "http://gstools.org/api/get_open_instances/";
1167 $result = z_fetch_url($serverdata);
1168 if ($result["success"]) {
1169 $servers = json_decode($result["body"]);
1171 foreach($servers->data AS $server)
1172 poco_check_server($server->instance_address);
1176 set_config('poco','last_federation_discovery', time());
1179 function poco_discover($complete = false) {
1181 // Update the server list
1182 poco_discover_federation();
1186 $requery_days = intval(get_config("system", "poco_requery_days"));
1188 if ($requery_days == 0)
1191 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1193 $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));
1195 foreach ($r AS $server) {
1197 if (!poco_check_server($server["url"], $server["network"])) {
1198 // The server is not reachable? Okay, then we will try it later
1199 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1203 // Fetch all users from the other server
1204 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1206 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1208 $retdata = z_fetch_url($url);
1209 if ($retdata["success"]) {
1210 $data = json_decode($retdata["body"]);
1212 poco_discover_server($data, 2);
1214 if (get_config('system','poco_discovery') > 1) {
1216 $timeframe = get_config('system','poco_discovery_since');
1217 if ($timeframe == 0)
1220 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1222 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1223 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1227 $retdata = z_fetch_url($url);
1228 if ($retdata["success"]) {
1229 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1230 $success = poco_discover_server(json_decode($retdata["body"]));
1233 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1234 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1235 poco_discover_server_users($data, $server);
1239 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1240 if (!$complete AND (--$no_of_queries == 0))
1243 // If the server hadn't replied correctly, then force a sanity check
1244 poco_check_server($server["url"], $server["network"], true);
1246 // If we couldn't reach the server, we will try it some time later
1247 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1252 function poco_discover_server_users($data, $server) {
1254 if (!isset($data->entry))
1257 foreach ($data->entry AS $entry) {
1259 if (isset($entry->urls)) {
1260 foreach($entry->urls as $url)
1261 if($url->type == 'profile') {
1262 $profile_url = $url->value;
1263 $urlparts = parse_url($profile_url);
1264 $username = end(explode("/", $urlparts["path"]));
1267 if ($username != "") {
1268 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1270 // Fetch all contacts from a given user from the other server
1271 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1273 $retdata = z_fetch_url($url);
1274 if ($retdata["success"])
1275 poco_discover_server(json_decode($retdata["body"]), 3);
1280 function poco_discover_server($data, $default_generation = 0) {
1282 if (!isset($data->entry) OR !count($data->entry))
1287 foreach ($data->entry AS $entry) {
1289 $profile_photo = '';
1293 $updated = '0000-00-00 00:00:00';
1298 $generation = $default_generation;
1300 $name = $entry->displayName;
1302 if(isset($entry->urls)) {
1303 foreach($entry->urls as $url) {
1304 if($url->type == 'profile') {
1305 $profile_url = $url->value;
1308 if($url->type == 'webfinger') {
1309 $connect_url = str_replace('acct:' , '', $url->value);
1315 if(isset($entry->photos)) {
1316 foreach($entry->photos as $photo) {
1317 if($photo->type == 'profile') {
1318 $profile_photo = $photo->value;
1324 if(isset($entry->updated))
1325 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1327 if(isset($entry->network))
1328 $network = $entry->network;
1330 if(isset($entry->currentLocation))
1331 $location = $entry->currentLocation;
1333 if(isset($entry->aboutMe))
1334 $about = html2bbcode($entry->aboutMe);
1336 if(isset($entry->gender))
1337 $gender = $entry->gender;
1339 if(isset($entry->generation) AND ($entry->generation > 0))
1340 $generation = ++$entry->generation;
1342 if(isset($entry->tags))
1343 foreach($entry->tags as $tag)
1344 $keywords = implode(", ", $tag);
1346 if ($generation > 0) {
1349 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1350 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1351 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1358 * @brief Removes unwanted parts from a contact url
1360 * @param string $url Contact url
1361 * @return string Contact url with the wanted parts
1363 function clean_contact_url($url) {
1364 $parts = parse_url($url);
1366 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1369 $new_url = $parts["scheme"]."://".$parts["host"];
1371 if (isset($parts["port"]))
1372 $new_url .= ":".$parts["port"];
1374 if (isset($parts["path"]))
1375 $new_url .= $parts["path"];
1381 * @brief Fetch the gcontact id, add an entry if not existed
1383 * @param arr $contact contact array
1384 * @return bool|int Returns false if not found, integer if contact was found
1386 function get_gcontact_id($contact) {
1390 if ($contact["network"] == NETWORK_PHANTOM)
1393 if ($contact["network"] == NETWORK_STATUSNET)
1394 $contact["network"] = NETWORK_OSTATUS;
1396 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1397 $contact["url"] = clean_contact_url($contact["url"]);
1399 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1400 dbesc(normalise_link($contact["url"])));
1403 $gcontact_id = $r[0]["id"];
1405 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1406 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1407 dbesc($contact["name"]),
1408 dbesc($contact["nick"]),
1409 dbesc($contact["addr"]),
1410 dbesc($contact["network"]),
1411 dbesc($contact["url"]),
1412 dbesc(normalise_link($contact["url"])),
1413 dbesc($contact["photo"]),
1414 dbesc(datetime_convert()),
1415 dbesc(datetime_convert()),
1416 dbesc($contact["location"]),
1417 dbesc($contact["about"]),
1418 intval($contact["generation"])
1421 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1422 dbesc(normalise_link($contact["url"])));
1425 $gcontact_id = $r[0]["id"];
1428 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1429 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1430 dbesc(normalise_link($contact["url"])),
1431 intval($gcontact_id));
1433 return $gcontact_id;
1437 * @brief Updates the gcontact table from a given array
1439 * @param arr $contact contact array
1440 * @return bool|int Returns false if not found, integer if contact was found
1442 function update_gcontact($contact) {
1444 /// @todo update contact table as well
1446 $gcontact_id = get_gcontact_id($contact);
1451 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1452 `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1453 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1454 intval($gcontact_id));
1456 // Get all field names
1458 foreach ($r[0] AS $field => $data)
1459 $fields[$field] = $data;
1461 unset($fields["url"]);
1462 unset($fields["updated"]);
1464 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1465 // This value is still transmitted via poco.
1466 if ($contact["keywords"] == "0")
1467 unset($contact["keywords"]);
1469 if ($r[0]["keywords"] == "0")
1470 $r[0]["keywords"] = "";
1472 // assign all unassigned fields from the database entry
1473 foreach ($fields AS $field => $data)
1474 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1475 $contact[$field] = $r[0][$field];
1477 if ($contact["network"] == NETWORK_STATUSNET)
1478 $contact["network"] = NETWORK_OSTATUS;
1480 if (!isset($contact["updated"]))
1481 $contact["updated"] = datetime_convert();
1483 if ($contact["server_url"] == "") {
1484 $server_url = $contact["url"];
1486 $server_url = matching_url($server_url, $contact["alias"]);
1487 if ($server_url != "")
1488 $contact["server_url"] = $server_url;
1490 $server_url = matching_url($server_url, $contact["photo"]);
1491 if ($server_url != "")
1492 $contact["server_url"] = $server_url;
1494 $server_url = matching_url($server_url, $contact["notify"]);
1495 if ($server_url != "")
1496 $contact["server_url"] = $server_url;
1498 $contact["server_url"] = normalise_link($contact["server_url"]);
1500 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1501 $hostname = str_replace("http://", "", $contact["server_url"]);
1502 $contact["addr"] = $contact["nick"]."@".$hostname;
1505 // Check if any field changed
1507 unset($fields["generation"]);
1509 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1510 foreach ($fields AS $field => $data)
1511 if ($contact[$field] != $r[0][$field]) {
1512 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1516 if ($contact["generation"] < $r[0]["generation"]) {
1517 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1523 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1525 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1526 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1527 `alias` = '%s', `notify` = '%s', `url` = '%s',
1528 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1529 `server_url` = '%s', `connect` = '%s'
1530 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1531 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1532 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1533 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1534 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1535 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1536 intval($contact["generation"]), dbesc($contact["updated"]),
1537 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1538 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1541 // Now update the contact entry with the user id "0" as well.
1542 // This is used for the shadow copies of public items.
1543 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1544 dbesc(normalise_link($contact["url"])));
1547 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1549 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1551 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1552 `network` = '%s', `bd` = '%s', `gender` = '%s',
1553 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1554 `location` = '%s', `about` = '%s'
1556 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1557 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1558 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1559 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1563 return $gcontact_id;
1567 * @brief Updates the gcontact entry from probe
1569 * @param str $url profile link
1571 function update_gcontact_from_probe($url) {
1572 $data = probe_url($url);
1574 if ($data["network"] == NETWORK_PHANTOM)
1577 update_gcontact($data);
1581 * @brief Fetches users of given GNU Social server
1583 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1585 * @param str $server Server address
1587 function gs_fetch_users($server) {
1589 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1593 $url = $server."/main/statistics";
1595 $result = z_fetch_url($url);
1596 if (!$result["success"])
1599 $statistics = json_decode($result["body"]);
1601 if (is_object($statistics->config)) {
1602 if ($statistics->config->instance_with_ssl)
1603 $server = "https://";
1605 $server = "http://";
1607 $server .= $statistics->config->instance_address;
1609 $hostname = $statistics->config->instance_address;
1611 if ($statistics->instance_with_ssl)
1612 $server = "https://";
1614 $server = "http://";
1616 $server .= $statistics->instance_address;
1618 $hostname = $statistics->instance_address;
1621 if (is_object($statistics->users))
1622 foreach ($statistics->users AS $nick => $user) {
1623 $profile_url = $server."/".$user->nickname;
1625 $contact = array("url" => $profile_url,
1626 "name" => $user->fullname,
1627 "addr" => $user->nickname."@".$hostname,
1628 "nick" => $user->nickname,
1629 "about" => $user->bio,
1630 "network" => NETWORK_OSTATUS,
1631 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1632 get_gcontact_id($contact);
1637 * @brief Asking GNU Social server on a regular base for their user data
1640 function gs_discover() {
1642 $requery_days = intval(get_config("system", "poco_requery_days"));
1644 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1646 $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",
1647 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1652 foreach ($r AS $server) {
1653 gs_fetch_users($server["url"]);
1654 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));