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