Start graph and import refactoring
[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 = "../";
  }
// $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php';
function databaseError($errMsg) require(ROOT.'/solarium/vendor/autoload.php');
{ require(ROOT.'/solarium/library/Solarium/Autoloader.php');
die($errMsg); Solarium\Autoloader::register();
} // check solarium version available
  //echo 'Solarium library version: ' . Solarium\Client::VERSION . ' - ';
function ucsmart($str) { $config = array(
$shortWords = Array("The","Pty","Ltd","Inc","Red","Oil","A","An","And","At","For","In" 'endpoint' => array(
,"Of","On","Or","The","To","With"); 'localhost' => array(
$strArray = explode(" ",preg_replace("/(?<=(?<!:|’s)\W) 'host' => '127.0.0.1',
(A|An|And|At|For|In|Of|On|Or|The|To|With) 'port' => 8983,
(?=\W)/e", 'strtolower("$1")', ucwords(strtolower($str)))); 'path' => '/solr/contracts/',
foreach($strArray as &$word) { )
if (strlen($word) <= 4 && !in_array($word,$shortWords)) $word = strtoupper($word); )
} );
return implode(" ",$strArray); // create a client instance
} $solr_client = new Solarium\Client($config);
   
function percent($num_amount, $num_total) {  
$count1 = $num_amount / $num_total; $openid = new LightOpenID($_SERVER['HTTP_HOST']);
$count2 = $count1 * 100; // you have to open the session to be able to modify or remove it
$count = number_format($count2, 2); session_start();
return $count; function login() {
} global $openid;
function array_sum_all($a) { if (!$openid->mode) {
if(!is_array($a)) return $a; $openid->required = array('contact/email');
foreach($a as $key=>$value) $openid->identity = 'https://www.google.com/accounts/o8/id';
$totale += array_sum_all($value); header('Location: ' . $openid->authUrl());
return $totale; }
} }
// magic query modifiers  
$agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING); function auth() {
if ($agency != "") $agencyQ = "agencyName = '" . $agency . "' AND "; global $openid;
  if ($_SESSION['authed'] == true) {
$supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING); return true;
if ($supplier != "") { }
$supplierParts = explode("-", $supplier);  
$supplierName = "%".$supplierParts[1]."%"; if ($openid->mode) {
$supplierABN = $supplierParts[0]; $attr = $openid->getAttributes();
if ($supplierParts[0] > 0) $supplierQ = ' "supplierABN" = :supplierABN AND '; if ($attr['contact/email'] != 'maxious@gmail.com') {
else $supplierQ = ' "supplierName" LIKE :supplierName AND '; die('Access Denied');
} } else {
  $_SESSION['authed'] = true;
$startYear = 2007; }
$year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT); } else {
if ($year != "") $yearQ = "YEAR(publishDate) = " . $year . " AND "; login();
  }
$standardQ = ' "childCN" = 0 '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010'; }*/
$start =0.0;  
  // $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function include_header($title) { function databaseError($errMsg) {
global $start; if ($errMsg[2] != "") {
?> echo '<div class="alert-message error">';
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" die(print_r($errMsg, true));
"http://www.w3.org/TR/html4/strict.dtd"> echo "</div>";
<html> }
<head> }
<title>Contract Dashboard - <?php echo $title; ?></title> function cleanseName($input) {
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css">  
  return trim(join(" ",array_filter(explode(" ",strtolower($input)), function($v, $k) {
<script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script> $cleanseNamesCorp = Array(
<link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" /> "ltd",
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> "limited",
<script type="text/javascript"> "australia",
$(document).ready(function() "australian",
{ "australasia",
//hide the all of the element with class msg_body "(aus)",
$(".msg_body").hide(); "(aust)",
//toggle the componenet with class msg_body "(australia)",
$(".msg_head").click(function() "the",
{ "pty",
$(this).next(".msg_body").slideToggle(600); "contractors",
}); "p/l",
}); "inc.",
</script> "inc",
  "incorporated"
<style type="text/css" title="currentStyle"> );
@import "media/css/demo_table.css"; return !in_array($v,$cleanseNamesCorp) ;
</style> }, ARRAY_FILTER_USE_BOTH)));
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script> }
<script type="text/javascript" charset="utf-8"> function ucsmart($str) {
jQuery.fn.dataTableExt.aTypes.unshift( $shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In"
function ( sData ) , "Of", "On", "Or", "The", "To", "With");
{ $strArray = explode(" ", preg_replace_callback("/(?<=(?<!:|’s)\W)
var sValidChars = "0123456789.-,"; (A|An|And|At|For|In|Of|On|Or|The|To|With)
var Char; (?=\W)/",
  function($matches) { return strtolower($matches[1]); } , ucwords(strtolower($str))));
/* Check the numeric part */ foreach ($strArray as &$word) {
for ( i=1 ; i<sData.length ; i++ ) if (strlen($word) <= 4 && !in_array($word, $shortWords))
{ $word = strtoupper($word);
Char = sData.charAt(i); }
if (sValidChars.indexOf(Char) == -1) return implode(" ", $strArray);
{ }
return null;  
} function percent($num_amount, $num_total) {
} $count1 = $num_amount / $num_total;
  $count2 = $count1 * 100;
/* Check prefixed by currency */ $count = number_format($count2, 2);
if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) return $count;
{ }
return 'currency';  
} function array_sum_all($a) {
return null; if (!is_array($a))
} return $a;
); $totale = 0;
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) { foreach ($a as $key => $value)
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ $totale += array_sum_all($value);
var x = a == "-" ? 0 : a.replace( /,/g, "" ); return $totale;
var y = b == "-" ? 0 : b.replace( /,/g, "" ); }
   
