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 if ($profile_url == "")
180 $urlparts = parse_url($profile_url);
181 if (!isset($urlparts["scheme"]))
184 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
185 "identi.ca", "alpha.app.net")))
188 // Don't store the statusnet connector as network
189 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
190 if ($network == NETWORK_STATUSNET)
193 // Assure that there are no parameter fragments in the profile url
194 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
195 $profile_url = clean_contact_url($profile_url);
197 $alternate = poco_alternate_ostatus_url($profile_url);
199 $orig_updated = $updated;
201 // The global contacts should contain the original picture, not the cached one
202 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
205 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
206 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
209 $network = $r[0]["network"];
211 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
212 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
213 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
216 $network = $r[0]["network"];
217 //$profile_url = $r[0]["url"];
221 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
222 dbesc(normalise_link($profile_url))
226 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
227 $network = $x[0]["network"];
229 if ($updated == "0000-00-00 00:00:00")
230 $updated = $x[0]["updated"];
232 $created = $x[0]["created"];
233 $server_url = $x[0]["server_url"];
234 $nick = $x[0]["nick"];
235 $addr = $x[0]["addr"];
236 $alias = $x[0]["alias"];
237 $notify = $x[0]["notify"];
239 $created = "0000-00-00 00:00:00";
242 $urlparts = parse_url($profile_url);
243 $nick = end(explode("/", $urlparts["path"]));
249 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
250 AND poco_reachable($profile_url, $server_url, $network, false)) {
251 $data = probe_url($profile_url);
253 $orig_profile = $profile_url;
255 $network = $data["network"];
256 $name = $data["name"];
257 $nick = $data["nick"];
258 $addr = $data["addr"];
259 $alias = $data["alias"];
260 $notify = $data["notify"];
261 $profile_url = $data["url"];
262 $profile_photo = $data["photo"];
263 $server_url = $data["baseurl"];
265 if ($alternate AND ($network == NETWORK_OSTATUS)) {
266 // Delete the old entry - if it exists
267 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
269 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
270 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
273 // possibly create a new entry
274 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
278 if ($alternate AND ($network == NETWORK_OSTATUS))
281 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
282 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
284 dbesc(normalise_link($profile_url))
288 if (($name == "") OR ($profile_photo == ""))
291 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
294 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
296 poco_check_server($server_url, $network);
298 $gcontact = array("url" => $profile_url,
302 "network" => $network,
303 "photo" => $profile_photo,
305 "location" => $location,
307 "keywords" => $keywords,
308 "server_url" => $server_url,
309 "connect" => $connect_url,
311 "updated" => $updated,
312 "generation" => $generation);
314 $gcid = update_gcontact($gcontact);
319 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
326 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
331 dbesc(datetime_convert())
334 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
335 dbesc(datetime_convert()),
346 function poco_reachable($profile, $server = "", $network = "", $force = false) {
349 $server = poco_detect_server($profile);
354 return poco_check_server($server, $network, $force);
357 function poco_detect_server($profile) {
359 // Try to detect the server path based upon some known standard paths
362 if ($server_url == "") {
363 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
364 if ($friendica != $profile) {
365 $server_url = $friendica;
366 $network = NETWORK_DFRN;
370 if ($server_url == "") {
371 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
372 if ($diaspora != $profile) {
373 $server_url = $diaspora;
374 $network = NETWORK_DIASPORA;
378 if ($server_url == "") {
379 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
380 if ($red != $profile) {
382 $network = NETWORK_DIASPORA;
389 function poco_alternate_ostatus_url($url) {
390 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
393 function poco_last_updated($profile, $force = false) {
395 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
396 dbesc(normalise_link($profile)));
398 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
399 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
400 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
402 if ($gcontacts[0]["server_url"] != "")
403 $server_url = $gcontacts[0]["server_url"];
405 $server_url = poco_detect_server($profile);
407 if ($server_url != "") {
408 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
411 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
412 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
417 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
418 dbesc($server_url), dbesc(normalise_link($profile)));
421 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
422 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
423 dbesc(normalise_link($server_url)));
426 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
427 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
432 // noscrape is really fast so we don't cache the call.
433 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
435 // Use noscrape if possible
436 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
439 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
441 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
443 $noscrape = json_decode($noscraperet["body"], true);
445 if (is_array($noscrape)) {
446 $contact = array("url" => $profile,
447 "network" => $server[0]["network"],
448 "generation" => $gcontacts[0]["generation"]);
450 $contact["name"] = $noscrape["fn"];
451 $contact["community"] = $noscrape["comm"];
453 if (isset($noscrape["tags"])) {
454 $keywords = implode(" ", $noscrape["tags"]);
456 $contact["keywords"] = $keywords;
459 $location = formatted_location($noscrape);
461 $contact["location"] = $location;
463 $contact["notify"] = $noscrape["dfrn-notify"];
465 // Remove all fields that are not present in the gcontact table
466 unset($noscrape["fn"]);
467 unset($noscrape["key"]);
468 unset($noscrape["homepage"]);
469 unset($noscrape["comm"]);
470 unset($noscrape["tags"]);
471 unset($noscrape["locality"]);
472 unset($noscrape["region"]);
473 unset($noscrape["country-name"]);
474 unset($noscrape["contacts"]);
475 unset($noscrape["dfrn-request"]);
476 unset($noscrape["dfrn-confirm"]);
477 unset($noscrape["dfrn-notify"]);
478 unset($noscrape["dfrn-poll"]);
480 $contact = array_merge($contact, $noscrape);
482 update_gcontact($contact);
484 return $noscrape["updated"];
490 // If we only can poll the feed, then we only do this once a while
491 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
492 return $gcontacts[0]["updated"];
494 $data = probe_url($profile);
496 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
497 // Then check the other link and delete this one
498 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
499 (normalise_link($profile) == normalise_link($data["alias"])) AND
500 (normalise_link($profile) != normalise_link($data["url"]))) {
502 // Delete the old entry
503 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
504 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
506 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
507 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
509 poco_last_updated($data["url"], $force);
514 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
515 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
516 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
520 $contact = array("generation" => $gcontacts[0]["generation"]);
522 $contact = array_merge($contact, $data);
524 $contact["server_url"] = $data["baseurl"];
526 unset($contact["batch"]);
527 unset($contact["poll"]);
528 unset($contact["request"]);
529 unset($contact["confirm"]);
530 unset($contact["poco"]);
531 unset($contact["priority"]);
532 unset($contact["pubkey"]);
533 unset($contact["baseurl"]);
535 update_gcontact($contact);
537 $feedret = z_fetch_url($data["poll"]);
539 if (!$feedret["success"]) {
540 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
541 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
545 $doc = new DOMDocument();
546 @$doc->loadXML($feedret["body"]);
548 $xpath = new DomXPath($doc);
549 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
551 $entries = $xpath->query('/atom:feed/atom:entry');
555 foreach ($entries AS $entry) {
556 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
557 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
559 if ($last_updated < $published)
560 $last_updated = $published;
562 if ($last_updated < $updated)
563 $last_updated = $updated;
566 // Maybe there aren't any entries. Then check if it is a valid feed
567 if ($last_updated == "")
568 if ($xpath->query('/atom:feed')->length > 0)
569 $last_updated = "0000-00-00 00:00:00";
571 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
572 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
574 if (($gcontacts[0]["generation"] == 0))
575 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
576 dbesc(normalise_link($profile)));
578 return($last_updated);
581 function poco_do_update($created, $updated, $last_failure, $last_contact) {
582 $now = strtotime(datetime_convert());
584 if ($updated > $last_contact)
585 $contact_time = strtotime($updated);
587 $contact_time = strtotime($last_contact);
589 $failure_time = strtotime($last_failure);
590 $created_time = strtotime($created);
592 // If there is no "created" time then use the current time
593 if ($created_time <= 0)
594 $created_time = $now;
596 // If the last contact was less than 24 hours then don't update
597 if (($now - $contact_time) < (60 * 60 * 24))
600 // If the last failure was less than 24 hours then don't update
601 if (($now - $failure_time) < (60 * 60 * 24))
604 // If the last contact was less than a week ago and the last failure is older than a week then don't update
605 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
608 // 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
609 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
612 // 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
613 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
619 function poco_to_boolean($val) {
620 if (($val == "true") OR ($val == 1))
622 if (($val == "false") OR ($val == 0))
628 function poco_check_server($server_url, $network = "", $force = false) {
630 // Unify the server address
631 $server_url = trim($server_url, "/");
632 $server_url = str_replace("/index.php", "", $server_url);
634 if ($server_url == "")
637 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
640 if ($servers[0]["created"] == "0000-00-00 00:00:00")
641 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
642 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
644 $poco = $servers[0]["poco"];
645 $noscrape = $servers[0]["noscrape"];
648 $network = $servers[0]["network"];
650 $last_contact = $servers[0]["last_contact"];
651 $last_failure = $servers[0]["last_failure"];
652 $version = $servers[0]["version"];
653 $platform = $servers[0]["platform"];
654 $site_name = $servers[0]["site_name"];
655 $info = $servers[0]["info"];
656 $register_policy = $servers[0]["register_policy"];
658 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
659 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
660 return ($last_contact >= $last_failure);
669 $register_policy = -1;
671 $last_contact = "0000-00-00 00:00:00";
672 $last_failure = "0000-00-00 00:00:00";
674 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
677 $orig_last_failure = $last_failure;
679 // Check if the page is accessible via SSL.
680 $server_url = str_replace("http://", "https://", $server_url);
681 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
683 // Maybe the page is unencrypted only?
684 $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 $server_url = str_replace("https://", "http://", $server_url);
687 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
689 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
692 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
693 // Workaround for bad configured servers (known nginx problem)
694 if ($serverret["debug"]["http_code"] != "403") {
695 $last_failure = datetime_convert();
698 } elseif ($network == NETWORK_DIASPORA)
699 $last_contact = datetime_convert();
703 $serverret = z_fetch_url($server_url);
705 if (!$serverret["success"] OR ($serverret["body"] == ""))
708 $lines = explode("\n",$serverret["header"]);
710 foreach($lines as $line) {
712 if(stristr($line,'X-Diaspora-Version:')) {
713 $platform = "Diaspora";
714 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
715 $version = trim(str_replace("x-diaspora-version:", "", $version));
716 $network = NETWORK_DIASPORA;
717 $versionparts = explode("-", $version);
718 $version = $versionparts[0];
725 // Test for Statusnet
726 // Will also return data for Friendica and GNU Social - but it will be overwritten later
727 // The "not implemented" is a special treatment for really, really old Friendica versions
728 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
729 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
730 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
731 $platform = "StatusNet";
732 $version = trim($serverret["body"], '"');
733 $network = NETWORK_OSTATUS;
736 // Test for GNU Social
737 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
738 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
739 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
740 $platform = "GNU Social";
741 $version = trim($serverret["body"], '"');
742 $network = NETWORK_OSTATUS;
745 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
746 if ($serverret["success"]) {
747 $data = json_decode($serverret["body"]);
749 if (isset($data->site->server)) {
750 $last_contact = datetime_convert();
752 if (isset($data->site->hubzilla)) {
753 $platform = $data->site->hubzilla->PLATFORM_NAME;
754 $version = $data->site->hubzilla->RED_VERSION;
755 $network = NETWORK_DIASPORA;
757 if (isset($data->site->redmatrix)) {
758 if (isset($data->site->redmatrix->PLATFORM_NAME))
759 $platform = $data->site->redmatrix->PLATFORM_NAME;
760 elseif (isset($data->site->redmatrix->RED_PLATFORM))
761 $platform = $data->site->redmatrix->RED_PLATFORM;
763 $version = $data->site->redmatrix->RED_VERSION;
764 $network = NETWORK_DIASPORA;
766 if (isset($data->site->friendica)) {
767 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
768 $version = $data->site->friendica->FRIENDICA_VERSION;
769 $network = NETWORK_DFRN;
772 $site_name = $data->site->name;
774 $data->site->closed = poco_to_boolean($data->site->closed);
775 $data->site->private = poco_to_boolean($data->site->private);
776 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
778 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
779 $register_policy = REGISTER_APPROVE;
780 elseif (!$data->site->closed AND !$data->site->private)
781 $register_policy = REGISTER_OPEN;
783 $register_policy = REGISTER_CLOSED;
788 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
790 $serverret = z_fetch_url($server_url."/statistics.json");
791 if ($serverret["success"]) {
792 $data = json_decode($serverret["body"]);
794 $version = $data->version;
796 $site_name = $data->name;
798 if (isset($data->network) AND ($platform == ""))
799 $platform = $data->network;
801 if ($platform == "Diaspora")
802 $network = NETWORK_DIASPORA;
804 if ($data->registrations_open)
805 $register_policy = REGISTER_OPEN;
807 $register_policy = REGISTER_CLOSED;
809 if (isset($data->version))
810 $last_contact = datetime_convert();
814 // Check for noscrape
815 // Friendica servers could be detected as OStatus servers
816 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
817 $serverret = z_fetch_url($server_url."/friendica/json");
819 if (!$serverret["success"])
820 $serverret = z_fetch_url($server_url."/friendika/json");
822 if ($serverret["success"]) {
823 $data = json_decode($serverret["body"]);
825 if (isset($data->version)) {
826 $last_contact = datetime_convert();
827 $network = NETWORK_DFRN;
829 $noscrape = $data->no_scrape_url;
830 $version = $data->version;
831 $site_name = $data->site_name;
833 $register_policy_str = $data->register_policy;
834 $platform = $data->platform;
836 switch ($register_policy_str) {
837 case "REGISTER_CLOSED":
838 $register_policy = REGISTER_CLOSED;
840 case "REGISTER_APPROVE":
841 $register_policy = REGISTER_APPROVE;
843 case "REGISTER_OPEN":
844 $register_policy = REGISTER_OPEN;
853 $serverret = z_fetch_url($server_url."/poco");
854 if ($serverret["success"]) {
855 $data = json_decode($serverret["body"]);
856 if (isset($data->totalResults)) {
857 $poco = $server_url."/poco";
858 $last_contact = datetime_convert();
863 // Check again if the server exists
864 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
866 $version = strip_tags($version);
867 $site_name = strip_tags($site_name);
868 $info = strip_tags($info);
869 $platform = strip_tags($platform);
872 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
873 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
878 intval($register_policy),
883 dbesc($last_contact),
884 dbesc($last_failure),
885 dbesc(normalise_link($server_url))
888 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
889 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
891 dbesc(normalise_link($server_url)),
895 intval($register_policy),
900 dbesc(datetime_convert()),
901 dbesc($last_contact),
902 dbesc($last_failure),
903 dbesc(datetime_convert())
906 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
911 function count_common_friends($uid,$cid) {
913 $r = q("SELECT count(*) as `total`
914 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
915 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
916 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
917 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
924 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
926 return $r[0]['total'];
932 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
935 $sql_extra = " order by rand() ";
937 $sql_extra = " order by `gcontact`.`name` asc ";
939 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
941 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
942 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
943 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
944 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
945 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
946 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
947 $sql_extra LIMIT %d, %d",
961 function count_common_friends_zcid($uid,$zcid) {
963 $r = q("SELECT count(*) as `total`
964 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
965 where `glink`.`zcid` = %d
966 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
972 return $r[0]['total'];
977 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
980 $sql_extra = " order by rand() ";
982 $sql_extra = " order by `gcontact`.`name` asc ";
984 $r = q("SELECT `gcontact`.*
985 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
986 where `glink`.`zcid` = %d
987 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
988 $sql_extra limit %d, %d",
1000 function count_all_friends($uid,$cid) {
1002 $r = q("SELECT count(*) as `total`
1003 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1004 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1005 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1011 return $r[0]['total'];
1017 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1019 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1021 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1022 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1023 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1024 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1025 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1038 function suggestion_query($uid, $start = 0, $limit = 80) {
1043 $network = array(NETWORK_DFRN);
1045 if (get_config('system','diaspora_enabled'))
1046 $network[] = NETWORK_DIASPORA;
1048 if (!get_config('system','ostatus_disabled'))
1049 $network[] = NETWORK_OSTATUS;
1051 $sql_network = implode("', '", $network);
1052 //$sql_network = "'".$sql_network."', ''";
1053 $sql_network = "'".$sql_network."'";
1055 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1056 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1057 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1058 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1059 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1060 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1061 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1062 AND `gcontact`.`network` IN (%s)
1063 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1073 if(count($r) && count($r) >= ($limit -1))
1076 $r2 = q("SELECT gcontact.* FROM gcontact
1077 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1078 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1079 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1080 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1081 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1082 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1083 AND `gcontact`.`network` IN (%s)
1084 ORDER BY rand() LIMIT %d, %d",
1094 foreach ($r2 AS $suggestion)
1095 $list[$suggestion["nurl"]] = $suggestion;
1097 foreach ($r AS $suggestion)
1098 $list[$suggestion["nurl"]] = $suggestion;
1100 while (sizeof($list) > ($limit))
1106 function update_suggestions() {
1112 /// TODO Check if it is really neccessary to poll the own server
1113 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1115 $done[] = $a->get_baseurl() . '/poco';
1117 if(strlen(get_config('system','directory'))) {
1118 $x = fetch_url(get_server()."/pubsites");
1120 $j = json_decode($x);
1122 foreach($j->entries as $entry) {
1124 poco_check_server($entry->url);
1126 $url = $entry->url . '/poco';
1127 if(! in_array($url,$done))
1128 poco_load(0,0,0,$entry->url . '/poco');
1134 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1135 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1136 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1140 foreach($r as $rr) {
1141 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1142 if(! in_array($base,$done))
1143 poco_load(0,0,0,$base);
1148 function poco_discover_federation() {
1149 $last = get_config('poco','last_federation_discovery');
1152 $next = $last + (24 * 60 * 60);
1157 // Discover Friendica, Hubzilla and Diaspora servers
1158 $serverdata = fetch_url("http://the-federation.info/pods.json");
1161 $servers = json_decode($serverdata);
1163 foreach($servers->pods AS $server)
1164 poco_check_server("https://".$server->host);
1167 // Discover GNU Social Servers
1168 if (!get_config('system','ostatus_disabled')) {
1169 $serverdata = "http://gstools.org/api/get_open_instances/";
1171 $result = z_fetch_url($serverdata);
1172 if ($result["success"]) {
1173 $servers = json_decode($result["body"]);
1175 foreach($servers->data AS $server)
1176 poco_check_server($server->instance_address);
1180 set_config('poco','last_federation_discovery', time());
1183 function poco_discover($complete = false) {
1185 // Update the server list
1186 poco_discover_federation();
1190 $requery_days = intval(get_config("system", "poco_requery_days"));
1192 if ($requery_days == 0)
1195 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1197 $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));
1199 foreach ($r AS $server) {
1201 if (!poco_check_server($server["url"], $server["network"])) {
1202 // The server is not reachable? Okay, then we will try it later
1203 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1207 // Fetch all users from the other server
1208 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1210 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1212 $retdata = z_fetch_url($url);
1213 if ($retdata["success"]) {
1214 $data = json_decode($retdata["body"]);
1216 poco_discover_server($data, 2);
1218 if (get_config('system','poco_discovery') > 1) {
1220 $timeframe = get_config('system','poco_discovery_since');
1221 if ($timeframe == 0)
1224 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1226 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1227 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1231 $retdata = z_fetch_url($url);
1232 if ($retdata["success"]) {
1233 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1234 $success = poco_discover_server(json_decode($retdata["body"]));
1237 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1238 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1239 poco_discover_server_users($data, $server);
1243 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1244 if (!$complete AND (--$no_of_queries == 0))
1247 // If the server hadn't replied correctly, then force a sanity check
1248 poco_check_server($server["url"], $server["network"], true);
1250 // If we couldn't reach the server, we will try it some time later
1251 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1256 function poco_discover_server_users($data, $server) {
1258 if (!isset($data->entry))
1261 foreach ($data->entry AS $entry) {
1263 if (isset($entry->urls)) {
1264 foreach($entry->urls as $url)
1265 if($url->type == 'profile') {
1266 $profile_url = $url->value;
1267 $urlparts = parse_url($profile_url);
1268 $username = end(explode("/", $urlparts["path"]));
1271 if ($username != "") {
1272 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1274 // Fetch all contacts from a given user from the other server
1275 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1277 $retdata = z_fetch_url($url);
1278 if ($retdata["success"])
1279 poco_discover_server(json_decode($retdata["body"]), 3);
1284 function poco_discover_server($data, $default_generation = 0) {
1286 if (!isset($data->entry) OR !count($data->entry))
1291 foreach ($data->entry AS $entry) {
1293 $profile_photo = '';
1297 $updated = '0000-00-00 00:00:00';
1302 $generation = $default_generation;
1304 $name = $entry->displayName;
1306 if(isset($entry->urls)) {
1307 foreach($entry->urls as $url) {
1308 if($url->type == 'profile') {
1309 $profile_url = $url->value;
1312 if($url->type == 'webfinger') {
1313 $connect_url = str_replace('acct:' , '', $url->value);
1319 if(isset($entry->photos)) {
1320 foreach($entry->photos as $photo) {
1321 if($photo->type == 'profile') {
1322 $profile_photo = $photo->value;
1328 if(isset($entry->updated))
1329 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1331 if(isset($entry->network))
1332 $network = $entry->network;
1334 if(isset($entry->currentLocation))
1335 $location = $entry->currentLocation;
1337 if(isset($entry->aboutMe))
1338 $about = html2bbcode($entry->aboutMe);
1340 if(isset($entry->gender))
1341 $gender = $entry->gender;
1343 if(isset($entry->generation) AND ($entry->generation > 0))
1344 $generation = ++$entry->generation;
1346 if(isset($entry->tags))
1347 foreach($entry->tags as $tag)
1348 $keywords = implode(", ", $tag);
1350 if ($generation > 0) {
1353 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1354 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1355 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1362 * @brief Removes unwanted parts from a contact url
1364 * @param string $url Contact url
1365 * @return string Contact url with the wanted parts
1367 function clean_contact_url($url) {
1368 $parts = parse_url($url);
1370 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1373 $new_url = $parts["scheme"]."://".$parts["host"];
1375 if (isset($parts["port"]))
1376 $new_url .= ":".$parts["port"];
1378 if (isset($parts["path"]))
1379 $new_url .= $parts["path"];
1381 if ($new_url != $url)
1382 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1388 * @brief Replace alternate OStatus user format with the primary one
1390 * @param arr $contact contact array (called by reference)
1392 function fix_alternate_contact_address(&$contact) {
1393 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1394 $data = probe_url($contact["url"]);
1395 if ($contact["network"] == NETWORK_OSTATUS) {
1396 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1397 $contact["url"] = $data["url"];
1398 $contact["addr"] = $data["addr"];
1399 $contact["alias"] = $data["alias"];
1400 $contact["server_url"] = $data["baseurl"];
1406 * @brief Fetch the gcontact id, add an entry if not existed
1408 * @param arr $contact contact array
1409 * @return bool|int Returns false if not found, integer if contact was found
1411 function get_gcontact_id($contact) {
1415 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1416 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1420 if ($contact["network"] == NETWORK_STATUSNET)
1421 $contact["network"] = NETWORK_OSTATUS;
1423 // Replace alternate OStatus user format with the primary one
1424 fix_alternate_contact_address($contact);
1426 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1427 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1428 $contact["url"] = clean_contact_url($contact["url"]);
1430 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1431 dbesc(normalise_link($contact["url"])));
1434 $gcontact_id = $r[0]["id"];
1436 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1437 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1438 dbesc($contact["name"]),
1439 dbesc($contact["nick"]),
1440 dbesc($contact["addr"]),
1441 dbesc($contact["network"]),
1442 dbesc($contact["url"]),
1443 dbesc(normalise_link($contact["url"])),
1444 dbesc($contact["photo"]),
1445 dbesc(datetime_convert()),
1446 dbesc(datetime_convert()),
1447 dbesc($contact["location"]),
1448 dbesc($contact["about"]),
1449 intval($contact["generation"])
1452 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1453 dbesc(normalise_link($contact["url"])));
1456 $gcontact_id = $r[0]["id"];
1458 // Complete newly added contacts from "probable" accounts
1459 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_FEED))) {
1460 logger("Probing ".$contact["url"], LOGGER_DEBUG);
1461 proc_run('php', 'include/gprobe.php', bin2hex($contact["url"]));
1466 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1467 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1468 dbesc(normalise_link($contact["url"])),
1469 intval($gcontact_id));
1471 return $gcontact_id;
1475 * @brief Updates the gcontact table from a given array
1477 * @param arr $contact contact array
1478 * @return bool|int Returns false if not found, integer if contact was found
1480 function update_gcontact($contact) {
1482 /// @todo update contact table as well
1484 $gcontact_id = get_gcontact_id($contact);
1489 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1490 `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1491 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1492 intval($gcontact_id));
1494 // Get all field names
1496 foreach ($r[0] AS $field => $data)
1497 $fields[$field] = $data;
1499 unset($fields["url"]);
1500 unset($fields["updated"]);
1502 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1503 // This value is still transmitted via poco.
1504 if ($contact["keywords"] == "0")
1505 unset($contact["keywords"]);
1507 if ($r[0]["keywords"] == "0")
1508 $r[0]["keywords"] = "";
1510 // assign all unassigned fields from the database entry
1511 foreach ($fields AS $field => $data)
1512 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1513 $contact[$field] = $r[0][$field];
1515 if ($contact["network"] == NETWORK_STATUSNET)
1516 $contact["network"] = NETWORK_OSTATUS;
1518 // Replace alternate OStatus user format with the primary one
1519 fix_alternate_contact_address($contact);
1521 if (!isset($contact["updated"]))
1522 $contact["updated"] = datetime_convert();
1524 if ($contact["server_url"] == "") {
1525 $server_url = $contact["url"];
1527 $server_url = matching_url($server_url, $contact["alias"]);
1528 if ($server_url != "")
1529 $contact["server_url"] = $server_url;
1531 $server_url = matching_url($server_url, $contact["photo"]);
1532 if ($server_url != "")
1533 $contact["server_url"] = $server_url;
1535 $server_url = matching_url($server_url, $contact["notify"]);
1536 if ($server_url != "")
1537 $contact["server_url"] = $server_url;
1539 $contact["server_url"] = normalise_link($contact["server_url"]);
1541 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1542 $hostname = str_replace("http://", "", $contact["server_url"]);
1543 $contact["addr"] = $contact["nick"]."@".$hostname;
1546 // Check if any field changed
1548 unset($fields["generation"]);
1550 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1551 foreach ($fields AS $field => $data)
1552 if ($contact[$field] != $r[0][$field]) {
1553 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1557 if ($contact["generation"] < $r[0]["generation"]) {
1558 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1564 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1566 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1567 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1568 `alias` = '%s', `notify` = '%s', `url` = '%s',
1569 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1570 `server_url` = '%s', `connect` = '%s'
1571 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1572 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1573 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1574 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1575 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1576 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1577 intval($contact["generation"]), dbesc($contact["updated"]),
1578 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1579 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1582 // Now update the contact entry with the user id "0" as well.
1583 // This is used for the shadow copies of public items.
1584 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1585 dbesc(normalise_link($contact["url"])));
1588 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1590 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1592 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1593 `network` = '%s', `bd` = '%s', `gender` = '%s',
1594 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1595 `location` = '%s', `about` = '%s'
1597 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1598 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1599 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1600 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1604 return $gcontact_id;
1608 * @brief Updates the gcontact entry from probe
1610 * @param str $url profile link
1612 function update_gcontact_from_probe($url) {
1613 $data = probe_url($url);
1615 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1616 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1620 update_gcontact($data);
1624 * @brief Fetches users of given GNU Social server
1626 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1628 * @param str $server Server address
1630 function gs_fetch_users($server) {
1632 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1636 $url = $server."/main/statistics";
1638 $result = z_fetch_url($url);
1639 if (!$result["success"])
1642 $statistics = json_decode($result["body"]);
1644 if (is_object($statistics->config)) {
1645 if ($statistics->config->instance_with_ssl)
1646 $server = "https://";
1648 $server = "http://";
1650 $server .= $statistics->config->instance_address;
1652 $hostname = $statistics->config->instance_address;
1654 if ($statistics->instance_with_ssl)
1655 $server = "https://";
1657 $server = "http://";
1659 $server .= $statistics->instance_address;
1661 $hostname = $statistics->instance_address;
1664 if (is_object($statistics->users))
1665 foreach ($statistics->users AS $nick => $user) {
1666 $profile_url = $server."/".$user->nickname;
1668 $contact = array("url" => $profile_url,
1669 "name" => $user->fullname,
1670 "addr" => $user->nickname."@".$hostname,
1671 "nick" => $user->nickname,
1672 "about" => $user->bio,
1673 "network" => NETWORK_OSTATUS,
1674 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1675 get_gcontact_id($contact);
1680 * @brief Asking GNU Social server on a regular base for their user data
1683 function gs_discover() {
1685 $requery_days = intval(get_config("system", "poco_requery_days"));
1687 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1689 $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",
1690 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1695 foreach ($r AS $server) {
1696 gs_fetch_users($server["url"]);
1697 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));