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) {  
if (strlen($word) <= 4 && !in_array($word, $shortWords)) function ucsmart($str) {
$word = strtoupper($word); $shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In"
} , "Of", "On", "Or", "The", "To", "With");
return implode(" ", $strArray); $strArray = explode(" ", preg_replace_callback("/(?<=(?<!:|’s)\W)
} (A|An|And|At|For|In|Of|On|Or|The|To|With)
  (?=\W)/",
function percent($num_amount, $num_total) { function($matches) { return strtolower($matches[1]); } , ucwords(strtolower($str))));
$count1 = $num_amount / $num_total; foreach ($strArray as &$word) {
$count2 = $count1 * 100; if (strlen($word) <= 4 && !in_array($word, $shortWords))
$count = number_format($count2, 2); $word = strtoupper($word);
return $count; }
} return implode(" ", $strArray);
  }
function array_sum_all($a) {  
if (!is_array($a)) function percent($num_amount, $num_total) {
return $a; $count1 = $num_amount / $num_total;
foreach ($a as $key => $value) $count2 = $count1 * 100;
$totale += array_sum_all($value); $count = number_format($count2, 2);
return $totale; return $count;
} }
   
// magic query modifiers function array_sum_all($a) {
$agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING); if (!is_array($a))
if ($agency != "") return $a;
$agencyQ = "agencyName = '" . $agency . "' AND "; $totale = 0;
  foreach ($a as $key => $value)
$supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING); $totale += array_sum_all($value);
if ($supplier != "") { return $totale;
$supplierParts = explode("-", $supplier); }
$supplierName = "%" . $supplierParts[1] . "%";  
$supplierABN = $supplierParts[0]; function show_stats($stats) {
if ($supplierParts[0] > 0) setlocale(LC_MONETARY, 'en_US');
$supplierQ = ' "supplierABN" = :supplierABN AND '; $value = number_format(doubleval($stats['total_value']) , 2);
else echo "<br/> {$stats['total']} contracts, total value $$value <br/>";
$supplierQ = ' "supplierName" LIKE :supplierName AND '; if ($stats['consultancy'] > 0) {
} echo "<b>Consultancies:</b> {$stats['consultancy']} contracts, ".percent($stats['consultancy'],$stats['total']);
  echo "%<br/>";
$startYear = 2007; }
$year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT); if ($stats['confidentialityContract']+$stats['confidentialityOutputs'] > 0) {
if ($year != "") { $confidentialities = $stats['confidentialityContract']+$stats['confidentialityOutputs'];
$yearQ = "YEAR(publishDate) = " . $year . " AND "; echo "<b>Confidentialities:</b> $confidentialities contracts, ".percent( $confidentialities,$stats['total'])."%";
} echo "( {$stats['confidentialityContract']} on the contract, {$stats['confidentialityOutputs']} on the outputs)";
$standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010'; echo "<br/>";
$start = 0.0; }
  echo "<b>Procurement methods:</b> ";
function local_url() { if ($stats['open'] > 0) {
return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/"; echo "Open {$stats['open']} contracts, ".percent($stats['open'],$stats['total']);
} echo "%, ";
  }
