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