fix indentation and misc errors according to PSR2 coding style guide

This commit is contained in:
Marc Tobias Metten
2016-09-14 03:16:46 +02:00
parent 74c06ef877
commit 4a321487f3
21 changed files with 406 additions and 374 deletions

View File

@@ -48,6 +48,7 @@ class Geocode
protected $sQuery = false; protected $sQuery = false;
protected $aStructuredQuery = false; protected $aStructuredQuery = false;
function Geocode(&$oDB) function Geocode(&$oDB)
{ {
$this->oDB =& $oDB; $this->oDB =& $oDB;
@@ -131,18 +132,18 @@ class Geocode
function setFeatureType($sFeatureType) function setFeatureType($sFeatureType)
{ {
switch ($sFeatureType) { switch ($sFeatureType) {
case 'country': case 'country':
$this->setRankRange(4, 4); $this->setRankRange(4, 4);
break; break;
case 'state': case 'state':
$this->setRankRange(8, 8); $this->setRankRange(8, 8);
break; break;
case 'city': case 'city':
$this->setRankRange(14, 16); $this->setRankRange(14, 16);
break; break;
case 'settlement': case 'settlement':
$this->setRankRange(8, 20); $this->setRankRange(8, 20);
break; break;
} }
} }
@@ -397,7 +398,7 @@ class Geocode
$sSQL .= ",extratags->'place' "; $sSQL .= ",extratags->'place' ";
if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) { if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
//only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
// with start- and endnumber, the common osm housenumbers are usually saved as points // with start- and endnumber, the common osm housenumbers are usually saved as points
$sHousenumbers = ""; $sHousenumbers = "";
$i = 0; $i = 0;
@@ -408,7 +409,7 @@ class Geocode
if ($i<$length) $sHousenumbers .= ", "; if ($i<$length) $sHousenumbers .= ", ";
} }
if (CONST_Use_US_Tiger_Data) { if (CONST_Use_US_Tiger_Data) {
//Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join) // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
$sSQL .= " union"; $sSQL .= " union";
$sSQL .= " select 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code"; $sSQL .= " select 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code";
$sSQL .= ", get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress "; $sSQL .= ", get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress ";
@@ -421,7 +422,7 @@ class Geocode
$sSQL .= ", (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance "; $sSQL .= ", (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance ";
$sSQL .= ", null as extra_place "; $sSQL .= ", null as extra_place ";
$sSQL .= " from (select place_id"; $sSQL .= " from (select place_id";
//interpolate the Tiger housenumbers here // interpolate the Tiger housenumbers here
$sSQL .= ", ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) as centroid, parent_place_id, housenumber_for_place"; $sSQL .= ", ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) as centroid, parent_place_id, housenumber_for_place";
$sSQL .= " from (location_property_tiger "; $sSQL .= " from (location_property_tiger ";
$sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) "; $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
@@ -444,7 +445,7 @@ class Geocode
$sSQL .= " where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance,"; $sSQL .= " where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance,";
$sSQL .= " null as extra_place "; $sSQL .= " null as extra_place ";
$sSQL .= " from (select place_id, calculated_country_code "; $sSQL .= " from (select place_id, calculated_country_code ";
//interpolate the housenumbers here // interpolate the housenumbers here
$sSQL .= ", CASE WHEN startnumber != endnumber THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) "; $sSQL .= ", CASE WHEN startnumber != endnumber THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
$sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) END as centroid"; $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) END as centroid";
$sSQL .= ", parent_place_id, housenumber_for_place "; $sSQL .= ", parent_place_id, housenumber_for_place ";
@@ -476,7 +477,8 @@ class Geocode
$sSQL .= " order by importance desc"; $sSQL .= " order by importance desc";
if (CONST_Debug) { if (CONST_Debug) {
echo "<hr>"; var_dump($sSQL); echo "<hr>";
var_dump($sSQL);
} }
$aSearchResults = chksql( $aSearchResults = chksql(
$this->oDB->getAll($sSQL), $this->oDB->getAll($sSQL),
@@ -738,6 +740,8 @@ class Geocode
name: full name (currently the same as langaddress) name: full name (currently the same as langaddress)
foundorder: secondary ordering for places with same importance foundorder: secondary ordering for places with same importance
*/ */
function lookup() function lookup()
{ {
if (!$this->sQuery && !$this->aStructuredQuery) return false; if (!$this->sQuery && !$this->aStructuredQuery) return false;
@@ -939,7 +943,7 @@ class Geocode
} }
} elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) { } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
// US ZIP+4 codes - if there is no token, // US ZIP+4 codes - if there is no token,
// merge in the 5-digit ZIP code // merge in the 5-digit ZIP code
if (isset($aValidTokens[$aData[1]])) { if (isset($aValidTokens[$aData[1]])) {
foreach ($aValidTokens[$aData[1]] as $aToken) { foreach ($aValidTokens[$aData[1]] as $aToken) {
if (!$aToken['class']) { if (!$aToken['class']) {
@@ -1413,7 +1417,8 @@ class Geocode
} }
if (CONST_Debug) { if (CONST_Debug) {
echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); echo "<br><b>Place IDs:</b> ";
var_Dump($aPlaceIDs);
} }
foreach ($aPlaceIDs as $iPlaceID) { foreach ($aPlaceIDs as $iPlaceID) {
@@ -1495,7 +1500,8 @@ class Geocode
} }
if (CONST_Debug) { if (CONST_Debug) {
echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); echo '<i>Recheck words:<\i>';
var_dump($aRecheckWords);
} }
$oPlaceLookup = new PlaceLookup($this->oDB); $oPlaceLookup = new PlaceLookup($this->oDB);
@@ -1577,15 +1583,15 @@ class Geocode
$aResult['name'] = $aResult['langaddress']; $aResult['name'] = $aResult['langaddress'];
// secondary ordering (for results with same importance (the smaller the better): // secondary ordering (for results with same importance (the smaller the better):
// - approximate importance of address parts // - approximate importance of address parts
$aResult['foundorder'] = -$aResult['addressimportance']/10; $aResult['foundorder'] = -$aResult['addressimportance']/10;
// - number of exact matches from the query // - number of exact matches from the query
if (isset($this->exactMatchCache[$aResult['place_id']])) { if (isset($this->exactMatchCache[$aResult['place_id']])) {
$aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']]; $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
} elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) { } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
$aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']]; $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
} }
// - importance of the class/type // - importance of the class/type
if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
&& $aClassType[$aResult['class'].':'.$aResult['type']]['importance'] && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
) { ) {
@@ -1625,9 +1631,5 @@ class Geocode
} }
return $aSearchResults; return $aSearchResults;
} // end lookup() } // end lookup()
} // end class } // end class

View File

