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) echo "<br/>";
$supplierQ = ' "supplierABN" = :supplierABN AND '; if ($stats['consultancy'] > 0) {
else echo "<b>Consultancies:</b> {$stats['consultancy']} contracts, ".percent($stats['consultancy'],$stats['total']);
$supplierQ = ' "supplierName" LIKE :supplierName AND '; echo "%<br/>";
} }
  if ($stats['confidentialityContract']+$stats['confidentialityOutputs'] > 0) {
$startYear = 2007; $confidentialities = $stats['confidentialityContract']+$stats['confidentialityOutputs'];
$year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT); echo "<b>Confidentialities:</b> $confidentialities contracts, ".percent( $confidentialities,$stats['total'])."%";
if ($year != "") { echo "( {$stats['confidentialityContract']} on the contract, {$stats['confidentialityOutputs']} on the outputs)";
$yearQ = "YEAR(publishDate) = " . $year . " AND "; echo "<br/>";
} }
$standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010'; echo "<b>Procurement methods:</b> ";
$start = 0.0; if ($stats['open'] > 0) {
  echo "Open {$stats['open']} contracts, ".percent($stats['open'],$stats['total']);
function local_url() { echo "%, ";
return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/"; }
} if ($stats['openSON'] > 0) {
  echo "Open via SON {$stats['openSON']} contracts, ".percent($stats['openSON'],$stats['total']);
function include_header($title) { echo "%, ";
global $start; }
?> if ($stats['prequalified'] > 0) {
<!DOCTYPE html> echo "Prequalified {$stats['prequalified']} contracts, ".percent($stats['prequalified'],$stats['total']);
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1" echo "%, ";
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" }
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" if ($stats['limited'] > 0) {
xmlns:gr="http://purl.org/goodrelations/v1#" echo "limited {$stats['limited']} contracts, ".percent($stats['limited'],$stats['total']);
xmlns:dc="http://purl.org/dc/terms/" echo "%, ";
xmlns:pc="http://purl.org/procurement#" }
xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#" }
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"  
xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#" // magic query modifiers
prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# $agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING);
rdfs: http://www.w3.org/2000/01/rdf-schema# if ($agency != "")
gr: http://purl.org/goodrelations/v1# $agencyQ = "agencyName = '" . $agency . "' AND ";
dcterms: http://purl.org/dc/terms/  
pc: http://purl.org/procurement/public-contracts# $supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING);
cpv: http://purl.org/weso/pscs/cpv/2008/resource/ if ($supplier != "") {
unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml# $supplierParts = explode("-", $supplier);
v: http://www.w3.org/2006/vcard/ns# $supplierName = "%" . $supplierParts[1] . "%";
payment: http://reference.data.gov.uk/def/payment# $supplierABN = $supplierParts[0];
br: http://purl.org/business-register# if ($supplierParts[0] > 0)
xsd: http://www.w3.org/2001/XMLSchema# $supplierQ = ' "supplierABN" = :supplierABN AND ';
pcdt: http://purl.org/procurement/public-contracts-datatypes#"> else
<head> $supplierQ = ' "supplierName" ILIKE :supplierName AND ';
<title><?php echo $title; ?> - Contract Dashboard</title> }
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">  
<link rel="stylesheet" type="text/css" href="bootstrap-responsive.css"> $startYear = 2007;
<!-- Le HTML5 shim, for IE6-8 support of HTML elements --> $year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT);
<!--[if lt IE 9]> if ($year != "") {
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> $yearQ = 'extract(year from "contractStart") = ' . $year . " AND ";
<![endif]--> }
<script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script> $standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';
<link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" /> $start = 0.0;
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>  
<script type="text/javascript"> function local_url() {
$(document).ready(function() return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
{ }
//hide the all of the element with class msg_body  
$(".msg_body").hide(); function include_header($title) {
//toggle the componenet with class msg_body global $start;
$(".msg_head").click(function() ?>
{ <!DOCTYPE html>
$(this).next(".msg_body").slideToggle(600); <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#"
}); xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
</script> xmlns:gr="http://purl.org/goodrelations/v1#"
  xmlns:dc="http://purl.org/dc/terms/"
<style type="text/css" title="currentStyle"> xmlns:pc="http://purl.org/procurement#"
@import "media/css/demo_table.css"; xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#"
</style> xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script> xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#"
<script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script> prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
<script type="text/javascript" charset="utf-8"> rdfs: http://www.w3.org/2000/01/rdf-schema#
jQuery.fn.dataTableExt.aTypes.unshift( gr: http://purl.org/goodrelations/v1#
function ( sData ) dcterms: http://purl.org/dc/terms/
{ pc: http://purl.org/procurement/public-contracts#
var sValidChars = "0123456789.-,"; cpv: http://purl.org/weso/pscs/cpv/2008/resource/
var Char; unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#
  v: http://www.w3.org/2006/vcard/ns#
/* Check the numeric part */ payment: http://reference.data.gov.uk/def/payment#
for ( i=1 ; i<sData.length ; i++ ) br: http://purl.org/business-register#
{ xsd: http://www.w3.org/2001/XMLSchema#
Char = sData.charAt(i); pcdt: http://purl.org/procurement/public-contracts-datatypes#">
if (sValidChars.indexOf(Char) == -1) <head>
{ <title><?php echo $title; ?> - Contract Dashboard</title>
return null; <meta name="viewport" content="width=device-width, initial-scale=1">
} <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
} <link rel="stylesheet" type="text/css" href="bootstrap-responsive.css">
  <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
/* Check prefixed by currency */ <!--[if lt IE 9]>
if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
{ <![endif]-->
return 'currency'; <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" />
return null; <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
} <script type="text/javascript">
); $(document).ready(function()
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) { {
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ //hide the all of the element with class msg_body
var x = a == "-" ? 0 : a.replace( /,/g, "" ); $(".msg_body").hide();
var y = b == "-" ? 0 : b.replace( /,/g, "" ); //toggle the componenet with class msg_body
  $(".msg_head").click(function()
/* Remove the currency sign */ {
x = x.substring( 1 ); $(this).next(".msg_body").slideToggle(600);
y = y.substring( 1 ); });
  });
/* Parse and return */ </script>
x = parseFloat( x );  
y = parseFloat( y ); <style type="text/css" title="currentStyle">
return x - y; @import "media/css/demo_table.css";
}; </style>
  <script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) { <script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script>
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ <script type="text/javascript" charset="utf-8">
var x = a == "-" ? 0 : a.replace( /,/g, "" ); jQuery.fn.dataTableExt.aTypes.unshift(
var y = b == "-" ? 0 : b.replace( /,/g, "" ); function ( sData )
  {
/* Remove the currency sign */ var sValidChars = "0123456789.-,";
x = x.substring( 1 ); var Char;
y = y.substring( 1 );  
  /* Check the numeric part */
/* Parse and return */ for ( i=1 ; i<sData.length ; i++ )
x = parseFloat( x ); {
y = parseFloat( y ); Char = sData.charAt(i);
return y - x; if (sValidChars.indexOf(Char) == -1)
}; {
$(document).ready(function() { return null;
$('table').dataTable(); }
} ); }
</script>  
<link type="text/css" rel="stylesheet" href="style.css"> /* Check prefixed by currency */
</head> if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )
<body> {
<div class="navbar"> return 'currency';
<div class="navbar-inner"> }
<div class="container-fluid"> return null;
<a class="brand" href="#">contract dashboard</a> }
<ul class="nav"> );
<li><a href="displayAgency.php">agencies</a></li> jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
<li><a href="displaySupplier.php">suppliers</a></li> /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
<li><a href="displayCategory.php">categories</a></li> var x = a == "-" ? 0 : a.replace( /,/g, "" );
<li><a href="displayCalendar.php">time periods</a></li> var y = b == "-" ? 0 : b.replace( /,/g, "" );
<!-- <li class="dropdown">  
<a href="#" class="dropdown-toggle">metrics</a> /* Remove the currency sign */
<ul class="dropdown-menu">--> x = x.substring( 1 );
<li><a href="displayProcurementMethod.php">tenderm</a></li> y = y.substring( 1 );
<li><a href="displayConfidentialities.php">confidentiality</a></li>  
<li><a href="displayConsultancies.php">consultancies</a></li> /* Parse and return */
<li><a href="displayAmendments.php">amendments</a></li> x = parseFloat( x );
<li><a href="displayMap.php">geo</a></li> y = parseFloat( y );
</ul> return x - y;
  };
   
