fix heuristics
[contractdashboard.git] / lib / common.inc.php
blob:a/lib/common.inc.php -> blob:b/lib/common.inc.php
<?php <?php
date_default_timezone_set("Australia/ACT"); date_default_timezone_set("Australia/ACT");
   
error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
   
   
$conn = new PDO("pgsql:dbname=contractDashboard;user=postgres;password=snmc;host=localhost"); include('db.inc.php');
   
if (!$conn) { define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME));
die("A database error occurred.\n"); if (strstr($_SERVER['PHP_SELF'], "labs/") || strstr($_SERVER['PHP_SELF'], "admin/") || strstr($_SERVER['PHP_SELF'], "heuristics/")) {
} $basePath = "../";
  }
define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME)); /*require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php';
if (strstr($_SERVER['PHP_SELF'], "labs/") || strstr($_SERVER['PHP_SELF'], "admin/") || strstr($_SERVER['PHP_SELF'], "heuristics/")) { require(ROOT.'/solarium/vendor/autoload.php');
$basePath = "../"; require(ROOT.'/solarium/library/Solarium/Autoloader.php');
} Solarium\Autoloader::register();
require $basePath."lib/amon-php/amon.php"; // check solarium version available
Amon::config(array('address'=> 'http://127.0.0.1:2464', //echo 'Solarium library version: ' . Solarium\Client::VERSION . ' - ';
'protocol' => 'http', $config = array(
'secret_key' => "JBcSUdFOi5lK0vCjLjbHDpQamcBnRA4iV7QLaTADeDQ")); 'endpoint' => array(
Amon::setup_exception_handler(); 'localhost' => array(
  'host' => '127.0.0.1',
require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php'; 'port' => 8983,
$openid = new LightOpenID($_SERVER['HTTP_HOST']); 'path' => '/solr/contracts/',
// you have to open the session to be able to modify or remove it )
session_start(); )
function login() { );
global $openid; // create a client instance
if (!$openid->mode) { $solr_client = new Solarium\Client($config);
$openid->required = array('contact/email');  
$openid->identity = 'https://www.google.com/accounts/o8/id';  
header('Location: ' . $openid->authUrl()); $openid = new LightOpenID($_SERVER['HTTP_HOST']);
} // you have to open the session to be able to modify or remove it
} session_start();
  function login() {
function auth() { global $openid;
global $openid; if (!$openid->mode) {
if ($_SESSION['authed'] == true) { $openid->required = array('contact/email');
return true; $openid->identity = 'https://www.google.com/accounts/o8/id';
} header('Location: ' . $openid->authUrl());
  }
if ($openid->mode) { }
$attr = $openid->getAttributes();  
if ($attr['contact/email'] != 'maxious@gmail.com') { function auth() {
die('Access Denied'); global $openid;
} else { if ($_SESSION['authed'] == true) {
$_SESSION['authed'] = true; return true;
} }
} else {  
login(); if ($openid->mode) {
} $attr = $openid->getAttributes();
} if ($attr['contact/email'] != 'maxious@gmail.com') {
  die('Access Denied');
// $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } else {
function databaseError($errMsg) { $_SESSION['authed'] = true;
if ($errMsg[2] != "") { }
echo '<div class="alert-message error">'; } else {
Amon::log(print_r($errMsg, true).print_r($_REQUEST, true).print_r($_SERVER, true), array('error')); login();
die(print_r($errMsg, true)); }
echo "</div>"; }*/
}  
} // $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  function databaseError($errMsg) {
function ucsmart($str) { if ($errMsg[2] != "") {
$shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In" echo '<div class="alert-message error">';
, "Of", "On", "Or", "The", "To", "With"); die(print_r($errMsg, true));
$strArray = explode(" ", preg_replace("/(?<=(?<!:|’s)\W) echo "</div>";
(A|An|And|At|For|In|Of|On|Or|The|To|With) }
(?=\W)/e", 'strtolower("$1")', ucwords(strtolower($str)))); }
foreach ($strArray as &$word) { function cleanseName($input) {
if (strlen($word) <= 4 && !in_array($word, $shortWords))  
$word = strtoupper($word); return trim(join(" ",array_filter(explode(" ",strtolower($input)), function($v, $k) {
} $cleanseNamesCorp = Array(
return implode(" ", $strArray); "ltd",
} "limited",
  "australia",
function percent($num_amount, $num_total) { "australian",
$count1 = $num_amount / $num_total; "australasia",
$count2 = $count1 * 100; "(aus)",
$count = number_format($count2, 2); "(aust)",
return $count; "(australia)",
} "the",
  "pty",
function array_sum_all($a) { "contractors",
if (!is_array($a)) "p/l",
return $a; "inc.",
foreach ($a as $key => $value) "inc",
$totale += array_sum_all($value); "incorporated"
return $totale; );
} return !in_array($v,$cleanseNamesCorp) ;
  }, ARRAY_FILTER_USE_BOTH)));
// magic query modifiers }
$agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING); function ucsmart($str) {
if ($agency != "") $shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In"
$agencyQ = "agencyName = '" . $agency . "' AND "; , "Of", "On", "Or", "The", "To", "With", "Use", "No", "Yes");
  $strArray = explode(" ", preg_replace_callback("/(?<=(?<!:|’s)\W)
$supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING); (A|An|And|At|For|In|Of|On|Or|The|To|With)
if ($supplier != "") { (?=\W)/",
$supplierParts = explode("-", $supplier); function($matches) { return strtolower($matches[1]); } , ucwords(strtolower($str))));
$supplierName = "%" . $supplierParts[1] . "%"; foreach ($strArray as &$word) {
$supplierABN = $supplierParts[0]; if (strlen($word) <= 4 && !in_array($word, $shortWords))
if ($supplierParts[0] > 0) $word = strtoupper($word);
$supplierQ = ' "supplierABN" = :supplierABN AND '; }
else return implode(" ", $strArray);
$supplierQ = ' "supplierName" LIKE :supplierName AND '; }
}  
  function percent($num_amount, $num_total) {
$startYear = 2007; $count1 = $num_amount / $num_total;
$year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT); $count2 = $count1 * 100;
if ($year != "") { $count = number_format($count2, 2);
$yearQ = "YEAR(publishDate) = " . $year . " AND "; return $count;
} }
$standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';  
$start = 0.0; function array_sum_all($a) {
  if (!is_array($a))
function local_url() { return $a;
return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/"; $totale = 0;
} foreach ($a as $key => $value)
  $totale += array_sum_all($value);
function include_header($title) { return $totale;
global $start; }
?>  
<!DOCTYPE html> function show_stats($stats) {
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1" setlocale(LC_MONETARY, 'en_US');
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" $value = number_format(doubleval($stats['total_value']) , 2);
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" echo "<br/> {$stats['total']} contracts, total value $$value <br/>";
xmlns:gr="http://purl.org/goodrelations/v1#" if ($stats['consultancy'] > 0) {
xmlns:dc="http://purl.org/dc/terms/" echo "<b>Consultancies:</b> {$stats['consultancy']} contracts, ".percent($stats['consultancy'],$stats['total']);
xmlns:pc="http://purl.org/procurement#" echo "%<br/>";
xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#" }
xmlns:xsd="http://www.w3.org/2001/XMLSchema#" if ($stats['confidentialityContract']+$stats['confidentialityOutputs'] > 0) {
xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#" $confidentialities = $stats['confidentialityContract']+$stats['confidentialityOutputs'];
prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# echo "<b>Confidentialities:</b> $confidentialities contracts, ".percent( $confidentialities,$stats['total'])."%";
rdfs: http://www.w3.org/2000/01/rdf-schema# echo "( {$stats['confidentialityContract']} on the contract, {$stats['confidentialityOutputs']} on the outputs)";
gr: http://purl.org/goodrelations/v1# echo "<br/>";
dcterms: http://purl.org/dc/terms/ }
pc: http://purl.org/procurement/public-contracts# echo "<b>Procurement methods:</b> ";
cpv: http://purl.org/weso/pscs/cpv/2008/resource/ if ($stats['open'] > 0) {
unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml# echo "Open {$stats['open']} contracts, ".percent($stats['open'],$stats['total']);
v: http://www.w3.org/2006/vcard/ns# echo "%, ";
payment: http://reference.data.gov.uk/def/payment# }
br: http://purl.org/business-register# if ($stats['openSON'] > 0) {
xsd: http://www.w3.org/2001/XMLSchema# echo "Open via SON {$stats['openSON']} contracts, ".percent($stats['openSON'],$stats['total']);
pcdt: http://purl.org/procurement/public-contracts-datatypes#"> echo "%, ";
<head> }
<title><?php echo $title; ?> - Contract Dashboard</title> if ($stats['prequalified'] > 0) {
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> echo "Prequalified {$stats['prequalified']} contracts, ".percent($stats['prequalified'],$stats['total']);
<link rel="stylesheet" type="text/css" href="bootstrap-responsive.css"> echo "%, ";
<!-- Le HTML5 shim, for IE6-8 support of HTML elements --> }
<!--[if lt IE 9]> if ($stats['limited'] > 0) {
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> echo "limited {$stats['limited']} contracts, ".percent($stats['limited'],$stats['total']);
<![endif]--> echo "%, ";
<script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script> }
<link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" /> }
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>  
<script type="text/javascript"> // magic query modifiers
$(document).ready(function() $agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING);
{ if ($agency != "")
//hide the all of the element with class msg_body $agencyQ = "agencyName = '" . $agency . "' AND ";
$(".msg_body").hide();  
//toggle the componenet with class msg_body $supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING);
$(".msg_head").click(function() if ($supplier != "") {
{ if ($supplier[0] !== '-') {
$(this).next(".msg_body").slideToggle(600); $supplierParts = explode("-", $supplier);
});  
}); $supplierABN = array_shift($supplierParts);
</script> $supplierName = "%" . implode('-',$supplierParts) . "%";
   
<style type="text/css" title="currentStyle"> $supplierQ = ' "supplierABN" = :supplierABN AND ';
@import "media/css/demo_table.css"; } else {
</style> $supplierName = "%" . substr($supplier,1) . "%";
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script> $supplierQ = ' "supplierName" ILIKE :supplierName AND ';
<script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script> }
<script type="text/javascript" charset="utf-8"> }
jQuery.fn.dataTableExt.aTypes.unshift(  
function ( sData ) $startYear = 2007;
{ $year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT);
var sValidChars = "0123456789.-,"; if ($year != "") {
var Char; $yearQ = 'extract(year from "contractStart") = ' . $year . " AND ";
  }
/* Check the numeric part */ $standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';
for ( i=1 ; i<sData.length ; i++ ) $start = 0.0;
{  
Char = sData.charAt(i); function local_url() {
if (sValidChars.indexOf(Char) == -1) return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
{ }
return null;  
} function include_header($title) {
} global $start;
  ?>
/* Check prefixed by currency */ <!DOCTYPE html>
if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1"
{ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
return 'currency'; xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
} xmlns:gr="http://purl.org/goodrelations/v1#"
return null; xmlns:dc="http://purl.org/dc/terms/"
} xmlns:pc="http://purl.org/procurement#"
); xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#"
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) { xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#"
var x = a == "-" ? 0 : a.replace( /,/g, "" ); prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
var y = b == "-" ? 0 : b.replace( /,/g, "" ); rdfs: http://www.w3.org/2000/01/rdf-schema#
  gr: http://purl.org/goodrelations/v1#
/* Remove the currency sign */ dcterms: http://purl.org/dc/terms/
x = x.substring( 1 ); pc: http://purl.org/procurement/public-contracts#
y = y.substring( 1 ); cpv: http://purl.org/weso/pscs/cpv/2008/resource/
  unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#
/* Parse and return */ v: http://www.w3.org/2006/vcard/ns#
x = parseFloat( x ); payment: http://reference.data.gov.uk/def/payment#
y = parseFloat( y ); br: http://purl.org/business-register#
return x - y; xsd: http://www.w3.org/2001/XMLSchema#
}; pcdt: http://purl.org/procurement/public-contracts-datatypes#">
  <head>
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) { <title><?php echo $title; ?> - Contract Dashboard</title>
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ <meta name="viewport" content="width=device-width, initial-scale=1">
var x = a == "-" ? 0 : a.replace( /,/g, "" ); <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
var y = b == "-" ? 0 : b.replace( /,/g, "" ); <link rel="stylesheet" type="text/css" href="bootstrap-responsive.css">
  <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
/* Remove the currency sign */ <!--[if lt IE 9]>
x = x.substring( 1 ); <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
y = y.substring( 1 ); <![endif]-->
  <script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script>
/* Parse and return */ <link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />
x = parseFloat( x ); <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
y = parseFloat( y ); <script type="text/javascript">
return y - x; $(document).ready(function()
}; {
$(document).ready(function() { //hide the all of the element with class msg_body
$('table').dataTable(); $(".msg_body").hide();
} ); //toggle the componenet with class msg_body
</script> $(".msg_head").click(function()
<link type="text/css" rel="stylesheet" href="style.css"> {
</head> $(this).next(".msg_body").slideToggle(600);
<body> });
<div class="navbar"> });
<div class="navbar-inner"> </script>
<div class="container-fluid">  
<a class="brand" href="#">contract dashboard</a> <style type="text/css" title="currentStyle">
<ul class="nav"> @import "media/css/demo_table.css";
<li><a href="displayAgency.php">agencies</a></li> </style>
<li><a href="displaySupplier.php">suppliers</a></li> <script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
<li><a href="displayCategory.php">categories</a></li> <script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script>
<li><a href="displayCalendar.php">time periods</a></li> <script type="text/javascript" charset="utf-8">
<!-- <li class="dropdown"> jQuery.fn.dataTableExt.aTypes.unshift(
<a href="#" class="dropdown-toggle">metrics</a> function ( sData )
<ul class="dropdown-menu">--> {
<li><a href="displayProcurementMethod.php">tenderm</a></li> var sValidChars = "0123456789.-,";
<li><a href="displayConfidentialities.php">confidentiality</a></li> var Char;
<li><a href="displayConsultancies.php">consultancies</a></li>  
<li><a href="displayAmendments.php">amendments</a></li> /* Check the numeric part */
<li><a href="displayMap.php">geo</a></li> for ( i=1 ; i<sData.length ; i++ )
</ul> {
  Char = sData.charAt(i);
  if (sValidChars.indexOf(Char) == -1)
<form method="post" action="search.php" class="pull-right"> {
<input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" /> return null;
<input type="hidden" id="searchID" name="searchID" value=""/> }
</form> }
   
</div> /* Check prefixed by currency */
</div><!-- /topbar-inner --> if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )
</div><!-- /topbar --> {
</div><!-- /topbar-wrapper --> return 'currency';
<script type="text/javascript"> }
  return null;
var options_xml = { }
script: function (input) { return "search_autosuggest.php?input="+input; }, );
varname:"input", jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
callback: function (obj) { document.getElementById('searchID').value = obj.id; } /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
}; var x = a == "-" ? 0 : a.replace( /,/g, "" );
var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml); var y = b == "-" ? 0 : b.replace( /,/g, "" );
</script>  
<div class="container-fluid"> /* Remove the currency sign */
<div class="row-fluid"> x = x.substring( 1 );
<div class="span3"> y = y.substring( 1 );
<div class="well sidebar-nav">  
<li class="nav-header">Filter by:</li> /* Parse and return */