new stats box
new stats box

<?php <?php
if (php_sapi_name() != "cli") { if (php_sapi_name() != "cli") {
include_once ("../lib/common.inc.php"); include_once ("../lib/common.inc.php");
//auth(); //auth();
$contractNoticeFields = array( $contractNoticeFields = array(
"importFile", "importFile",
"agencyName", "agencyName",
"parentCN", "parentCN",
"CNID", "CNID",
"publishDate", "publishDate",
"amendDate", "amendDate",
"contractStart", "contractStart",
"contractEnd", "contractEnd",
"value", "value",
"description", "description",
"agencyID", "agencyID",
"category", "category",
"procurementMethod", "procurementMethod",
"atmID", "atmID",
"SONID", "SONID",
"confidentialityContract", "confidentialityContract",
"confidentialityContractReason", "confidentialityContractReason",
"confidentialityOutputs", "confidentialityOutputs",
"confidentialityOutputsReason", "confidentialityOutputsReason",
"consultancy", "consultancy",
"consultancyReason", "consultancyReason",
"amendmentReason", "amendmentReason",
"supplierName", "supplierName",
"supplierAddress", "supplierAddress",
"supplierCity", "supplierCity",
"supplierPostcode", "supplierPostcode",
"supplierCountry", "supplierCountry",
"supplierABNExempt", "supplierABNExempt",
"supplierABN", "supplierABN",
"contactBranch", "contactBranch",
"contactDivision", "contactDivision",
"contactPostcode" "contactPostcode"
); );
   
$contractNoticeInsertQ = 'INSERT INTO contractnotice ("' . implode('" , "', $contractNoticeFields) . '") VALUES ( '; $contractNoticeInsertQ = 'INSERT INTO contractnotice ("' . implode('" , "', $contractNoticeFields) . '") VALUES ( ';
foreach ($contractNoticeFields as $key => $f) { foreach ($contractNoticeFields as $key => $f) {
$contractNoticeInsertQ.= ($key == 0 ? "" : ", ") . "?"; $contractNoticeInsertQ.= ($key == 0 ? "" : ", ") . "?";
} }
$contractNoticeInsertQ.= ");"; $contractNoticeInsertQ.= ");";
$contractNoticeInsertQ = $conn->prepare($contractNoticeInsertQ); $contractNoticeInsertQ = $conn->prepare($contractNoticeInsertQ);
function processFile($fpath) { function processFile($fpath) {
global $conn, $contractNoticeFields, $contractNoticeInsertQ; global $conn, $contractNoticeFields, $contractNoticeInsertQ;
$success = 0; $success = 0;
$row = 1; $row = 1;
$handle = fopen($fpath, "r"); $handle = fopen($fpath, "r");
//"t" mode string translates windows line breaks to unix //"t" mode string translates windows line breaks to unix
//On the 15 April 2014 AusTender Contract Notice functionality changed to improve transparency. Two new fields have been introduced to capture the ‘Amendment Value’ and the ‘Amendment Start Date’. Where applicable, these fields will display on amendment records published after this date. //On the 15 April 2014 AusTender Contract Notice functionality changed to improve transparency. Two new fields have been introduced to capture the ‘Amendment Value’ and the ‘Amendment Start Date’. Where applicable, these fields will display on amendment records published after this date.
$datamapping0712 = array( $datamapping0712 = array(
"Agency" => "agencyName", "Agency" => "agencyName",
"Parent CN ID" => "parentCN", "Parent CN ID" => "parentCN",
"CN ID" => "CNID", "CN ID" => "CNID",
"Publish Date" => "publishDate", "Publish Date" => "publishDate",
"Amendment Date" => "amendDate", "Amendment Date" => "amendDate",
"Amendment Publish Date" => "amendDate", "Amendment Publish Date" => "amendDate",
"Status" => "", "Status" => "",
"StartDate" => "contractStart", "StartDate" => "contractStart",
"EndDate" => "contractEnd", "EndDate" => "contractEnd",
"Value" => "value", "Value" => "value",
"Description" => "description", "Description" => "description",
"Agency Ref Id" => "agencyID", "Agency Ref Id" => "agencyID",
"Agency Ref. ID" => "agencyID", "Agency Ref. ID" => "agencyID",
"Category" => "category", "Category" => "category",
"Procurement Method" => "procurementMethod", "Procurement Method" => "procurementMethod",
"ATM ID" => "atmID", "ATM ID" => "atmID",
"SON ID" => "SONID", "SON ID" => "SONID",
"Confidentiality - Contract" => "confidentialityContract", "Confidentiality - Contract" => "confidentialityContract",
"Confidentiality - Contract Reason(s)" => "confidentialityContractReason", "Confidentiality - Contract Reason(s)" => "confidentialityContractReason",
"Confidentiality - Outputs" => "confidentialityOutputs", "Confidentiality - Outputs" => "confidentialityOutputs",
"Confidentiality - Outputs Reason(s)" => "confidentialityOutputsReason", "Confidentiality - Outputs Reason(s)" => "confidentialityOutputsReason",
"Consultancy" => "consultancy", "Consultancy" => "consultancy",
"Consultancy Reason(s)" => "consultancyReason", "Consultancy Reason(s)" => "consultancyReason",
"Amendment Reason" => "amendmentReason", "Amendment Reason" => "amendmentReason",
"Supplier Name" => "supplierName", "Supplier Name" => "supplierName",
"Supplier Address" => "supplierAddress", "Supplier Address" => "supplierAddress",
"Supplier City" => "supplierCity", "Supplier City" => "supplierCity",
"Supplier Postcode" => "supplierPostcode", "Supplier Postcode" => "supplierPostcode",
"Supplier Country" => "supplierCountry", "Supplier Country" => "supplierCountry",
"Supplier ABNExempt" => "supplierABNExempt", "Supplier ABNExempt" => "supplierABNExempt",
"Supplier ABN" => "supplierABN", "Supplier ABN" => "supplierABN",
"Agency Branch" => "contactBranch", "Agency Branch" => "contactBranch",
"Agency Divison" => "contactDivision", "Agency Divison" => "contactDivision",
"Agency Postcode" => "contactPostcode", "Agency Postcode" => "contactPostcode",
"" => "" "" => ""
); );
   
   
while (($data = fgetcsv($handle, 1200, "\t")) !== false) { while (($data = fgetcsv($handle, 1200, "\t")) !== false) {
$num = count($data); $num = count($data);
if ($row == 3) { if ($row == 3) {
$headers = $data; $headers = $data;
} elseif ($row > 3) { } elseif ($row > 3) {
if ($num > count($datamapping0712)) { if ($num > count($datamapping0712)) {
die("<font color=red>Error in data import; data mapping fields out of bounds or changed</font><br>" . $fname . print_r($data)); die("<font color=red>Error in data import; data mapping fields out of bounds or changed</font><br>" . $fname . print_r($data));
} }
$contractNoticeInsert = Array(); $contractNoticeInsert = Array();
$supplierInsert = Array(); $supplierInsert = Array();
$agencyInsert = Array(); $agencyInsert = Array();
$contractNoticeInsert[] = $fpath; $contractNoticeInsert[] = $fpath;
$keys = array_keys($datamapping0712); $keys = array_keys($datamapping0712);
for ($c = 0; $c < $num; $c++) { for ($c = 0; $c < $num; $c++) {
$data[$c] = trim($data[$c], "="); $data[$c] = trim($data[$c], "=");
$data[$c] = trim($data[$c], "\""); $data[$c] = trim($data[$c], "\"");
if (in_array(($datamapping0712[$headers[$c]]), $contractNoticeFields)) { if (in_array(($datamapping0712[$headers[$c]]), $contractNoticeFields)) {
if (($datamapping0712[$headers[$c]]) == "parentCN" || ($datamapping0712[$headers[$c]]) == "CNID") { if (($datamapping0712[$headers[$c]]) == "parentCN" || ($datamapping0712[$headers[$c]]) == "CNID") {
$data[$c] = substr($data[$c], 2); // take off the "CN" prefix $data[$c] = substr($data[$c], 2); // take off the "CN" prefix
if ($data[$c] > 0 && $data[$c] != '0') { if ($data[$c] > 0 && $data[$c] != '0' && $data[$c] != '') {
$contractNoticeInsert[] = $data[$c]; $contractNoticeInsert[] = $data[$c];
} else { } else {
$contractNoticeInsert[] = null; $contractNoticeInsert[] = null;
} }
} elseif (($datamapping0712[$headers[$c]]) == "supplierABN") { } elseif (($datamapping0712[$headers[$c]]) == "supplierABN" || ($datamapping0712[$headers[$c]]) == "SONID") {
if ($data[$c] > 0 && $data[$c] != '0') { if ($data[$c] > 0 && $data[$c] != '0' && $data[$c] != '') {
$contractNoticeInsert[] = $data[$c]; $contractNoticeInsert[] = $data[$c];
} else { } else {
$contractNoticeInsert[] = null; $contractNoticeInsert[] = null;
} }
} elseif (($datamapping0712[$headers[$c]]) == "amendDate" || ($datamapping0712[$headers[$c]]) == "publishDate" || ($datamapping0712[$headers[$c]]) == "contractStart" || ($datamapping0712[$headers[$c]]) == "contractEnd") { } elseif (($datamapping0712[$headers[$c]]) == "amendDate" || ($datamapping0712[$headers[$c]]) == "publishDate" || ($datamapping0712[$headers[$c]]) == "contractStart" || ($datamapping0712[$headers[$c]]) == "contractEnd") {
$contractNoticeInsert[] = date('Y-m-d H:i:s', strtotime($data[$c])); $contractNoticeInsert[] = date('Y-m-d H:i:s', strtotime($data[$c]));
} else { } else {
if (strstr("\" =", $data[$c] > 0)) { if (strstr("\" =", $data[$c] > 0)) {
die("Invalid Description field" . $contractNoticeInsert); die("Invalid Description field" . $contractNoticeInsert);
} }
$colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($data[$c])); $colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($data[$c]));
   
$contractNoticeInsert[] = $colvalue; $contractNoticeInsert[] = $colvalue;
} }
} }
} }
flush(); flush();
$contractNoticeInsertQ->execute($contractNoticeInsert); $contractNoticeInsertQ->execute($contractNoticeInsert);
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[1] == 7 && strpos($errors[2], "duplicate key")) { if ($errors[1] == 7 && strpos($errors[2], "duplicate key")) {
} elseif ($errors[1] <= 0) { } elseif ($errors[1] <= 0) {
//print_r($errors); //print_r($errors);
$success = 1; $success = 1;
} else { } else {
foreach ($contractNoticeFields as $key => $cnf) { foreach ($contractNoticeFields as $key => $cnf) {
echo var_dump($contractNoticeInsert[$key]) . $cnf . "<br>"; echo var_dump($contractNoticeInsert[$key]) . $cnf . "<br>";
} }
echo $data[2] . " failed CN insert.<br>" . print_r($errors, true) . "<br> row $row <br><br>\n"; echo $data[2] . " failed CN insert.<br>" . print_r($errors, true) . "<br> row $row <br><br>\n";
} }
   
flush(); flush();
//echo "<hr>\n"; //echo "<hr>\n";
} }
$row++; $row++;
} }
fclose($handle); fclose($handle);
$contractNoticeInsertQ->closeCursor(); $contractNoticeInsertQ->closeCursor();
   
return $success; return $success;
} }
   
$path = 'data/'; $path = 'data/';
if ($_REQUEST["fname"] == "") { if ($_REQUEST["fname"] == "") {
echo "Get files from: https://www.tenders.gov.au/?event=public.reports.list<br>"; echo "Get files from: https://www.tenders.gov.au/?event=public.reports.list<br>";
$dhandle = opendir($path); $dhandle = opendir($path);
// define an array to hold the files // define an array to hold the files
$files = array(); $files = array();
if ($dhandle) { if ($dhandle) {
// loop through all of the files // loop through all of the files
while (false !== ($fname = readdir($dhandle))) { while (false !== ($fname = readdir($dhandle))) {
if (($fname != '.') && ($fname != '..')) { if (($fname != '.') && ($fname != '..')) {
$files[date("c", filemtime($path . $fname)) . md5($fname)] = $fname; $files[date("c", filemtime($path . $fname)) . md5($fname)] = $fname;
} }
} }
} }
ksort($files); ksort($files);
foreach ($files as $date => $fname) { foreach ($files as $date => $fname) {
echo "<a href=\"import.php?fname=$fname\">$fname</a>&nbsp;" . filesize($path . $fname) . "&nbsp;" . $date . "<br/>"; echo "<a href=\"import.php?fname=$fname\">$fname</a>&nbsp;" . filesize($path . $fname) . "&nbsp;" . $date . "<br/>";
} }
} else { } else {
$success = 0; $success = 0;
$fname = $_REQUEST["fname"]; $fname = $_REQUEST["fname"];
echo " ============== $fname ============== <br>"; echo " ============== $fname ============== <br>";
flush(); flush();
$success+= processFile($path . $fname, "contractnotice"); $success+= processFile($path . $fname, "contractnotice");
$success+= processFile($path . $fname, "agency"); $success+= processFile($path . $fname, "agency");
$success+= processFile($path . $fname, "supplier"); $success+= processFile($path . $fname, "supplier");
echo "<br> $success records successfully created"; echo "<br> $success records successfully created";
   
flush(); flush();
// run post import data processing // run post import data processing
// //
if ($success > 0) { if ($success > 0) {
$conn->exec("update datasets set \"lastUpdated\" = NOW() where title = 'Contract Notices'"); $conn->exec("update datasets set \"lastUpdated\" = NOW() where title = 'Contract Notices'");
/* echo "link amend<br>"; echo "link amend<br>";
include ("linkAmendments.php"); include ("linkAmendments.php");
echo "update UNSPSC<br>"; echo "update UNSPSC<br>";
include ("updateUNSPSC.php");*/ include ("updateUNSPSC.php");
} }
// cn // cn
   
// agency // agency
//include ("setAgencyStatus.php"); //include ("setAgencyStatus.php");
//include ("setAgencyURLABN.php"); //include ("setAgencyURLABN.php");
} }
} }
?> ?>
   
<?php <?php
   
include_once ("../lib/common.inc.php"); include_once ("../lib/common.inc.php");
auth();  
/* todo gaps /* todo gaps
Contract ID,Department,Portfolio,Division,Branch,Agency Ref,Contract Date,End Date,Value,Office PCode,Description,Procurement Desc,Confidentiality Reason,Consultancy,ANZSCC Code,ANSCC Desc,Supplier,Supplier Postal Addr,Supplier Suburb,Supplier State,Supplier Country,Supplier PCode,Supplier ABN,Supplier DUNS,Supplier ACN,S/O Reference Num Contract ID,Department,Portfolio,Division,Branch,Agency Ref,Contract Date,End Date,Value,Office PCode,Description,Procurement Desc,Confidentiality Reason,Consultancy,ANZSCC Code,ANSCC Desc,Supplier,Supplier Postal Addr,Supplier Suburb,Supplier State,Supplier Country,Supplier PCode,Supplier ABN,Supplier DUNS,Supplier ACN,S/O Reference Num
1694570,Department of Defence,Defence,NEW SOUTH WALES,RAN HMAS WATSON,1906458734 ,30-Jun-2007,30-Jun-2007,16083.96,2612,AIRLINE TICKETS,direct source,,No,731,Passenger transportation by air,QANTAS AIRWAYS LTD,PO Box PB 747,MASCOT,NSW,Australia,2020,16009661901,750512642,009661901 , 1694570,Department of Defence,Defence,NEW SOUTH WALES,RAN HMAS WATSON,1906458734 ,30-Jun-2007,30-Jun-2007,16083.96,2612,AIRLINE TICKETS,direct source,,No,731,Passenger transportation by air,QANTAS AIRWAYS LTD,PO Box PB 747,MASCOT,NSW,Australia,2020,16009661901,750512642,009661901 ,
   
*/ */
$contractNoticeFields = array( $contractNoticeFields = array(
"importFile", "importFile",
"agencyName", "agencyName",
"parentCN", "parentCN",
"CNID", "CNID",
"publishDate", "publishDate",
"amendDate", "amendDate",
"contractStart", "contractStart",
"contractEnd", "contractEnd",
"value", "value",
"description", "description",
"agencyID", "agencyID",
"categoryUNSPSC", "categoryUNSPSC",
"category", "category",
"procurementMethod", "procurementMethod",
"atmID", "atmID",
"SONID", "SONID",
  "SONPanelArrangement",
"confidentialityContract", "confidentialityContract",
"confidentialityContractReason", "confidentialityContractReason",
"confidentialityOutputs", "confidentialityOutputs",
"confidentialityOutputsReason", "confidentialityOutputsReason",
"consultancy", "consultancy",
"consultancyReason", "consultancyReason",
"amendmentReason", "amendmentReason",
"supplierName", "supplierName",
"supplierAddress", "supplierAddress",
"supplierCity", "supplierCity",
"supplierPostcode", "supplierPostcode",
"supplierCountry", "supplierCountry",
"supplierABNExempt", "supplierABNExempt",
"supplierABN", "supplierABN",
"contactBranch", "contactBranch",
"contactDivision", "contactDivision",
"contactPostcode" "contactPostcode"
); );
   
$contractNoticeInsertQ = 'INSERT INTO contractnotice ("' . implode('" , "', $contractNoticeFields) . '") VALUES ( '; $contractNoticeInsertQ = 'INSERT INTO contractnotice ("' . implode('" , "', $contractNoticeFields) . '") VALUES ( ';
foreach ($contractNoticeFields as $key => $f) { foreach ($contractNoticeFields as $key => $f) {
$contractNoticeInsertQ.= ($key == 0 ? "" : ", ") . "?"; $contractNoticeInsertQ.= ($key == 0 ? "" : ", ") . "?";
} }
$contractNoticeInsertQ.= ");"; $contractNoticeInsertQ.= ");";
$contractNoticeInsertQ = $conn->prepare($contractNoticeInsertQ); $contractNoticeInsertQ = $conn->prepare($contractNoticeInsertQ);
   
  $contractNoticeUpdateQ = 'UPDATE contractnotice SET ("' . implode('" , "', $contractNoticeFields) . '") = ( ';
  foreach ($contractNoticeFields as $key => $f) {
  $contractNoticeUpdateQ.= ($key == 0 ? "" : ", ") . "?";
  }
  $contractNoticeUpdateQ.= ') where "CNID" = ?;';
  $contractNoticeUpdateQ = $conn->prepare($contractNoticeUpdateQ);
   