<form method="post" action="search.php" class="pull-right"> jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
<input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" /> /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
<input type="hidden" id="searchID" name="searchID" value=""/> var x = a == "-" ? 0 : a.replace( /,/g, "" );
</form> var y = b == "-" ? 0 : b.replace( /,/g, "" );
   
</div> /* Remove the currency sign */
</div><!-- /topbar-inner --> x = x.substring( 1 );
</div><!-- /topbar --> y = y.substring( 1 );
</div><!-- /topbar-wrapper -->  
<script type="text/javascript"> /* Parse and return */
  x = parseFloat( x );
var options_xml = { y = parseFloat( y );
script: function (input) { return "search_autosuggest.php?input="+input; }, return y - x;
varname:"input", };
callback: function (obj) { document.getElementById('searchID').value = obj.id; } $(document).ready(function() {
}; $('table').dataTable();
var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml); } );
</script> </script>
<div class="container-fluid"> <link type="text/css" rel="stylesheet" href="style.css">
<div class="row-fluid"> </head>
<div class="span3"> <body>
<div class="well sidebar-nav"> <div class="navbar">
<li class="nav-header">Filter by:</li> <div class="navbar-inner">
<li>2008</li> <div class="container-fluid">
</div> <a class="brand" href="#">contract dashboard</a>
</div> <ul class="nav">
<div class="span9"> <li><a href="displayAgency.php">agencies</a></li>
<?php <li><a href="displaySupplier.php">suppliers</a></li>
$start = (float) array_sum(explode(' ', microtime())); <li><a href="displaySON.php">standing offers</a></li>
} <li><a href="displayCategory.php">categories</a></li>
  <li><a href="displayCalendar.php">dates</a></li>