@@ -4,9 +4,10 @@ class ParameterParser
{ {
private $aParams; private $aParams;
function __construct($aParams = NULL)
function __construct($aParams = null)
{ {
$this->aParams = ($aParams === NULL) ? $_GET : $aParams; $this->aParams = ($aParams === null) ? $_GET : $aParams;
} }
function getBool($sName, $bDefault = false) function getBool($sName, $bDefault = false)
@@ -77,9 +78,9 @@ class ParameterParser
return $aDefault; return $aDefault;
} }
function getPreferredLanguages($sFallback = NULL) function getPreferredLanguages($sFallback = null)
{ {
if ($sFallback === NULL && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) { if ($sFallback === null && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
$sFallback = $_SERVER["HTTP_ACCEPT_LANGUAGE"]; $sFallback = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
} }

View File

@@ -237,15 +237,18 @@ class PlaceLookup
// returns an array which will contain the keys /* returns an array which will contain the keys
// aBoundingBox * aBoundingBox
// and may also contain one or more of the keys * and may also contain one or more of the keys
// asgeojson * asgeojson
// askml * askml
// assvg * assvg
// astext * astext
// lat * lat
// lon * lon
*/
function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null) function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null)
{ {
@@ -301,7 +304,7 @@ class PlaceLookup
(string)$aPointPolygon['maxlon'] (string)$aPointPolygon['maxlon']
); );
} }
} // CONST_Search_AreaPolygons }
// as a fallback we generate a bounding box without knowing the size of the geometry // as a fallback we generate a bounding box without knowing the size of the geometry
if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) { if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {

View File

@@ -5,11 +5,13 @@ class ReverseGeocode
protected $oDB; protected $oDB;
protected $iMaxRank = 28; protected $iMaxRank = 28;
function ReverseGeocode(&$oDB) function ReverseGeocode(&$oDB)
{ {
$this->oDB =& $oDB; $this->oDB =& $oDB;
} }
function setZoom($iZoom) function setZoom($iZoom)
{ {
// Zoom to rank, this could probably be calculated but a lookup gives fine control // Zoom to rank, this could probably be calculated but a lookup gives fine control
@@ -38,8 +40,13 @@ class ReverseGeocode
$this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28; $this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
} }
// returns { place_id =>, type => '(osm|tiger)' }
// fails if no place was found /* lookup()
* returns { place_id =>, type => '(osm|tiger)' }
* fails if no place was found
*/
function lookup($fLat, $fLon, $bDoInterpolation = true) function lookup($fLat, $fLon, $bDoInterpolation = true)
{ {
$sPointSQL = 'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)'; $sPointSQL = 'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)';
@@ -111,7 +118,7 @@ class ReverseGeocode
if ($aPlaceLine) { if ($aPlaceLine) {
if (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine); if (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine);
if ($aPlace['rank_search'] == 30) { if ($aPlace['rank_search'] == 30) {
// if a house was already found in placex, we have to find out, // if a house was already found in placex, we have to find out,
// if the placex house or the interpolated house are closer to the searched point // if the placex house or the interpolated house are closer to the searched point
// distance between point and placex house // distance between point and placex house
$sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID; $sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID;
@@ -204,5 +211,4 @@ class ReverseGeocode
'fraction' => ($bPlaceIsTiger || $bPlaceIsLine) ? $fFraction : -1 'fraction' => ($bPlaceIsTiger || $bPlaceIsLine) ? $fFraction : -1
); );
} }
} }

View File

@@ -1,5 +1,6 @@
<?php <?php
function getCmdOpt($aArg, $aSpec, &$aResult, $bExitOnError = false, $bExitOnUnknown = false) function getCmdOpt($aArg, $aSpec, &$aResult, $bExitOnError = false, $bExitOnUnknown = false)
{ {
$aQuick = array(); $aQuick = array();

View File

@@ -2,6 +2,7 @@
require_once('DB.php'); require_once('DB.php');
function &getDB($bNew = false, $bPersistent = false) function &getDB($bNew = false, $bPersistent = false)
{ {
// Get the database object // Get the database object

View File

@@ -9,6 +9,7 @@ require_once('ParameterParser.php');
* *
*/ */
function chksql($oSql, $sMsg = "Database request failed") function chksql($oSql, $sMsg = "Database request failed")
{ {
if (!PEAR::isError($oSql)) return $oSql; if (!PEAR::isError($oSql)) return $oSql;
@@ -95,4 +96,3 @@ if (CONST_NoAccessControl) {
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') exit; if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') exit;
if (CONST_Debug) header('Content-type: text/html; charset=utf-8'); if (CONST_Debug) header('Content-type: text/html; charset=utf-8');

View File

@@ -1,5 +1,6 @@
<?php <?php
function fail($sError, $sUserError = false) function fail($sError, $sUserError = false)
{ {
if (!$sUserError) $sUserError = $sError; if (!$sUserError) $sUserError = $sError;
@@ -98,10 +99,6 @@ function getTokensFromSets($aSets)
} }
/*
GB Postcode functions
*/
function gbPostcodeCalculate($sPostcode, $sPostcodeSector, $sPostcodeEnd, &$oDB) function gbPostcodeCalculate($sPostcode, $sPostcodeSector, $sPostcodeEnd, &$oDB)
{ {
// Try an exact match on the gb_postcode table // Try an exact match on the gb_postcode table
@@ -599,72 +596,78 @@ function addQuotes($s)
return "'".$s."'"; return "'".$s."'";
} }
// returns boolean
function validLatLon($fLat, $fLon) function validLatLon($fLat, $fLon)
{ {
return ($fLat <= 90.1 && $fLat >= -90.1 && $fLon <= 180.1 && $fLon >= -180.1); return ($fLat <= 90.1 && $fLat >= -90.1 && $fLon <= 180.1 && $fLon >= -180.1);
} }
// Do we have anything that looks like a lat/lon pair?
// returns array(lat,lon,query_with_lat_lon_removed)
// or null
function looksLikeLatLonPair($sQuery) function looksLikeLatLonPair($sQuery)
{ {
// Do we have anything that looks like a lat/lon pair?
// returns array(lat,lon,query_with_lat_lon_removed)
// or null
$sFound = null; $sFound = null;
$fQueryLat = null; $fQueryLat = null;
$fQueryLon = null; $fQueryLon = null;
if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[° ]+([0-9.]+)?[\']*[, ]+([EW])[ ]+([0-9]+)[° ]+([0-9]+[0-9.]*)[\']*?\\b/', $sQuery, $aData)) { if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[° ]+([0-9.]+)?[\']*[, ]+([EW])[ ]+([0-9]+)[° ]+([0-9]+[0-9.]*)[\']*?\\b/', $sQuery, $aData)) {
// 1 2 3 4 5 6 /* 1 2 3 4 5 6
// degrees decimal minutes * degrees decimal minutes
// N 40 26.767, W 79 58.933 * N 40 26.767, W 79 58.933
// N 40°26.767, W 79°58.933 * N 40°26.767, W 79°58.933
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60); $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
$fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60); $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
} elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+[0-9.]*)?[\']*[ ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+[0-9.]*)?[\' ]+([EW])\\b/', $sQuery, $aData)) { } elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+[0-9.]*)?[\']*[ ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+[0-9.]*)?[\' ]+([EW])\\b/', $sQuery, $aData)) {
// 1 2 3 4 5 6 /* 1 2 3 4 5 6
// degrees decimal minutes * degrees decimal minutes
// 40 26.767 N, 79 58.933 W * 40 26.767 N, 79 58.933 W
// 40° 26.767 N 79° 58.933 W * 40° 26.767 N 79° 58.933 W
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60); $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
$fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60); $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
} elseif (preg_match('/\\b([NS])[ ]([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″"]*[, ]+([EW])[ ]([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″"]*\\b/', $sQuery, $aData)) { } elseif (preg_match('/\\b([NS])[ ]([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″"]*[, ]+([EW])[ ]([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″"]*\\b/', $sQuery, $aData)) {
// 1 2 3 4 5 6 7 8 /* 1 2 3 4 5 6 7 8
// degrees decimal seconds * degrees decimal seconds
// N 40 26 46 W 79 58 56 * N 40 26 46 W 79 58 56
// N 40° 26 46″, W 79° 58 56″ * N 40° 26 46″, W 79° 58 56″
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60 + $aData[4]/3600); $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60 + $aData[4]/3600);
$fQueryLon = ($aData[5]=='E'?1:-1) * ($aData[6] + $aData[7]/60 + $aData[8]/3600); $fQueryLon = ($aData[5]=='E'?1:-1) * ($aData[6] + $aData[7]/60 + $aData[8]/3600);
} elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″" ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″" ]+([EW])\\b/', $sQuery, $aData)) { } elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″" ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+)[\' ]+([0-9]+)[″" ]+([EW])\\b/', $sQuery, $aData)) {
// 1 2 3 4 5 6 7 8 /* 1 2 3 4 5 6 7 8
// degrees decimal seconds * degrees decimal seconds
// 40 26 46 N 79 58 56 W * 40 26 46 N 79 58 56 W
// 40° 26 46″ N, 79° 58 56″ W * 40° 26 46″ N, 79° 58 56″ W
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = ($aData[4]=='N'?1:-1) * ($aData[1] + $aData[2]/60 + $aData[3]/3600); $fQueryLat = ($aData[4]=='N'?1:-1) * ($aData[1] + $aData[2]/60 + $aData[3]/3600);
$fQueryLon = ($aData[8]=='E'?1:-1) * ($aData[5] + $aData[6]/60 + $aData[7]/3600); $fQueryLon = ($aData[8]=='E'?1:-1) * ($aData[5] + $aData[6]/60 + $aData[7]/3600);
} elseif (preg_match('/\\b([NS])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*[, ]+([EW])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*\\b/', $sQuery, $aData)) { } elseif (preg_match('/\\b([NS])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*[, ]+([EW])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*\\b/', $sQuery, $aData)) {
// 1 2 3 4 /* 1 2 3 4
// degrees decimal * degrees decimal
// N 40.446° W 79.982° * N 40.446° W 79.982°
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2]); $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2]);
$fQueryLon = ($aData[3]=='E'?1:-1) * ($aData[4]); $fQueryLon = ($aData[3]=='E'?1:-1) * ($aData[4]);
} elseif (preg_match('/\\b([0-9]+[0-9]*\\.[0-9]+)[° ]+([NS])[, ]+([0-9]+[0-9]*\\.[0-9]+)[° ]+([EW])\\b/', $sQuery, $aData)) { } elseif (preg_match('/\\b([0-9]+[0-9]*\\.[0-9]+)[° ]+([NS])[, ]+([0-9]+[0-9]*\\.[0-9]+)[° ]+([EW])\\b/', $sQuery, $aData)) {
// 1 2 3 4 /* 1 2 3 4
// degrees decimal * degrees decimal
// 40.446° N 79.982° W * 40.446° N 79.982° W
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = ($aData[2]=='N'?1:-1) * ($aData[1]); $fQueryLat = ($aData[2]=='N'?1:-1) * ($aData[1]);
$fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[3]); $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[3]);
} elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData)) { } elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData)) {
// 1 2 3 4 /* 1 2 3 4
// degrees decimal * degrees decimal
// 12.34, 56.78 * 12.34, 56.78
// [12.456,-78.90] * [12.456,-78.90]
*/
$sFound = $aData[0]; $sFound = $aData[0];
$fQueryLat = $aData[2]; $fQueryLat = $aData[2];
$fQueryLon = $aData[3]; $fQueryLon = $aData[3];
@@ -679,7 +682,7 @@ function looksLikeLatLonPair($sQuery)
function geometryText2Points($geometry_as_text, $fRadius) function geometryText2Points($geometry_as_text, $fRadius)
{ {
$aPolyPoints = NULL; $aPolyPoints = null;
if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch)) { if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch)) {
// //
preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER); preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);