function processFile($fpath) { function processFile($fpath) {
global $conn, $contractNoticeFields, $contractNoticeInsertQ; global $conn, $contractNoticeFields, $contractNoticeInsertQ, $contractNoticeUpdateQ;
$row = 1; $row = 1;
$success = 0; $success = 0;
ini_set('auto_detect_line_endings',TRUE); ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($fpath, "r"); $handle = fopen($fpath, "r");
//"t" mode string translates windows line breaks to unix //"t" mode string translates windows line breaks to unix
$datamapping0712 = array( $datamapping0712 = array(
   
// "_id" => "", // "_id" => "",
"Agency Name" => "agencyName", "Agency Name" => "agencyName",
"Parent Contract ID" => "parentCN", "Parent Contract ID" => "parentCN",
"Contract ID" => "CNID", "Contract ID" => "CNID",
"Publish Date" => "publishDate", "Publish Date" => "publishDate",
"AmendmentDate" => "amendDate", "Amendment Date" => "amendDate",
"Start Date" => "contractStart", "Start Date" => "contractStart",
"End Date" => "contractEnd", "End Date" => "contractEnd",
"Value" => "value", "Value" => "value",
"Description" => "description", "Description" => "description",
"Agency Ref ID" => "agencyID", "Agency Ref ID" => "agencyID",
"UNSPSC Code" => "categoryUNSPSC", "UNSPSC Code" => "categoryUNSPSC",
"Title" => "category", "UNSPSC Title" => "category",
"Procurement Method" => "procurementMethod", "Procurement Method" => "procurementMethod",
"TenderNumber" => "atmID", "ATM ID" => "atmID",
"SON ID" => "SONID", "SON ID" => "SONID",
  "Panel Arrangement" => "SONPanelArrangement",
"Confidentiality Contract Flag" => "confidentialityContract", "Confidentiality Contract Flag" => "confidentialityContract",
"Confidentiality Contract Reason" => "confidentialityContractReason", "Confidentiality Contract Reason" => "confidentialityContractReason",
"Confidentiality Outputs Flag" => "confidentialityOutputs", "Confidentiality Outputs Flag" => "confidentialityOutputs",
"Confidentiality Outputs Reason" => "confidentialityOutputsReason", "Confidentiality Outputs Reason" => "confidentialityOutputsReason",
"Consultancy Flag" => "consultancy", "Consultancy Flag" => "consultancy",
"Consultancy Reason" => "consultancyReason", "Consultancy Reason" => "consultancyReason",
"Amendment Reason" => "amendmentReason", "Amendment Reason" => "amendmentReason",
"Supplier Name" => "supplierName", "Supplier Name" => "supplierName",
"SupplierAddress" => "supplierAddress", "Supplier Address" => "supplierAddress",
"SupplierSuburb" => "supplierCity", "Supplier Suburb" => "supplierCity",
"Supplier Postcode" => "supplierPostcode", "Supplier Postcode" => "supplierPostcode",
"Supplier Country" => "supplierCountry", "Supplier Country" => "supplierCountry",
"Supplier ABN Exempt" => "supplierABNExempt", "Supplier ABN Exempt" => "supplierABNExempt",
"ABN" => "supplierABN", "Supplier ABN" => "supplierABN",
"Contact Name" => "", "Contact Name" => "",
"Contact Phone" => "", "Contact Phone" => "",
"Branch" => "contactBranch", "Branch" => "contactBranch",
"Division" => "contactDivision", "Division" => "contactDivision",
"Office Postcode" => "contactPostcode", "Office Postcode" => "contactPostcode",
   
); );
   
   
while (($data = fgetcsv($handle, 10000)) !== false) { while (($data = fgetcsv($handle, 10000)) !== false) {
//print_r($data); //print_r($data);
$num = count($data); $num = count($data);
if ($row == 1) { if ($row == 1) {
$headers = $data; $headers = $data;
} elseif ($row > 1) { } elseif ($row >30000 && $row < 59000) {
if ($num > count($datamapping0712)) { if ($num > count($datamapping0712)) {
die("<font color=red>Error in data import; data mapping fields out of bounds or changed $num > ".count($datamapping0712)."</font><br>" . $fpath . print_r($data)); die("<font color=red>Error in data import; data mapping fields out of bounds or changed $num > ".count($datamapping0712)."</font><br>" . $fpath . print_r($data));
} }
$contractNoticeInsert = Array(); $contractNoticeInsert = Array();
$supplierInsert = Array(); $supplierInsert = Array();
$agencyInsert = Array(); $agencyInsert = Array();
$contractNoticeInsert[] = $fpath; $contractNoticeInsert[] = $fpath;
$keys = array_keys($datamapping0712); $keys = array_keys($datamapping0712);
for ($c = 0; $c < $num; $c++) { for ($c = 0; $c < $num; $c++) {
$data[$c] = trim($data[$c], "="); $data[$c] = trim($data[$c], "=");
$data[$c] = trim($data[$c], "\""); $data[$c] = trim($data[$c], "\"");
if (in_array(($datamapping0712[$headers[$c]]), $contractNoticeFields)) { if (in_array(($datamapping0712[$headers[$c]]), $contractNoticeFields)) {
if (($datamapping0712[$headers[$c]]) == "parentCN" || ($datamapping0712[$headers[$c]]) == "CNID") { if (($datamapping0712[$headers[$c]]) == "parentCN" || ($datamapping0712[$headers[$c]]) == "CNID") {
$data[$c] = substr($data[$c], 2); // take off the "CN" prefix $data[$c] = substr($data[$c], 2); // take off the "CN" prefix
if ($data[$c] > 0 && $data[$c] != '0') { if ($data[$c] > 0 && $data[$c] != '0') {
$contractNoticeInsert[] = $data[$c]; $contractNoticeInsert[] = $data[$c];
} else { } else {
$contractNoticeInsert[] = null; $contractNoticeInsert[] = null;
} }
} elseif (($datamapping0712[$headers[$c]]) == "supplierABN") { } elseif (($datamapping0712[$headers[$c]]) == "supplierABN") {
if ($data[$c] > 0 && $data[$c] != '0') { if ($data[$c] > 0 && $data[$c] != '0') {
$contractNoticeInsert[] = $data[$c]; $contractNoticeInsert[] = $data[$c];
} else { } else {
$contractNoticeInsert[] = null; $contractNoticeInsert[] = null;
} }
} elseif (($datamapping0712[$headers[$c]]) == "amendDate" || ($datamapping0712[$headers[$c]]) == "publishDate" || ($datamapping0712[$headers[$c]]) == "contractStart" || ($datamapping0712[$headers[$c]]) == "contractEnd") { } elseif (($datamapping0712[$headers[$c]]) == "amendDate" || ($datamapping0712[$headers[$c]]) == "publishDate" || ($datamapping0712[$headers[$c]]) == "contractStart" || ($datamapping0712[$headers[$c]]) == "contractEnd") {
//echo $datamapping0712[$headers[$c]]." ".$data[$c]." ".date('Y-m-d H:i:s', strtotime(str_replace('/','-',$data[$c])))."\n"; //echo $datamapping0712[$headers[$c]]." ".$data[$c]." ".date('Y-m-d H:i:s', strtotime(str_replace('/','-',$data[$c])))."\n";
$contractNoticeInsert[] = date('Y-m-d H:i:s', strtotime(str_replace('/','-',$data[$c]))); $contractNoticeInsert[] = date('Y-m-d H:i:s', strtotime(str_replace('/','-',$data[$c])));
} else { } else {
if (strstr("\" =", $data[$c] > 0)) { if (strstr("\" =", $data[$c] > 0)) {
die("Invalid Description field" . $contractNoticeInsert); die("Invalid Description field" . $contractNoticeInsert);
} }
$colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($data[$c])); $colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($data[$c]));
   
$contractNoticeInsert[] = $colvalue; $contractNoticeInsert[] = $colvalue;
} }
} }
} }
flush(); flush();
// print_r($contractNoticeInsert); // print_r($contractNoticeInsert);
$contractNoticeInsertQ->execute($contractNoticeInsert); /* $contractNoticeInsertQ->execute($contractNoticeInsert);
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[1] == 7 && strpos($errors[2], "duplicate key")) { if ($errors[1] == 7 && strpos($errors[2], "duplicate key")) {
// echo "dupe {$data[2]} row $row <br>\n"; echo "dupe {$data[2]} row $row <br>\n";
} else { } else {
if ($errors[1] == 0) { if ($errors[1] == 0) {
echo "success {$data[2]} row $row <br>\n"; echo "success insert {$data[2]} row $row <br>\n";
$success++; $success++;
} else { } else {
foreach ($contractNoticeFields as $key => $cnf) { foreach ($contractNoticeFields as $key => $cnf) {
echo var_dump($contractNoticeInsert[$key]) . $cnf . "<br>"; echo var_dump($contractNoticeInsert[$key]) . $cnf . "<br>";
} }
echo $data[2] . " failed CN insert.<br>" . print_r($errors, true) . "<br> row $row <br><br>\n"; echo $data[2] . " failed CN insert.<br>" . print_r($errors, true) . "<br> row $row <br><br>\n";
} }
} }*/
   
   
  $contractNoticeUpdate = $contractNoticeInsert;
  $contractNoticeUpdate[] = $data[2];
  #var_dump($contractNoticeUpdate);
  /*$i =0;
  while($i < 35) {
  echo "{$contractNoticeFields[$i]} : {$contractNoticeUpdate[$i]}<br/>";
  $i++;
  }*/
  $contractNoticeUpdateQ->execute($contractNoticeUpdate);
  $errors = $conn->errorInfo();
   
  if ($errors[1] == 0) {
  // echo "success update {$data[2]} row $row <br>\n";
  $success++;
  } else {
  foreach ($contractNoticeFields as $key => $cnf) {
  echo var_dump($contractNoticeUpdate[$key]) . $cnf . "<br>";
  }
  echo $data[2] . " failed CN update.<br>" . print_r($errors, true) . "<br> row $row <br><br>\n";
  }
   
flush(); flush();
  //die('endlol');
//echo "<hr>\n"; //echo "<hr>\n";
} }
$row++; $row++;
} }
fclose($handle); fclose($handle);
$contractNoticeInsertQ->closeCursor(); $contractNoticeInsertQ->closeCursor();
   
return $success; return $success;
} }
   
$path = 'datagovdata/'; $path = 'datagovdata/';
if ($_REQUEST["fname"] == "" && $argv[1] == "") { if ($_REQUEST["fname"] == "" && $argv[1] == "") {
echo "Get files from: https://www.tenders.gov.au/?event=public.reports.list<br>"; echo "Get files from: https://www.tenders.gov.au/?event=public.reports.list<br>";
$dhandle = opendir($path); $dhandle = opendir($path);
// define an array to hold the files // define an array to hold the files
$files = array(); $files = array();
if ($dhandle) { if ($dhandle) {
// loop through all of the files // loop through all of the files
while (false !== ($fname = readdir($dhandle))) { while (false !== ($fname = readdir($dhandle))) {
if (($fname != '.') && ($fname != '..')) { if (($fname != '.') && ($fname != '..')) {
$files[date("c", filemtime($path . $fname)) . md5($fname)] = $fname; $files[date("c", filemtime($path . $fname)) . md5($fname)] = $fname;
} }
} }
} }
ksort($files); ksort($files);
foreach ($files as $date => $fname) { foreach ($files as $date => $fname) {
echo "<a href=\"importdatagov.php?fname=$fname\">$fname</a>&nbsp;" . filesize($path . $fname) . "&nbsp;" . $date . "<br/>"; echo "<a href=\"importdatagov.php?fname=$fname\">$fname</a>&nbsp;" . filesize($path . $fname) . "&nbsp;" . $date . "<br/>";
} }
} else { } else {
$success = 0; $success = 0;
$fname = $_REQUEST["fname"]; $fname = $_REQUEST["fname"];
if ($argv[1] != "") $fname = $argv[1]; if ($argv[1] != "") $fname = $argv[1];
echo " ============== $fname ============== <br>"; echo " ============== $fname ============== <br>";
flush(); flush();
$success+= processFile($path . $fname, "contractnotice"); $success+= processFile($path . $fname, "contractnotice");
$success+= processFile($path . $fname, "agency"); $success+= processFile($path . $fname, "agency");
$success+= processFile($path . $fname, "supplier"); $success+= processFile($path . $fname, "supplier");
echo "<br> $success records successfully created"; echo "<br> $success records successfully created";
   
flush(); flush();
// run post import data processing // run post import data processing
// //
if ($success > 0) { if ($success > 0) {
$conn->exec("update datasets set \"lastUpdated\" = NOW() where title = 'Contract Notices'"); $conn->exec("update datasets set \"lastUpdated\" = NOW() where title = 'Contract Notices'");
echo "link amend<br>"; /*echo "link amend<br>";
include ("linkAmendments.php"); include ("linkAmendments.php");
echo "update UNSPSC<br>"; echo "update UNSPSC<br>";
include ("updateUNSPSC.php"); include ("updateUNSPSC.php");*/
} }
// cn // cn
   
// agency // agency
//include ("setAgencyStatus.php"); //include ("setAgencyStatus.php");
//include ("setAgencyURLABN.php"); //include ("setAgencyURLABN.php");
   
} }
?> ?>
   
<?php <?php
include_once ("../lib/common.inc.php"); include_once ("../lib/common.inc.php");
if (php_sapi_name() != "cli") {  
   
//auth();  
}  
$query = 'update contractnotice set "parentCN" = null where "parentCN" = \'0\''; $query = 'update contractnotice set "parentCN" = null where "parentCN" = \'0\'';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$query = 'update contractnotice set "supplierABN" = null where "supplierABN" = \'0\''; $query = 'update contractnotice set "supplierABN" = null where "supplierABN" = \'0\'';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$query = 'SELECT c."CNID",c."parentCN",p."childCN" FROM contractnotice as c LEFT OUTER JOIN contractnotice as p on c."parentCN" = p."CNID" $query = 'SELECT c."CNID",c."parentCN",p."childCN" FROM contractnotice as c LEFT OUTER JOIN contractnotice as p on c."parentCN" = p."CNID"
WHERE WHERE
c."parentCN" IS NOT NULL AND p."childCN" IS NULL '; c."parentCN" IS NOT NULL AND p."childCN" IS NULL ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
if ($row['parentCN'] != 0) { if ($row['parentCN'] != 0) {
$conn->exec('UPDATE contractnotice SET "childCN" = \'' . $conn->exec('UPDATE contractnotice SET "childCN" = \'' .
$row['CNID'] . '\' where "CNID" = \'' . $row['CNID'] . '\' where "CNID" = \'' .
$row['parentCN'] . '\';'); $row['parentCN'] . '\';');
echo 'UPDATE contractnotice SET "childCN" = \'' . echo 'UPDATE contractnotice SET "childCN" = \'' .
$row['CNID'] . '\' where "CNID" = \'' . $row['CNID'] . '\' where "CNID" = \'' .
$row['parentCN'] . '\';'; $row['parentCN'] . '\';';
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[1] == 7 || $errors[1] ==0) if ($errors[1] == 7 || $errors[1] ==0)
echo $row['CNID'] . " linked to parent " . $row['parentCN'] . echo $row['CNID'] . " linked to parent " . $row['parentCN'] .
"<br>\n"; "<br>\n";
else print_r($errors); else print_r($errors);
} }
} }
// also need to eliminate CN 100528/100529 - check for double parent CNs with no childCN, latest sequent CN id keeps childCN = 0 // also need to eliminate CN 100528/100529 - check for double parent CNs with no childCN, latest sequent CN id keeps childCN = 0
$query = 'SELECT "parentCN", array_agg("CNID"), count(*) from contractnotice WHERE "parentCN" IN $query = 'SELECT "parentCN", array_agg("CNID"), count(*) from contractnotice WHERE "parentCN" IN
( (
SELECT "parentCN" SELECT "parentCN"
FROM contractnotice FROM contractnotice
GROUP BY "parentCN" GROUP BY "parentCN"
HAVING COUNT(*) > 1 HAVING COUNT(*) > 1
AND "parentCN" IS NOT NULL AND "parentCN" IS NOT NULL
) )
AND "childCN" IS NULL AND "childCN" IS NULL
GROUP BY "parentCN" having count(*) > 1'; GROUP BY "parentCN" having count(*) > 1';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$cnids = explode(",",str_replace(Array("{","}"),"",$row['array_agg'])); $cnids = explode(",",str_replace(Array("{","}"),"",$row['array_agg']));
$last_cnid = array_pop($cnids); $last_cnid = array_pop($cnids);
foreach ($cnids as $cnid) { foreach ($cnids as $cnid) {
$conn->exec('UPDATE contractnotice SET "childCN" = \'' . $conn->exec('UPDATE contractnotice SET "childCN" = \'' .
$last_cnid . '\' where "CNID" = \'' . $last_cnid . '\' where "CNID" = \'' .
$cnid . '\';'); $cnid . '\';');
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[1] == 7 || $errors[1] ==0) if ($errors[1] == 7 || $errors[1] ==0)
echo $cnid . " linked to latest child " . $last_cnid . echo $cnid . " linked to latest child " . $last_cnid .
"<br>\n"; "<br>\n";
else print_r($errors); else print_r($errors);
} }
} }
   
?> ?>
   
<?php <?php
   
