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