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