include_once ("./lib/common.inc.php"); include_once("./lib/common.inc.php");
if ($_REQUEST['agency']) { if ($_REQUEST['agency']) {
   
$agency = htmlentities(strip_tags($_REQUEST['agency'])); $agency = htmlentities(strip_tags($_REQUEST['agency']));
include_header($agency); include_header($agency);
echo '<center><h1>'.$agency.'</h1></center>'; echo '<center><h1>' . $agency . '</h1></center>';
agencySuppliersGraph($agency); $query = 'SELECT category, min("categoryUNSPSC") AS "categoryUNSPSC", count(*) AS count, sum(value) AS value FROM contractnotice
// MethodCountGraph($agency); WHERE "agencyName" LIKE :agency AND ' . " " . $standardQ . ' ' . $yearQ . ' GROUP BY category ORDER BY count(*) DESC LIMIT 10';
// CnCGraph($agency);  
// MethodValueGraph($agency);  
/* biggest contracts  
spending by year  
spending by industry/category  
spending by supplier  
   
spread procurement methods (stacked bar graph)  
+ percent consultancies + percent confidential (bar graph)  
   
Average value by procurement type  
   
--- info  
website, procurement plan, annual reports  
Breakdown of divisions/branches  
Breakdown percentage,number,value by procurement type  
Histograph, overlaying number value reported per week over X years  
Compliance statistics: amendments, delay in reporting average and number completely late */  
   
$query = 'SELECT "CNID", "description", "value", "agencyName", "category",  
"contractStart", "supplierName"  
FROM contractnotice  
WHERE ' .$yearQ . ' "agencyName" like :agency and "childCN" is null  
ORDER BY "value" DESC limit 100';  
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":agency", $agency); $query->bindParam(":agency", $agency);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
echo "<table> <thead> $query = '
  SELECT
  sum((consultancy = \'Yes\')::int) AS consultancy,
  sum(("confidentialityContract" = \'Yes\')::int) AS "confidentialityContract",
  sum(("confidentialityOutputs" = \'Yes\')::int) AS "confidentialityOutputs",
  sum((("procurementMethod" = \'Open\' OR "procurementMethod" = \'Open tender\') AND "SONID" IS null)::int) AS open,
  sum((("procurementMethod" = \'Open\' OR "procurementMethod" = \'Open tender\') AND "SONID" IS NOT null)::int) AS "openSON",
  sum(("procurementMethod" = \'Prequalified tender\' OR "procurementMethod" = \'Select\')::INT) AS prequalified,
  sum(("procurementMethod" = \'Direct\' OR "procurementMethod" = \'Limited tender\')::int) AS limited,
  COUNT(*) AS total
  FROM contractnotice
  WHERE "supplierABN" = \'51194660183\'
  ';
  /*
  * Procurement method in text, seperate Open via SON from Open
  * Consultancies, Confidentialities percentage
  Compliance statistics: amendments, delay in reporting average and number completely late */
   
   
  echo "<h3>Categories</h3><table> <thead>
  <tr>
  <th>Category</th>
  <th>Contracts Count</th>
  <th>Total Contract Value</th>
  </tr>
  </thead>";
  foreach ($query->fetchAll() as $row) {
  setlocale(LC_MONETARY, 'en_US');
  $value = number_format(doubleval($row['value']), 2);
  $category = urlencode($row['category']);
  echo("<tr>
  <td><B><a href='displayCategory.php?category=$category'>{$row['category']}</a></b></td>
  <td>{$row['count']}</td>
  <td>\$$value</td>
  </tr>");
  }
  echo "</table><br/>";
   
  $query = 'SELECT contractnotice."SONID", min(title) AS title, count(*), sum(value) AS value FROM contractnotice INNER JOIN standingoffers ON contractnotice."SONID" = standingoffers."SONID"
  WHERE "agencyName" LIKE :agency AND ' . " " . $standardQ . ' ' . $yearQ . 'AND contractnotice."SONID" != \'\' GROUP BY contractnotice."SONID"';
  $query = $conn->prepare($query);
  $query->bindParam(":agency", $agency);
  $query->execute();
  databaseError($conn->errorInfo());
  $sonrows = "";
  foreach ($query->fetchAll() as $row) {
  setlocale(LC_MONETARY, 'en_US');
  $value = number_format(doubleval($row['value']), 2);
  $sonrows .= "<tr>
  <td><B><a href=\"displaySON.php?SONID={$row['SONID']}\">{$row['title']}</a></b></td>
  <td>{$row['count']}</td>
  <td>\$$value</td>
  </tr>";
  }
  if (strlen($sonrows) > 1) {
  echo "<h3>Standing Offers/Panels</h3><table> <thead>
  <tr>
  <th>Standing Offer</th>
  <th>Contracts Count</th>
  <th>Total Contract Value</th>
  </tr>
  </thead>$sonrows</table><br/>";
  }
   
  $query = 'SELECT SUM(value) AS value, count(*), text_mode("supplierName") "supplierName", min("supplierABN") AS "supplierABN", (
  CASE WHEN "supplierABN" != 0 THEN "supplierABN"::TEXT ELSE lower("supplierName") END) AS "supplierID" FROM contractnotice
  WHERE ' . $yearQ . " " . $standardQ . ' AND "agencyName" LIKE :agency
  GROUP BY "supplierID" ORDER BY "value" DESC';
  $query = $conn->prepare($query);
  $query->bindParam(":agency", $agency);
  $query->execute();
  databaseError($conn->errorInfo());
  echo "<h3>Suppliers</h3><table> <thead>
  <tr>
  <th>Supplier</th>
  <th>Contracts Count</th>
  <th>Total Contract Value</th>
  </tr>
  </thead>";
  foreach ($query->fetchAll() as $row) {
  setlocale(LC_MONETARY, 'en_US');
  $value = number_format(doubleval($row['value']), 2);
  $supplierID = $row['supplierABN'] . '-' . urlencode($row['supplierName']);
  echo("<tr>
  <td><B><a href=\"displaySupplier.php?supplier=$supplierID\" >{$row['supplierName']}</a></b></td>
  <td>{$row['count']}</td>
  <td>\$$value</td>
  </tr>");
  }
  echo "</table><br/>";
   
  $query = 'SELECT "CNID", "description", "value", "agencyName", "category",
  "contractStart", "supplierName"
  FROM contractnotice
  WHERE ' . $yearQ . ' "agencyName" LIKE :agency AND "childCN" IS NULL
  ORDER BY "value" DESC LIMIT 100';
  $query = $conn->prepare($query);
  $query->bindParam(":agency", $agency);
  $query->execute();
  databaseError($conn->errorInfo());
   
  echo "<h3>Contracts</h3><table> <thead>
<tr> <tr>
<th>Contract Notice Number</th> <th>Contract Notice Number</th>
<th>Contract Description</th> <th>Contract Description</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
<th>Agency</th> <th>Agency</th>
<th>Contract Start Date</th> <th>Contract Start Date</th>
<th>Supplier</th> <th>Supplier</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value']), 2); $value = number_format(doubleval($row['value']), 2);
echo ("<tr> echo("<tr>
<td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td> <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>
<td><b>{$row['description']}</b></a></td> <td><b>{$row['description']}</b></a></td>
<td>\$$value</td><td>{$row['agencyName']}</td> <td>\$$value</td><td>{$row['agencyName']}</td>
<td>{$row['contractStart']}</td> <td>{$row['contractStart']}</td>
<td>{$row['supplierName']}</td> <td>{$row['supplierName']}</td>
</tr>"); </tr>");
} }
echo "</table>"; echo "</table>";
} else { } else {
/* /*
split by portfolio split by portfolio
*/ */
include_header("Agencies"); include_header("Agencies");
agenciesGraph(); agenciesGraph();
$query = 'SELECT SUM("value"), "agencyName" $query = 'SELECT SUM("value"), "agencyName"
FROM contractnotice FROM contractnotice
WHERE ' .$yearQ . ' "childCN" is null WHERE ' . $yearQ . ' "childCN" IS NULL
GROUP BY "agencyName" '; GROUP BY "agencyName" ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
echo "<table> <thead> echo "<table> <thead>
<tr> <tr>
<th>Agency</th> <th>Agency</th>
<th>Total Contracts Value</th> <th>Total Contracts Value</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row[0]), 2); $value = number_format(doubleval($row[0]), 2);
$agency = stripslashes($row[1]); $agency = stripslashes($row[1]);
echo ("<tr><td><b><a href=\"displayAgency.php?agency={$agency}\">{$agency}</a></b></td><td>\$$value</td></tr>\n"); echo("<tr><td><b><a href=\"displayAgency.php?agency={$agency}\">{$agency}</a></b></td><td>\$$value</td></tr>\n");
} }
echo "</table>"; echo "</table>";
} }
include_footer(); include_footer();
?> ?>
   
<?php <?php
   
include_once("./lib/common.inc.php"); include_once("./lib/common.inc.php");
/* /*
   
   
agencies that use alot of consultacies agencies that use alot of consultacies
suppliers that provide alot suppliers that provide alot
how much is spent overall per year how much is spent overall per year
*/ */
   
include_header("Consultancies"); include_header("Consultancies");
$query = ' $query = '
SELECT SUM(value) as value, count(*), min("supplierName"), unnest(string_to_array("consultancyReason",\';\')) reason SELECT SUM(value) as value, count(*), text_mode("supplierName"), unnest(string_to_array("consultancyReason",\';\')) reason
FROM contractnotice where ' .$yearQ . ' "consultancy" = \'Yes\' and "childCN" is null FROM contractnotice where ' .$yearQ . ' "consultancy" = \'Yes\' and "childCN" is null
GROUP BY "supplierABN",reason order by value desc GROUP BY "supplierABN",reason order by value desc
'; ';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
echo "<table>"; echo "<table>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row[0]),2); $value = number_format(doubleval($row[0]),2);
echo ("<tr><td><b>{$row[2]}</b></td><td>{$row[3]}</td><td>{$row[1]} contracts</td><td>\$$value</td></tr>"); echo ("<tr><td><b>{$row[2]}</b></td><td>{$row[3]}</td><td>{$row[1]} contracts</td><td>\$$value</td></tr>");
} }
echo "</table>"; echo "</table>";
include_footer(); include_footer();
?> ?>
   
   
   
<?php <?php
   
include_once("./lib/common.inc.php"); include_once("./lib/common.inc.php");
$query = 'SELECT * $query = 'SELECT *
FROM contractnotice FROM contractnotice
WHERE "CNID" = :CNID LIMIT 1'; WHERE "CNID" = :CNID LIMIT 1';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":CNID", $_REQUEST['CNID']); $query->bindParam(":CNID", $_REQUEST['CNID']);
$query->execute(); $query->execute();
$contractResult = $query->fetch(PDO::FETCH_ASSOC); $contractResult = $query->fetch(PDO::FETCH_ASSOC);
if (!$contractResult) { if (!$contractResult) {
header("Status: 404 Not Found"); header("Status: 404 Not Found");
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
include_header("Contract Not Found"); include_header("Contract Not Found");
echo "<center><h1>No Contract Notice with that ID found</h1></center>"; echo "<center><h1>No Contract Notice with that ID found</h1></center>";
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
} else { } else {
$description = ucsmart($contractResult["description"]); $description = ucsmart($contractResult["description"]);
include_header($description); include_header($description);
echo '<center><h1>'.$description.'</h1></center> echo '<center><h1>'.$description.'</h1></center>
<div about="http://contracts.disclosurelo.gs/displayContract.php?CNID='.$contractResult["CNID"].'" typeof="pc:Contract">'; <div about="http://contracts.disclosurelo.gs/displayContract.php?CNID='.$contractResult["CNID"].'" typeof="pc:Contract">';
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
foreach (array_filter($contractResult) as $key => $value) { foreach (array_filter($contractResult) as $key => $value) {
echo "<b>$key</b>&nbsp;"; echo "<b>$key</b>&nbsp;";
switch ($key) { switch ($key) {
case "supplierABN": case "supplierABN":
break; break;
case "supplierName": case "supplierName":
echo ' echo '
<a href="displaySupplier.php?supplier=' . $contractResult['supplierABN'] . '-' . urlencode($contractResult['supplierName']) . '"> <a href="displaySupplier.php?supplier=' . $contractResult['supplierABN'] . '-' . urlencode($contractResult['supplierName']) . '">
<span rel="pc:contractingAuthority" typeof="gr:BusinessEntity"> <span rel="pc:contractingAuthority" typeof="gr:BusinessEntity">
<span property="gr:legalName">' <span property="gr:legalName">'
. $contractResult['supplierName'] . . $contractResult['supplierName'] .
'</span>'. '</span>'.
(isset($contractResult['supplierABN']) && $contractResult['supplierABN'] != '' ? ' (ABN: <span property="br:officialNumber" lang="">'.$contractResult['supplierABN'].'</span>)' : '') (isset($contractResult['supplierABN']) && $contractResult['supplierABN'] != '' ? ' (ABN: <span property="br:officialNumber" lang="">'.$contractResult['supplierABN'].'</span>)' : '')
.'</span></a>'; .'</span></a>';
break; break;
case "CNID": case "CNID":
echo '<span property="pc:referenceNumber" lang="">'.$value.'</span>'; echo '<span property="pc:referenceNumber" lang="">'.$value.'</span>';
break;  
case "categoryUNSPSC":  
break; break;
case "category": case "category":
echo '<span rel="pc:mainObject" resource="[unspsc:'.$contractResult["categoryUNSPSC"].']">'.$value.'</span>'; echo '<span rel="pc:mainObject" resource="[unspsc:'.$contractResult["categoryUNSPSC"].']">'.$value.'</span>';
break; break;
case "SONID": case "SONID":
echo '<a href="displaySON.php?SONID=' . urlencode($value) . '">' . $value . "</a>"; echo '<a href="displaySON.php?SONID=' . urlencode($value) . '">' . $value . "</a>";
break; break;
case "agencyName": case "agencyName":
echo '<a href="displayAgency.php?agency=' . urlencode($value) . '">' . $value . "</a>"; echo '<a href="displayAgency.php?agency=' . urlencode($value) . '">' . $value . "</a>";
break; break;
case "contractStart": case "contractStart":
echo '<span property="pc:startDate" content="'.$value.'" datatype="xsd:date">'.$value.'</span>'; echo '<span property="pc:startDate" content="'.$value.'" datatype="xsd:date">'.$value.'</span>';
break; break;
case "contractEnd": case "contractEnd":
echo '<span property="pc:endDate" content="'.$value.'" datatype="xsd:date">'.$value.'</span>'; echo '<span property="pc:endDate" content="'.$value.'" datatype="xsd:date">'.$value.'</span>';
break; break;
case "value": case "value":
echo '<span rel="pc:agreedPrice" typeof="gr:PriceSpecification"> echo '<span rel="pc:agreedPrice" typeof="gr:PriceSpecification">
<span property="gr:hasCurrency" content="AUD" lang="">$ </span> <span property="gr:hasCurrency" content="AUD" lang="">$ </span>
<span property="gr:hasCurrencyValue" content="'.doubleval($value).'" datatype="xsd:float">' . number_format(doubleval($value), 2) <span property="gr:hasCurrencyValue" content="'.doubleval($value).'" datatype="xsd:float">' . number_format(doubleval($value), 2)
.'</span></span>'; .'</span></span>';
break; break;
case "description": case "description":
echo '<span property="dcterms:title">'.$value.'</span>'; echo '<span property="dcterms:title">'.$value.'</span>';
break; break;
default: default:
echo str_replace(" ", "<br>", ucsmart($value)); echo str_replace(" ", "<br>", ucsmart($value));
} }
echo "<br>\n"; echo "<br>\n";
} }
echo '<br><a href="https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN' . $_REQUEST['CNID'] . '"> View original record @ tenders.gov.au</a><br> echo '<br><a href="https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN' . $_REQUEST['CNID'] . '"> View original record @ tenders.gov.au</a><br>
</div>'; </div>';
   
/*$query = $solr_client->createMoreLikeThis(); /*$query = $solr_client->createMoreLikeThis();
   
$query->setQuery('id:'.$_REQUEST['CNID']); $query->setQuery('id:'.$_REQUEST['CNID']);
$query->setMltFields('description'); $query->setMltFields('description');
$query->setMinimumDocumentFrequency(1); $query->setMinimumDocumentFrequency(1);
$query->setMinimumTermFrequency(1); $query->setMinimumTermFrequency(1);
$query->setInterestingTerms('description'); $query->setInterestingTerms('description');
$query->setMatchInclude(true); $query->setMatchInclude(true);
   
// this executes the query and returns the result // this executes the query and returns the result
$resultset = $solr_client->select($query); $resultset = $solr_client->select($query);
   
// display the total number of documents found by solr // display the total number of documents found by solr
echo 'Found '.$resultset->getNumFound(). ' similar results: <table>'; echo 'Found '.$resultset->getNumFound(). ' similar results: <table>';
   
   
foreach ($resultset as $row) { foreach ($resultset as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value'][0]), 2); $value = number_format(doubleval($row['value'][0]), 2);
echo ("<tr> echo ("<tr>
<td><a href=\"displayContract.php?CNID={$row['id']}\">{$row['id']}</a></td> <td><a href=\"displayContract.php?CNID={$row['id']}\">{$row['id']}</a></td>
<td><b>{$row['description'][0]}</b></a></td> <td><b>{$row['description'][0]}</b></a></td>
<td>\$$value</td><td>{$row['agencyName'][0]}</td> <td>\$$value</td><td>{$row['agencyName'][0]}</td>
<td>{$row['contractStart'][0]}</td> <td>{$row['contractStart'][0]}</td>
<td>{$row['supplierName'][0]}</td> <td>{$row['supplierName'][0]}</td>
</tr>"); </tr>");
} }
echo "</table>";*/ echo "</table>";*/
   
   
$query = 'SELECT * FROM heuristic_results where "CNID" = :CNID'; $query = 'SELECT * FROM heuristic_results where "CNID" = :CNID';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$agencyName = $input . '%'; $agencyName = $input . '%';
$query->bindParam(":CNID", $_REQUEST['CNID']); $query->bindParam(":CNID", $_REQUEST['CNID']);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $r) { foreach ($query->fetchAll() as $r) {
echo "<b>{$r['heuristic_name']}</b>: {$r['heuristic_value']} (raw value: {$r['raw_value']}, mean: {$r['mean']}, stddev: {$r['stddev']})<br>"; echo "<b>{$r['heuristic_name']}</b>: {$r['heuristic_value']} (raw value: {$r['raw_value']}, mean: {$r['mean']}, stddev: {$r['stddev']})<br>";
} }
} }
include_footer(); include_footer();
?> ?>
   
<?php <?php
include_once("./lib/common.inc.php"); include_once("./lib/common.inc.php");
   
// TODO // TODO
// color suppliers based on value? static list of high value suppliers? // color suppliers based on value? static list of high value suppliers?
// TODO sigma // TODO sigma
// link on contracts site? // link on contracts site?
// allow higher zoom levels // allow higher zoom levels
// describe methodology and yellow/red color meaning, creative commons attribution // describe methodology and yellow/red color meaning, creative commons attribution
$used_node_ids = Array(); $used_node_ids = Array();
$included_panel_ids = Array(); $included_panel_ids = Array();
$used_edge_ids = Array(); $used_edge_ids = Array();
function add_node($id, $label, $parent = "", $panel = false) function add_node($id, $label, $parent = "", $panel = false)
{ {
global $used_node_ids; global $used_node_ids;
if (!in_array($id, $used_node_ids)) { if (!in_array($id, $used_node_ids)) {
echo "<node id='" . urlencode($id) . "' label=\"" . str_replace('"','',str_replace("&", "and", $label)) . "\" " . ($parent != "" ? "pid='$parent'><viz:size value='" . rand(1, 50) . "'/>" : "><viz:size value='2'/>") echo "<node id='" . urlencode($id) . "' label=\"" . str_replace('"','',str_replace("&", "and", $label)) . "\" " . ($parent != "" ? "pid='$parent'><viz:size value='" . rand(1, 50) . "'/>" : "><viz:size value='2'/>")
. "<viz:color b='" . ($panel ? 0 : 0) . "' g='" . ($panel ? 0 : 255) . "' r='" . ($panel ? 255 : 255) . "'/>"; . "<viz:color b='" . ($panel ? 0 : 0) . "' g='" . ($panel ? 0 : 255) . "' r='" . ($panel ? 255 : 255) . "'/>";
echo "</node>" . PHP_EOL; echo "</node>" . PHP_EOL;
$used_node_ids[] = $id; $used_node_ids[] = $id;
} }
} }
   
function add_edge($from, $to, $weight = '1.0') function add_edge($from, $to, $weight = '1.0')
{ {
global $used_edge_ids, $included_panel_ids; global $used_edge_ids, $included_panel_ids;
$id = urlencode($from . '-' . $to); $id = urlencode($from . '-' . $to);
   
if (!in_array($id, $used_edge_ids)) { if (!in_array($id, $used_edge_ids)) {
echo "<edge id='" . $id . "' source='" . urlencode($from) . "' target='" . urlencode($to) . "' weight='" . $weight . "'>" . PHP_EOL; echo "<edge id='" . $id . "' source='" . urlencode($from) . "' target='" . urlencode($to) . "' weight='" . $weight . "'>" . PHP_EOL;
if ($weight != 0.1) { if ($weight != 0.1) {
echo "<viz:color b='192' g='192' r='192'/>"; echo "<viz:color b='192' g='192' r='192'/>";
} else { } else {
echo "<viz:color b='0' g='0' r='255'/>"; echo "<viz:color b='0' g='0' r='255'/>";
} }
echo "</edge>" . PHP_EOL; echo "</edge>" . PHP_EOL;
$used_edge_ids[] = $id; $used_edge_ids[] = $id;
} }
} }
   
$edges = Array(); $edges = Array();
header('Content-Type: application/gexf+xml'); header('Content-Type: application/gexf+xml');
echo '<?xml version="1.0" encoding="UTF-8"?> echo '<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:viz="http://www.gexf.net/1.2draft/viz" version="1.2"> <gexf xmlns="http://www.gexf.net/1.2draft" xmlns:viz="http://www.gexf.net/1.2draft/viz" version="1.2">
<meta lastmodifieddate="2009-03-20"> <meta lastmodifieddate="2009-03-20">
<creator>Gexf.net</creator> <creator>Gexf.net</creator>
<description>A hello world! file</description> <description>A hello world! file</description>
</meta> </meta>
<graph mode="static" defaultedgetype="directed"> <graph mode="static" defaultedgetype="directed">
   
<nodes>' . PHP_EOL; <nodes>' . PHP_EOL;
   
$query = ' $query = '
SELECT "supplierABN", min("supplierName") AS "supplierName", contractnotice."SONID", count(*), sum(value) AS value SELECT "supplierABN", text_mode("supplierName") AS "supplierName", contractnotice."SONID", count(*), sum(value) AS value
FROM contractnotice FROM contractnotice
WHERE "childCN" IS NULL WHERE "childCN" IS NULL
AND extract(year from "publishDate") = \'2016\' AND extract(year from "publishDate") = \'2016\'
AND "supplierABN" in (select distinct "supplierABN" from contractnotice where (left("categoryUNSPSC"::text,2) = \'43\' or left("categoryUNSPSC"::text,2) = \'80\') ) AND "supplierABN" in (select distinct "supplierABN" from contractnotice where (left("categoryUNSPSC"::text,2) = \'43\' or left("categoryUNSPSC"::text,2) = \'80\') )
AND contractnotice."SONID" != \'\' AND contractnotice."SONID" IS NOT NULL GROUP BY "supplierABN", contractnotice."SONID"'; AND contractnotice."SONID" != \'\' AND contractnotice."SONID" IS NOT NULL GROUP BY "supplierABN", contractnotice."SONID"';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
add_node($row['supplierABN'], $row['supplierName'], "",false); add_node($row['supplierABN'], $row['supplierName'], "",false);
$included_panel_ids[] = $row['SONID']; $included_panel_ids[] = $row['SONID'];
$edges[] = array("head" => $row['SONID'], "tail" => $row['supplierABN'], "weight" => $row['count']); $edges[] = array("head" => $row['SONID'], "tail" => $row['supplierABN'], "weight" => $row['count']);
} }
   
$query = 'SELECT "SONID", title FROM standingoffers'; $query = 'SELECT "SONID", title FROM standingoffers';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
// if (in_array($row['SONID'], $included_panel_ids)){ // if (in_array($row['SONID'], $included_panel_ids)){
add_node($row['SONID'], $row['title'], "", true); add_node($row['SONID'], $row['title'], "", true);
// } // }
} }
   
$query = 'select "SONID", abn,name from standingoffer_suppliers'; $query = 'select "SONID", abn,name from standingoffer_suppliers';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
add_node($row['abn'], $row['name']); add_node($row['abn'], $row['name']);
   
$edges[] = array("head"=>$row['SONID'], "tail"=>$row['abn'], "weight"=> 0.1); $edges[] = array("head"=>$row['SONID'], "tail"=>$row['abn'], "weight"=> 0.1);
} }
   
echo '</nodes> echo '</nodes>
<edges>' . PHP_EOL; <edges>' . PHP_EOL;
foreach ($edges as $edge) { foreach ($edges as $edge) {
add_edge($edge['head'], $edge['tail']); add_edge($edge['head'], $edge['tail']);
} }
echo ' </edges> echo ' </edges>
</graph> </graph>
</gexf>' . PHP_EOL; </gexf>' . PHP_EOL;
   
?> ?>
   
<?php <?php
include_once ("./lib/common.inc.php"); include_once("./lib/common.inc.php");
if ($_REQUEST['SONID']) { if ($_REQUEST['SONID']) {
$query = 'SELECT title from standingoffers where "SONID" = :SONID'; $query = 'SELECT title FROM standingoffers WHERE "SONID" = :SONID';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":SONID", $_REQUEST['SONID']); $query->bindParam(":SONID", $_REQUEST['SONID']);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
$title = reset($query->fetchAll())['title']; $title = reset($query->fetchAll())['title'];
include_header($title); include_header($title);
echo "<center><h1>".$_REQUEST['SONID']." - ".$title."</h1></center>"; echo "<center><h1>" . $_REQUEST['SONID'] . " - " . $title . "</h1></center>";
$query = 'select category, min("categoryUNSPSC") as "categoryUNSPSC" from contractnotice where "SONID" = :SONID group by category';  
$query = $conn->prepare($query);  
$query->bindParam(":SONID", $_REQUEST['SONID']);  
$query->execute();  
databaseError($conn->errorInfo());  
echo "Categories: ";  
foreach ($query->fetchAll() as $row) {  
echo "<span class='label label-warning'><a href='displayCategory.php?category={$row['category']}'>{$row['category']}</a></span>&nbsp; ";  
}  
echo "<br/>";  
$query = 'select "supplierABN", min("supplierName") as "supplierName", count(*), sum(value) as value from contractnotice  
WHERE '.$yearQ.' "childCN" is null AND "SONID" = :SONID group by "supplierABN"  
union select abn as "supplierABN",name as "supplierName",0 as sum,0 as value from standingoffer_suppliers  
where "SONID" = :SONID and abn not in (select distinct "supplierABN" as abn from contractnotice where "SONID" = :SONID)';  
$query = $conn->prepare($query);  
$query->bindParam(":SONID", $_REQUEST['SONID']);  
$query->execute();  
databaseError($conn->errorInfo());  
echo '<br><a href="https://www.tenders.gov.au/?event=public.advancedsearch.CNSONRedirect&type=sonSearchEvent&SONID=' . $_REQUEST['SONID'] . '"> View original record @ tenders.gov.au</a><br>'; echo '<br><a href="https://www.tenders.gov.au/?event=public.advancedsearch.CNSONRedirect&type=sonSearchEvent&SONID=' . $_REQUEST['SONID'] . '"> View original record @ tenders.gov.au</a><br>';
  /*
  * Procurement method in text, seperate Open via SON from Open
  * Consultancies, Confidentialities percentage
  */
  $query = 'SELECT category, min("categoryUNSPSC") AS "categoryUNSPSC", count(*) AS count, sum(value) AS value
  FROM contractnotice
  WHERE "SONID" = :SONID
  GROUP BY category';
  $query = $conn->prepare($query);
  $query->bindParam(":SONID", $_REQUEST['SONID']);
  $query->execute();
  databaseError($conn->errorInfo());
  echo "<h3>Categories</h3><table> <thead>
  <tr>
  <th>Category</th>
  <th>Contracts Count</th>
  <th>Total Contract Value</th>
  </tr>
  </thead>";
  foreach ($query->fetchAll() as $row) {
  setlocale(LC_MONETARY, 'en_US');
  $value = number_format(doubleval($row['value']), 2);
  $category = urlencode($row['category']);
  echo("<tr>
  <td><B><a href='displayCategory.php?category=$category'>{$row['category']}</a></b></td>
  <td>{$row['count']}</td>
  <td>\$$value</td>
  </tr>");
  }
  echo "</table><br/>";
   
echo "<table> <thead> $query = 'SELECT "supplierABN", text_mode("supplierName") AS "supplierName", count(*), sum(value) AS value FROM contractnotice
  WHERE ' . $yearQ . ' "childCN" IS NULL AND "SONID" = :SONID GROUP BY "supplierABN"
  UNION SELECT abn AS "supplierABN",name AS "supplierName",0 AS sum,0 AS value FROM standingoffer_suppliers
  WHERE "SONID" = :SONID AND abn NOT IN (SELECT DISTINCT "supplierABN" AS abn FROM contractnotice WHERE "SONID" = :SONID)';
  $query = $conn->prepare($query);
  $query->bindParam(":SONID", $_REQUEST['SONID']);
  $query->execute();
  databaseError($conn->errorInfo());
   
  echo "<h3>Suppliers</h3><table> <thead>
<tr> <tr>
<th>Supplier</th> <th>Supplier</th>
<th>Contracts Count</th> <th>Contracts Count</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value']) , 2); $value = number_format(doubleval($row['value']), 2);
$supplier = stripslashes($row['supplierABN'] . '-' . $row['supplierName']); $supplier = stripslashes($row['supplierABN'] . '-' . $row['supplierName']);
echo ("<tr> echo("<tr>
<td><b><a href=\"displaySupplier.php?supplier={$supplier}\">{$row['supplierName']}</a></b></td> <td><b><a href=\"displaySupplier.php?supplier={$supplier}\">{$row['supplierName']}</a></b></td>
<td>{$row['count']}</td> <td>{$row['count']}</td>
<td>\$$value</td> <td>\$$value</td>
</tr>"); </tr>");
} }
echo "</table><table> <thead> echo "</table><br/><h3>Contracts</h3><table> <thead>
<tr> <tr>
<th>Contract Notice Number</th> <th>Contract Notice Number</th>
<th>Contract Description</th> <th>Contract Description</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
<th>Agency</th> <th>Agency</th>
<th>Contract Start Date</th> <th>Contract Start Date</th>
<th>Supplier</th> <th>Supplier</th>
</tr> </tr>
</thead>"; </thead>";
$query = 'SELECT "CNID", description, value, "agencyName", contractnotice."SONID", "contractStart", "supplierName" $query = 'SELECT "CNID", title, description, value, "agencyName", contractnotice."SONID", "contractStart", "supplierName"
FROM contractnotice FROM contractnotice INNER JOIN standingoffers ON contractnotice."SONID" = standingoffers."SONID"
WHERE '.$yearQ.' "childCN" is null WHERE ' . $yearQ . ' "childCN" IS NULL
AND contractnotice."SONID" = :SONID AND contractnotice."SONID" = :SONID
ORDER BY value DESC'; ORDER BY VALUE DESC';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":SONID", $_REQUEST['SONID']); $query->bindParam(":SONID", $_REQUEST['SONID']);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value']) , 2); $value = number_format(doubleval($row['value']), 2);
echo ("<tr> echo("<tr>
<td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td> <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>
<td><b>{$row['description']}</b></a></td> <td><b>{$row['description']}</b></a></td>
<td>\$$value</td><td>{$row['agencyName']}</td> <td>\$$value</td><td>{$row['agencyName']}</td>
<td>{$row['contractStart']}</td> <td>{$row['contractStart']}</td>
<td>{$row['supplierName']}</td> <td>{$row['supplierName']}</td>
</tr>"); </tr>");
} }
echo "</table>"; echo "</table>";
} else { } else {
/*  
split by main categories  
*/  
include_header("Standing Offers"); include_header("Standing Offers");
$query = 'SELECT sum(value), count(*), contractnotice."SONID", min(title) as title $query = 'SELECT sum(value), count(*), contractnotice."SONID", min(title) AS title, text_mode(category) as category
FROM contractnotice inner join standingoffers on contractnotice."SONID" = standingoffers."SONID" FROM contractnotice INNER JOIN standingoffers ON contractnotice."SONID" = standingoffers."SONID"
WHERE '.$yearQ.' "childCN" is null and contractnotice."SONID" != \'\' WHERE ' . $yearQ . ' "childCN" IS NULL AND contractnotice."SONID" != \'\'
GROUP BY contractnotice."SONID" ORDER BY sum(value) DESC '; GROUP BY contractnotice."SONID" ORDER BY sum(VALUE) DESC ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
echo "<table> <thead> echo "<table> <thead>
<tr> <tr>
<th>SONID</th> <th>SONID</th>
  <th>Main category</th>
<th>Total Contracts Value</th> <th>Total Contracts Value</th>
<th>Number of Contracts</th> <th>Number of Contracts</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['sum']) , 2); $value = number_format(doubleval($row['sum']), 2);
echo ("<tr><td><A href=\"displaySON.php?SONID={$row['SONID']}\"><b>{$row['title']}</b></a></td><td>\$$value</td><td>{$row['count']}</td></tr>"); $title = $row['SONID'];
} if (strlen($row['title']) > 1) $title = $row['title'];
echo "</table>"; echo("<tr><td><A href=\"displaySON.php?SONID={$row['SONID']}\"><b>$title</b></a></td><td>{$row['category']}</td><td>\$$value</td><td>{$row['count']}</td></tr>");
  }
  echo "</table>";
} }
include_footer(); include_footer();
   
   
<?php <?php
   