View File

@@ -1,5 +1,6 @@
<?php <?php
function logStart(&$oDB, $sType = '', $sQuery = '', $aLanguageList = array()) function logStart(&$oDB, $sType = '', $sQuery = '', $aLanguageList = array())
{ {
$fStartTime = microtime(true); $fStartTime = microtime(true);
@@ -70,5 +71,4 @@ function logEnd(&$oDB, $hLog, $iNumResults)
); );
file_put_contents(CONST_Log_File, $aOutdata, FILE_APPEND | LOCK_EX); file_put_contents(CONST_Log_File, $aOutdata, FILE_APPEND | LOCK_EX);
} }
} }

View File

@@ -1,5 +1,6 @@
<?php <?php
function formatOSMType($sType, $bIncludeExternal = true) function formatOSMType($sType, $bIncludeExternal = true)
{ {
if ($sType == 'N') return 'node'; if ($sType == 'N') return 'node';
@@ -38,4 +39,3 @@ function detailsLink($aFeature, $sTitle = false)
return '<a href="details.php?place_id='.$aFeature['place_id'].'">'.($sTitle?$sTitle:$aFeature['place_id']).'</a>'; return '<a href="details.php?place_id='.$aFeature['place_id'].'">'.($sTitle?$sTitle:$aFeature['place_id']).'</a>';
} }

View File