/* Remove the currency sign */ function show_stats($stats) {
x = x.substring( 1 ); setlocale(LC_MONETARY, 'en_US');
y = y.substring( 1 ); $value = number_format(doubleval($stats['total_value']) , 2);
  echo "<br/> {$stats['total']} contracts, total value $$value <br/>";
/* Parse and return */ if ($stats['consultancy'] > 0) {
x = parseFloat( x ); echo "<b>Consultancies:</b> {$stats['consultancy']} contracts, ".percent($stats['consultancy'],$stats['total']);
y = parseFloat( y ); echo "%<br/>";
return x - y; }
}; if ($stats['confidentialityContract']+$stats['confidentialityOutputs'] > 0) {
  $confidentialities = $stats['confidentialityContract']+$stats['confidentialityOutputs'];
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) { echo "<b>Confidentialities:</b> $confidentialities contracts, ".percent( $confidentialities,$stats['total'])."%";
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ echo "( {$stats['confidentialityContract']} on the contract, {$stats['confidentialityOutputs']} on the outputs)";
var x = a == "-" ? 0 : a.replace( /,/g, "" ); echo "<br/>";
var y = b == "-" ? 0 : b.replace( /,/g, "" ); }
  echo "<b>Procurement methods:</b> ";
/* Remove the currency sign */ if ($stats['open'] > 0) {
x = x.substring( 1 ); echo "Open {$stats['open']} contracts, ".percent($stats['open'],$stats['total']);
y = y.substring( 1 ); echo "%, ";
  }
/* Parse and return */ if ($stats['openSON'] > 0) {
x = parseFloat( x ); echo "Open via SON {$stats['openSON']} contracts, ".percent($stats['openSON'],$stats['total']);
y = parseFloat( y ); echo "%, ";
return y - x; }
}; if ($stats['prequalified'] > 0) {
$(document).ready(function() { echo "Prequalified {$stats['prequalified']} contracts, ".percent($stats['prequalified'],$stats['total']);
$('table').dataTable(); echo "%, ";
} ); }
</script> if ($stats['limited'] > 0) {
<link type="text/css" rel="stylesheet" href="style.css"> echo "limited {$stats['limited']} contracts, ".percent($stats['limited'],$stats['total']);
</head> echo "%, ";
<body><div id="doc3" class="yui-t4"> }
<div id="hd"> }
<h1> contract dashboard</h1>  
</div> // magic query modifiers
<div id="sitenav"> $agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING);
<a href="displayAgency.php">agencies</a> if ($agency != "")
<a href="displaySupplier.php">suppliers</a> $agencyQ = "agencyName = '" . $agency . "' AND ";
<a href="displayCategory.php">product/service categories</a>  
<a href="displayCalendar.php">time periods</a> $supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING);
| metrics | if ($supplier != "") {
<a href="displayProcurementMethod.php">procurement method</a> if ($supplier[0] !== '-') {
<a href="displayConfidentialities.php">contractual confidentiality</a> $supplierParts = explode("-", $supplier);
<a href="displayConsultancies.php">consultancies</a>  
<a href="displayAmendments.php">amendments</a> $supplierABN = array_shift($supplierParts);
<a href="displayMap.php">postcodes</a> $supplierName = "%" . implode('-',$supplierParts) . "%";
<div id="search"><form method="post" action="search.php" class="asholder">  
<label for="searchKeyword">search</label> $supplierQ = ' "supplierABN" = :supplierABN AND ';
<input type="text" id="searchKeyword" name="searchKeyword" value="" style="width:150px" /> } else {
<input type="hidden" id="searchID" name="searchID" value=""/><input type="submit" value="submit" /> $supplierName = "%" . substr($supplier,1) . "%";
</form></div> $supplierQ = ' "supplierName" ILIKE :supplierName AND ';
<script type="text/javascript"> }
  }