include_once ("./lib/common.inc.php"); include_once("./lib/common.inc.php");
if ($_REQUEST['supplier']) { if ($_REQUEST['supplier']) {
   
$supplierS = htmlentities(strip_tags($_REQUEST['supplier'])); $supplierS = htmlentities(strip_tags($_REQUEST['supplier']));
include_header(str_replace("%","",$supplierName)); $title = $supplierName;
echo '<center><h1>'.str_replace("%","",$supplierName).'</h1></center>'; if ($supplierABN) {
agenciesGraph(); $query = 'SELECT text_mode("supplierName") AS "supplierName" FROM contractnotice WHERE "supplierABN" = :supplierABN GROUP BY "supplierABN"';
// MethodCountGraph($supplierS); $query = $conn->prepare($query);
// CnCGraph($supplierS); $query->bindParam(":supplierABN", $supplierABN);
// MethodValueGraph($supplierS); $query->execute();
/* lobbyist ties databaseError($conn->errorInfo());
  $title = reset($query->fetchAll())['supplierName'];
links to ABR/ASIC/Google News/ASX/Court records }
  include_header(str_replace("%", "", $title));
total value to various agencies (bar graph) echo '<center><h1>' . str_replace("%", "", $title) . '</h1></center>';
  if ($supplierABN) {
spread procurement methods + percent consultancies + percent confidential (bar graph) $query = 'SELECT distinct on (lower("supplierName")) "supplierName" from contractnotice where "supplierABN" = :supplierABN';
  $query = $conn->prepare($query);
spread of contract values  
   
spread of industries (textual?) */  
// echo '<img src="graphs/displayMethodCountGraph.php?month=' . stripslashes($supplier) . '">';  
// echo '<img src="graphs/displayCnCGraph.php?month=' . stripslashes($supplier) . '">';  
$query = 'select contractnotice."SONID", min(title) as title, count(*), sum(value) as value from contractnotice inner join standingoffers on contractnotice."SONID" = standingoffers."SONID" WHERE ' .$yearQ . ' ' .  
$supplierQ . ' ' . $standardQ  
. ' and contractnotice."SONID" != \'\' group by contractnotice."SONID"';  
$query = $conn->prepare($query);  
   
   
if ($supplierParts[0] > 0) {  
$query->bindParam(":supplierABN", $supplierABN); $query->bindParam(":supplierABN", $supplierABN);
} else { $query->execute();
$query->bindParam(":supplierName", $supplierName); databaseError($conn->errorInfo());
} echo "<b>Also known as:</b> ".implode(', ', $query->fetchAll(PDO::FETCH_COLUMN, 0));
$query->execute(); }
databaseError($conn->errorInfo());  
echo "<table> <thead> $query = '
<tr> SELECT
<th>Standing Offer</th> sum((consultancy = \'Yes\')::int) AS consultancy,
  sum(("confidentialityContract" = \'Yes\')::int) AS "confidentialityContract",
  sum(("confidentialityOutputs" = \'Yes\')::int) AS "confidentialityOutputs",
  sum((("procurementMethod" = \'Open\' OR "procurementMethod" = \'Open tender\') AND "SONID" IS null)::int) AS open,
  sum((("procurementMethod" = \'Open\' OR "procurementMethod" = \'Open tender\') AND "SONID" IS NOT null)::int) AS "openSON",
  sum(("procurementMethod" = \'Prequalified tender\' OR "procurementMethod" = \'Select\')::INT) AS prequalified,
  sum(("procurementMethod" = \'Direct\' OR "procurementMethod" = \'Limited tender\')::int) AS limited,
  COUNT(*) AS total
  FROM contractnotice
  WHERE' . $supplierQ . " " . $standardQ ;
  $query = $conn->prepare($query);
  if ($supplierParts[0] > 0) {
  $query->bindParam(":supplierABN", $supplierABN);
  } else {
  $query->bindParam(":supplierName", $supplierName);
  }
  $query->execute();
  databaseError($conn->errorInfo());
   
  $stats = reset($query->fetchAll());
  show_stats($stats);
   
  $query = 'SELECT category, min("categoryUNSPSC") AS "categoryUNSPSC", count(*) AS count, sum(value) AS value FROM contractnotice
  WHERE ' . $supplierQ . " " . $standardQ . ' GROUP BY category ORDER BY count(*) DESC LIMIT 10';
  $query = $conn->prepare($query);
  if ($supplierParts[0] > 0) {
  $query->bindParam(":supplierABN", $supplierABN);
  } else {
  $query->bindParam(":supplierName", $supplierName);
  }
  $query->execute();
  databaseError($conn->errorInfo());
   
   
  echo "<h3>Categories</h3><table> <thead>
  <tr>
  <th>Category</th>
<th>Contracts Count</th> <th>Contracts Count</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value']), 2); $value = number_format(doubleval($row['value']), 2);
echo ("<tr> $category = urlencode($row['category']);
  echo("<tr>
  <td><B><a href='displayCategory.php?category=$category'>{$row['category']}</a></b></td>
  <td>{$row['count']}</td>
  <td>\$$value</td>
  </tr>");
  }
  echo "</table><br/>";
   
   
  $query = 'SELECT SUM("value") AS "value", count(*), MAX(contractnotice."agencyName") AS agencyname FROM contractnotice JOIN agency_nametoabn ON contractnotice."agencyName"=agency_nametoabn."agencyName"
  WHERE ' . $yearQ . ' ' . $supplierQ . ' "childCN" IS NULL
  GROUP BY abn ORDER BY SUM("value") DESC';
  $query = $conn->prepare($query);
  if (count($supplierParts) > 0) {
  if ($supplierParts[0] > 0) {
  $query->bindParam(":supplierABN", $supplierABN);
  } else {
  $query->bindParam(":supplierName", $supplierName);
  }
  }
  $query->execute();
  databaseError($conn->errorInfo());
   
  echo "<h3>Agencies</h3><table> <thead>
  <tr>
  <th>Agency</th>
  <th>Contracts Count</th>
  <th>Total Contract Value</th>
  </tr>
  </thead>";
  foreach ($query->fetchAll() as $row) {
  setlocale(LC_MONETARY, 'en_US');
  $value = number_format(doubleval($row['value']), 2);
  $agency =urlencode($row['agencyname']);
  echo("<tr>
  <td><B><a href=\"displayAgency.php?agency=$agency\">{$row['agencyname']}</a></b></td>
  <td>{$row['count']}</td>
  <td>\$$value</td>
  </tr>");
  }
  echo "</table><br/>";
   
  $query = 'SELECT contractnotice."SONID", min(title) AS title, count(*), sum(value) AS value FROM contractnotice INNER JOIN standingoffers ON contractnotice."SONID" = standingoffers."SONID" WHERE ' . $yearQ . ' ' .
  $supplierQ . ' ' . $standardQ
  . ' AND contractnotice."SONID" != \'\' GROUP BY contractnotice."SONID"';
  $query = $conn->prepare($query);
   
   
  if ($supplierParts[0] > 0) {
  $query->bindParam(":supplierABN", $supplierABN);
  } else {
  $query->bindParam(":supplierName", $supplierName);
  }
  $query->execute();
  databaseError($conn->errorInfo());
  $sonrows = "";
  foreach ($query->fetchAll() as $row) {
  setlocale(LC_MONETARY, 'en_US');
  $value = number_format(doubleval($row['value']), 2);
  $sonrows .= "<tr>
<td><B><a href=\"displaySON.php?SONID={$row['SONID']}\">{$row['title']}</a></b></td> <td><B><a href=\"displaySON.php?SONID={$row['SONID']}\">{$row['title']}</a></b></td>
<td>{$row['count']}</td> <td>{$row['count']}</td>
<td>\$$value</td> <td>\$$value</td>
</tr>"); </tr>";
} }
echo "</table><table> <thead> if (strlen($sonrows) > 1) {
  echo "<h3>Standing Offers/Panels</h3><table> <thead>
  <tr>
  <th>Standing Offer</th>
  <th>Contracts Count</th>
  <th>Total Contract Value</th>
  </tr>
  </thead>$sonrows</table><br/>";
  }
  echo "<table><h3>Contracts</h3> <thead>
<tr> <tr>
<th>Contract Notice Number</th> <th>Contract Notice Number</th>
<th>Contract Description</th> <th>Contract Description</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
<th>Agency</th> <th>Agency</th>
<th>Contract Start Date</th> <th>Contract Start Date</th>
<th>Supplier</th> <th>Supplier</th>
</tr> </tr>
</thead>"; </thead>";
$query = 'SELECT "CNID", "description", "value", "agencyName", "category", $query = 'SELECT "CNID", "description", "value", "agencyName", "category",
"contractStart", "supplierName" "contractStart", "supplierName"
FROM contractnotice WHERE ' .$yearQ . ' ' . FROM contractnotice WHERE ' . $yearQ . ' ' .
$supplierQ . ' ' . $standardQ $supplierQ . ' ' . $standardQ
. ' ORDER BY value DESC'; . ' ORDER BY VALUE DESC';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
   
   
if ($supplierParts[0] > 0) { if ($supplierParts[0] > 0) {
$query->bindParam(":supplierABN", $supplierABN); $query->bindParam(":supplierABN", $supplierABN);
} else { } else {
$query->bindParam(":supplierName", $supplierName); $query->bindParam(":supplierName", $supplierName);
} }
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value']), 2); $value = number_format(doubleval($row['value']), 2);
echo ("<tr> echo("<tr>
<td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td> <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>
<td><b>{$row['description']}</b></a></td> <td><b>{$row['description']}</b></a></td>
<td>\$$value</td><td>{$row['agencyName']}</td> <td>\$$value</td><td>{$row['agencyName']}</td>
<td>{$row['contractStart']}</td> <td>{$row['contractStart']}</td>
<td>{$row['supplierName']}</td> <td>{$row['supplierName']}</td>
</tr>"); </tr>");
} }
echo "</table>"; echo "</table>";
} else { } else {
/* /*
histograph of supplier size/value histograph of supplier size/value
*/ */
include_header("Suppliers"); include_header("Suppliers");
suppliersGraph(); suppliersGraph();
$query = 'SELECT SUM("value") as val, mode("supplierName") as supplierName, "supplierABN",( $query = 'SELECT SUM("value") AS val, text_mode("supplierName") AS supplierName, "supplierABN",(
case when "supplierABN" != 0 THEN lower("supplierABN"::text) ELSE lower("supplierName") END) as supplierID CASE WHEN "supplierABN" != 0 THEN lower("supplierABN"::TEXT) ELSE lower("supplierName") END) AS supplierID
FROM contractnotice FROM contractnotice
WHERE ' .$yearQ . ' "childCN" is null WHERE ' . $yearQ . ' "childCN" IS NULL
GROUP BY supplierID,"supplierABN" GROUP BY supplierID,"supplierABN"
ORDER BY val DESC ORDER BY val DESC
LIMIT 100'; LIMIT 100';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
echo "<table> <thead> echo "<table> <thead>
<tr> <tr>
<th>Position</th> <th>Position</th>
<th>Supplier</th> <th>Supplier</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
</tr> </tr>
</thead>"; </thead>";
$i = 1; $i = 1;
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['val']), 2); $value = number_format(doubleval($row['val']), 2);
$supplier = stripslashes($row['supplierABN'] . '-' . $row['suppliername']); $supplier = stripslashes($row['supplierABN'] . '-' . $row['suppliername']);
echo ("<tr><td>$i</td><td><b><a href=\"displaySupplier.php?supplier={$supplier}\">" . ucsmart($row['suppliername']) . "</a></b></td><td>\$$value</td></tr>\n"); echo("<tr><td>$i</td><td><b><a href=\"displaySupplier.php?supplier={$supplier}\">" . ucsmart($row['suppliername']) . "</a></b></td><td>\$$value</td></tr>\n");
$i++; $i++;
} }
echo "</table>"; echo "</table>";
} }
include_footer(); include_footer();
?> ?>
   
-- https://wiki.postgresql.org/wiki/Aggregate_Mode -- https://wiki.postgresql.org/wiki/Aggregate_Mode
CREATE OR REPLACE FUNCTION _final_mode(anyarray) CREATE OR REPLACE FUNCTION _final_mode(anyarray)
RETURNS anyelement AS RETURNS anyelement AS
$BODY$ $BODY$
SELECT a SELECT a
FROM unnest($1) a FROM unnest($1) a
GROUP BY 1 GROUP BY 1
ORDER BY COUNT(1) DESC, 1 ORDER BY COUNT(1) DESC, 1
LIMIT 1; LIMIT 1;
$BODY$ $BODY$
LANGUAGE 'sql' IMMUTABLE; LANGUAGE 'sql' IMMUTABLE;
-- Tell Postgres how to use our aggregate -- Tell Postgres how to use our aggregate
CREATE AGGREGATE mode(anyelement) ( CREATE AGGREGATE text_mode(anyelement) (
SFUNC=array_append, --Function to call for each row. Just builds the array SFUNC=array_append, --Function to call for each row. Just builds the array
STYPE=anyarray, STYPE=anyarray,
FINALFUNC=_final_mode, --Function to call after everything has been added to array FINALFUNC=_final_mode, --Function to call after everything has been added to array
INITCOND='{}' --Initialize an empty array when starting INITCOND='{}' --Initialize an empty array when starting
); );
   
  CREATE VIEW suppliers AS
  select distinct on ("supplierABN") "supplierABN", "supplierName", count("supplierName") from contractnotice
  where "supplierABN" is not null
  group by "supplierABN", "supplierName"
  order by "supplierABN" asc, count("supplierName") desc;
<?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"); $conn = new PDO("pgsql:dbname=contractdashboard;user=postgres;password=snmc;host=localhost");
   
if (!$conn) { if (!$conn) {
die("A database error occurred.\n"); die("A database error occurred.\n");
} }
   
define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME)); define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME));
if (strstr($_SERVER['PHP_SELF'], "labs/") || strstr($_SERVER['PHP_SELF'], "admin/") || strstr($_SERVER['PHP_SELF'], "heuristics/")) { if (strstr($_SERVER['PHP_SELF'], "labs/") || strstr($_SERVER['PHP_SELF'], "admin/") || strstr($_SERVER['PHP_SELF'], "heuristics/")) {
$basePath = "../"; $basePath = "../";
} }
require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php'; /*require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php';
require(ROOT.'/solarium/vendor/autoload.php'); require(ROOT.'/solarium/vendor/autoload.php');
require(ROOT.'/solarium/library/Solarium/Autoloader.php'); require(ROOT.'/solarium/library/Solarium/Autoloader.php');
Solarium\Autoloader::register(); Solarium\Autoloader::register();
// check solarium version available // check solarium version available
//echo 'Solarium library version: ' . Solarium\Client::VERSION . ' - '; //echo 'Solarium library version: ' . Solarium\Client::VERSION . ' - ';
$config = array( $config = array(
'endpoint' => array( 'endpoint' => array(
'localhost' => array( 'localhost' => array(
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'port' => 8983, 'port' => 8983,
'path' => '/solr/contracts/', 'path' => '/solr/contracts/',
) )
) )
); );
// create a client instance // create a client instance
$solr_client = new Solarium\Client($config); $solr_client = new Solarium\Client($config);
   
   
$openid = new LightOpenID($_SERVER['HTTP_HOST']); $openid = new LightOpenID($_SERVER['HTTP_HOST']);
// you have to open the session to be able to modify or remove it // you have to open the session to be able to modify or remove it
session_start(); session_start();
function login() { function login() {
global $openid; global $openid;
if (!$openid->mode) { if (!$openid->mode) {
$openid->required = array('contact/email'); $openid->required = array('contact/email');
$openid->identity = 'https://www.google.com/accounts/o8/id'; $openid->identity = 'https://www.google.com/accounts/o8/id';
header('Location: ' . $openid->authUrl()); header('Location: ' . $openid->authUrl());
} }
} }
   
function auth() { function auth() {
global $openid; global $openid;
if ($_SESSION['authed'] == true) { if ($_SESSION['authed'] == true) {
return true; return true;
} }
   
if ($openid->mode) { if ($openid->mode) {
$attr = $openid->getAttributes(); $attr = $openid->getAttributes();
if ($attr['contact/email'] != 'maxious@gmail.com') { if ($attr['contact/email'] != 'maxious@gmail.com') {
die('Access Denied'); die('Access Denied');
} else { } else {
$_SESSION['authed'] = true; $_SESSION['authed'] = true;
} }
} else { } else {
login(); login();
} }
} }*/
   
// $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function databaseError($errMsg) { function databaseError($errMsg) {
if ($errMsg[2] != "") { if ($errMsg[2] != "") {
echo '<div class="alert-message error">'; echo '<div class="alert-message error">';
die(print_r($errMsg, true)); die(print_r($errMsg, true));
echo "</div>"; echo "</div>";
} }
} }
   
function ucsmart($str) { function ucsmart($str) {
$shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In" $shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In"
, "Of", "On", "Or", "The", "To", "With"); , "Of", "On", "Or", "The", "To", "With");
$strArray = explode(" ", preg_replace_callback("/(?<=(?<!:|’s)\W) $strArray = explode(" ", preg_replace_callback("/(?<=(?<!:|’s)\W)
(A|An|And|At|For|In|Of|On|Or|The|To|With) (A|An|And|At|For|In|Of|On|Or|The|To|With)
(?=\W)/", (?=\W)/",
function($matches) { return strtolower($matches[1]); } , ucwords(strtolower($str)))); function($matches) { return strtolower($matches[1]); } , ucwords(strtolower($str))));
foreach ($strArray as &$word) { foreach ($strArray as &$word) {
if (strlen($word) <= 4 && !in_array($word, $shortWords)) if (strlen($word) <= 4 && !in_array($word, $shortWords))
$word = strtoupper($word); $word = strtoupper($word);
} }
return implode(" ", $strArray); return implode(" ", $strArray);
} }
   