@@ -35,9 +35,9 @@ if ($aResult['list']) {
printf( printf(
" %-40s | %12s | %7s | %13s | %31s | %8s\n", " %-40s | %12s | %7s | %13s | %31s | %8s\n",
$sKey, $sKey,
$aDetails['totalBlocks'], $aDetails['totalBlocks'],
(int)$aDetails['currentBucketSize'], (int)$aDetails['currentBucketSize'],
$aDetails['currentlyBlocked']?'Y':'N', $aDetails['currentlyBlocked']?'Y':'N',
date("r", $aDetails['lastBlockTimestamp']), date("r", $aDetails['lastBlockTimestamp']),
$aDetails['isSleeping']?'Y':'N' $aDetails['isSleeping']?'Y':'N'
); );

View File

@@ -90,12 +90,14 @@ EOD;
$oDB->query($sSQL); $oDB->query($sSQL);
} }
function degreesAndMinutesToDecimal($iDegrees, $iMinutes = 0, $fSeconds = 0, $sNSEW = 'N') function degreesAndMinutesToDecimal($iDegrees, $iMinutes = 0, $fSeconds = 0, $sNSEW = 'N')
{ {
$sNSEW = strtoupper($sNSEW); $sNSEW = strtoupper($sNSEW);
return ($sNSEW == 'S' || $sNSEW == 'W'?-1:1) * ((float)$iDegrees + (float)$iMinutes/60 + (float)$fSeconds/3600); return ($sNSEW == 'S' || $sNSEW == 'W'?-1:1) * ((float)$iDegrees + (float)$iMinutes/60 + (float)$fSeconds/3600);
} }
function _parseWikipediaContent($sPageText) function _parseWikipediaContent($sPageText)
{ {
$sPageText = str_replace("\n", ' ', $sPageText); $sPageText = str_replace("\n", ' ', $sPageText);
@@ -113,83 +115,83 @@ function _parseWikipediaContent($sPageText)
$aState = array('body'); $aState = array('body');
foreach ($aPageText as $i => $sPart) { foreach ($aPageText as $i => $sPart) {
switch ($sPart) { switch ($sPart) {
case '{{': case '{{':
array_unshift($aTemplateStack, array('', array())); array_unshift($aTemplateStack, array('', array()));
array_unshift($aState, 'template'); array_unshift($aState, 'template');
break; break;
case '}}': case '}}':
if ($aState[0] == 'template' || $aState[0] == 'templateparam') { if ($aState[0] == 'template' || $aState[0] == 'templateparam') {
$aTemplate = array_shift($aTemplateStack); $aTemplate = array_shift($aTemplateStack);
array_shift($aState); array_shift($aState);
$aTemplates[] = $aTemplate; $aTemplates[] = $aTemplate;
}
break;
case '[[':
$sLinkPage = '';
$sLinkSyn = '';
array_unshift($aState, 'link');
break;
case ']]':
if ($aState[0] == 'link' || $aState[0] == 'linksynonim') {
if (!$sLinkSyn) $sLinkSyn = $sLinkPage;
if (substr($sLinkPage, 0, 6) == 'Image:') $sLinkSyn = substr($sLinkPage, 6);
$aLinks[] = array($sLinkPage, $sLinkSyn);
array_shift($aState);
switch ($aState[0]) {
case 'template':
$aTemplateStack[0][0] .= trim($sPart);
break;
case 'templateparam':
$aTemplateStack[0][1][0] .= $sLinkSyn;
break;
case 'link':
$sLinkPage .= trim($sPart);
break;
case 'linksynonim':
$sLinkSyn .= $sPart;
break;
case 'body':
$sPageBody .= $sLinkSyn;
break;
default:
var_dump($aState, $sPageName, $aTemplateStack, $sPart, $aPageText);
fail('unknown state');
} }
}
break;
case '|':
if ($aState[0] == 'template' || $aState[0] == 'templateparam') {
// Create a new template paramater
$aState[0] = 'templateparam';
array_unshift($aTemplateStack[0][1], '');
}
if ($aState[0] == 'link') $aState[0] = 'linksynonim';
break;
default:
switch ($aState[0]) {
case 'template':
$aTemplateStack[0][0] .= trim($sPart);
break; break;
case 'templateparam': case '[[':
$aTemplateStack[0][1][0] .= $sPart; $sLinkPage = '';
$sLinkSyn = '';
array_unshift($aState, 'link');
break; break;
case 'link': case ']]':
$sLinkPage .= trim($sPart); if ($aState[0] == 'link' || $aState[0] == 'linksynonim') {
if (!$sLinkSyn) $sLinkSyn = $sLinkPage;
if (substr($sLinkPage, 0, 6) == 'Image:') $sLinkSyn = substr($sLinkPage, 6);
$aLinks[] = array($sLinkPage, $sLinkSyn);
array_shift($aState);
switch ($aState[0]) {
case 'template':
$aTemplateStack[0][0] .= trim($sPart);
break;
case 'templateparam':
$aTemplateStack[0][1][0] .= $sLinkSyn;
break;
case 'link':
$sLinkPage .= trim($sPart);
break;
case 'linksynonim':
$sLinkSyn .= $sPart;
break;
case 'body':
$sPageBody .= $sLinkSyn;
break;
default:
var_dump($aState, $sPageName, $aTemplateStack, $sPart, $aPageText);
fail('unknown state');
}
}
break; break;
case 'linksynonim': case '|':
$sLinkSyn .= $sPart; if ($aState[0] == 'template' || $aState[0] == 'templateparam') {
break; // Create a new template paramater
case 'body': $aState[0] = 'templateparam';
$sPageBody .= $sPart; array_unshift($aTemplateStack[0][1], '');
}
if ($aState[0] == 'link') $aState[0] = 'linksynonim';
break; break;
default: default:
var_dump($aState, $aPageText); switch ($aState[0]) {
fail('unknown state'); case 'template':
} $aTemplateStack[0][0] .= trim($sPart);
break; break;
case 'templateparam':
$aTemplateStack[0][1][0] .= $sPart;
break;
case 'link':
$sLinkPage .= trim($sPart);
break;
case 'linksynonim':
$sLinkSyn .= $sPart;
break;
case 'body':
$sPageBody .= $sPart;
break;
default:
var_dump($aState, $aPageText);
fail('unknown state');
}
break;
} }
} }
return $aTemplates; return $aTemplates;
@@ -201,7 +203,7 @@ function _templatesToProperties($aTemplates)
foreach ($aTemplates as $iTemplate => $aTemplate) { foreach ($aTemplates as $iTemplate => $aTemplate) {
$aParams = array(); $aParams = array();
foreach (array_reverse($aTemplate[1]) as $iParam => $sParam) { foreach (array_reverse($aTemplate[1]) as $iParam => $sParam) {
if (($iPos = strpos($sParam, '=')) === FALSE) { if (($iPos = strpos($sParam, '=')) === false) {
$aParams[] = trim($sParam); $aParams[] = trim($sParam);
} else { } else {
$aParams[trim(substr($sParam, 0, $iPos))] = trim(substr($sParam, $iPos+1)); $aParams[trim(substr($sParam, 0, $iPos))] = trim(substr($sParam, $iPos+1));
@@ -224,7 +226,7 @@ function _templatesToProperties($aTemplates)
if (!isset($aPageProperties['sWebsite']) && isset($aParams['website']) && $aParams['website']) { if (!isset($aPageProperties['sWebsite']) && isset($aParams['website']) && $aParams['website']) {
if (preg_match('#^\\[?([^ \\]]+)[^\\]]*\\]?$#', $aParams['website'], $aMatch)) { if (preg_match('#^\\[?([^ \\]]+)[^\\]]*\\]?$#', $aParams['website'], $aMatch)) {
$aPageProperties['sWebsite'] = $aMatch[1]; $aPageProperties['sWebsite'] = $aMatch[1];
if (strpos($aPageProperties['sWebsite'], ':/'.'/') === FALSE) { if (strpos($aPageProperties['sWebsite'], ':/'.'/') === false) {
$aPageProperties['sWebsite'] = 'http:/'.'/'.$aPageProperties['sWebsite']; $aPageProperties['sWebsite'] = 'http:/'.'/'.$aPageProperties['sWebsite'];
} }
} }
@@ -306,7 +308,7 @@ function _templatesToProperties($aTemplates)
if (isset($aCMDResult['parse-wikipedia'])) { if (isset($aCMDResult['parse-wikipedia'])) {
$oDB =& getDB(); $oDB =& getDB();
$aArticleNames = $oDB->getCol('select page_title from content where page_namespace = 0 and page_id %10 = '.$aCMDResult['parse-wikipedia'].' and (page_content ilike \'%{{Coord%\' or (page_content ilike \'%lat%\' and page_content ilike \'%lon%\'))'); $aArticleNames = $oDB->getCol('select page_title from content where page_namespace = 0 and page_id %10 = '.$aCMDResult['parse-wikipedia'].' and (page_content ilike \'%{{Coord%\' or (page_content ilike \'%lat%\' and page_content ilike \'%lon%\'))');
// $aArticleNames = $oDB->getCol($sSQL = 'select page_title from content where page_namespace = 0 and (page_content ilike \'%{{Coord%\' or (page_content ilike \'%lat%\' and page_content ilike \'%lon%\')) and page_title in (\'Virginia\')'); // $aArticleNames = $oDB->getCol($sSQL = 'select page_title from content where page_namespace = 0 and (page_content ilike \'%{{Coord%\' or (page_content ilike \'%lat%\' and page_content ilike \'%lon%\')) and page_title in (\'Virginia\')');
foreach ($aArticleNames as $sArticleName) { foreach ($aArticleNames as $sArticleName) {
$sPageText = $oDB->getOne('select page_content from content where page_namespace = 0 and page_title = \''.pg_escape_string($sArticleName).'\''); $sPageText = $oDB->getOne('select page_content from content where page_namespace = 0 and page_title = \''.pg_escape_string($sArticleName).'\'');
$aP = _templatesToProperties(_parseWikipediaContent($sPageText)); $aP = _templatesToProperties(_parseWikipediaContent($sPageText));
@@ -342,16 +344,18 @@ if (isset($aCMDResult['parse-wikipedia'])) {
} }
} }
function nominatimXMLStart($hParser, $sName, $aAttr) function nominatimXMLStart($hParser, $sName, $aAttr)
{ {
global $aNominatRecords; global $aNominatRecords;
switch ($sName) { switch ($sName) {
case 'PLACE': case 'PLACE':
$aNominatRecords[] = $aAttr; $aNominatRecords[] = $aAttr;
break; break;
} }
} }
function nominatimXMLEnd($hParser, $sName) function nominatimXMLEnd($hParser, $sName)
{ {
} }
@@ -373,104 +377,104 @@ if (isset($aCMDResult['link'])) {
$fMaxDist = 0.0000001; $fMaxDist = 0.0000001;
$bUnknown = false; $bUnknown = false;
switch (strtolower($aRecord['infobox_type'])) { switch (strtolower($aRecord['infobox_type'])) {
case 'former country': case 'former country':
continue 2; continue 2;
case 'sea': case 'sea':
$fMaxDist = 60; // effectively turn it off $fMaxDist = 60; // effectively turn it off
$sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist); $sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist);
break; break;
case 'country': case 'country':
case 'island': case 'island':
case 'islands': case 'islands':
case 'continent': case 'continent':
$fMaxDist = 60; // effectively turn it off $fMaxDist = 60; // effectively turn it off
$sURL .= "&featuretype=country"; $sURL .= "&featuretype=country";
$sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist); $sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist);
break; break;
case 'prefecture japan': case 'prefecture japan':
$aRecord['name'] = trim(str_replace(' Prefecture', ' ', $aRecord['name'])); $aRecord['name'] = trim(str_replace(' Prefecture', ' ', $aRecord['name']));
break; break;
case 'state': case 'state':
case '#us state': case '#us state':
case 'county': case 'county':
case 'u.s. state': case 'u.s. state':
case 'u.s. state symbols': case 'u.s. state symbols':
case 'german state': case 'german state':
case 'province or territory of canada': case 'province or territory of canada':
case 'indian jurisdiction': case 'indian jurisdiction':
case 'province': case 'province':
case 'french region': case 'french region':
case 'region of italy': case 'region of italy':
case 'kommune': case 'kommune':
case '#australia state or territory': case '#australia state or territory':
case 'russian federal subject': case 'russian federal subject':
$fMaxDist = 4; $fMaxDist = 4;
$sURL .= "&featuretype=state"; $sURL .= "&featuretype=state";
$sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist); $sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist);
break; break;
case 'protected area': case 'protected area':
$fMaxDist = 1; $fMaxDist = 1;
$sURL .= "&nearlat=".$aRecord['lat']; $sURL .= "&nearlat=".$aRecord['lat'];
$sURL .= "&nearlon=".$aRecord['lon']; $sURL .= "&nearlon=".$aRecord['lon'];
$sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist); $sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist);
break; break;
case 'settlement': case 'settlement':
$bUnknown = true; $bUnknown = true;
break; break;
case 'french commune': case 'french commune':
case 'italian comune': case 'italian comune':
case 'uk place': case 'uk place':
case 'italian comune': case 'italian comune':
case 'australian place': case 'australian place':
case 'german place': case 'german place':
case '#geobox': case '#geobox':
case 'u.s. county': case 'u.s. county':
case 'municipality': case 'municipality':
case 'city japan': case 'city japan':
case 'russian inhabited locality': case 'russian inhabited locality':
case 'finnish municipality/land area': case 'finnish municipality/land area':
case 'england county': case 'england county':
case 'israel municipality': case 'israel municipality':
case 'russian city': case 'russian city':
case 'city': case 'city':
$fMaxDist = 0.2; $fMaxDist = 0.2;
$sURL .= "&featuretype=settlement"; $sURL .= "&featuretype=settlement";
$sURL .= "&viewbox=".($aRecord['lon']-0.5).",".($aRecord['lat']+0.5).",".($aRecord['lon']+0.5).",".($aRecord['lat']-0.5); $sURL .= "&viewbox=".($aRecord['lon']-0.5).",".($aRecord['lat']+0.5).",".($aRecord['lon']+0.5).",".($aRecord['lat']-0.5);
break; break;
case 'mountain': case 'mountain':
case 'mountain pass': case 'mountain pass':
case 'river': case 'river':
case 'lake': case 'lake':
case 'airport': case 'airport':
$fMaxDist = 0.2; $fMaxDist = 0.2;
$sURL .= "&viewbox=".($aRecord['lon']-0.5).",".($aRecord['lat']+0.5).",".($aRecord['lon']+0.5).",".($aRecord['lat']-0.5); $sURL .= "&viewbox=".($aRecord['lon']-0.5).",".($aRecord['lat']+0.5).",".($aRecord['lon']+0.5).",".($aRecord['lat']-0.5);
break; break;
case 'ship begin': case 'ship begin':
$fMaxDist = 0.1; $fMaxDist = 0.1;
$aTypes = array('wreck'); $aTypes = array('wreck');
$sURL .= "&viewbox=".($aRecord['lon']-0.01).",".($aRecord['lat']+0.01).",".($aRecord['lon']+0.01).",".($aRecord['lat']-0.01); $sURL .= "&viewbox=".($aRecord['lon']-0.01).",".($aRecord['lat']+0.01).",".($aRecord['lon']+0.01).",".($aRecord['lat']-0.01);
$sURL .= "&nearlat=".$aRecord['lat']; $sURL .= "&nearlat=".$aRecord['lat'];
$sURL .= "&nearlon=".$aRecord['lon']; $sURL .= "&nearlon=".$aRecord['lon'];
break; break;
case 'road': case 'road':
case 'university': case 'university':
case 'company': case 'company':
case 'department': case 'department':
$fMaxDist = 0.005; $fMaxDist = 0.005;
$sURL .= "&viewbox=".($aRecord['lon']-0.01).",".($aRecord['lat']+0.01).",".($aRecord['lon']+0.01).",".($aRecord['lat']-0.01); $sURL .= "&viewbox=".($aRecord['lon']-0.01).",".($aRecord['lat']+0.01).",".($aRecord['lon']+0.01).",".($aRecord['lat']-0.01);
$sURL .= "&bounded=1"; $sURL .= "&bounded=1";
$sURL .= "&nearlat=".$aRecord['lat']; $sURL .= "&nearlat=".$aRecord['lat'];
$sURL .= "&nearlon=".$aRecord['lon']; $sURL .= "&nearlon=".$aRecord['lon'];
break; break;
default: default:
$bUnknown = true; $bUnknown = true;
$fMaxDist = 0.005; $fMaxDist = 0.005;
$sURL .= "&viewbox=".($aRecord['lon']-0.01).",".($aRecord['lat']+0.01).",".($aRecord['lon']+0.01).",".($aRecord['lat']-0.01); $sURL .= "&viewbox=".($aRecord['lon']-0.01).",".($aRecord['lat']+0.01).",".($aRecord['lon']+0.01).",".($aRecord['lat']-0.01);
// $sURL .= "&bounded=1"; // $sURL .= "&bounded=1";
$sURL .= "&nearlat=".$aRecord['lat']; $sURL .= "&nearlat=".$aRecord['lat'];
$sURL .= "&nearlon=".$aRecord['lon']; $sURL .= "&nearlon=".$aRecord['lon'];
echo "-- Unknown: ".$aRecord['infobox_type']."\n"; echo "-- Unknown: ".$aRecord['infobox_type']."\n";
break; break;
} }
$sNameURL = $sURL.'&q='.urlencode($aRecord['name']); $sNameURL = $sURL.'&q='.urlencode($aRecord['name']);
@@ -494,7 +498,7 @@ if (isset($aCMDResult['link'])) {
$hXMLParser = xml_parser_create(); $hXMLParser = xml_parser_create();
xml_set_element_handler($hXMLParser, 'nominatimXMLStart', 'nominatimXMLEnd'); xml_set_element_handler($hXMLParser, 'nominatimXMLStart', 'nominatimXMLEnd');
xml_parse($hXMLParser, $sXML, true); xml_parse($hXMLParser, $sXML, true);
xml_parser_free($hXMLParser);# xml_parser_free($hXMLParser);
} }
} }
@@ -522,9 +526,15 @@ if (isset($aCMDResult['link'])) {
} else { } else {
$sSQL = "update wikipedia_article set osm_type="; $sSQL = "update wikipedia_article set osm_type=";
switch ($aNominatRecords[$i]['OSM_TYPE']) { switch ($aNominatRecords[$i]['OSM_TYPE']) {
case 'relation': $sSQL .= "'R'"; break; case 'relation':
case 'way': $sSQL .= "'W'"; break; $sSQL .= "'R'";
case 'node': $sSQL .= "'N'"; break; break;
case 'way':
$sSQL .= "'W'";
break;
case 'node':
$sSQL .= "'N'";
break;
} }
$sSQL .= ", osm_id=".$aNominatRecords[$i]['OSM_ID']." where language = '".pg_escape_string($aRecord['language'])."' and title = '".pg_escape_string($aRecord['title'])."'"; $sSQL .= ", osm_id=".$aNominatRecords[$i]['OSM_ID']." where language = '".pg_escape_string($aRecord['language'])."' and title = '".pg_escape_string($aRecord['title'])."'";
$oDB->query($sSQL); $oDB->query($sSQL);

View File

@@ -1,8 +1,7 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
// Apache log file $sFile = "sample.log.txt"; // Apache log file
$sFile = "sample.log.txt";
$sHost1 = 'http://mq-open-search-lm02.ihost.aol.com:8000/nominatim/v1'; $sHost1 = 'http://mq-open-search-lm02.ihost.aol.com:8000/nominatim/v1';
$sHost2 = 'http://mq-open-search-lm03.ihost.aol.com:8000/nominatim/v1'; $sHost2 = 'http://mq-open-search-lm03.ihost.aol.com:8000/nominatim/v1';
@@ -50,13 +49,13 @@ while (($sLine = fgets($hFile, 10000)) !== false) {
$sRes = $sURL1.":\n"; $sRes = $sURL1.":\n";
for ($j = 0; $j < strlen($sRes1); $j+=40) { for ($j = 0; $j < strlen($sRes1); $j+=40) {
$sRes .= substr($sRes1, $j, 40)."\n"; $sRes .= substr($sRes1, $j, 40)."\n";
} }
file_put_contents('log/'.$i.'.1', $sRes); file_put_contents('log/'.$i.'.1', $sRes);
$sRes = $sURL2.":\n"; $sRes = $sURL2.":\n";
for ($j = 0; $j < strlen($sRes2); $j+=40) { for ($j = 0; $j < strlen($sRes2); $j+=40) {
$sRes .= substr($sRes2, $j, 40)."\n"; $sRes .= substr($sRes2, $j, 40)."\n";
} }
file_put_contents('log/'.$i.'.2', $sRes); file_put_contents('log/'.$i.'.2', $sRes);
} }

View File

@@ -94,8 +94,9 @@ if ($aCMDResult['create-db'] || $aCMDResult['all']) {
if ($aCMDResult['setup-db'] || $aCMDResult['all']) { if ($aCMDResult['setup-db'] || $aCMDResult['all']) {
echo "Setup DB\n"; echo "Setup DB\n";
$bDidSomething = true; $bDidSomething = true;
// TODO: path detection, detection memory, etc.
// TODO: path detection, detection memory, etc.
//
$oDB =& getDB(); $oDB =& getDB();
$fPostgresVersion = getPostgresVersion($oDB); $fPostgresVersion = getPostgresVersion($oDB);
@@ -649,6 +650,7 @@ if (!$bDidSomething) {
echo "Setup finished.\n"; echo "Setup finished.\n";
} }
function pgsqlRunScriptFile($sFilename) function pgsqlRunScriptFile($sFilename)
{ {
if (!file_exists($sFilename)) fail('unable to find '.$sFilename); if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
@@ -698,7 +700,6 @@ function pgsqlRunScriptFile($sFilename)
fclose($ahGzipPipes[1]); fclose($ahGzipPipes[1]);
proc_close($hGzipProcess); proc_close($hGzipProcess);
} }
} }
function pgsqlRunScript($sScript, $bfatal = true) function pgsqlRunScript($sScript, $bfatal = true)
@@ -712,7 +713,7 @@ function pgsqlRunScript($sScript, $bfatal = true)
$sCMD .= ' -v ON_ERROR_STOP=1'; $sCMD .= ' -v ON_ERROR_STOP=1';
$aDescriptors = array( $aDescriptors = array(
0 => array('pipe', 'r'), 0 => array('pipe', 'r'),
1 => STDOUT, 1 => STDOUT,
2 => STDERR 2 => STDERR
); );
$ahPipes = null; $ahPipes = null;
@@ -844,6 +845,4 @@ function create_sql_functions($aCMDResult)
$sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate); $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
} }
pgsqlRunScript($sTemplate); pgsqlRunScript($sTemplate);
} }

