text mode
text mode

<?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); agencySuppliersGraph($agency);
// MethodCountGraph($agency); /*
// CnCGraph($agency); * * Common categories and uncommon categories
// MethodValueGraph($agency); * Procurement method in text, seperate Open via SON from Open
/* biggest contracts * Consultancies, Confidentialities percentage
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 */ Compliance statistics: amendments, delay in reporting average and number completely late */
   
$query = 'SELECT "CNID", "description", "value", "agencyName", "category", $query = 'SELECT "CNID", "description", "value", "agencyName", "category",
"contractStart", "supplierName" "contractStart", "supplierName"
FROM contractnotice FROM contractnotice
WHERE ' .$yearQ . ' "agencyName" like :agency and "childCN" is null WHERE ' .$yearQ . ' "agencyName" like :agency and "childCN" is null
ORDER BY "value" DESC limit 100'; 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> echo "<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['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) {
  $query = 'SELECT text_mode("supplierName") as "supplierName" from contractnotice where "supplierABN" = :supplierABN group by "supplierABN"';
  $query = $conn->prepare($query);
  $query->bindParam(":supplierABN", $supplierABN);
  $query->execute();
  databaseError($conn->errorInfo());
  $title = reset($query->fetchAll())['supplierName'];
  }
  include_header(str_replace("%","",$title));
  echo '<center><h1>'.str_replace("%","",$title).'</h1></center>';
agenciesGraph(); agenciesGraph();
// MethodCountGraph($supplierS); /*
// CnCGraph($supplierS); * Make supplier name the most common name for this ABN
// MethodValueGraph($supplierS); * Common names and uncommon names
/* lobbyist ties * Common categories and uncommon categories
  * Procurement method in text, seperate Open via SON from Open
links to ABR/ASIC/Google News/ASX/Court records * Consultancies, Confidentialities percentage
  */
total value to various agencies (bar graph)  
   
spread procurement methods + percent consultancies + percent confidential (bar graph)  
   
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 . ' ' . $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 $supplierQ . ' ' . $standardQ
. ' and contractnotice."SONID" != \'\' group by contractnotice."SONID"'; . ' and contractnotice."SONID" != \'\' group by contractnotice."SONID"';
$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());
echo "<table> <thead> echo "<h3>Standing Offers/Panels</h3><table> <thead>
<tr> <tr>
<th>Standing Offer</th> <th>Standing Offer</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> echo ("<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> echo "</table><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
$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
} }
?> ?>
   
<?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>";
} }
?> ?>