function percent($num_amount, $num_total) { function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total; $count1 = $num_amount / $num_total;
$count2 = $count1 * 100; $count2 = $count1 * 100;
$count = number_format($count2, 2); $count = number_format($count2, 2);
return $count; return $count;
} }
   
function array_sum_all($a) { function array_sum_all($a) {
if (!is_array($a)) if (!is_array($a))
return $a; return $a;
  $totale = 0;
foreach ($a as $key => $value) foreach ($a as $key => $value)
$totale += array_sum_all($value); $totale += array_sum_all($value);
return $totale; return $totale;
} }
   
// magic query modifiers // magic query modifiers
$agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING); $agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING);
if ($agency != "") if ($agency != "")
$agencyQ = "agencyName = '" . $agency . "' AND "; $agencyQ = "agencyName = '" . $agency . "' AND ";
   
$supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING); $supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING);
if ($supplier != "") { if ($supplier != "") {
$supplierParts = explode("-", $supplier); $supplierParts = explode("-", $supplier);
$supplierName = "%" . $supplierParts[1] . "%"; $supplierName = "%" . $supplierParts[1] . "%";
$supplierABN = $supplierParts[0]; $supplierABN = $supplierParts[0];
if ($supplierParts[0] > 0) if ($supplierParts[0] > 0)
$supplierQ = ' "supplierABN" = :supplierABN AND '; $supplierQ = ' "supplierABN" = :supplierABN AND ';
else else
$supplierQ = ' "supplierName" ILIKE :supplierName AND '; $supplierQ = ' "supplierName" ILIKE :supplierName AND ';
} }
   
$startYear = 2007; $startYear = 2007;
$year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT); $year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT);
if ($year != "") { if ($year != "") {
$yearQ = 'extract(year from "contractStart") = ' . $year . " AND "; $yearQ = 'extract(year from "contractStart") = ' . $year . " AND ";
} }
$standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010'; $standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';
$start = 0.0; $start = 0.0;
   
function local_url() { function local_url() {
return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/"; return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
} }
   
function include_header($title) { function include_header($title) {
global $start; global $start;
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" version="XHTML+RDFa 1.1" <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#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:gr="http://purl.org/goodrelations/v1#" xmlns:gr="http://purl.org/goodrelations/v1#"
xmlns:dc="http://purl.org/dc/terms/" xmlns:dc="http://purl.org/dc/terms/"
xmlns:pc="http://purl.org/procurement#" xmlns:pc="http://purl.org/procurement#"
xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#" xmlns:unspsc="http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#" xmlns:pcdt="http://purl.org/procurement/public-contracts-datatypes#"
prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# prefix="rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfs: http://www.w3.org/2000/01/rdf-schema# rdfs: http://www.w3.org/2000/01/rdf-schema#
gr: http://purl.org/goodrelations/v1# gr: http://purl.org/goodrelations/v1#
dcterms: http://purl.org/dc/terms/ dcterms: http://purl.org/dc/terms/
pc: http://purl.org/procurement/public-contracts# pc: http://purl.org/procurement/public-contracts#
cpv: http://purl.org/weso/pscs/cpv/2008/resource/ cpv: http://purl.org/weso/pscs/cpv/2008/resource/
unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml# unspsc: http://www.ksl.stanford.edu/projects/DAML/UNSPSC.daml#
v: http://www.w3.org/2006/vcard/ns# v: http://www.w3.org/2006/vcard/ns#
payment: http://reference.data.gov.uk/def/payment# payment: http://reference.data.gov.uk/def/payment#
br: http://purl.org/business-register# br: http://purl.org/business-register#
xsd: http://www.w3.org/2001/XMLSchema# xsd: http://www.w3.org/2001/XMLSchema#
pcdt: http://purl.org/procurement/public-contracts-datatypes#"> pcdt: http://purl.org/procurement/public-contracts-datatypes#">
<head> <head>
<title><?php echo $title; ?> - Contract Dashboard</title> <title><?php echo $title; ?> - Contract Dashboard</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="bootstrap-responsive.css"> <link rel="stylesheet" type="text/css" href="bootstrap-responsive.css">
<!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]> <!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> <![endif]-->
<script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script> <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" /> <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" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function() $(document).ready(function()
{ {
//hide the all of the element with class msg_body //hide the all of the element with class msg_body
$(".msg_body").hide(); $(".msg_body").hide();
//toggle the componenet with class msg_body //toggle the componenet with class msg_body
$(".msg_head").click(function() $(".msg_head").click(function()
{ {
$(this).next(".msg_body").slideToggle(600); $(this).next(".msg_body").slideToggle(600);
}); });
}); });
</script> </script>
   
<style type="text/css" title="currentStyle"> <style type="text/css" title="currentStyle">
@import "media/css/demo_table.css"; @import "media/css/demo_table.css";
</style> </style>
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script> <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" language="javascript" src="lib/bootstrap-dropdown.js"></script>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
jQuery.fn.dataTableExt.aTypes.unshift( jQuery.fn.dataTableExt.aTypes.unshift(
function ( sData ) function ( sData )
{ {
var sValidChars = "0123456789.-,"; var sValidChars = "0123456789.-,";
var Char; var Char;
/* Check the numeric part */ /* Check the numeric part */
for ( i=1 ; i<sData.length ; i++ ) for ( i=1 ; i<sData.length ; i++ )
{ {
Char = sData.charAt(i); Char = sData.charAt(i);
if (sValidChars.indexOf(Char) == -1) if (sValidChars.indexOf(Char) == -1)
{ {
return null; return null;
} }
} }
/* Check prefixed by currency */ /* Check prefixed by currency */
if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )
{ {
return 'currency'; return 'currency';
} }
return null; return null;
} }
); );
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) { 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) */ /* 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 x = a == "-" ? 0 : a.replace( /,/g, "" );
var y = b == "-" ? 0 : b.replace( /,/g, "" ); var y = b == "-" ? 0 : b.replace( /,/g, "" );
/* Remove the currency sign */ /* Remove the currency sign */
x = x.substring( 1 ); x = x.substring( 1 );
y = y.substring( 1 ); y = y.substring( 1 );
/* Parse and return */ /* Parse and return */
x = parseFloat( x ); x = parseFloat( x );
y = parseFloat( y ); y = parseFloat( y );
return x - y; return x - y;
}; };
   
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) { 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) */ /* 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 x = a == "-" ? 0 : a.replace( /,/g, "" );
var y = b == "-" ? 0 : b.replace( /,/g, "" ); var y = b == "-" ? 0 : b.replace( /,/g, "" );
/* Remove the currency sign */ /* Remove the currency sign */
x = x.substring( 1 ); x = x.substring( 1 );
y = y.substring( 1 ); y = y.substring( 1 );
/* Parse and return */ /* Parse and return */
x = parseFloat( x ); x = parseFloat( x );
y = parseFloat( y ); y = parseFloat( y );
return y - x; return y - x;
}; };
$(document).ready(function() { $(document).ready(function() {
$('table').dataTable(); $('table').dataTable();
} ); } );
</script> </script>
<link type="text/css" rel="stylesheet" href="style.css"> <link type="text/css" rel="stylesheet" href="style.css">
</head> </head>
<body> <body>
<div class="navbar"> <div class="navbar">
<div class="navbar-inner"> <div class="navbar-inner">
<div class="container-fluid"> <div class="container-fluid">
<a class="brand" href="#">contract dashboard</a> <a class="brand" href="#">contract dashboard</a>
<ul class="nav"> <ul class="nav">
<li><a href="displayAgency.php">agencies</a></li> <li><a href="displayAgency.php">agencies</a></li>
<li><a href="displaySupplier.php">suppliers</a></li> <li><a href="displaySupplier.php">suppliers</a></li>
<li><a href="displaySON.php">standing offers</a></li> <li><a href="displaySON.php">standing offers</a></li>
<li><a href="displayCategory.php">categories</a></li> <li><a href="displayCategory.php">categories</a></li>
<li><a href="displayCalendar.php">dates</a></li> <li><a href="displayCalendar.php">dates</a></li>
<li><a href="displayProcurementMethod.php">tenderm</a></li> <li><a href="displayProcurementMethod.php">tenderm</a></li>
<li><a href="displayConfidentialities.php">confidentiality</a></li> <li><a href="displayConfidentialities.php">confidentiality</a></li>
<li><a href="displayConsultancies.php">consultancies</a></li> <li><a href="displayConsultancies.php">consultancies</a></li>
<li><a href="displayAmendments.php">amendments</a></li> <li><a href="displayAmendments.php">amendments</a></li>
<li><a href="displayMap.php">geo</a></li> <li><a href="displayMap.php">geo</a></li>
</ul> </ul>
   
   
<form method="get" action="search.php" class="pull-right"> <form method="get" action="search.php" class="pull-right">
<input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" /> <input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" />
<input type="hidden" id="searchID" name="searchID" value=""/> <input type="hidden" id="searchID" name="searchID" value=""/>
</form> </form>
   
</div> </div>
</div><!-- /topbar-inner --> </div><!-- /topbar-inner -->
</div><!-- /topbar --> </div><!-- /topbar -->
</div><!-- /topbar-wrapper --> </div><!-- /topbar-wrapper -->
<script type="text/javascript"> <script type="text/javascript">
/* var options_xml = { var options_xml = {
script: function (input) { return "search_autosuggest.php?input="+input; }, script: function (input) { return "search_autosuggest.php?input="+input; },
varname:"input", varname:"input",
callback: function (obj) { document.getElementById('searchID').value = obj.id; } callback: function (obj) { document.getElementById('searchID').value = obj.id; }
}; };
var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml);*/ var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml);
</script> </script>
<div class="container-fluid"> <div class="container-fluid">
<div class="row-fluid"> <div class="row-fluid">
<div class="span3"> <div class="span3">
<h3> Filter by: </h3> <h3> Filter by: </h3>
<div class="well sidebar-nav"> <div class="well sidebar-nav">
<li class="nav-header">Year</li> <li class="nav-header">Year</li>
<?php <?php
foreach (range(2007,2016) as $year) { foreach (range(2007,2016) as $year) {
$get = $_GET; $get = $_GET;
$get['year'] = $year; $get['year'] = $year;
$query = http_build_query($get); $query = http_build_query($get);
echo "<li><A href='?$query'>"; echo "<li><A href='?$query'>";
if ($_GET['year'] == $year) echo "<b>"; if ($_GET['year'] == $year) echo "<b>";
echo "$year"; echo "$year";
if ($_GET['year'] == $year) echo "</b>"; if ($_GET['year'] == $year) echo "</b>";
echo "</a></li>"; echo "</a></li>";
} }
?> ?>
</div> </div>
</div> </div>
<div class="span9"> <div class="span9">
<?php <?php
$start = (float) array_sum(explode(' ', microtime())); $start = (float) array_sum(explode(' ', microtime()));
} }
   
function include_footer() { function include_footer() {
global $start; global $start;
$end = (float) array_sum(explode(' ', microtime())); $end = (float) array_sum(explode(' ', microtime()));
   
echo '</div> <footer> <small> Incorporates AusTender materials under a Creative Commons Attribution 3.0 Australia licence (CC BY 3.0 AU) https://creativecommons.org/licenses/by/3.0/au/ <br/> AusTender materials are released by the Department of Finance. <br/> AusTender materials are subject to change and should be verified on the AusTender website to ensure the information is up to date and correct: www.tenders.gov.au. <br/>' . "Processing time: " . sprintf("%.4f", ($end - $start)) . " seconds" . '</small> </footer>'; echo '</div> <footer>' . "Processing time: " . sprintf("%.4f", ($end - $start)) . " seconds" . ' <footer>';
   
if (strpos($_SERVER['SERVER_NAME'], ".gs")) { if (strpos($_SERVER['SERVER_NAME'], ".gs")) {
?> ?>
<script type="text/javascript"> <script type="text/javascript">
   
var _gaq = _gaq || []; var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12341040-3']); _gaq.push(['_setAccount', 'UA-12341040-3']);
_gaq.push(['_trackPageview']); _gaq.push(['_trackPageview']);
   
(function() { (function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); })();
   
</script> </script>
<?php <?php
} }
echo '</div> </div></body> </html>'; echo '</div> </div></body> </html>';
} }
   
include ("graphs.inc.php"); include ("graphs.inc.php");
   
<?php <?php
$includedFlot = false; $includedFlot = false;
   
function includeFlot() { function includeFlot() {
if (!$includedFlot) { if (!$includedFlot) {
echo ' <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="lib/flot/excanvas.min.js"></script><![endif]--> echo ' <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="lib/flot/excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.pie.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.pie.js"></script>
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.selection.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.selection.js"></script>
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.stack.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.stack.js"></script>
   
'; ';
$includedFlot = true; $includedFlot = true;
} }
} }
   
function CNDistributionGraph() { function CNDistributionGraph() {
global $conn; global $conn;
includeFlot(); includeFlot();
?> ?>
<center><div id="cndist" style="width:900px;height:550px"></div></center> <center><div id="cndist" style="width:900px;height:550px"></div></center>
<script type="text/javascript"> <script type="text/javascript">
var placeholder = $("#cndist"); var placeholder = $("#cndist");
$(function () { $(function () {
   
var d1 = []; var d1 = [];
var d2 = []; var d2 = [];
<?php <?php
$query = 'select cnid, count(*) from $query = 'select cnid, count(*) from
(select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid (select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid
from contractnotice where "CNID"::integer < 999999 from contractnotice where "CNID"::integer < 999999
and "CNID" not like \'%-A%\' and "CNID" not like \'%-A%\'
and "parentCN" is null) as a group by cnid order by cnid'; and "parentCN" is null) as a group by cnid order by cnid';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
echo("Export terminated, db error" . print_r($errors, true)); echo("Export terminated, db error" . print_r($errors, true));
return Array(); return Array();
} }
   
foreach ($query->fetchAll() as $delta) { foreach ($query->fetchAll() as $delta) {
   
echo "d1.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n"; echo "d1.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
}; };
$query = 'select cnid, count(*) from (select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid $query = 'select cnid, count(*) from (select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid
from contractnotice where "CNID" not like \'%-A%\' and "parentCN" is not null) from contractnotice where "CNID" not like \'%-A%\' and "parentCN" is not null)
as a group by cnid order by cnid'; as a group by cnid order by cnid';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
echo("Export terminated, db error" . print_r($errors, true)); echo("Export terminated, db error" . print_r($errors, true));
return Array(); return Array();
} }
   
foreach ($query->fetchAll() as $delta) { foreach ($query->fetchAll() as $delta) {
   
echo "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n"; echo "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
}; };
d1d2Graph(); d1d2Graph();
} }
function d1d2Graph($time = false) { function d1d2Graph($time = false) {
?> ?>
   
var data = [ var data = [
{ {
data: d1, data: d1,
series: { series: {
lines: { show: true }, lines: { show: true },
points: { show: true } points: { show: true }
} }
<?php if (!$time){ <?php if (!$time){
echo ',bars: { show: true }'; echo ',bars: { show: true }';
}?> }?>
}, },
{ {
data: d2, data: d2,
series: { series: {
lines: { show: true }, lines: { show: true },
points: { show: true } points: { show: true }
} }
<?php if (!$time){ <?php if (!$time){
echo ',bars: { show: true }'; echo ',bars: { show: true }';
} else { } else {
echo ',yaxis: 2'; echo ',yaxis: 2';
} }
?> ?>
}] }]
; ;
var options = var options =
{ {
grid: { hoverable: true, clickable: true, labelMargin: 17 }, grid: { hoverable: true, clickable: true, labelMargin: 17 },
selection: { mode: "x" } <?php if ($time){ selection: { mode: "x" } <?php if ($time){
echo ', xaxis: { echo ', xaxis: {
mode: "time" mode: "time"
}';} else { }';} else {
echo ', series: { echo ', series: {
stack: true stack: true
},'; },';
} ?> } ?>
}; };
   
placeholder.bind("plotselected", function (event, ranges) { placeholder.bind("plotselected", function (event, ranges) {
plot = $.plot(placeholder, data, plot = $.plot(placeholder, data,
$.extend(true, {}, options, { $.extend(true, {}, options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to } xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
})); }));
}); });
var previousPoint = null; var previousPoint = null;
placeholder.bind("plothover", function (event, pos, item) { placeholder.bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2)); $("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2)); $("#y").text(pos.y.toFixed(2));
if (item) { if (item) {
if (previousPoint != item.dataIndex) { if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex; previousPoint = item.dataIndex;
$("#tooltip").remove(); $("#tooltip").remove();
var x = item.datapoint[0].toFixed(2), var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2); y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, showTooltip(item.pageX, item.pageY,
item.series.label + " of " + x + " = " + y); item.series.label + " of " + x + " = " + y);
} }
} }
else { else {
$("#tooltip").remove(); $("#tooltip").remove();
previousPoint = null; previousPoint = null;
} }
}); });
   
var plot = $.plot(placeholder, data, var plot = $.plot(placeholder, data,
options); options);
}); });
   
function showTooltip(x, y, contents) { function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( { $('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute', position: 'absolute',
display: 'none', display: 'none',
top: y + 5, top: y + 5,
left: x + 5, left: x + 5,
border: '1px solid #fdd', border: '1px solid #fdd',
padding: '2px', padding: '2px',
'background-color': '#fee', 'background-color': '#fee',
opacity: 0.80 opacity: 0.80
}).appendTo("body").fadeIn(200); }).appendTo("body").fadeIn(200);
} }
</script> </script>
<?php <?php
} }
   
function agenciesGraph() { function agenciesGraph() {
   
global $conn, $yearQ, $supplierParts,$supplierQ, $supplierABN, $supplierName; global $conn, $yearQ, $supplierParts,$supplierQ, $supplierABN, $supplierName;
includeFlot(); includeFlot();
$query = 'SELECT SUM("value") as val, MAX(contractnotice."agencyName") as agencyname FROM contractnotice join agency_nametoabn on contractnotice."agencyName"=agency_nametoabn."agencyName" $query = 'SELECT SUM("value") as val, MAX(contractnotice."agencyName") as agencyname FROM contractnotice join agency_nametoabn on contractnotice."agencyName"=agency_nametoabn."agencyName"
WHERE ' .$yearQ . ' '.$supplierQ.' "childCN" is null WHERE ' .$yearQ . ' '.$supplierQ.' "childCN" is null
GROUP BY abn ORDER BY SUM("value") DESC'; GROUP BY abn ORDER BY SUM("value") DESC';
$query = $conn->prepare($query); $query = $conn->prepare($query);
if (count($supplierParts) > 0) { if (count($supplierParts) > 0) {
if ($supplierParts[0] > 0) { if ($supplierParts[0] > 0) {
$query->bindParam(":supplierABN", $supplierABN); $query->bindParam(":supplierABN", $supplierABN);
} else { } else {
$query->bindParam(":supplierName", $supplierName); $query->bindParam(":supplierName", $supplierName);
} }
} }
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
echo("Export terminated, db error" . print_r($errors, true)); echo("Export terminated, db error" . print_r($errors, true));
return Array(); return Array();
} }
?> ?>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
// data // data
var data = [ var data = [
<?php <?php
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
echo '{ label: "' . $row['agencyname'] . '", data: ' . doubleval($row["val"]) . '},'; echo '{ label: "' . $row['agencyname'] . '", data: ' . doubleval($row["val"]) . '},';
} }
?> ?>
]; ];
// GRAPH 7 // GRAPH 7
$.plot($("#graph7"), data, $.plot($("#graph7"), data,
{ {
series: { series: {
pie: { pie: {
show: true, show: true,
radius: 1, radius: 1,
tilt: 0.75, tilt: 0.75,
label: { label: {
show: true, show: true,
radius: 1, radius: 1,
formatter: function(label, series){ formatter: function(label, series){
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>'; return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
}, },
background: { background: {
opacity: 0.5, opacity: 0.5,
color: '#000' color: '#000'
} }
}, },
combine: { combine: {
color: '#999', color: '#999',
threshold: 0.012 threshold: 0.012
} }
} }
}, },
legend: { legend: {
show: false show: false
} }
}); });
}); });
</script> </script>
<div id="graph7" style="width:900px;height:550px"></div> <div id="graph7" style="width:900px;height:550px"></div>
   