View File

@@ -42,24 +42,24 @@ if ($aCMDResult['wiki-import']) {
$sLabel = trim($aMatch[1]); $sLabel = trim($aMatch[1]);
$sClass = trim($aMatch[2]); $sClass = trim($aMatch[2]);
$sType = trim($aMatch[3]); $sType = trim($aMatch[3]);
# hack around a bug where building=yes was imported with // hack around a bug where building=yes was imported with
# quotes into the wiki // quotes into the wiki
$sType = preg_replace('/&quot;/', '', $sType); $sType = preg_replace('/&quot;/', '', $sType);
# sanity check, in case somebody added garbage in the wiki // sanity check, in case somebody added garbage in the wiki
if (preg_match('/^\\w+$/', $sClass) < 1 if (preg_match('/^\\w+$/', $sClass) < 1
|| preg_match('/^\\w+$/', $sType) < 1 || preg_match('/^\\w+$/', $sType) < 1
) { ) {
trigger_error("Bad class/type for language $sLanguage: $sClass=$sType"); trigger_error("Bad class/type for language $sLanguage: $sClass=$sType");
exit; exit;
} }
# blacklisting: disallow certain class/type combinations // blacklisting: disallow certain class/type combinations
if (isset($aTagsBlacklist[$sClass]) && in_array($sType, $aTagsBlacklist[$sClass])) { if (isset($aTagsBlacklist[$sClass]) && in_array($sType, $aTagsBlacklist[$sClass])) {
# fwrite(STDERR, "Blacklisted: ".$sClass."/".$sType."\n"); // fwrite(STDERR, "Blacklisted: ".$sClass."/".$sType."\n");
continue; continue;
} }
# whitelisting: if class is in whitelist, allow only tags in the list // whitelisting: if class is in whitelist, allow only tags in the list
if (isset($aTagsWhitelist[$sClass]) && !in_array($sType, $aTagsWhitelist[$sClass])) { if (isset($aTagsWhitelist[$sClass]) && !in_array($sType, $aTagsWhitelist[$sClass])) {
# fwrite(STDERR, "Non-Whitelisted: ".$sClass."/".$sType."\n"); // fwrite(STDERR, "Non-Whitelisted: ".$sClass."/".$sType."\n");
continue; continue;
} }
$aPairs[$sClass.'|'.$sType] = array($sClass, $sType); $aPairs[$sClass.'|'.$sType] = array($sClass, $sType);

View File

@@ -237,7 +237,7 @@ if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
// First check if there are new updates published (except for minutelies - there's always new diffs to process) // First check if there are new updates published (except for minutelies - there's always new diffs to process)
if (CONST_Replication_Update_Interval > 60) { if (CONST_Replication_Update_Interval > 60) {
unset($aReplicationLag); unset($aReplicationLag);
exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel); exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel);
while ($iErrorLevel > 0 || $aReplicationLag[0] < 1) { while ($iErrorLevel > 0 || $aReplicationLag[0] < 1) {
if ($iErrorLevel) { if ($iErrorLevel) {
echo "Error: $iErrorLevel. "; echo "Error: $iErrorLevel. ";
@@ -247,7 +247,7 @@ if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
} }
sleep(CONST_Replication_Recheck_Interval); sleep(CONST_Replication_Recheck_Interval);
unset($aReplicationLag); unset($aReplicationLag);
exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel); exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel);
} }
// There are new replication files - use osmosis to download the file // There are new replication files - use osmosis to download the file
echo "\n".date('Y-m-d H:i:s')." Replication Delay is ".$aReplicationLag[0]."\n"; echo "\n".date('Y-m-d H:i:s')." Replication Delay is ".$aReplicationLag[0]."\n";
@@ -326,6 +326,7 @@ if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
} }
} }
function getosmosistimestamp($sOsmosisConfigDirectory) function getosmosistimestamp($sOsmosisConfigDirectory)
{ {
$sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt'); $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');

View File

@@ -67,4 +67,3 @@ if (!$aResult['reverse-only']) {
else echo "."; else echo ".";
} }
} }