function include_footer() { <li><a href="displayProcurementMethod.php">tenderm</a></li>
global $start; <li><a href="displayConfidentialities.php">confidentiality</a></li>
$end = (float) array_sum(explode(' ', microtime())); <li><a href="displayConsultancies.php">consultancies</a></li>
  <li><a href="displayAmendments.php">amendments</a></li>
echo '</div> <footer>' . "Processing time: " . sprintf("%.4f", ($end - $start)) . " seconds" . ' <footer>'; <li><a href="displayMap.php">geo</a></li>
  </ul>
if (strpos($_SERVER['SERVER_NAME'], ".gs")) {  
?>  
<script type="text/javascript"> <form method="get" action="search.php" class="pull-right">
  <input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" />
var _gaq = _gaq || []; <input type="hidden" id="searchID" name="searchID" value=""/>
_gaq.push(['_setAccount', 'UA-12341040-3']); </form>
_gaq.push(['_trackPageview']);  
  </div>
(function() { </div><!-- /topbar-inner -->
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; </div><!-- /topbar -->
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; </div><!-- /topbar-wrapper -->
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); <script type="text/javascript">
})();  
  var options_xml = {
</script> script: function (input) { return "search_autosuggest.php?input="+input; },
<?php varname:"input",
} callback: function (obj) { document.getElementById('searchID').value = obj.id; }
echo '</div> </div></body> </html>'; };
} var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml);
  </script>
include ("graphs.inc.php"); <div class="container-fluid">
  <div class="row-fluid">
  <div class="span3">
  <h3> Filter by: </h3>
  <div class="well sidebar-nav">
  <li class="nav-header">Year</li>
  <?php
  foreach (range(2007,2017) as $year) {
  $get = $_GET;
  $get['year'] = $year;
  $query = http_build_query($get);
  echo "<li><A href='?$query'>";
  if ($_GET['year'] == $year) echo "<b>";
  echo "$year";
  if ($_GET['year'] == $year) echo "</b>";
  echo "</a></li>";
  }
  ?>
  </div>
  </div>
  <div class="span9">
  <?php
  $start = (float) array_sum(explode(' ', microtime()));
  }
   
  function include_footer() {
  global $start;
  $end = (float) array_sum(explode(' ', microtime()));
   
  echo '</div> <footer>' . "Processing time: " . sprintf("%.4f", ($end - $start)) . " seconds" . ' <footer>';
   
  if (strpos($_SERVER['SERVER_NAME'], ".gs")) {
  ?>
  <script type="text/javascript">
   
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-12341040-3']);
  _gaq.push(['_trackPageview']);
   
  (function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
   
  </script>
  <?php
  }
  echo '</div> </div></body> </html>';
  }
   
  include ("graphs.inc.php");