<?php <?php
} }
   
; ;
   
function agencySuppliersGraph($agency) { function agencySuppliersGraph($agency) {
   
global $conn,$startYear, $yearQ; global $conn,$startYear, $yearQ;
includeFlot(); includeFlot();
   
$topX = 20; $topX = 20;
$query = 'SELECT SUM(value) as val, mode("supplierName") "supplierName" FROM contractnotice WHERE ' .$yearQ . ' extract ("YEAR" from "contractStart") >= :startYear AND "childCN" is null AND "agencyName" like :agency $query = 'SELECT SUM(value) as val, text_mode("supplierName") "supplierName" FROM contractnotice WHERE ' .$yearQ . ' extract ("YEAR" from "contractStart") >= :startYear AND "childCN" is null AND "agencyName" like :agency
GROUP BY lower("supplierName") ORDER BY val DESC limit '.$topX; GROUP BY lower("supplierName") ORDER BY val DESC limit '.$topX;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":startYear", $startYear); $query->bindParam(":startYear", $startYear);
$query->bindParam(":agency", $agency); $query->bindParam(":agency", $agency);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
$suppliers = Array(); $suppliers = Array();
$values = Array(); $values = Array();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$suppliers[] = ucsmart($row['supplierName']); $suppliers[] = ucsmart($row['supplierName']);
$values[] = doubleval($row["val"]); $values[] = doubleval($row["val"]);
} }
   
   
$query = 'SELECT sum(a.val) as value, count(1) as count from (SELECT SUM(value) as val, mode("supplierName") FROM contractnotice WHERE ' .$yearQ . '(extract ("YEAR" from "contractStart") >= :startYear) AND "childCN" is null and "agencyName" like :agency $query = 'SELECT sum(a.val) as value, count(1) as count from (SELECT SUM(value) as val, text_mode("supplierName") FROM contractnotice WHERE ' .$yearQ . '(extract ("YEAR" from "contractStart") >= :startYear) AND "childCN" is null and "agencyName" like :agency
GROUP BY lower("supplierName") ORDER BY val DESC LIMIT 184467440 OFFSET '.$topX.') as a'; GROUP BY lower("supplierName") ORDER BY val DESC LIMIT 184467440 OFFSET '.$topX.') as a';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":startYear", $startYear); $query->bindParam(":startYear", $startYear);
$query->bindParam(":agency", $agency); $query->bindParam(":agency", $agency);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
if ($row['count'] > 0) { if ($row['count'] > 0) {
$suppliers[] = $row['count'] . " other suppliers"; $suppliers[] = $row['count'] . " other suppliers";
$values[] = doubleval($row[0]); $values[] = doubleval($row[0]);
} }
} }
?> ?>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
// data // data
var data = [ var data = [
<?php <?php
foreach ($suppliers as $key => $supplier) { foreach ($suppliers as $key => $supplier) {
echo '{ label: "' . $supplier . '", data: ' . doubleval($values[$key]) . '},'; echo '{ label: "' . $supplier . '", data: ' . doubleval($values[$key]) . '},';
} }
?> ?>
]; ];
// GRAPH 7 // GRAPH 7
$.plot($("#graph7"), data, $.plot($("#graph7"), data,
{ {
series: { series: {
pie: { pie: {
show: true, show: true,
radius: 1, radius: 1,
tilt: 0.75, tilt: 0.75,
label: { label: {
show: true, show: true,
radius: 1, radius: 1,
formatter: function(label, series){ formatter: function(label, series){
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>'; return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
}, },
background: { background: {
opacity: 0.5, opacity: 0.5,
color: '#000' color: '#000'
} }
}, },
combine: { combine: {
color: '#999', color: '#999',
threshold: 0.012 threshold: 0.012
} }
} }
}, },
legend: { legend: {
show: false show: false
} }
}); });
}); });
</script> </script>
<div id="graph7" style="width:900px;height:550px"></div> <div id="graph7" style="width:900px;height:550px"></div>
   
<?php <?php
} }
   
function CnCGraph() { function CnCGraph() {
   
global $conn; global $conn;
$query = 'select procurementMethod, count(1) as count, SUM(value) as val, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice $query = 'select procurementMethod, count(1) as count, SUM(value) as val, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice
where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month'; where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
$methods = Array("Direct", "Open", "Select"); $methods = Array("Direct", "Open", "Select");
$dates = Array(); $dates = Array();
$methodCountsP = Array(); $methodCountsP = Array();
$methodCounts = Array(); $methodCounts = Array();
$maxValue = 0; $maxValue = 0;
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
if ($row['val'] > $maxValue) if ($row['val'] > $maxValue)
$maxValue = $row['val']; $maxValue = $row['val'];
$date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"]; $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
if (array_search($date, $dates) === false) { if (array_search($date, $dates) === false) {
$dates[$row["year"] * 100 + $row["month"]] = $date; $dates[$row["year"] * 100 + $row["month"]] = $date;
ksort($dates); ksort($dates);
} }
$methodCountsP[$row["procurementMethod"]][$date] = $row["count"]; $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
} }
foreach ($methods as $method) { foreach ($methods as $method) {
foreach ($dates as $date) { foreach ($dates as $date) {
if ($methodCountsP[$method][$date] > 0) if ($methodCountsP[$method][$date] > 0)
$methodCounts[$method][] = $methodCountsP[$method][$date]; $methodCounts[$method][] = $methodCountsP[$method][$date];
else else
$methodCounts[$method][] = 0; $methodCounts[$method][] = 0;
} }
} }
$dates = array_values($dates); $dates = array_values($dates);
$totalRecords = array_sum_all($methodCounts); $totalRecords = array_sum_all($methodCounts);
   
function formatCallback($aVal) { function formatCallback($aVal) {
global $totalRecords; global $totalRecords;
return percent($aVal, $totalRecords) . "%"; return percent($aVal, $totalRecords) . "%";
} }
   
$attributes = Array(); $attributes = Array();
$attributeNames = Array( $attributeNames = Array(
"Consultancies", "Consultancies",
"Confidentialities" "Confidentialities"
); );
$query = 'SELECT \'consultancy\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ consultancy=\'Yes\' AND "childCN" is null;'; $query = 'SELECT \'consultancy\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ consultancy=\'Yes\' AND "childCN" is null;';
$result = $conn->query($query); $result = $conn->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC); $row = $result->fetch(PDO::FETCH_ASSOC);
$attributes[0] = $row[1]; $attributes[0] = $row[1];
$query = 'SELECT \'confidentiality\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ (confidentialityContract=\'Yes\' OR confidentialityOutputs=\'Yes\') AND "childCN" is null;'; $query = 'SELECT \'confidentiality\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ (confidentialityContract=\'Yes\' OR confidentialityOutputs=\'Yes\') AND "childCN" is null;';
$result = $conn->query($query); $result = $conn->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC); $row = $result->fetch(PDO::FETCH_ASSOC);
$attributes[1] = $row[1]; $attributes[1] = $row[1];
} }
   
function ContractPublishedGraph() { function ContractPublishedGraph() {
   
global $conn, $yearQ; global $conn, $yearQ;
$query = 'SELECT extract(year from "contractStart"),extract(month from "contractStart"), $query = 'SELECT extract(year from "contractStart"),extract(month from "contractStart"),
SUM(value) as val, count(1) as count FROM contractnotice SUM(value) as val, count(1) as count FROM contractnotice
WHERE '.$yearQ.' (extract(year from "contractStart") >= 2008) WHERE '.$yearQ.' (extract(year from "contractStart") >= 2008)
AND "childCN" is null AND "childCN" is null
GROUP BY extract(month from "contractStart"), extract(year from "contractStart") GROUP BY extract(month from "contractStart"), extract(year from "contractStart")
ORDER BY extract(year from "contractStart"), extract(month from "contractStart")'; ORDER BY extract(year from "contractStart"), extract(month from "contractStart")';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
$dates = Array(); $dates = Array();
$values = Array(); $values = Array();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row["val"]), 2); $value = number_format(doubleval($row["val"]), 2);
$month_name = date('F', mktime(0, 0, 0, $row[1])); $month_name = date('F', mktime(0, 0, 0, $row[1]));
$dates[] = $month_name . " {$row[0]}"; $dates[] = $month_name . " {$row[0]}";
$counts[] = doubleval($row["count"]); $counts[] = doubleval($row["count"]);
$values[] = doubleval($row["val"]); $values[] = doubleval($row["val"]);
} }
} }
   
function ContractStartingGraph() { function ContractStartingGraph() {
   
global $conn, $yearQ; global $conn, $yearQ;
$query = 'SELECT extract (YEAR from "contractStart") as year, extract (MONTH from "contractStart") as month, $query = 'SELECT extract (YEAR from "contractStart") as year, extract (MONTH from "contractStart") as month,
SUM(value) as val, count(*) as count FROM contractnotice SUM(value) as val, count(*) as count FROM contractnotice
WHERE '.$yearQ.' extract (YEAR from "contractStart") >= 2008 WHERE '.$yearQ.' extract (YEAR from "contractStart") >= 2008
AND "childCN" is null AND "childCN" is null
GROUP BY extract (MONTH from "contractStart"), extract (YEAR from "contractStart") GROUP BY extract (MONTH from "contractStart"), extract (YEAR from "contractStart")
ORDER BY extract (YEAR from "contractStart"), extract (MONTH from"contractStart")'; ORDER BY extract (YEAR from "contractStart"), extract (MONTH from"contractStart")';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
$dates = Array(); $dates = Array();
$counts = Array(); $counts = Array();
$values = Array(); $values = Array();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row["val"]), 2); $value = number_format(doubleval($row["val"]), 2);
$date = mktime(0, 0, 0, $row["month"],1,$row["year"])*1000; $date = mktime(0, 0, 0, $row["month"],1,$row["year"])*1000;
if ($row["count"] > 1) { if ($row["count"] > 1) {
$dates[] = $date; $dates[] = $date;
$counts[] = $row["count"]; $counts[] = $row["count"];
$values[] = $row["val"]; $values[] = $row["val"];
} }
} }
includeFlot(); includeFlot();
?> ?>
<center><div id="cstart" style="width:900px;height:550px"></div></center> <center><div id="cstart" style="width:900px;height:550px"></div></center>
<script type="text/javascript"> <script type="text/javascript">
var placeholder = $("#cstart"); var placeholder = $("#cstart");
$(function () { $(function () {
   
var d1 = []; var d1 = [];
var d2 = []; var d2 = [];
<?php <?php
foreach ($counts as $key => $count) { foreach ($counts as $key => $count) {
   
echo "d1.push([ " . $dates[$key] . ", " . $count . "]); \n"; echo "d1.push([ " . $dates[$key] . ", " . $count . "]); \n";
}; };
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
   
echo "d2.push([ " . $dates[$key] . ", " . $value . "]); \n"; echo "d2.push([ " . $dates[$key] . ", " . $value . "]); \n";
}; };
d1d2Graph(true); d1d2Graph(true);
} }
   
function MethodCountGraph() { function MethodCountGraph() {
   
global $conn; global $conn;
$query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice $query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice
where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month'; where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month';
$methods = Array("Direct", "Open", "Select"); $methods = Array("Direct", "Open", "Select");
$dates = Array(); $dates = Array();
$methodCountsP = Array(); $methodCountsP = Array();
$methodCounts = Array(); $methodCounts = Array();
$maxValue = 0; $maxValue = 0;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
if ($row['value'] > $maxValue) if ($row['value'] > $maxValue)
$maxValue = $row['value']; $maxValue = $row['value'];
$date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"]; $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
if (array_search($date, $dates) === false) { if (array_search($date, $dates) === false) {
$dates[$row["year"] * 100 + $row["month"]] = $date; $dates[$row["year"] * 100 + $row["month"]] = $date;
ksort($dates); ksort($dates);
} }
$methodCountsP[$row["procurementMethod"]][$date] = $row["count"]; $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
} }
foreach ($methods as $method) { foreach ($methods as $method) {
foreach ($dates as $date) { foreach ($dates as $date) {
if ($methodCountsP[$method][$date] > 0) if ($methodCountsP[$method][$date] > 0)
$methodCounts[$method][] = $methodCountsP[$method][$date]; $methodCounts[$method][] = $methodCountsP[$method][$date];
else else
$methodCounts[$method][] = 0; $methodCounts[$method][] = 0;
} }
} }
$dates = array_values($dates); $dates = array_values($dates);
$totalRecords = array_sum_all($methodCounts); $totalRecords = array_sum_all($methodCounts);
} }
   
function MethodValueGraph() { function MethodValueGraph() {
   
global $conn; global $conn;
$query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice $query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice
where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month"; where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month";
$methods = Array("Direct", "Open", "Select"); $methods = Array("Direct", "Open", "Select");
$dates = Array(); $dates = Array();
$methodValuesP = Array(); $methodValuesP = Array();
$methodValues = Array(); $methodValues = Array();
$maxValue = 0; $maxValue = 0;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
if ($row['value'] > $maxValue) if ($row['value'] > $maxValue)
$maxValue = $row['value']; $maxValue = $row['value'];
$date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"]; $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
if (array_search($date, $dates) === false) { if (array_search($date, $dates) === false) {
$dates[$row["year"] * 100 + $row["month"]] = $date; $dates[$row["year"] * 100 + $row["month"]] = $date;
ksort($dates); ksort($dates);
} }
$methodValuesP[$row["procurementMethod"]][$date] = $row["value"]; $methodValuesP[$row["procurementMethod"]][$date] = $row["value"];
} }
foreach ($methods as $method) { foreach ($methods as $method) {
foreach ($dates as $date) { foreach ($dates as $date) {
if ($methodValuesP[$method][$date] > 0) if ($methodValuesP[$method][$date] > 0)
$methodValues[$method][] = $methodValuesP[$method][$date]; $methodValues[$method][] = $methodValuesP[$method][$date];
else else
$methodValues[$method][] = 0; $methodValues[$method][] = 0;
} }
} }
$dates = array_values($dates); $dates = array_values($dates);
$totalRecords = array_sum_all($methodValues); $totalRecords = array_sum_all($methodValues);
} }
   
function SuppliersGraph() { function SuppliersGraph() {
   
global $conn, $yearQ; global $conn, $yearQ;
includeFlot(); includeFlot();
$topX = 10; $topX = 10;
$suppliers = Array(); $suppliers = Array();
$values = Array(); $values = Array();
   
   
$query = 'SELECT SUM("value") as value, mode("supplierName") as supplierName, ( $query = 'SELECT SUM("value") as value, text_mode("supplierName") as supplierName, (
case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID
FROM contractnotice FROM contractnotice
WHERE ' .$yearQ . ' "childCN" is null WHERE ' .$yearQ . ' "childCN" is null
GROUP BY supplierID GROUP BY supplierID
ORDER BY value DESC ORDER BY value DESC
LIMIT ' . $topX; LIMIT ' . $topX;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
// $value = number_format(doubleval($row["value"]) , 2); // $value = number_format(doubleval($row["value"]) , 2);
$suppliers[] = ucsmart($row[1]); $suppliers[] = ucsmart($row[1]);
$values[] = doubleval($row["value"]); $values[] = doubleval($row["value"]);
} }
   
$query = 'SELECT sum(a.svalue) as val, suppliercountry from (SELECT sum("value") as svalue, max("supplierCountry") as suppliercountry $query = 'SELECT sum(a.svalue) as val, suppliercountry from (SELECT sum("value") as svalue, max("supplierCountry") as suppliercountry
FROM contractnotice WHERE "childCN" is null and "supplierCountry" NOT ILIKE \'Australia\' FROM contractnotice WHERE "childCN" is null and "supplierCountry" NOT ILIKE \'Australia\'
GROUP BY "supplierName" ORDER BY svalue LIMIT 18446744073 OFFSET 10) as a group by suppliercountry order by val DESC limit 10 '; GROUP BY "supplierName" ORDER BY svalue LIMIT 18446744073 OFFSET 10) as a group by suppliercountry order by val DESC limit 10 ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$suppliers[] = "Other suppliers in " . ucsmart($row["suppliercountry"]); $suppliers[] = "Other suppliers in " . ucsmart($row["suppliercountry"]);
$values[] = doubleval($row[0]); $values[] = doubleval($row[0]);
} }
   
   
$query = 'SELECT sum(a.value) as val, substring( $query = 'SELECT sum(a.value) as val, substring(
supplierpostcode from 0 for 2) as postcode from (SELECT sum(value) as value, max("supplierPostcode") as supplierpostcode, max("supplierCountry") as suppliercountry supplierpostcode from 0 for 2) as postcode from (SELECT sum(value) as value, max("supplierPostcode") as supplierpostcode, max("supplierCountry") as suppliercountry
FROM contractnotice WHERE "childCN" is null FROM contractnotice WHERE "childCN" is null
GROUP BY "supplierABN" ORDER BY sum(value) LIMIT 1844674 OFFSET 10) as a GROUP BY "supplierABN" ORDER BY sum(value) LIMIT 1844674 OFFSET 10) as a
WHERE (suppliercountry ILIKE \'Australia\') WHERE (suppliercountry ILIKE \'Australia\')
group by substring( group by substring(
supplierpostcode from 0 for 2) supplierpostcode from 0 for 2)
order by val DESC;'; order by val DESC;';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
if ($row['postcode'][0] == 2 && $row['postcode'][1] == 6) if ($row['postcode'][0] == 2 && $row['postcode'][1] == 6)
$ACTvalue += $row[0]; $ACTvalue += $row[0];
else if ($row['postcode'][0] == 2 || $row['postcode'][0] == 1) else if ($row['postcode'][0] == 2 || $row['postcode'][0] == 1)
$NSWvalue += $row[0]; $NSWvalue += $row[0];
else if ($row['postcode'][0] == 3 || $row['postcode'][0] == 8) else if ($row['postcode'][0] == 3 || $row['postcode'][0] == 8)
$Vicvalue += $row[0]; $Vicvalue += $row[0];
else if ($row['postcode'][0] == 4 || $row['postcode'][0] == 9) else if ($row['postcode'][0] == 4 || $row['postcode'][0] == 9)
$QLDvalue += $row[0]; $QLDvalue += $row[0];
else if ($row['postcode'][0] == 5) else if ($row['postcode'][0] == 5)
$SAvalue += $row[0]; $SAvalue += $row[0];
else if ($row['postcode'][0] == 6) else if ($row['postcode'][0] == 6)
$WAvalue += $row[0]; $WAvalue += $row[0];
else if ($row['postcode'][0] == 7) else if ($row['postcode'][0] == 7)
$Tasvalue += $row[0]; $Tasvalue += $row[0];
else if ($row['postcode'][0] == 0) else if ($row['postcode'][0] == 0)
$NTvalue += $row[0]; $NTvalue += $row[0];
} }
$suppliers[] = "Other suppliers in Australia - ACT"; $suppliers[] = "Other suppliers in Australia - ACT";
$values[] = doubleval($ACTvalue); $values[] = doubleval($ACTvalue);
$suppliers[] = "Other suppliers in Australia - NSW"; $suppliers[] = "Other suppliers in Australia - NSW";
$values[] = doubleval($NSWvalue); $values[] = doubleval($NSWvalue);
$suppliers[] = "Other suppliers in Australia - Victoria"; $suppliers[] = "Other suppliers in Australia - Victoria";
$values[] = doubleval($Vicvalue); $values[] = doubleval($Vicvalue);
$suppliers[] = "Other suppliers in Australia - Queensland"; $suppliers[] = "Other suppliers in Australia - Queensland";
$values[] = doubleval($QLDvalue); $values[] = doubleval($QLDvalue);
$suppliers[] = "Other suppliers in Australia - NT"; $suppliers[] = "Other suppliers in Australia - NT";
$values[] = doubleval($NTvalue); $values[] = doubleval($NTvalue);
$suppliers[] = "Other suppliers in Australia - West Australia"; $suppliers[] = "Other suppliers in Australia - West Australia";
$values[] = doubleval($WAvalue); $values[] = doubleval($WAvalue);
$suppliers[] = "Other suppliers in Australia - South Australia"; $suppliers[] = "Other suppliers in Australia - South Australia";
$values[] = doubleval($SAvalue); $values[] = doubleval($SAvalue);
$suppliers[] = "Other suppliers in Australia - Tasmania"; $suppliers[] = "Other suppliers in Australia - Tasmania";
$values[] = doubleval($Tasvalue); $values[] = doubleval($Tasvalue);
?> ?>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
// data // data
var data = [ var data = [
<?php <?php
foreach ($suppliers as $key => $supplier) { foreach ($suppliers as $key => $supplier) {
echo '{ label: "' . $supplier . '", data: ' . doubleval($values[$key]) . '},'; echo '{ label: "' . $supplier . '", data: ' . doubleval($values[$key]) . '},';
} }
?> ?>
]; ];
// GRAPH 7 // GRAPH 7
$.plot($("#graph7"), data, $.plot($("#graph7"), data,
{ {
series: { series: {
pie: { pie: {
show: true, show: true,
radius: 1, radius: 1,
tilt: 0.75, tilt: 0.75,
label: { label: {
show: true, show: true,
radius: 1, radius: 1,
formatter: function(label, series){ formatter: function(label, series){
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>'; return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
}, },
background: { background: {
opacity: 0.5, opacity: 0.5,
color: '#000' color: '#000'
} }
}, },
combine: { combine: {
color: '#999', color: '#999',
threshold: 0.012 threshold: 0.012
} }
} }
}, },
legend: { legend: {
show: false show: false
} }
}); });
}); });
</script> </script>
<div id="graph7" style="width:900px;height:550px"></div> <div id="graph7" style="width:900px;height:550px"></div>
   