View File

@@ -1,21 +1,23 @@
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-website.php');
require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M');
$sOutputFormat = 'html'; require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-website.php');
require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M');
$oDB =& getDB(); $sOutputFormat = 'html';
$sSQL = "select placex.place_id, calculated_country_code as country_code, name->'name' as name, i.* from placex, import_polygon_delete i where placex.osm_id = i.osm_id and placex.osm_type = i.osm_type and placex.class = i.class and placex.type = i.type"; $oDB =& getDB();
$aPolygons = chksql($oDB->getAll($sSQL), "Could not get list of deleted OSM elements.");
$sSQL = "select placex.place_id, calculated_country_code as country_code, name->'name' as name, i.* from placex, import_polygon_delete i where placex.osm_id = i.osm_id and placex.osm_type = i.osm_type and placex.class = i.class and placex.type = i.type";
$aPolygons = chksql($oDB->getAll($sSQL), "Could not get list of deleted OSM elements.");
if (CONST_DEBUG) {
var_dump($aPolygons);
exit;
}
if (CONST_DEBUG) {
var_dump($aPolygons);
exit;
}
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -66,30 +68,32 @@ table td {
<table> <table>
<?php <?php
if (!$aPolygons) exit;
if (!$aPolygons) exit;
echo "<tr>";
// var_dump($aPolygons[0]);
foreach ($aPolygons[0] as $sCol => $sVal) {
echo "<th>".$sCol."</th>";
}
echo "</tr>";
foreach ($aPolygons as $aRow) {
echo "<tr>"; echo "<tr>";
//var_dump($aPolygons[0]); foreach ($aRow as $sCol => $sVal) {
foreach ($aPolygons[0] as $sCol => $sVal) { switch ($sCol) {
echo "<th>".$sCol."</th>"; case 'osm_id':
echo '<td>'.osmLink($aRow).'</td>';
break;
case 'place_id':
echo '<td>'.detailsLink($aRow).'</td>';
break;
default:
echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
break;
}
} }
echo "</tr>"; echo "</tr>";
foreach ($aPolygons as $aRow) { }
echo "<tr>";
foreach ($aRow as $sCol => $sVal) {
switch ($sCol) {
case 'osm_id':
echo '<td>'.osmLink($aRow).'</td>';
break;
case 'place_id':
echo '<td>'.detailsLink($aRow).'</td>';
break;
default:
echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
break;
}
}
echo "</tr>";
}
?> ?>
</table> </table>