var options_xml = {  
script: function (input) { return "search_autosuggest.php?input="+input; }, $startYear = 2007;
varname:"input", $year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT);
callback: function (obj) { document.getElementById('searchID').value = obj.id; } if ($year != "") {
}; $yearQ = 'extract(year from "contractStart") = ' . $year . " AND ";
var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml); }
</script> $standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';
  $start = 0.0;
</div>  
<div id="bd" role="main"> function local_url() {
<div id="yui-main"> return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
<div class="yui-b"><div class="yui-g"> }
<?php  
$start = (float) array_sum(explode(' ',microtime())); function include_header($title) {
} global $start;
  ?>
function include_footer() { <!DOCTYPE html>
global $start; <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1"
$end = (float) array_sum(explode(' ',microtime())); xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
?> xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
</div> xmlns:gr="http://purl.org/goodrelations/v1#"
</div> xmlns:dc="http://purl.org/dc/terms/"
</div> xmlns:pc="http://purl.org/procurement#"
<div class="yui-b"> xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#"
Filter by:<ul> xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
<li>year xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#"
<ul><li>2008</li> prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
</ul> rdfs: http://www.w3.org/2000/01/rdf-schema#
</li> gr: http://purl.org/goodrelations/v1#
</ul> <br> </div> </div> dcterms: http://purl.org/dc/terms/
  pc: http://purl.org/procurement/public-contracts#
<?php cpv: http://purl.org/weso/pscs/cpv/2008/resource/
echo '<div id="ft"><p>'."Processing time: ". sprintf("%.4f", ($end-$start))." seconds".'</p></div>'; unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#
echo '</div> </body> </html>'; v: http://www.w3.org/2006/vcard/ns#
} payment: http://reference.data.gov.uk/def/payment#
include ("graphs.inc.php"); br: http://purl.org/business-register#
?> xsd: http://www.w3.org/2001/XMLSchema#
  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">
  <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 -->
  <!--[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>
  <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>
  <script type="text/javascript">
  $(document).ready(function()
  {
  //hide the all of the element with class msg_body
  $(".msg_body").hide();
  //toggle the componenet with class msg_body
  $(".msg_head").click(function()
  {
  $(this).next(".msg_body").slideToggle(600);
  });
  });
  </script>
   
  <style type="text/css" title="currentStyle">
  @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>
  <script type="text/javascript" charset="utf-8">
  jQuery.fn.dataTableExt.aTypes.unshift(
  function ( sData )
  {
  var sValidChars = "0123456789.-,";
  var Char;
   
  /* Check the numeric part */
  for ( i=1 ; i<sData.length ; i++ )
  {
  Char = sData.charAt(i);
  if (sValidChars.indexOf(Char) == -1)
  {
  return null;
  }
  }
   
  /* Check prefixed by currency */
  if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )
  {
  return 'currency';
  }
  return null;
  }
  );
  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) */
  var x = a == "-" ? 0 : a.replace( /,/g, "" );
  var y = b == "-" ? 0 : b.replace( /,/g, "" );
   
  /* Remove the currency sign */
  x = x.substring( 1 );
  y = y.substring( 1 );
   
  /* Parse and return */
  x = parseFloat( x );
  y = parseFloat( y );
  return x - y;
  };
   
  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, "" );
  var y = b == "-" ? 0 : b.replace( /,/g, "" );
   
  /* Remove the currency sign */
  x = x.substring( 1 );
  y = y.substring( 1 );
   
  /* Parse and return */
  x = parseFloat( x );
  y = parseFloat( y );
  return y - x;
  };
  $(document).ready(function() {
  $('table').dataTable();
  } );
  </script>
  <link type="text/css" rel="stylesheet" href="style.css">
  </head>
  <body>
  <div class="navbar">
  <div class="navbar-inner">
  <div class="container-fluid">