function include_header($title) { if ($stats['openSON'] > 0) {
global $start; echo "Open via SON {$stats['openSON']} contracts, ".percent($stats['openSON'],$stats['total']);
?> echo "%, ";
<!DOCTYPE html> }
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1" if ($stats['prequalified'] > 0) {
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" echo "Prequalified {$stats['prequalified']} contracts, ".percent($stats['prequalified'],$stats['total']);
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" echo "%, ";
xmlns:gr="http://purl.org/goodrelations/v1#" }
xmlns:dc="http://purl.org/dc/terms/" if ($stats['limited'] > 0) {
xmlns:pc="http://purl.org/procurement#" echo "limited {$stats['limited']} contracts, ".percent($stats['limited'],$stats['total']);
xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#" echo "%, ";
xmlns:xsd="http://www.w3.org/2001/XMLSchema#" }
xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#" }
prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#  
rdfs: http://www.w3.org/2000/01/rdf-schema# // magic query modifiers
gr: http://purl.org/goodrelations/v1# $agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING);
dcterms: http://purl.org/dc/terms/ if ($agency != "")
pc: http://purl.org/procurement/public-contracts# $agencyQ = "agencyName = '" . $agency . "' AND ";
cpv: http://purl.org/weso/pscs/cpv/2008/resource/  
unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml# $supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING);
v: http://www.w3.org/2006/vcard/ns# if ($supplier != "") {
payment: http://reference.data.gov.uk/def/payment# if ($supplier[0] !== '-') {
br: http://purl.org/business-register# $supplierParts = explode("-", $supplier);
xsd: http://www.w3.org/2001/XMLSchema#  
pcdt: http://purl.org/procurement/public-contracts-datatypes#"> $supplierABN = array_shift($supplierParts);
<head> $supplierName = "%" . implode('-',$supplierParts) . "%";
<title><?php echo $title; ?> - Contract Dashboard</title>  
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> $supplierQ = ' "supplierABN" = :supplierABN AND ';
<link rel="stylesheet" type="text/css" href="bootstrap-responsive.css"> } else {
<!-- Le HTML5 shim, for IE6-8 support of HTML elements --> $supplierName = "%" . substr($supplier,1) . "%";
<!--[if lt IE 9]> $supplierQ = ' "supplierName" ILIKE :supplierName AND ';
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> }
<![endif]--> }
<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" /> $startYear = 2007;
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> $year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT);
<script type="text/javascript"> if ($year != "") {
$(document).ready(function() $yearQ = 'extract(year from "contractStart") = ' . $year . " AND ";
{ }
//hide the all of the element with class msg_body $standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';
$(".msg_body").hide(); $start = 0.0;
//toggle the componenet with class msg_body  
$(".msg_head").click(function() function local_url() {
{ return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
$(this).next(".msg_body").slideToggle(600); }
});  
}); function include_header($title) {
</script> global $start;
  ?>
<style type="text/css" title="currentStyle"> <!DOCTYPE html>
@import "media/css/demo_table.css"; <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1"
</style> xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script> xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
<script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script> xmlns:gr="http://purl.org/goodrelations/v1#"
<script type="text/javascript" charset="utf-8"> xmlns:dc="http://purl.org/dc/terms/"
jQuery.fn.dataTableExt.aTypes.unshift( xmlns:pc="http://purl.org/procurement#"
function ( sData ) xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#"
{ xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
var sValidChars = "0123456789.-,"; xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#"
var Char; prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
  rdfs: http://www.w3.org/2000/01/rdf-schema#
/* Check the numeric part */ gr: http://purl.org/goodrelations/v1#
for ( i=1 ; i<sData.length ; i++ ) dcterms: http://purl.org/dc/terms/
{ pc: http://purl.org/procurement/public-contracts#
Char = sData.charAt(i); cpv: http://purl.org/weso/pscs/cpv/2008/resource/
if (sValidChars.indexOf(Char) == -1) unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#
{ v: http://www.w3.org/2006/vcard/ns#
return null; payment: http://reference.data.gov.uk/def/payment#
} br: http://purl.org/business-register#
} xsd: http://www.w3.org/2001/XMLSchema#
  pcdt: http://purl.org/procurement/public-contracts-datatypes#">
/* Check prefixed by currency */ <head>
if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) <title><?php echo $title; ?> - Contract Dashboard</title>
{ <meta name="viewport" content="width=device-width, initial-scale=1">
return 'currency'; <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
} <link rel="stylesheet" type="text/css" href="bootstrap-responsive.css">
return null; <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
} <!--[if lt IE 9]>
); <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) { <![endif]-->
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ <script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script>
var x = a == "-" ? 0 : a.replace( /,/g, "" ); <link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />
var y = b == "-" ? 0 : b.replace( /,/g, "" ); <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  <script type="text/javascript">
/* Remove the currency sign */ $(document).ready(function()
x = x.substring( 1 ); {
y = y.substring( 1 ); //hide the all of the element with class msg_body
  $(".msg_body").hide();
/* Parse and return */ //toggle the componenet with class msg_body
x = parseFloat( x ); $(".msg_head").click(function()
y = parseFloat( y ); {
return x - y; $(this).next(".msg_body").slideToggle(600);
}; });
  });
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) { </script>
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */  
var x = a == "-" ? 0 : a.replace( /,/g, "" ); <style type="text/css" title="currentStyle">
var y = b == "-" ? 0 : b.replace( /,/g, "" ); @import "media/css/demo_table.css";
  </style>
/* Remove the currency sign */ <script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
x = x.substring( 1 ); <script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script>
y = y.substring( 1 ); <script type="text/javascript" charset="utf-8">
  jQuery.fn.dataTableExt.aTypes.unshift(
/* Parse and return */ function ( sData )
x = parseFloat( x ); {
y = parseFloat( y ); var sValidChars = "0123456789.-,";
return y - x; var Char;
};  
$(document).ready(function() { /* Check the numeric part */
$('table').dataTable(); for ( i=1 ; i<sData.length ; i++ )
} ); {
</script> Char = sData.charAt(i);
<link type="text/css" rel="stylesheet" href="style.css"> if (sValidChars.indexOf(Char) == -1)
</head> {
<body> return null;
<div class="navbar"> }
<div class="navbar-inner"> }
<div class="container-fluid">  
<a class="brand" href="#">contract dashboard</a> /* Check prefixed by currency */
<ul class="nav"> if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )
<li><a href="displayAgency.php">agencies</a></li> {
<li><a href="displaySupplier.php">suppliers</a></li> return 'currency';
<li><a href="displayCategory.php">categories</a></li> }
<li><a href="displayCalendar.php">time periods</a></li> return null;
<!-- <li class="dropdown"> }
<a href="#" class="dropdown-toggle">metrics</a> );
<ul class="dropdown-menu">--> jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
<li><a href="displayProcurementMethod.php">tenderm</a></li> /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
<li><a href="displayConfidentialities.php">confidentiality</a></li> var x = a == "-" ? 0 : a.replace( /,/g, "" );
<li><a href="displayConsultancies.php">consultancies</a></li> var y = b == "-" ? 0 : b.replace( /,/g, "" );
<li><a href="displayAmendments.php">amendments</a></li>  
<li><a href="displayMap.php">geo</a></li> /* Remove the currency sign */
</ul> x = x.substring( 1 );
  y = y.substring( 1 );
   
<form method="post" action="search.php" class="pull-right"> /* Parse and return */
<input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" /> x = parseFloat( x );
<input type="hidden" id="searchID" name="searchID" value=""/> y = parseFloat( y );
</form> return x - y;
  };
</div>  
</div><!-- /topbar-inner --> jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
</div><!-- /topbar --> /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
</div><!-- /topbar-wrapper --> var x = a == "-" ? 0 : a.replace( /,/g, "" );
<script type="text/javascript"> var y = b == "-" ? 0 : b.replace( /,/g, "" );
   
var options_xml = { /* Remove the currency sign */
script: function (input) { return "search_autosuggest.php?input="+input; }, x = x.substring( 1 );
varname:"input", y = y.substring( 1 );
callback: function (obj) { document.getElementById('searchID').value = obj.id; }  
}; /* Parse and return */
var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml); x = parseFloat( x );
</script> y = parseFloat( y );
<div class="container-fluid"> return y - x;
<div class="row-fluid"> };
<div class="span3"> $(document).ready(function() {
<div class="well sidebar-nav"> $('table').dataTable();