View File

@@ -35,7 +35,7 @@ if (count($aOsmIds) > CONST_Places_Max_ID_count) {
userError('Bulk User: Only ' . CONST_Places_Max_ID_count . " ids are allowed in one request."); userError('Bulk User: Only ' . CONST_Places_Max_ID_count . " ids are allowed in one request.");
} }
foreach ($aOsmIds AS $sItem) { foreach ($aOsmIds as $sItem) {
// Skip empty sItem // Skip empty sItem
if (empty($sItem)) continue; if (empty($sItem)) continue;

View File

@@ -1,39 +1,41 @@
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-website.php');
require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M');
$oParams = new ParameterParser(); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-website.php');
require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M');
$sOutputFormat = 'html'; $oParams = new ParameterParser();
$iDays = $oParams->getInt('days', 1);
$bReduced = $oParams->getBool('reduced', false);
$sClass = $oParams->getString('class', false);
$oDB =& getDB(); $sOutputFormat = 'html';
$iDays = $oParams->getInt('days', 1);
$bReduced = $oParams->getBool('reduced', false);
$sClass = $oParams->getString('class', false);
$iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error')); $oDB =& getDB();
$aPolygons = array(); $iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error'));
while ($iTotalBroken && !sizeof($aPolygons)) {
$sSQL = 'select osm_type as "type",osm_id as "id",class as "key",type as "value",name->\'name\' as "name",';
$sSQL .= 'country_code as "country",errormessage as "error message",updated';
$sSQL .= " from import_polygon_error";
$sSQL .= " where updated > 'now'::timestamp - '".$iDays." day'::interval";
$iDays++;
if ($bReduced) $sSQL .= " and errormessage like 'Area reduced%'"; $aPolygons = array();
if ($sClass) $sSQL .= " and class = '".pg_escape_string($sClass)."'"; while ($iTotalBroken && !sizeof($aPolygons)) {
$sSQL .= " order by updated desc limit 1000"; $sSQL = 'select osm_type as "type",osm_id as "id",class as "key",type as "value",name->\'name\' as "name",';
$aPolygons = chksql($oDB->getAll($sSQL)); $sSQL .= 'country_code as "country",errormessage as "error message",updated';
} $sSQL .= " from import_polygon_error";
$sSQL .= " where updated > 'now'::timestamp - '".$iDays." day'::interval";
$iDays++;
if ($bReduced) $sSQL .= " and errormessage like 'Area reduced%'";
if ($sClass) $sSQL .= " and class = '".pg_escape_string($sClass)."'";
$sSQL .= " order by updated desc limit 1000";
$aPolygons = chksql($oDB->getAll($sSQL));
}
if (CONST_Debug) {
var_dump($aPolygons);
exit;
}
if (CONST_Debug) {
var_dump($aPolygons);
exit;
}
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -82,24 +84,24 @@ table td {
<?php <?php
echo "<p>Total number of broken polygons: $iTotalBroken</p>"; echo "<p>Total number of broken polygons: $iTotalBroken</p>";
if (!$aPolygons) exit; if (!$aPolygons) exit;
echo "<table>"; echo "<table>";
echo "<tr>"; echo "<tr>";
//var_dump($aPolygons[0]); //var_dump($aPolygons[0]);
foreach ($aPolygons[0] as $sCol => $sVal) { foreach ($aPolygons[0] as $sCol => $sVal) {
echo "<th>".$sCol."</th>"; echo "<th>".$sCol."</th>";
} }
echo "<th>&nbsp;</th>"; echo "<th>&nbsp;</th>";
echo "<th>&nbsp;</th>"; echo "<th>&nbsp;</th>";
echo "</tr>"; echo "</tr>";
$aSeen = array(); $aSeen = array();
foreach ($aPolygons as $aRow) { foreach ($aPolygons as $aRow) {
if (isset($aSeen[$aRow['type'].$aRow['id']])) continue; if (isset($aSeen[$aRow['type'].$aRow['id']])) continue;
$aSeen[$aRow['type'].$aRow['id']] = 1; $aSeen[$aRow['type'].$aRow['id']] = 1;
echo "<tr>"; echo "<tr>";
foreach ($aRow as $sCol => $sVal) { foreach ($aRow as $sCol => $sVal) {
switch ($sCol) { switch ($sCol) {
case 'error message': case 'error message':
if (preg_match('/Self-intersection\\[([0-9.\\-]+) ([0-9.\\-]+)\\]/', $sVal, $aMatch)) { if (preg_match('/Self-intersection\\[([0-9.\\-]+) ([0-9.\\-]+)\\]/', $sVal, $aMatch)) {
$aRow['lat'] = $aMatch[2]; $aRow['lat'] = $aMatch[2];
@@ -115,17 +117,18 @@ table td {
default: default:
echo "<td>".($sVal?$sVal:'&nbsp;')."</td>"; echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
break; break;
}
} }
echo "<td><a href=\"http://localhost:8111/import?url=http://www.openstreetmap.org/api/0.6/".$sOSMType.'/'.$aRow['id']."/full\" target=\"josm\">josm</a></td>";
if (isset($aRow['lat'])) {
echo "<td><a href=\"http://open.mapquestapi.com/dataedit/index_flash.html?lat=".$aRow['lat']."&lon=".$aRow['lon']."&zoom=18\" target=\"potlatch2\">P2</a></td>";
} else {
echo "<td>&nbsp;</td>";
}
echo "</tr>";
} }
echo "</table>"; echo "<td><a href=\"http://localhost:8111/import?url=http://www.openstreetmap.org/api/0.6/".$sOSMType.'/'.$aRow['id']."/full\" target=\"josm\">josm</a></td>";
if (isset($aRow['lat'])) {
echo "<td><a href=\"http://open.mapquestapi.com/dataedit/index_flash.html?lat=".$aRow['lat']."&lon=".$aRow['lon']."&zoom=18\" target=\"potlatch2\">P2</a></td>";
} else {
echo "<td>&nbsp;</td>";
}
echo "</tr>";
}
echo "</table>";
?> ?>
</body> </body>
</html> </html>

View File

@@ -4,6 +4,7 @@
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/init-website.php');
function statusError($sMsg) function statusError($sMsg)
{ {
header("HTTP/1.0 500 Internal Server Error"); header("HTTP/1.0 500 Internal Server Error");
@@ -34,4 +35,3 @@ if (!$iWordID) {
echo "OK"; echo "OK";
exit; exit;