<?php <?php
} }
?> ?>
   
/* /*
* File: demo_table.css * File: demo_table.css
* CVS: $Id$ * CVS: $Id$
* Description: CSS descriptions for DataTables demo pages * Description: CSS descriptions for DataTables demo pages
* Author: Allan Jardine * Author: Allan Jardine
* Created: Tue May 12 06:47:22 BST 2009 * Created: Tue May 12 06:47:22 BST 2009
* Modified: $Date$ by $Author$ * Modified: $Date$ by $Author$
* Language: CSS * Language: CSS
* Project: DataTables * Project: DataTables
* *
* Copyright 2009 Allan Jardine. All Rights Reserved. * Copyright 2009 Allan Jardine. All Rights Reserved.
* *
* *************************************************************************** * ***************************************************************************
* DESCRIPTION * DESCRIPTION
* *
* The styles given here are suitable for the demos that are used with the standard DataTables * The styles given here are suitable for the demos that are used with the standard DataTables
* distribution (see www.datatables.net). You will most likely wish to modify these styles to * distribution (see www.datatables.net). You will most likely wish to modify these styles to
* meet the layout requirements of your site. * meet the layout requirements of your site.
* *
* Common issues: * Common issues:
* 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is
* no conflict between the two pagination types. If you want to use full_numbers pagination * no conflict between the two pagination types. If you want to use full_numbers pagination
* ensure that you either have "example_alt_pagination" as a body class name, or better yet, * ensure that you either have "example_alt_pagination" as a body class name, or better yet,
* modify that selector. * modify that selector.
* Note that the path used for Images is relative. All images are by default located in * Note that the path used for Images is relative. All images are by default located in
* ../images/ - relative to this CSS file. * ../images/ - relative to this CSS file.
*/ */
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables features * DataTables features
*/ */
   
.dataTables_wrapper { .dataTables_wrapper {
position: relative; position: relative;
min-height: 302px; /*min-height: 302px;*/
clear: both; clear: both;
_height: 302px; /*_height: 302px;*/
zoom: 1; /* Feeling sorry for IE */ zoom: 1; /* Feeling sorry for IE */
} }
   
.dataTables_processing { .dataTables_processing {
position: absolute; position: absolute;
top: 50%; top: 50%;
left: 50%; left: 50%;
width: 250px; width: 250px;
height: 30px; height: 30px;
margin-left: -125px; margin-left: -125px;
margin-top: -15px; margin-top: -15px;
padding: 14px 0 2px 0; padding: 14px 0 2px 0;
border: 1px solid #ddd; border: 1px solid #ddd;
text-align: center; text-align: center;
color: #999; color: #999;
font-size: 14px; font-size: 14px;
background-color: white; background-color: white;
} }
   
/*.dataTables_length {*/ /*.dataTables_length {*/
/* width: 40%;*/ /* width: 40%;*/
/* float: left;*/ /* float: left;*/
/*}*/ /*}*/
/**/ /**/
/*.dataTables_filter {*/ /*.dataTables_filter {*/
/* width: 50%;*/ /* width: 50%;*/
/* float: right;*/ /* float: right;*/
/* text-align: right;*/ /* text-align: right;*/
/*}*/ /*}*/
   
.dataTables_info { .dataTables_info {
width: 60%; width: 60%;
float: left; float: left;
} }
   
.dataTables_paginate { .dataTables_paginate {
width: 44px; width: 44px;
* width: 50px; * width: 50px;
float: right; float: right;
text-align: right; text-align: right;
} }
   
/* Pagination nested */ /* Pagination nested */
.paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next {
height: 19px; height: 19px;
width: 19px; width: 19px;
margin-left: 3px; margin-left: 3px;
float: left; float: left;
} }
   
.paginate_disabled_previous { .paginate_disabled_previous {
background-image: url('../images/back_disabled.jpg'); background-image: url('../images/back_disabled.jpg');
} }
   
.paginate_enabled_previous { .paginate_enabled_previous {
background-image: url('../images/back_enabled.jpg'); background-image: url('../images/back_enabled.jpg');
} }
   
.paginate_disabled_next { .paginate_disabled_next {
background-image: url('../images/forward_disabled.jpg'); background-image: url('../images/forward_disabled.jpg');
} }
   
.paginate_enabled_next { .paginate_enabled_next {
background-image: url('../images/forward_enabled.jpg'); background-image: url('../images/forward_enabled.jpg');
} }
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables display * DataTables display
*/ */
table.display { table.display {
margin: 0 auto; margin: 0 auto;
clear: both; clear: both;
width: 100%; width: 100%;
/* Note Firefox 3.5 and before have a bug with border-collapse /* Note Firefox 3.5 and before have a bug with border-collapse
* ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 )
* border-spacing: 0; is one possible option. Conditional-css.com is * border-spacing: 0; is one possible option. Conditional-css.com is
* useful for this kind of thing * useful for this kind of thing
* *
* Further note IE 6/7 has problems when calculating widths with border width. * Further note IE 6/7 has problems when calculating widths with border width.
* It subtracts one px relative to the other browsers from the first column, and * It subtracts one px relative to the other browsers from the first column, and
* adds one to the end... * adds one to the end...
* *
* If you want that effect I'd suggest setting a border-top/left on th/td's and * If you want that effect I'd suggest setting a border-top/left on th/td's and
* then filling in the gaps with other borders. * then filling in the gaps with other borders.
*/ */
} }
   
table.display thead th { table.display thead th {
padding: 3px 18px 3px 10px; padding: 3px 18px 3px 10px;
border-bottom: 1px solid black; border-bottom: 1px solid black;
font-weight: bold; font-weight: bold;
cursor: pointer; cursor: pointer;
* cursor: hand; * cursor: hand;
} }
   
table.display tfoot th { table.display tfoot th {
padding: 3px 18px 3px 10px; padding: 3px 18px 3px 10px;
border-top: 1px solid black; border-top: 1px solid black;
font-weight: bold; font-weight: bold;
} }
   
table.display tr.heading2 td { table.display tr.heading2 td {
border-bottom: 1px solid #aaa; border-bottom: 1px solid #aaa;
} }
   
table.display td { table.display td {
padding: 3px 10px; padding: 3px 10px;
} }
   
table.display td.center { table.display td.center {
text-align: center; text-align: center;
} }
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables sorting * DataTables sorting
*/ */
   
.sorting_asc { .sorting_asc {
background: url('../images/sort_asc.png') no-repeat center right; background: url('../images/sort_asc.png') no-repeat center right;
} }
   
.sorting_desc { .sorting_desc {
background: url('../images/sort_desc.png') no-repeat center right; background: url('../images/sort_desc.png') no-repeat center right;
} }
   
.sorting { .sorting {
background: url('../images/sort_both.png') no-repeat center right; background: url('../images/sort_both.png') no-repeat center right;
} }
   
.sorting_asc_disabled { .sorting_asc_disabled {
background: url('../images/sort_asc_disabled.png') no-repeat center right; background: url('../images/sort_asc_disabled.png') no-repeat center right;
} }
   
.sorting_desc_disabled { .sorting_desc_disabled {
background: url('../images/sort_desc_disabled.png') no-repeat center right; background: url('../images/sort_desc_disabled.png') no-repeat center right;
} }
   
   
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables row classes * DataTables row classes
*/ */
table.display tr.odd.gradeA { table.display tr.odd.gradeA {
background-color: #ddffdd; background-color: #ddffdd;
} }
   
table.display tr.even.gradeA { table.display tr.even.gradeA {
background-color: #eeffee; background-color: #eeffee;
} }
   
table.display tr.odd.gradeC { table.display tr.odd.gradeC {
background-color: #ddddff; background-color: #ddddff;
} }
   
table.display tr.even.gradeC { table.display tr.even.gradeC {
background-color: #eeeeff; background-color: #eeeeff;
} }
   
table.display tr.odd.gradeX { table.display tr.odd.gradeX {
background-color: #ffdddd; background-color: #ffdddd;
} }
   
table.display tr.even.gradeX { table.display tr.even.gradeX {
background-color: #ffeeee; background-color: #ffeeee;
} }
   
table.display tr.odd.gradeU { table.display tr.odd.gradeU {
background-color: #ddd; background-color: #ddd;
} }
   
table.display tr.even.gradeU { table.display tr.even.gradeU {
background-color: #eee; background-color: #eee;
} }
   
   
tr.odd { tr.odd {
background-color: #E2E4FF; background-color: #E2E4FF;
} }
   
tr.even { tr.even {
background-color: white; background-color: white;
} }
   
   
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Misc * Misc
*/ */
.dataTables_scroll { .dataTables_scroll {
clear: both; clear: both;
} }
   
.dataTables_scrollBody { .dataTables_scrollBody {
*margin-top: -1px; *margin-top: -1px;
} }
   
.top, .bottom { .top, .bottom {
padding: 15px; padding: 15px;
background-color: #F5F5F5; background-color: #F5F5F5;
border: 1px solid #CCCCCC; border: 1px solid #CCCCCC;
} }
   
.top .dataTables_info { .top .dataTables_info {
float: none; float: none;
} }
   
.clear { .clear {
clear: both; clear: both;
} }
   
.dataTables_empty { .dataTables_empty {
text-align: center; text-align: center;
} }
   
tfoot input { tfoot input {
margin: 0.5em 0; margin: 0.5em 0;
width: 100%; width: 100%;
color: #444; color: #444;
} }
   
tfoot input.search_init { tfoot input.search_init {
color: #999; color: #999;
} }
   
td.group { td.group {
background-color: #d1cfd0; background-color: #d1cfd0;
border-bottom: 2px solid #A19B9E; border-bottom: 2px solid #A19B9E;
border-top: 2px solid #A19B9E; border-top: 2px solid #A19B9E;
} }
   
td.details { td.details {
background-color: #d1cfd0; background-color: #d1cfd0;
border: 2px solid #A19B9E; border: 2px solid #A19B9E;
} }
   
   
.example_alt_pagination div.dataTables_info { .example_alt_pagination div.dataTables_info {
width: 40%; width: 40%;
} }
   
.paging_full_numbers { .paging_full_numbers {
width: 400px; width: 400px;
height: 22px; height: 22px;
line-height: 22px; line-height: 22px;
} }
   
.paging_full_numbers span.paginate_button, .paging_full_numbers span.paginate_button,
.paging_full_numbers span.paginate_active { .paging_full_numbers span.paginate_active {
border: 1px solid #aaa; border: 1px solid #aaa;
-webkit-border-radius: 5px; -webkit-border-radius: 5px;
-moz-border-radius: 5px; -moz-border-radius: 5px;
padding: 2px 5px; padding: 2px 5px;
margin: 0 3px; margin: 0 3px;
cursor: pointer; cursor: pointer;
*cursor: hand; *cursor: hand;
} }
   
.paging_full_numbers span.paginate_button { .paging_full_numbers span.paginate_button {
background-color: #ddd; background-color: #ddd;
} }
   
.paging_full_numbers span.paginate_button:hover { .paging_full_numbers span.paginate_button:hover {
background-color: #ccc; background-color: #ccc;
} }
   
.paging_full_numbers span.paginate_active { .paging_full_numbers span.paginate_active {
background-color: #99B3FF; background-color: #99B3FF;
} }
   
table.display tr.even.row_selected td { table.display tr.even.row_selected td {
background-color: #B0BED9; background-color: #B0BED9;
} }
   
table.display tr.odd.row_selected td { table.display tr.odd.row_selected td {
background-color: #9FAFD1; background-color: #9FAFD1;
} }
   
   
/* /*
* Sorting classes for columns * Sorting classes for columns
*/ */
/* For the standard odd/even */ /* For the standard odd/even */
tr.odd td.sorting_1 { tr.odd td.sorting_1 {
background-color: #D3D6FF; background-color: #D3D6FF;
} }
   
tr.odd td.sorting_2 { tr.odd td.sorting_2 {
background-color: #DADCFF; background-color: #DADCFF;
} }
   
tr.odd td.sorting_3 { tr.odd td.sorting_3 {
background-color: #E0E2FF; background-color: #E0E2FF;
} }
   
tr.even td.sorting_1 { tr.even td.sorting_1 {
background-color: #EAEBFF; background-color: #EAEBFF;
} }
   
tr.even td.sorting_2 { tr.even td.sorting_2 {
background-color: #F2F3FF; background-color: #F2F3FF;
} }
   
tr.even td.sorting_3 { tr.even td.sorting_3 {
background-color: #F9F9FF; background-color: #F9F9FF;
} }
   
   
/* For the Conditional-CSS grading rows */ /* For the Conditional-CSS grading rows */
/* /*
Colour calculations (based off the main row colours) Colour calculations (based off the main row colours)
Level 1: Level 1:
dd > c4 dd > c4
ee > d5 ee > d5
Level 2: Level 2:
dd > d1 dd > d1
ee > e2 ee > e2
*/ */
tr.odd.gradeA td.sorting_1 { tr.odd.gradeA td.sorting_1 {
background-color: #c4ffc4; background-color: #c4ffc4;
} }
   
tr.odd.gradeA td.sorting_2 { tr.odd.gradeA td.sorting_2 {
background-color: #d1ffd1; background-color: #d1ffd1;
} }
   
tr.odd.gradeA td.sorting_3 { tr.odd.gradeA td.sorting_3 {
background-color: #d1ffd1; background-color: #d1ffd1;
} }
   
tr.even.gradeA td.sorting_1 { tr.even.gradeA td.sorting_1 {
background-color: #d5ffd5; background-color: #d5ffd5;
} }
   
tr.even.gradeA td.sorting_2 { tr.even.gradeA td.sorting_2 {
background-color: #e2ffe2; background-color: #e2ffe2;
} }
   
tr.even.gradeA td.sorting_3 { tr.even.gradeA td.sorting_3 {
background-color: #e2ffe2; background-color: #e2ffe2;
} }
   
tr.odd.gradeC td.sorting_1 { tr.odd.gradeC td.sorting_1 {
background-color: #c4c4ff; background-color: #c4c4ff;
} }
   
tr.odd.gradeC td.sorting_2 { tr.odd.gradeC td.sorting_2 {
background-color: #d1d1ff; background-color: #d1d1ff;
} }
   
tr.odd.gradeC td.sorting_3 { tr.odd.gradeC td.sorting_3 {
background-color: #d1d1ff; background-color: #d1d1ff;
} }
   
tr.even.gradeC td.sorting_1 { tr.even.gradeC td.sorting_1 {
background-color: #d5d5ff; background-color: #d5d5ff;
} }
   
tr.even.gradeC td.sorting_2 { tr.even.gradeC td.sorting_2 {
background-color: #e2e2ff; background-color: #e2e2ff;
} }
   
tr.even.gradeC td.sorting_3 { tr.even.gradeC td.sorting_3 {
background-color: #e2e2ff; background-color: #e2e2ff;
} }
   
tr.odd.gradeX td.sorting_1 { tr.odd.gradeX td.sorting_1 {
background-color: #ffc4c4; background-color: #ffc4c4;
} }
   
tr.odd.gradeX td.sorting_2 { tr.odd.gradeX td.sorting_2 {
background-color: #ffd1d1; background-color: #ffd1d1;
} }
   
tr.odd.gradeX td.sorting_3 { tr.odd.gradeX td.sorting_3 {
background-color: #ffd1d1; background-color: #ffd1d1;
} }
   
tr.even.gradeX td.sorting_1 { tr.even.gradeX td.sorting_1 {
background-color: #ffd5d5; background-color: #ffd5d5;
} }
   
tr.even.gradeX td.sorting_2 { tr.even.gradeX td.sorting_2 {
background-color: #ffe2e2; background-color: #ffe2e2;
} }
   
tr.even.gradeX td.sorting_3 { tr.even.gradeX td.sorting_3 {
background-color: #ffe2e2; background-color: #ffe2e2;
} }
   
tr.odd.gradeU td.sorting_1 { tr.odd.gradeU td.sorting_1 {
background-color: #c4c4c4; background-color: #c4c4c4;
} }
   
tr.odd.gradeU td.sorting_2 { tr.odd.gradeU td.sorting_2 {
background-color: #d1d1d1; background-color: #d1d1d1;
} }
   
tr.odd.gradeU td.sorting_3 { tr.odd.gradeU td.sorting_3 {
background-color: #d1d1d1; background-color: #d1d1d1;
} }
   
tr.even.gradeU td.sorting_1 { tr.even.gradeU td.sorting_1 {
background-color: #d5d5d5; background-color: #d5d5d5;
} }
   
tr.even.gradeU td.sorting_2 { tr.even.gradeU td.sorting_2 {
background-color: #e2e2e2; background-color: #e2e2e2;
} }
   
tr.even.gradeU td.sorting_3 { tr.even.gradeU td.sorting_3 {
background-color: #e2e2e2; background-color: #e2e2e2;
} }
   
   
/* /*
* Row highlighting example * Row highlighting example
*/ */
.ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted {
background-color: #ECFFB3; background-color: #ECFFB3;
} }
   
.ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted {
background-color: #E6FF99; background-color: #E6FF99;
} }
   
.ex_highlight_row #example tr.even:hover { .ex_highlight_row #example tr.even:hover {
background-color: #ECFFB3; background-color: #ECFFB3;
} }
   
.ex_highlight_row #example tr.even:hover td.sorting_1 { .ex_highlight_row #example tr.even:hover td.sorting_1 {
background-color: #DDFF75; background-color: #DDFF75;
} }
   
.ex_highlight_row #example tr.even:hover td.sorting_2 { .ex_highlight_row #example tr.even:hover td.sorting_2 {
background-color: #E7FF9E; background-color: #E7FF9E;
} }
   
.ex_highlight_row #example tr.even:hover td.sorting_3 { .ex_highlight_row #example tr.even:hover td.sorting_3 {
background-color: #E2FF89; background-color: #E2FF89;
} }
   
.ex_highlight_row #example tr.odd:hover { .ex_highlight_row #example tr.odd:hover {
background-color: #E6FF99; background-color: #E6FF99;
} }
   
.ex_highlight_row #example tr.odd:hover td.sorting_1 { .ex_highlight_row #example tr.odd:hover td.sorting_1 {
background-color: #D6FF5C; background-color: #D6FF5C;
} }
   
.ex_highlight_row #example tr.odd:hover td.sorting_2 { .ex_highlight_row #example tr.odd:hover td.sorting_2 {
background-color: #E0FF84; background-color: #E0FF84;
} }
   
.ex_highlight_row #example tr.odd:hover td.sorting_3 { .ex_highlight_row #example tr.odd:hover td.sorting_3 {
background-color: #DBFF70; background-color: #DBFF70;
} }
   
   
/* /*
* KeyTable * KeyTable
*/ */
table.KeyTable td { table.KeyTable td {
border: 3px solid transparent; border: 3px solid transparent;
} }
   
table.KeyTable td.focus { table.KeyTable td.focus {
border: 3px solid #3366FF; border: 3px solid #3366FF;
} }
   
table.display tr.gradeA { table.display tr.gradeA {
background-color: #eeffee; background-color: #eeffee;
} }
   
table.display tr.gradeC { table.display tr.gradeC {
background-color: #ddddff; background-color: #ddddff;
} }
   
table.display tr.gradeX { table.display tr.gradeX {
background-color: #ffdddd; background-color: #ffdddd;
} }
   
table.display tr.gradeU { table.display tr.gradeU {
background-color: #ddd; background-color: #ddd;
} }
   
div.box { div.box {
height: 100px; height: 100px;
padding: 10px; padding: 10px;
overflow: auto; overflow: auto;
border: 1px solid #8080FF; border: 1px solid #8080FF;
background-color: #E5E5FF; background-color: #E5E5FF;
} }
   
