3 * @file include/socgraph.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/network.php");
13 require_once("include/html2bbcode.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
20 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
21 * and add the entries to the gcontact (Global Contact) table, or update existing entries
22 * if anything (name or photo) has changed.
23 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
25 * Once the global contact is stored add (if necessary) the contact linkage which associates
26 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
27 * pointing to the same global contact id.
34 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
39 if((! $url) || (! $uid)) {
40 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
55 $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') ;
57 logger('poco_load: ' . $url, LOGGER_DEBUG);
61 logger('poco_load: returns ' . $s, LOGGER_DATA);
63 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
65 if(($a->get_curl_code() > 299) || (! $s))
70 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
72 if(! isset($j->entry))
76 foreach($j->entry as $entry) {
84 $updated = '0000-00-00 00:00:00';
91 $name = $entry->displayName;
93 if(isset($entry->urls)) {
94 foreach($entry->urls as $url) {
95 if($url->type == 'profile') {
96 $profile_url = $url->value;
99 if($url->type == 'webfinger') {
100 $connect_url = str_replace('acct:' , '', $url->value);
105 if(isset($entry->photos)) {
106 foreach($entry->photos as $photo) {
107 if($photo->type == 'profile') {
108 $profile_photo = $photo->value;
114 if(isset($entry->updated))
115 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
117 if(isset($entry->network))
118 $network = $entry->network;
120 if(isset($entry->currentLocation))
121 $location = $entry->currentLocation;
123 if(isset($entry->aboutMe))
124 $about = html2bbcode($entry->aboutMe);
126 if(isset($entry->gender))
127 $gender = $entry->gender;
129 if(isset($entry->generation) AND ($entry->generation > 0))
130 $generation = ++$entry->generation;
132 if(isset($entry->tags))
133 foreach($entry->tags as $tag)
134 $keywords = implode(", ", $tag);
136 // If you query a Friendica server for its profiles, the network has to be Friendica
137 /// TODO It could also be a Redmatrix server
139 // $network = NETWORK_DFRN;
141 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
143 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
144 // Deactivated because we now update Friendica contacts in dfrn.php
145 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
146 // q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
147 // WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
152 // dbesc(normalise_link($profile_url)),
153 // dbesc(NETWORK_DFRN));
155 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
157 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
165 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
171 // 1: Profiles on this server
172 // 2: Contacts of profiles on this server
173 // 3: Contacts of contacts of profiles on this server
178 if ($profile_url == "")
181 $urlparts = parse_url($profile_url);
182 if (!isset($urlparts["scheme"]))
185 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
186 "identi.ca", "alpha.app.net")))
189 // Don't store the statusnet connector as network
190 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
191 if ($network == NETWORK_STATUSNET)
194 // Assure that there are no parameter fragments in the profile url
195 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
196 $profile_url = clean_contact_url($profile_url);
198 $alternate = poco_alternate_ostatus_url($profile_url);
200 $orig_updated = $updated;
202 // The global contacts should contain the original picture, not the cached one
203 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
206 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
207 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
210 $network = $r[0]["network"];
212 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
213 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
214 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
217 $network = $r[0]["network"];
218 //$profile_url = $r[0]["url"];
222 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
223 dbesc(normalise_link($profile_url))
227 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
228 $network = $x[0]["network"];
230 if ($updated == "0000-00-00 00:00:00")
231 $updated = $x[0]["updated"];
233 $created = $x[0]["created"];
234 $server_url = $x[0]["server_url"];
235 $nick = $x[0]["nick"];
236 $addr = $x[0]["addr"];
237 $alias = $x[0]["alias"];
238 $notify = $x[0]["notify"];
240 $created = "0000-00-00 00:00:00";
243 $urlparts = parse_url($profile_url);
244 $nick = end(explode("/", $urlparts["path"]));
250 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
251 AND poco_reachable($profile_url, $server_url, $network, false)) {
252 $data = probe_url($profile_url);
254 $orig_profile = $profile_url;
256 $network = $data["network"];
257 $name = $data["name"];
258 $nick = $data["nick"];
259 $addr = $data["addr"];
260 $alias = $data["alias"];
261 $notify = $data["notify"];
262 $profile_url = $data["url"];
263 $profile_photo = $data["photo"];
264 $server_url = $data["baseurl"];
266 if ($alternate AND ($network == NETWORK_OSTATUS)) {
267 // Delete the old entry - if it exists
268 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
270 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
271 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
274 // possibly create a new entry
275 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
279 if ($alternate AND ($network == NETWORK_OSTATUS))
282 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
283 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
285 dbesc(normalise_link($profile_url))
289 if (($name == "") OR ($profile_photo == ""))
292 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
295 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
297 poco_check_server($server_url, $network);
299 $gcontact = array("url" => $profile_url,
303 "network" => $network,
304 "photo" => $profile_photo,
306 "location" => $location,
308 "keywords" => $keywords,
309 "server_url" => $server_url,
310 "connect" => $connect_url,
312 "updated" => $updated,
313 "generation" => $generation);
315 $gcid = update_gcontact($gcontact);
320 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
327 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
332 dbesc(datetime_convert())
335 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
336 dbesc(datetime_convert()),
347 function poco_reachable($profile, $server = "", $network = "", $force = false) {
350 $server = poco_detect_server($profile);
355 return poco_check_server($server, $network, $force);
358 function poco_detect_server($profile) {
360 // Try to detect the server path based upon some known standard paths
363 if ($server_url == "") {
364 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
365 if ($friendica != $profile) {
366 $server_url = $friendica;
367 $network = NETWORK_DFRN;
371 if ($server_url == "") {
372 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
373 if ($diaspora != $profile) {
374 $server_url = $diaspora;
375 $network = NETWORK_DIASPORA;
379 if ($server_url == "") {
380 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
381 if ($red != $profile) {
383 $network = NETWORK_DIASPORA;
390 function poco_alternate_ostatus_url($url) {
391 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
394 function poco_last_updated($profile, $force = false) {
396 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
397 dbesc(normalise_link($profile)));
399 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
400 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
401 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
403 if ($gcontacts[0]["server_url"] != "")
404 $server_url = $gcontacts[0]["server_url"];
406 $server_url = poco_detect_server($profile);
408 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
409 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
413 if ($server_url != "") {
414 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
417 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
418 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
420 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
424 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
425 dbesc($server_url), dbesc(normalise_link($profile)));
428 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
429 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
430 dbesc(normalise_link($server_url)));
433 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
434 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
439 // noscrape is really fast so we don't cache the call.
440 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
442 // Use noscrape if possible
443 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
446 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
448 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
450 $noscrape = json_decode($noscraperet["body"], true);
452 if (is_array($noscrape)) {
453 $contact = array("url" => $profile,
454 "network" => $server[0]["network"],
455 "generation" => $gcontacts[0]["generation"]);
457 if (isset($noscrape["fn"]))
458 $contact["name"] = $noscrape["fn"];
460 if (isset($noscrape["comm"]))
461 $contact["community"] = $noscrape["comm"];
463 if (isset($noscrape["tags"])) {
464 $keywords = implode(" ", $noscrape["tags"]);
466 $contact["keywords"] = $keywords;
469 $location = formatted_location($noscrape);
471 $contact["location"] = $location;
473 if (isset($noscrape["dfrn-notify"]))
474 $contact["notify"] = $noscrape["dfrn-notify"];
476 // Remove all fields that are not present in the gcontact table
477 unset($noscrape["fn"]);
478 unset($noscrape["key"]);
479 unset($noscrape["homepage"]);
480 unset($noscrape["comm"]);
481 unset($noscrape["tags"]);
482 unset($noscrape["locality"]);
483 unset($noscrape["region"]);
484 unset($noscrape["country-name"]);
485 unset($noscrape["contacts"]);
486 unset($noscrape["dfrn-request"]);
487 unset($noscrape["dfrn-confirm"]);
488 unset($noscrape["dfrn-notify"]);
489 unset($noscrape["dfrn-poll"]);
491 // Set the date of the last contact
492 /// @todo By now the function "update_gcontact" doesn't work with this field
493 //$contact["last_contact"] = datetime_convert();
495 $contact = array_merge($contact, $noscrape);
497 update_gcontact($contact);
499 if (trim($noscrape["updated"]) != "") {
500 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
501 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
503 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
505 return $noscrape["updated"];
512 // If we only can poll the feed, then we only do this once a while
513 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
514 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
515 return $gcontacts[0]["updated"];
518 $data = probe_url($profile);
520 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
521 // Then check the other link and delete this one
522 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
523 (normalise_link($profile) == normalise_link($data["alias"])) AND
524 (normalise_link($profile) != normalise_link($data["url"]))) {
526 // Delete the old entry
527 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
528 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
530 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
531 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
533 poco_last_updated($data["url"], $force);
535 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
539 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
540 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
541 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
543 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
547 $contact = array("generation" => $gcontacts[0]["generation"]);
549 $contact = array_merge($contact, $data);
551 $contact["server_url"] = $data["baseurl"];
553 unset($contact["batch"]);
554 unset($contact["poll"]);
555 unset($contact["request"]);
556 unset($contact["confirm"]);
557 unset($contact["poco"]);
558 unset($contact["priority"]);
559 unset($contact["pubkey"]);
560 unset($contact["baseurl"]);
562 update_gcontact($contact);
564 $feedret = z_fetch_url($data["poll"]);
566 if (!$feedret["success"]) {
567 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
568 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
570 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
574 $doc = new DOMDocument();
575 @$doc->loadXML($feedret["body"]);
577 $xpath = new DomXPath($doc);
578 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
580 $entries = $xpath->query('/atom:feed/atom:entry');
584 foreach ($entries AS $entry) {
585 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
586 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
588 if ($last_updated < $published)
589 $last_updated = $published;
591 if ($last_updated < $updated)
592 $last_updated = $updated;
595 // Maybe there aren't any entries. Then check if it is a valid feed
596 if ($last_updated == "")
597 if ($xpath->query('/atom:feed')->length > 0)
598 $last_updated = "0000-00-00 00:00:00";
600 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
601 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
603 if (($gcontacts[0]["generation"] == 0))
604 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
605 dbesc(normalise_link($profile)));
607 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
609 return($last_updated);
612 function poco_do_update($created, $updated, $last_failure, $last_contact) {
613 $now = strtotime(datetime_convert());
615 if ($updated > $last_contact)
616 $contact_time = strtotime($updated);
618 $contact_time = strtotime($last_contact);
620 $failure_time = strtotime($last_failure);
621 $created_time = strtotime($created);
623 // If there is no "created" time then use the current time
624 if ($created_time <= 0)
625 $created_time = $now;
627 // If the last contact was less than 24 hours then don't update
628 if (($now - $contact_time) < (60 * 60 * 24))
631 // If the last failure was less than 24 hours then don't update
632 if (($now - $failure_time) < (60 * 60 * 24))
635 // If the last contact was less than a week ago and the last failure is older than a week then don't update
636 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
639 // 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
640 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
643 // 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
644 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
650 function poco_to_boolean($val) {
651 if (($val == "true") OR ($val == 1))
653 if (($val == "false") OR ($val == 0))
659 function poco_check_server($server_url, $network = "", $force = false) {
661 // Unify the server address
662 $server_url = trim($server_url, "/");
663 $server_url = str_replace("/index.php", "", $server_url);
665 if ($server_url == "")
668 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
671 if ($servers[0]["created"] == "0000-00-00 00:00:00")
672 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
673 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
675 $poco = $servers[0]["poco"];
676 $noscrape = $servers[0]["noscrape"];
679 $network = $servers[0]["network"];
681 $last_contact = $servers[0]["last_contact"];
682 $last_failure = $servers[0]["last_failure"];
683 $version = $servers[0]["version"];
684 $platform = $servers[0]["platform"];
685 $site_name = $servers[0]["site_name"];
686 $info = $servers[0]["info"];
687 $register_policy = $servers[0]["register_policy"];
689 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
690 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
691 return ($last_contact >= $last_failure);
700 $register_policy = -1;
702 $last_contact = "0000-00-00 00:00:00";
703 $last_failure = "0000-00-00 00:00:00";
705 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
708 $orig_last_failure = $last_failure;
710 // Check if the page is accessible via SSL.
711 $server_url = str_replace("http://", "https://", $server_url);
712 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
714 // Maybe the page is unencrypted only?
715 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
716 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
717 $server_url = str_replace("https://", "http://", $server_url);
718 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
720 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
723 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
724 // Workaround for bad configured servers (known nginx problem)
725 if ($serverret["debug"]["http_code"] != "403") {
726 $last_failure = datetime_convert();
729 } elseif ($network == NETWORK_DIASPORA)
730 $last_contact = datetime_convert();
734 $serverret = z_fetch_url($server_url);
736 if (!$serverret["success"] OR ($serverret["body"] == ""))
739 $lines = explode("\n",$serverret["header"]);
741 foreach($lines as $line) {
743 if(stristr($line,'X-Diaspora-Version:')) {
744 $platform = "Diaspora";
745 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
746 $version = trim(str_replace("x-diaspora-version:", "", $version));
747 $network = NETWORK_DIASPORA;
748 $versionparts = explode("-", $version);
749 $version = $versionparts[0];
756 // Test for Statusnet
757 // Will also return data for Friendica and GNU Social - but it will be overwritten later
758 // The "not implemented" is a special treatment for really, really old Friendica versions
759 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
760 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
761 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
762 $platform = "StatusNet";
763 $version = trim($serverret["body"], '"');
764 $network = NETWORK_OSTATUS;
767 // Test for GNU Social
768 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
769 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
770 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
771 $platform = "GNU Social";
772 $version = trim($serverret["body"], '"');
773 $network = NETWORK_OSTATUS;
776 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
777 if ($serverret["success"]) {
778 $data = json_decode($serverret["body"]);
780 if (isset($data->site->server)) {
781 $last_contact = datetime_convert();
783 if (isset($data->site->hubzilla)) {
784 $platform = $data->site->hubzilla->PLATFORM_NAME;
785 $version = $data->site->hubzilla->RED_VERSION;
786 $network = NETWORK_DIASPORA;
788 if (isset($data->site->redmatrix)) {
789 if (isset($data->site->redmatrix->PLATFORM_NAME))
790 $platform = $data->site->redmatrix->PLATFORM_NAME;
791 elseif (isset($data->site->redmatrix->RED_PLATFORM))
792 $platform = $data->site->redmatrix->RED_PLATFORM;
794 $version = $data->site->redmatrix->RED_VERSION;
795 $network = NETWORK_DIASPORA;
797 if (isset($data->site->friendica)) {
798 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
799 $version = $data->site->friendica->FRIENDICA_VERSION;
800 $network = NETWORK_DFRN;
803 $site_name = $data->site->name;
805 $data->site->closed = poco_to_boolean($data->site->closed);
806 $data->site->private = poco_to_boolean($data->site->private);
807 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
809 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
810 $register_policy = REGISTER_APPROVE;
811 elseif (!$data->site->closed AND !$data->site->private)
812 $register_policy = REGISTER_OPEN;
814 $register_policy = REGISTER_CLOSED;
819 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
821 $serverret = z_fetch_url($server_url."/statistics.json");
822 if ($serverret["success"]) {
823 $data = json_decode($serverret["body"]);
825 $version = $data->version;
827 $site_name = $data->name;
829 if (isset($data->network) AND ($platform == ""))
830 $platform = $data->network;
832 if ($platform == "Diaspora")
833 $network = NETWORK_DIASPORA;
835 if ($data->registrations_open)
836 $register_policy = REGISTER_OPEN;
838 $register_policy = REGISTER_CLOSED;
840 if (isset($data->version))
841 $last_contact = datetime_convert();
845 // Check for noscrape
846 // Friendica servers could be detected as OStatus servers
847 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
848 $serverret = z_fetch_url($server_url."/friendica/json");
850 if (!$serverret["success"])
851 $serverret = z_fetch_url($server_url."/friendika/json");
853 if ($serverret["success"]) {
854 $data = json_decode($serverret["body"]);
856 if (isset($data->version)) {
857 $last_contact = datetime_convert();
858 $network = NETWORK_DFRN;
860 $noscrape = $data->no_scrape_url;
861 $version = $data->version;
862 $site_name = $data->site_name;
864 $register_policy_str = $data->register_policy;
865 $platform = $data->platform;
867 switch ($register_policy_str) {
868 case "REGISTER_CLOSED":
869 $register_policy = REGISTER_CLOSED;
871 case "REGISTER_APPROVE":
872 $register_policy = REGISTER_APPROVE;
874 case "REGISTER_OPEN":
875 $register_policy = REGISTER_OPEN;
884 $serverret = z_fetch_url($server_url."/poco");
885 if ($serverret["success"]) {
886 $data = json_decode($serverret["body"]);
887 if (isset($data->totalResults)) {
888 $poco = $server_url."/poco";
889 $last_contact = datetime_convert();
894 // Check again if the server exists
895 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
897 $version = strip_tags($version);
898 $site_name = strip_tags($site_name);
899 $info = strip_tags($info);
900 $platform = strip_tags($platform);
903 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
904 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
909 intval($register_policy),
914 dbesc($last_contact),
915 dbesc($last_failure),
916 dbesc(normalise_link($server_url))
919 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
920 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
922 dbesc(normalise_link($server_url)),
926 intval($register_policy),
931 dbesc(datetime_convert()),
932 dbesc($last_contact),
933 dbesc($last_failure),
934 dbesc(datetime_convert())
937 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
942 function count_common_friends($uid,$cid) {
944 $r = q("SELECT count(*) as `total`
945 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
946 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
947 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
948 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
955 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
957 return $r[0]['total'];
963 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
966 $sql_extra = " order by rand() ";
968 $sql_extra = " order by `gcontact`.`name` asc ";
970 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
972 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
973 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
974 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
975 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
976 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
977 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
978 $sql_extra LIMIT %d, %d",
992 function count_common_friends_zcid($uid,$zcid) {
994 $r = q("SELECT count(*) as `total`
995 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
996 where `glink`.`zcid` = %d
997 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1003 return $r[0]['total'];
1008 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1011 $sql_extra = " order by rand() ";
1013 $sql_extra = " order by `gcontact`.`name` asc ";
1015 $r = q("SELECT `gcontact`.*
1016 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1017 where `glink`.`zcid` = %d
1018 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1019 $sql_extra limit %d, %d",
1031 function count_all_friends($uid,$cid) {
1033 $r = q("SELECT count(*) as `total`
1034 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1035 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1036 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1042 return $r[0]['total'];
1048 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1050 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1052 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1053 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1054 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1055 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1056 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1069 function suggestion_query($uid, $start = 0, $limit = 80) {
1074 $network = array(NETWORK_DFRN);
1076 if (get_config('system','diaspora_enabled'))
1077 $network[] = NETWORK_DIASPORA;
1079 if (!get_config('system','ostatus_disabled'))
1080 $network[] = NETWORK_OSTATUS;
1082 $sql_network = implode("', '", $network);
1083 //$sql_network = "'".$sql_network."', ''";
1084 $sql_network = "'".$sql_network."'";
1086 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1087 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1088 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1089 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1090 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1091 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1092 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1093 AND `gcontact`.`network` IN (%s)
1094 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1104 if(count($r) && count($r) >= ($limit -1))
1107 $r2 = q("SELECT gcontact.* FROM gcontact
1108 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1109 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1110 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1111 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1112 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1113 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1114 AND `gcontact`.`network` IN (%s)
1115 ORDER BY rand() LIMIT %d, %d",
1125 foreach ($r2 AS $suggestion)
1126 $list[$suggestion["nurl"]] = $suggestion;
1128 foreach ($r AS $suggestion)
1129 $list[$suggestion["nurl"]] = $suggestion;
1131 while (sizeof($list) > ($limit))
1137 function update_suggestions() {
1143 /// TODO Check if it is really neccessary to poll the own server
1144 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1146 $done[] = $a->get_baseurl() . '/poco';
1148 if(strlen(get_config('system','directory'))) {
1149 $x = fetch_url(get_server()."/pubsites");
1151 $j = json_decode($x);
1153 foreach($j->entries as $entry) {
1155 poco_check_server($entry->url);
1157 $url = $entry->url . '/poco';
1158 if(! in_array($url,$done))
1159 poco_load(0,0,0,$entry->url . '/poco');
1165 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1166 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1167 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1171 foreach($r as $rr) {
1172 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1173 if(! in_array($base,$done))
1174 poco_load(0,0,0,$base);
1179 function poco_discover_federation() {
1180 $last = get_config('poco','last_federation_discovery');
1183 $next = $last + (24 * 60 * 60);
1188 // Discover Friendica, Hubzilla and Diaspora servers
1189 $serverdata = fetch_url("http://the-federation.info/pods.json");
1192 $servers = json_decode($serverdata);
1194 foreach($servers->pods AS $server)
1195 poco_check_server("https://".$server->host);
1198 // Discover GNU Social Servers
1199 if (!get_config('system','ostatus_disabled')) {
1200 $serverdata = "http://gstools.org/api/get_open_instances/";
1202 $result = z_fetch_url($serverdata);
1203 if ($result["success"]) {
1204 $servers = json_decode($result["body"]);
1206 foreach($servers->data AS $server)
1207 poco_check_server($server->instance_address);
1211 set_config('poco','last_federation_discovery', time());
1214 function poco_discover($complete = false) {
1216 // Update the server list
1217 poco_discover_federation();
1221 $requery_days = intval(get_config("system", "poco_requery_days"));
1223 if ($requery_days == 0)
1226 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1228 $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));
1230 foreach ($r AS $server) {
1232 if (!poco_check_server($server["url"], $server["network"])) {
1233 // The server is not reachable? Okay, then we will try it later
1234 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1238 // Fetch all users from the other server
1239 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1241 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1243 $retdata = z_fetch_url($url);
1244 if ($retdata["success"]) {
1245 $data = json_decode($retdata["body"]);
1247 poco_discover_server($data, 2);
1249 if (get_config('system','poco_discovery') > 1) {
1251 $timeframe = get_config('system','poco_discovery_since');
1252 if ($timeframe == 0)
1255 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1257 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1258 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1262 $retdata = z_fetch_url($url);
1263 if ($retdata["success"]) {
1264 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1265 $success = poco_discover_server(json_decode($retdata["body"]));
1268 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1269 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1270 poco_discover_server_users($data, $server);
1274 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1275 if (!$complete AND (--$no_of_queries == 0))
1278 // If the server hadn't replied correctly, then force a sanity check
1279 poco_check_server($server["url"], $server["network"], true);
1281 // If we couldn't reach the server, we will try it some time later
1282 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1287 function poco_discover_server_users($data, $server) {
1289 if (!isset($data->entry))
1292 foreach ($data->entry AS $entry) {
1294 if (isset($entry->urls)) {
1295 foreach($entry->urls as $url)
1296 if($url->type == 'profile') {
1297 $profile_url = $url->value;
1298 $urlparts = parse_url($profile_url);
1299 $username = end(explode("/", $urlparts["path"]));
1302 if ($username != "") {
1303 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1305 // Fetch all contacts from a given user from the other server
1306 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1308 $retdata = z_fetch_url($url);
1309 if ($retdata["success"])
1310 poco_discover_server(json_decode($retdata["body"]), 3);
1315 function poco_discover_server($data, $default_generation = 0) {
1317 if (!isset($data->entry) OR !count($data->entry))
1322 foreach ($data->entry AS $entry) {
1324 $profile_photo = '';
1328 $updated = '0000-00-00 00:00:00';
1333 $generation = $default_generation;
1335 $name = $entry->displayName;
1337 if(isset($entry->urls)) {
1338 foreach($entry->urls as $url) {
1339 if($url->type == 'profile') {
1340 $profile_url = $url->value;
1343 if($url->type == 'webfinger') {
1344 $connect_url = str_replace('acct:' , '', $url->value);
1350 if(isset($entry->photos)) {
1351 foreach($entry->photos as $photo) {
1352 if($photo->type == 'profile') {
1353 $profile_photo = $photo->value;
1359 if(isset($entry->updated))
1360 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1362 if(isset($entry->network))
1363 $network = $entry->network;
1365 if(isset($entry->currentLocation))
1366 $location = $entry->currentLocation;
1368 if(isset($entry->aboutMe))
1369 $about = html2bbcode($entry->aboutMe);
1371 if(isset($entry->gender))
1372 $gender = $entry->gender;
1374 if(isset($entry->generation) AND ($entry->generation > 0))
1375 $generation = ++$entry->generation;
1377 if(isset($entry->tags))
1378 foreach($entry->tags as $tag)
1379 $keywords = implode(", ", $tag);
1381 if ($generation > 0) {
1384 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1385 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1386 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1393 * @brief Removes unwanted parts from a contact url
1395 * @param string $url Contact url
1396 * @return string Contact url with the wanted parts
1398 function clean_contact_url($url) {
1399 $parts = parse_url($url);
1401 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1404 $new_url = $parts["scheme"]."://".$parts["host"];
1406 if (isset($parts["port"]))
1407 $new_url .= ":".$parts["port"];
1409 if (isset($parts["path"]))
1410 $new_url .= $parts["path"];
1412 if ($new_url != $url)
1413 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1419 * @brief Replace alternate OStatus user format with the primary one
1421 * @param arr $contact contact array (called by reference)
1423 function fix_alternate_contact_address(&$contact) {
1424 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1425 $data = probe_url($contact["url"]);
1426 if ($contact["network"] == NETWORK_OSTATUS) {
1427 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1428 $contact["url"] = $data["url"];
1429 $contact["addr"] = $data["addr"];
1430 $contact["alias"] = $data["alias"];
1431 $contact["server_url"] = $data["baseurl"];
1437 * @brief Fetch the gcontact id, add an entry if not existed
1439 * @param arr $contact contact array
1440 * @return bool|int Returns false if not found, integer if contact was found
1442 function get_gcontact_id($contact) {
1447 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1448 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1452 if ($contact["network"] == NETWORK_STATUSNET)
1453 $contact["network"] = NETWORK_OSTATUS;
1455 // All new contacts are hidden by default
1456 if (!isset($contact["hide"]))
1457 $contact["hide"] = true;
1459 // Replace alternate OStatus user format with the primary one
1460 fix_alternate_contact_address($contact);
1462 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1463 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1464 $contact["url"] = clean_contact_url($contact["url"]);
1466 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1467 dbesc(normalise_link($contact["url"])));
1470 $gcontact_id = $r[0]["id"];
1472 // Update every 90 days
1473 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1474 $last_failure_str = $r[0]["last_failure"];
1475 $last_failure = strtotime($r[0]["last_failure"]);
1476 $last_contact_str = $r[0]["last_contact"];
1477 $last_contact = strtotime($r[0]["last_contact"]);
1478 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1481 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1482 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1483 dbesc($contact["name"]),
1484 dbesc($contact["nick"]),
1485 dbesc($contact["addr"]),
1486 dbesc($contact["network"]),
1487 dbesc($contact["url"]),
1488 dbesc(normalise_link($contact["url"])),
1489 dbesc($contact["photo"]),
1490 dbesc(datetime_convert()),
1491 dbesc(datetime_convert()),
1492 dbesc($contact["location"]),
1493 dbesc($contact["about"]),
1494 intval($contact["hide"]),
1495 intval($contact["generation"])
1498 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1499 dbesc(normalise_link($contact["url"])));
1502 $gcontact_id = $r[0]["id"];
1504 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1509 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1510 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1513 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1514 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1515 dbesc(normalise_link($contact["url"])),
1516 intval($gcontact_id));
1518 return $gcontact_id;
1522 * @brief Updates the gcontact table from a given array
1524 * @param arr $contact contact array
1525 * @return bool|int Returns false if not found, integer if contact was found
1527 function update_gcontact($contact) {
1529 /// @todo update contact table as well
1531 $gcontact_id = get_gcontact_id($contact);
1536 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1537 `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1538 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1539 intval($gcontact_id));
1541 // Get all field names
1543 foreach ($r[0] AS $field => $data)
1544 $fields[$field] = $data;
1546 unset($fields["url"]);
1547 unset($fields["updated"]);
1548 unset($fields["hide"]);
1550 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1551 // This value is still transmitted via poco.
1552 if ($contact["keywords"] == "0")
1553 unset($contact["keywords"]);
1555 if ($r[0]["keywords"] == "0")
1556 $r[0]["keywords"] = "";
1558 // assign all unassigned fields from the database entry
1559 foreach ($fields AS $field => $data)
1560 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1561 $contact[$field] = $r[0][$field];
1563 if (!isset($contact["hide"]))
1564 $contact["hide"] = $r[0]["hide"];
1566 $fields["hide"] = $r[0]["hide"];
1568 if ($contact["network"] == NETWORK_STATUSNET)
1569 $contact["network"] = NETWORK_OSTATUS;
1571 // Replace alternate OStatus user format with the primary one
1572 fix_alternate_contact_address($contact);
1574 if (!isset($contact["updated"]))
1575 $contact["updated"] = datetime_convert();
1577 if ($contact["server_url"] == "") {
1578 $server_url = $contact["url"];
1580 $server_url = matching_url($server_url, $contact["alias"]);
1581 if ($server_url != "")
1582 $contact["server_url"] = $server_url;
1584 $server_url = matching_url($server_url, $contact["photo"]);
1585 if ($server_url != "")
1586 $contact["server_url"] = $server_url;
1588 $server_url = matching_url($server_url, $contact["notify"]);
1589 if ($server_url != "")
1590 $contact["server_url"] = $server_url;
1592 $contact["server_url"] = normalise_link($contact["server_url"]);
1594 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1595 $hostname = str_replace("http://", "", $contact["server_url"]);
1596 $contact["addr"] = $contact["nick"]."@".$hostname;
1599 // Check if any field changed
1601 unset($fields["generation"]);
1603 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1604 foreach ($fields AS $field => $data)
1605 if ($contact[$field] != $r[0][$field]) {
1606 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1610 if ($contact["generation"] < $r[0]["generation"]) {
1611 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1617 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1619 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1620 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1621 `alias` = '%s', `notify` = '%s', `url` = '%s',
1622 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1623 `server_url` = '%s', `connect` = '%s'
1624 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1625 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1626 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1627 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1628 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1629 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1630 intval($contact["generation"]), dbesc($contact["updated"]),
1631 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1632 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1635 // Now update the contact entry with the user id "0" as well.
1636 // This is used for the shadow copies of public items.
1637 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1638 dbesc(normalise_link($contact["url"])));
1641 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1643 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1645 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1646 `network` = '%s', `bd` = '%s', `gender` = '%s',
1647 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1648 `location` = '%s', `about` = '%s'
1650 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1651 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1652 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1653 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1657 return $gcontact_id;
1661 * @brief Updates the gcontact entry from probe
1663 * @param str $url profile link
1665 function update_gcontact_from_probe($url) {
1666 $data = probe_url($url);
1668 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1669 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1673 update_gcontact($data);
1677 * @brief Update the gcontact entry for a given user id
1679 * @param int $uid User ID
1681 function update_gcontact_for_user($uid) {
1682 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1683 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1684 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1685 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1686 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1688 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1689 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1690 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1693 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1694 "country-name" => $r[0]["country-name"]));
1696 // The "addr" field was added in 3.4.3 so it can be empty for older users
1697 if ($r[0]["addr"] != "")
1698 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1700 $addr = $r[0]["addr"];
1702 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1703 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1704 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1705 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1706 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1707 "nick" => $r[0]["nickname"], "addr" => $addr,
1708 "connect" => $addr, "server_url" => App::get_baseurl(),
1709 "generation" => 1, "network" => NETWORK_DFRN);
1711 update_gcontact($gcontact);
1715 * @brief Fetches users of given GNU Social server
1717 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1719 * @param str $server Server address
1721 function gs_fetch_users($server) {
1723 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1727 $url = $server."/main/statistics";
1729 $result = z_fetch_url($url);
1730 if (!$result["success"])
1733 $statistics = json_decode($result["body"]);
1735 if (is_object($statistics->config)) {
1736 if ($statistics->config->instance_with_ssl)
1737 $server = "https://";
1739 $server = "http://";
1741 $server .= $statistics->config->instance_address;
1743 $hostname = $statistics->config->instance_address;
1745 if ($statistics->instance_with_ssl)
1746 $server = "https://";
1748 $server = "http://";
1750 $server .= $statistics->instance_address;
1752 $hostname = $statistics->instance_address;
1755 if (is_object($statistics->users))
1756 foreach ($statistics->users AS $nick => $user) {
1757 $profile_url = $server."/".$user->nickname;
1759 $contact = array("url" => $profile_url,
1760 "name" => $user->fullname,
1761 "addr" => $user->nickname."@".$hostname,
1762 "nick" => $user->nickname,
1763 "about" => $user->bio,
1764 "network" => NETWORK_OSTATUS,
1765 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1766 get_gcontact_id($contact);
1771 * @brief Asking GNU Social server on a regular base for their user data
1774 function gs_discover() {
1776 $requery_days = intval(get_config("system", "poco_requery_days"));
1778 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1780 $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",
1781 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1786 foreach ($r AS $server) {
1787 gs_fetch_users($server["url"]);
1788 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));