/* /*
* File: demo_table_jui.css * File: demo_table_jui.css
* CVS: $Id$ * CVS: $Id$
* Description: CSS descriptions for DataTables demo pages * Description: CSS descriptions for DataTables demo pages
* Author: Allan Jardine * Author: Allan Jardine
* Created: Tue May 12 06:47:22 BST 2009 * Created: Tue May 12 06:47:22 BST 2009
* Modified: $Date$ by $Author$ * Modified: $Date$ by $Author$
* Language: CSS * Language: CSS
* Project: DataTables * Project: DataTables
* *
* Copyright 2009 Allan Jardine. All Rights Reserved. * Copyright 2009 Allan Jardine. All Rights Reserved.
* *
* *************************************************************************** * ***************************************************************************
* DESCRIPTION * DESCRIPTION
* *
* The styles given here are suitable for the demos that are used with the standard DataTables * The styles given here are suitable for the demos that are used with the standard DataTables
* distribution (see www.datatables.net). You will most likely wish to modify these styles to * distribution (see www.datatables.net). You will most likely wish to modify these styles to
* meet the layout requirements of your site. * meet the layout requirements of your site.
* *
* Common issues: * Common issues:
* 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is
* no conflict between the two pagination types. If you want to use full_numbers pagination * no conflict between the two pagination types. If you want to use full_numbers pagination
* ensure that you either have "example_alt_pagination" as a body class name, or better yet, * ensure that you either have "example_alt_pagination" as a body class name, or better yet,
* modify that selector. * modify that selector.
* Note that the path used for Images is relative. All images are by default located in * Note that the path used for Images is relative. All images are by default located in
* ../images/ - relative to this CSS file. * ../images/ - relative to this CSS file.
*/ */
   
   
/* /*
* jQuery UI specific styling * jQuery UI specific styling
*/ */
   
.paging_two_button .ui-button { .paging_two_button .ui-button {
float: left; float: left;
cursor: pointer; cursor: pointer;
* cursor: hand; * cursor: hand;
} }
   
.paging_full_numbers .ui-button { .paging_full_numbers .ui-button {
padding: 2px 6px; padding: 2px 6px;
margin: 0; margin: 0;
cursor: pointer; cursor: pointer;
* cursor: hand; * cursor: hand;
} }
   
.ui-buttonset .ui-button { .ui-buttonset .ui-button {
margin-right: -0.1em !important; margin-right: -0.1em !important;
} }
   
.paging_full_numbers { .paging_full_numbers {
width: 350px !important; width: 350px !important;
} }
   
.ui-toolbar { .ui-toolbar {
padding: 5px; padding: 5px;
} }
   
.dataTables_paginate { .dataTables_paginate {
width: auto; width: auto;
} }
   
.dataTables_info { .dataTables_info {
padding-top: 3px; padding-top: 3px;
} }
   
table.display thead th { table.display thead th {
padding: 3px 0px 3px 10px; padding: 3px 0px 3px 10px;
cursor: pointer; cursor: pointer;
* cursor: hand; * cursor: hand;
} }
   
   
/* /*
* Sort arrow icon positioning * Sort arrow icon positioning
*/ */
table.display thead th div.DataTables_sort_wrapper { table.display thead th div.DataTables_sort_wrapper {
position: relative; position: relative;
padding-right: 20px; padding-right: 20px;
padding-right: 20px; padding-right: 20px;
} }
   
table.display thead th div.DataTables_sort_wrapper span { table.display thead th div.DataTables_sort_wrapper span {
position: absolute; position: absolute;
top: 50%; top: 50%;
margin-top: -8px; margin-top: -8px;
right: 0; right: 0;
} }
   
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Everything below this line is the same as demo_table.css. This file is * Everything below this line is the same as demo_table.css. This file is
* required for 'cleanliness' of the markup * required for 'cleanliness' of the markup
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables features * DataTables features
*/ */
   
.dataTables_wrapper { .dataTables_wrapper {
position: relative; position: relative;
min-height: 302px; /*min-height: 302px;
_height: 302px; _height: 302px;*/
clear: both; clear: both;
} }
   
.dataTables_processing { .dataTables_processing {
position: absolute; position: absolute;
top: 0px; top: 0px;
left: 50%; left: 50%;
width: 250px; width: 250px;
margin-left: -125px; margin-left: -125px;
border: 1px solid #ddd; border: 1px solid #ddd;
text-align: center; text-align: center;
color: #999; color: #999;
font-size: 11px; font-size: 11px;
padding: 2px 0; padding: 2px 0;
} }
   
.dataTables_length { .dataTables_length {
width: 40%; width: 40%;
float: left; float: left;
} }
   
.dataTables_filter { .dataTables_filter {
width: 50%; width: 50%;
float: right; float: right;
text-align: right; text-align: right;
} }
   
.dataTables_info { .dataTables_info {
width: 50%; width: 50%;
float: left; float: left;
} }
   
.dataTables_paginate { .dataTables_paginate {
float: right; float: right;
text-align: right; text-align: right;
} }
   
/* Pagination nested */ /* Pagination nested */
.paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next {
height: 19px; height: 19px;
width: 19px; width: 19px;
margin-left: 3px; margin-left: 3px;
float: left; float: left;
} }
   
.paginate_disabled_previous { .paginate_disabled_previous {
background-image: url('../images/back_disabled.jpg'); background-image: url('../images/back_disabled.jpg');
} }
   
.paginate_enabled_previous { .paginate_enabled_previous {
background-image: url('../images/back_enabled.jpg'); background-image: url('../images/back_enabled.jpg');
} }
   
.paginate_disabled_next { .paginate_disabled_next {
background-image: url('../images/forward_disabled.jpg'); background-image: url('../images/forward_disabled.jpg');
} }
   
.paginate_enabled_next { .paginate_enabled_next {
background-image: url('../images/forward_enabled.jpg'); background-image: url('../images/forward_enabled.jpg');
} }
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables display * DataTables display
*/ */
table.display { table.display {
margin: 0 auto; margin: 0 auto;
width: 100%; width: 100%;
clear: both; clear: both;
border-collapse: collapse; border-collapse: collapse;
} }
   
table.display tfoot th { table.display tfoot th {
padding: 3px 0px 3px 10px; padding: 3px 0px 3px 10px;
font-weight: bold; font-weight: bold;
font-weight: normal; font-weight: normal;
} }
   
table.display tr.heading2 td { table.display tr.heading2 td {
border-bottom: 1px solid #aaa; border-bottom: 1px solid #aaa;
} }
   
table.display td { table.display td {
padding: 3px 10px; padding: 3px 10px;
} }
   
table.display td.center { table.display td.center {
text-align: center; text-align: center;
} }
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables sorting * DataTables sorting
*/ */
   
.sorting_asc { .sorting_asc {
background: url('../images/sort_asc.jpg') no-repeat center right; background: url('../images/sort_asc.jpg') no-repeat center right;
} }
   
.sorting_desc { .sorting_desc {
background: url('../images/sort_desc.jpg') no-repeat center right; background: url('../images/sort_desc.jpg') no-repeat center right;
} }
   
.sorting { .sorting {
background: url('../images/sort_both.jpg') no-repeat center right; background: url('../images/sort_both.jpg') no-repeat center right;
} }
   
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables row classes * DataTables row classes
*/ */
table.display tr.odd.gradeA { table.display tr.odd.gradeA {
background-color: #ddffdd; background-color: #ddffdd;
} }
   
table.display tr.even.gradeA { table.display tr.even.gradeA {
background-color: #eeffee; background-color: #eeffee;
} }
   
   
   
   
table.display tr.odd.gradeA { table.display tr.odd.gradeA {
background-color: #ddffdd; background-color: #ddffdd;
} }
   
table.display tr.even.gradeA { table.display tr.even.gradeA {
background-color: #eeffee; background-color: #eeffee;
} }
   
table.display tr.odd.gradeC { table.display tr.odd.gradeC {
background-color: #ddddff; background-color: #ddddff;
} }
   
table.display tr.even.gradeC { table.display tr.even.gradeC {
background-color: #eeeeff; background-color: #eeeeff;
} }
   
table.display tr.odd.gradeX { table.display tr.odd.gradeX {
background-color: #ffdddd; background-color: #ffdddd;
} }
   
table.display tr.even.gradeX { table.display tr.even.gradeX {
background-color: #ffeeee; background-color: #ffeeee;
} }
   
table.display tr.odd.gradeU { table.display tr.odd.gradeU {
background-color: #ddd; background-color: #ddd;
} }
   
table.display tr.even.gradeU { table.display tr.even.gradeU {
background-color: #eee; background-color: #eee;
} }
   
   
tr.odd { tr.odd {
background-color: #E2E4FF; background-color: #E2E4FF;
} }
   
tr.even { tr.even {
background-color: white; background-color: white;
} }
   
   
   
   
   
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Misc * Misc
*/ */
.dataTables_scroll { .dataTables_scroll {
clear: both; clear: both;
} }
   
.top, .bottom { .top, .bottom {
padding: 15px; padding: 15px;
background-color: #F5F5F5; background-color: #F5F5F5;
border: 1px solid #CCCCCC; border: 1px solid #CCCCCC;
} }
   
.top .dataTables_info { .top .dataTables_info {
float: none; float: none;
} }
   
.clear { .clear {
clear: both; clear: both;
} }
   
.dataTables_empty { .dataTables_empty {
text-align: center; text-align: center;
} }
   
tfoot input { tfoot input {
margin: 0.5em 0; margin: 0.5em 0;
width: 100%; width: 100%;
color: #444; color: #444;
} }
   
tfoot input.search_init { tfoot input.search_init {
color: #999; color: #999;
} }
   
td.group { td.group {
background-color: #d1cfd0; background-color: #d1cfd0;
border-bottom: 2px solid #A19B9E; border-bottom: 2px solid #A19B9E;
border-top: 2px solid #A19B9E; border-top: 2px solid #A19B9E;
} }
   
td.details { td.details {
background-color: #d1cfd0; background-color: #d1cfd0;
border: 2px solid #A19B9E; border: 2px solid #A19B9E;
} }
   
   
.example_alt_pagination div.dataTables_info { .example_alt_pagination div.dataTables_info {
width: 40%; width: 40%;
} }
   
.paging_full_numbers span.paginate_button, .paging_full_numbers span.paginate_button,
.paging_full_numbers span.paginate_active { .paging_full_numbers span.paginate_active {
border: 1px solid #aaa; border: 1px solid #aaa;
-webkit-border-radius: 5px; -webkit-border-radius: 5px;
-moz-border-radius: 5px; -moz-border-radius: 5px;
padding: 2px 5px; padding: 2px 5px;
margin: 0 3px; margin: 0 3px;
cursor: pointer; cursor: pointer;
*cursor: hand; *cursor: hand;
} }
   
.paging_full_numbers span.paginate_button { .paging_full_numbers span.paginate_button {
background-color: #ddd; background-color: #ddd;
} }
   
.paging_full_numbers span.paginate_button:hover { .paging_full_numbers span.paginate_button:hover {
background-color: #ccc; background-color: #ccc;
} }
   
.paging_full_numbers span.paginate_active { .paging_full_numbers span.paginate_active {
background-color: #99B3FF; background-color: #99B3FF;
} }
   
table.display tr.even.row_selected td { table.display tr.even.row_selected td {
background-color: #B0BED9; background-color: #B0BED9;
} }
   
table.display tr.odd.row_selected td { table.display tr.odd.row_selected td {
background-color: #9FAFD1; background-color: #9FAFD1;
} }
   
   
/* /*
* Sorting classes for columns * Sorting classes for columns
*/ */
/* For the standard odd/even */ /* For the standard odd/even */
tr.odd td.sorting_1 { tr.odd td.sorting_1 {
background-color: #D3D6FF; background-color: #D3D6FF;
} }
   
tr.odd td.sorting_2 { tr.odd td.sorting_2 {
background-color: #DADCFF; background-color: #DADCFF;
} }
   
tr.odd td.sorting_3 { tr.odd td.sorting_3 {
background-color: #E0E2FF; background-color: #E0E2FF;
} }
   
tr.even td.sorting_1 { tr.even td.sorting_1 {
background-color: #EAEBFF; background-color: #EAEBFF;
} }
   
tr.even td.sorting_2 { tr.even td.sorting_2 {
background-color: #F2F3FF; background-color: #F2F3FF;
} }
   
tr.even td.sorting_3 { tr.even td.sorting_3 {
background-color: #F9F9FF; background-color: #F9F9FF;
} }
   
   
/* For the Conditional-CSS grading rows */ /* For the Conditional-CSS grading rows */
/* /*
Colour calculations (based off the main row colours) Colour calculations (based off the main row colours)
Level 1: Level 1:
dd > c4 dd > c4
ee > d5 ee > d5
Level 2: Level 2:
dd > d1 dd > d1
ee > e2 ee > e2
*/ */
tr.odd.gradeA td.sorting_1 { tr.odd.gradeA td.sorting_1 {
background-color: #c4ffc4; background-color: #c4ffc4;
} }
   
tr.odd.gradeA td.sorting_2 { tr.odd.gradeA td.sorting_2 {
background-color: #d1ffd1; background-color: #d1ffd1;
} }
   
tr.odd.gradeA td.sorting_3 { tr.odd.gradeA td.sorting_3 {
background-color: #d1ffd1; background-color: #d1ffd1;
} }
   
tr.even.gradeA td.sorting_1 { tr.even.gradeA td.sorting_1 {
background-color: #d5ffd5; background-color: #d5ffd5;
} }
   
tr.even.gradeA td.sorting_2 { tr.even.gradeA td.sorting_2 {
background-color: #e2ffe2; background-color: #e2ffe2;
} }
   
tr.even.gradeA td.sorting_3 { tr.even.gradeA td.sorting_3 {
background-color: #e2ffe2; background-color: #e2ffe2;
} }
   
tr.odd.gradeC td.sorting_1 { tr.odd.gradeC td.sorting_1 {
background-color: #c4c4ff; background-color: #c4c4ff;
} }
   
tr.odd.gradeC td.sorting_2 { tr.odd.gradeC td.sorting_2 {
background-color: #d1d1ff; background-color: #d1d1ff;
} }
   
tr.odd.gradeC td.sorting_3 { tr.odd.gradeC td.sorting_3 {
background-color: #d1d1ff; background-color: #d1d1ff;
} }
   
tr.even.gradeC td.sorting_1 { tr.even.gradeC td.sorting_1 {
background-color: #d5d5ff; background-color: #d5d5ff;
} }
   
tr.even.gradeC td.sorting_2 { tr.even.gradeC td.sorting_2 {
background-color: #e2e2ff; background-color: #e2e2ff;
} }
   
tr.even.gradeC td.sorting_3 { tr.even.gradeC td.sorting_3 {
background-color: #e2e2ff; background-color: #e2e2ff;
} }
   
tr.odd.gradeX td.sorting_1 { tr.odd.gradeX td.sorting_1 {
background-color: #ffc4c4; background-color: #ffc4c4;
} }
   
tr.odd.gradeX td.sorting_2 { tr.odd.gradeX td.sorting_2 {
background-color: #ffd1d1; background-color: #ffd1d1;
} }
   
tr.odd.gradeX td.sorting_3 { tr.odd.gradeX td.sorting_3 {
background-color: #ffd1d1; background-color: #ffd1d1;
} }
   
tr.even.gradeX td.sorting_1 { tr.even.gradeX td.sorting_1 {
background-color: #ffd5d5; background-color: #ffd5d5;
} }
   
tr.even.gradeX td.sorting_2 { tr.even.gradeX td.sorting_2 {
background-color: #ffe2e2; background-color: #ffe2e2;
} }
   
tr.even.gradeX td.sorting_3 { tr.even.gradeX td.sorting_3 {
background-color: #ffe2e2; background-color: #ffe2e2;
} }
   
tr.odd.gradeU td.sorting_1 { tr.odd.gradeU td.sorting_1 {
background-color: #c4c4c4; background-color: #c4c4c4;
} }
   
tr.odd.gradeU td.sorting_2 { tr.odd.gradeU td.sorting_2 {
background-color: #d1d1d1; background-color: #d1d1d1;
} }
   
tr.odd.gradeU td.sorting_3 { tr.odd.gradeU td.sorting_3 {
background-color: #d1d1d1; background-color: #d1d1d1;
} }
   
tr.even.gradeU td.sorting_1 { tr.even.gradeU td.sorting_1 {
background-color: #d5d5d5; background-color: #d5d5d5;
} }
   
tr.even.gradeU td.sorting_2 { tr.even.gradeU td.sorting_2 {
background-color: #e2e2e2; background-color: #e2e2e2;
} }
   
tr.even.gradeU td.sorting_3 { tr.even.gradeU td.sorting_3 {
background-color: #e2e2e2; background-color: #e2e2e2;
} }
   
   
/* /*
* Row highlighting example * Row highlighting example
*/ */
.ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted {
background-color: #ECFFB3; background-color: #ECFFB3;
} }
   
.ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted {
background-color: #E6FF99; background-color: #E6FF99;
} }
<?php <?php
   
include_once ("./lib/common.inc.php"); include_once ("./lib/common.inc.php");
$input = strtolower($_REQUEST['input']); $input = strtolower($_REQUEST['input']);
$len = strlen($input); $len = strlen($input);
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0; $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;
$aResults = array(); $aResults = array();
$count = 0; $count = 0;
if ($len) { if ($len > 2) {
$query = 'SELECT mode("supplierName"), MAX("supplierABN"), count(*) as count $query = 'SELECT text_mode("supplierName"), MAX("supplierABN"), count(*) as count
FROM contractnotice FROM contractnotice
WHERE "supplierName" ILIKE :supplierName WHERE "supplierName" ILIKE :supplierName or "supplierABN"::text = :supplierABN
GROUP BY "supplierName" GROUP BY "supplierName"
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 4; LIMIT 4;
'; ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$supplierName = $input . '%'; $supplierName = $input . '%';
$query->bindParam(":supplierName", $supplierName); $query->bindParam(":supplierName", $supplierName);
  $supplierABN = $input ;
  $query->bindParam(":supplierABN", $supplierABN);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$count++; $count++;
$aResults[] = array( $aResults[] = array(
"id" => "supplier-" . $row[1] . '-' . $row[0], "id" => "supplier-" . $row[1] . '-' . htmlspecialchars($row[0]),
"value" => htmlspecialchars($row[0]), "value" => htmlspecialchars($row[0]),
"info" => htmlspecialchars("Supplier - " . $row['count'] . " records") "info" => htmlspecialchars("Supplier - " . $row['count'] . " records")
); );
} }
$query = 'SELECT MAX("agencyName"), count(*) as count $query = 'SELECT MAX("agencyName"), count(*) as count
FROM contractnotice FROM contractnotice
WHERE "agencyName" ILIKE :agencyName WHERE "agencyName" ILIKE :agencyName
GROUP BY "agencyName" GROUP BY "agencyName"
ORDER BY count DESC ORDER BY count DESC
LIMIT 4;'; LIMIT 4;';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$agencyName = $input . '%'; $agencyName = $input . '%';
$query->bindParam(":agencyName", $agencyName); $query->bindParam(":agencyName", $agencyName);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$count++; $count++;
$aResults[] = array( $aResults[] = array(
"id" => "agency-" . $row[0], "id" => "agency-" . $row[0],
"value" => htmlspecialchars($row[0]), "value" => htmlspecialchars($row[0]),
"info" => htmlspecialchars("Government Agency - " . $row['count'] . " records") "info" => htmlspecialchars("Government Agency - " . $row['count'] . " records")
); );
} }
$query = "SELECT \"CNID\", description, value FROM contractnotice $query = "SELECT \"CNID\", description, value FROM contractnotice
WHERE to_tsvector('english', description) @@ plainto_tsquery('english', :input)"; WHERE to_tsvector('english', description) @@ plainto_tsquery('english', :input)";
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":input", $input); $query->bindParam(":input", $input);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$count++; $count++;
$aResults[] = array( $aResults[] = array(
"id" => "cnid-" . $row[0], "id" => "cnid-" . $row[0],
"value" => htmlspecialchars($row['description']), "value" => htmlspecialchars($row['description']),
"info" => htmlspecialchars("Contract Notice - Value ".$row['value']) "info" => htmlspecialchars("Contract Notice - Value ".$row['value'])
); );
} }
} }
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Pragma: no-cache"); // HTTP/1.0 header("Pragma: no-cache"); // HTTP/1.0
if (isset($_REQUEST['json'])) { if (isset($_REQUEST['json'])) {
header("Content-Type: application/json"); header("Content-Type: application/json");
echo "{\"results\": ["; echo "{\"results\": [";
$arr = array(); $arr = array();
for ($i = 0; $i < count($aResults); $i++) { for ($i = 0; $i < count($aResults); $i++) {
$arr[] = "{\"id\": \"" . $aResults[$i]['id'] . "\", \"value\": \"" . $aResults[$i]['value'] . "\", \"info\": \"\"}"; $arr[] = "{\"id\": \"" . $aResults[$i]['id'] . "\", \"value\": \"" . $aResults[$i]['value'] . "\", \"info\": \"\"}";
} }
echo implode(", ", $arr); echo implode(", ", $arr);
echo "]}"; echo "]}";
} else { } else {
header("Content-Type: text/xml"); header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>"; echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
for ($i = 0; $i < count($aResults); $i++) { for ($i = 0; $i < count($aResults); $i++) {
echo "<rs id=\"" . $aResults[$i]['id'] . "\" info=\"" . $aResults[$i]['info'] . "\">" . $aResults[$i]['value'] . "</rs>"; echo "<rs id=\"" . $aResults[$i]['id'] . "\" info=\"" . $aResults[$i]['info'] . "\">" . $aResults[$i]['value'] . "</rs>";
} }
echo "</results>"; echo "</results>";
} }
?> ?>