tabs-to-spaces

This commit is contained in:
Marc Tobias Metten 2016-09-04 03:19:48 +02:00
parent cd6dcfa574
commit 832547f192
55 changed files with 8236 additions and 8232 deletions

14
COPYING
View File

@ -1,12 +1,12 @@
GNU GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE
Version 2, June 1991 Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed. of this license document, but changing it is not allowed.
Preamble Preamble
The licenses for most software are designed to take away your The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public freedom to share and change it. By contrast, the GNU General Public
@ -56,7 +56,7 @@ patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and The precise terms and conditions for copying, distribution and
modification follow. modification follow.
GNU GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains 0. This License applies to any program or other work which contains
@ -255,7 +255,7 @@ make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally. of promoting the sharing and reuse of software generally.
NO WARRANTY NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
@ -277,9 +277,9 @@ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES. POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it possible use to the public, the best way to achieve this is to make it

File diff suppressed because it is too large Load Diff

View File

@ -2,132 +2,132 @@
class ParameterParser 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)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
{ {
return $bDefault; return $bDefault;
} }
return (bool) $this->aParams[$sName]; return (bool) $this->aParams[$sName];
} }
function getInt($sName, $bDefault=false) function getInt($sName, $bDefault=false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
{ {
return $bDefault; return $bDefault;
} }
if (!preg_match('/^[+-]?[0-9]+$/', $this->aParams[$sName])) if (!preg_match('/^[+-]?[0-9]+$/', $this->aParams[$sName]))
{ {
userError("Integer number expected for parameter '$sName'"); userError("Integer number expected for parameter '$sName'");
} }
return (int) $this->aParams[$sName]; return (int) $this->aParams[$sName];
} }
function getFloat($sName, $bDefault=false) function getFloat($sName, $bDefault=false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
{ {
return $bDefault; return $bDefault;
} }
if (!preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $this->aParams[$sName])) if (!preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $this->aParams[$sName]))
{ {
userError("Floating-point number expected for parameter '$sName'"); userError("Floating-point number expected for parameter '$sName'");
} }
return (float) $this->aParams[$sName]; return (float) $this->aParams[$sName];
} }
function getString($sName, $bDefault=false) function getString($sName, $bDefault=false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
{ {
return $bDefault; return $bDefault;
} }
return $this->aParams[$sName]; return $this->aParams[$sName];
} }
function getSet($sName, $aValues, $sDefault=false) function getSet($sName, $aValues, $sDefault=false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
{ {
return $sDefault; return $sDefault;
} }
if (!in_array($this->aParams[$sName], $aValues)) if (!in_array($this->aParams[$sName], $aValues))
{ {
userError("Parameter '$sName' must be one of: ".join(', ', $aValues)); userError("Parameter '$sName' must be one of: ".join(', ', $aValues));
} }
return $this->aParams[$sName]; return $this->aParams[$sName];
} }
function getStringList($sName, $aDefault=false) function getStringList($sName, $aDefault=false)
{ {
$sValue = $this->getString($sName); $sValue = $this->getString($sName);
if ($sValue) if ($sValue)
{ {
return explode(',', $sValue); return explode(',', $sValue);
} }
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"];
} }
$aLanguages = array(); $aLanguages = array();
$sLangString = $this->getString('accept-language', $sFallback); $sLangString = $this->getString('accept-language', $sFallback);
if ($sLangString) if ($sLangString)
{ {
if (preg_match_all('/(([a-z]{1,8})(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $sLangString, $aLanguagesParse, PREG_SET_ORDER)) if (preg_match_all('/(([a-z]{1,8})(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $sLangString, $aLanguagesParse, PREG_SET_ORDER))
{ {
foreach($aLanguagesParse as $iLang => $aLanguage) foreach($aLanguagesParse as $iLang => $aLanguage)
{ {
$aLanguages[$aLanguage[1]] = isset($aLanguage[5])?(float)$aLanguage[5]:1 - ($iLang/100); $aLanguages[$aLanguage[1]] = isset($aLanguage[5])?(float)$aLanguage[5]:1 - ($iLang/100);
if (!isset($aLanguages[$aLanguage[2]])) $aLanguages[$aLanguage[2]] = $aLanguages[$aLanguage[1]]/10; if (!isset($aLanguages[$aLanguage[2]])) $aLanguages[$aLanguage[2]] = $aLanguages[$aLanguage[1]]/10;
} }
arsort($aLanguages); arsort($aLanguages);
} }
} }
if (!sizeof($aLanguages) && CONST_Default_Language) if (!sizeof($aLanguages) && CONST_Default_Language)
{ {
$aLanguages[CONST_Default_Language] = 1; $aLanguages[CONST_Default_Language] = 1;
} }
foreach($aLanguages as $sLanguage => $fLanguagePref) foreach($aLanguages as $sLanguage => $fLanguagePref)
{ {
$aLangPrefOrder['short_name:'.$sLanguage] = 'short_name:'.$sLanguage; $aLangPrefOrder['short_name:'.$sLanguage] = 'short_name:'.$sLanguage;
$aLangPrefOrder['name:'.$sLanguage] = 'name:'.$sLanguage; $aLangPrefOrder['name:'.$sLanguage] = 'name:'.$sLanguage;
} }
$aLangPrefOrder['short_name'] = 'short_name'; $aLangPrefOrder['short_name'] = 'short_name';
$aLangPrefOrder['name'] = 'name'; $aLangPrefOrder['name'] = 'name';
$aLangPrefOrder['brand'] = 'brand'; $aLangPrefOrder['brand'] = 'brand';
foreach($aLanguages as $sLanguage => $fLanguagePref) foreach($aLanguages as $sLanguage => $fLanguagePref)
{ {
$aLangPrefOrder['official_name:'.$sLanguage] = 'official_name:'.$sLanguage; $aLangPrefOrder['official_name:'.$sLanguage] = 'official_name:'.$sLanguage;
} }
$aLangPrefOrder['official_name'] = 'official_name'; $aLangPrefOrder['official_name'] = 'official_name';
$aLangPrefOrder['ref'] = 'ref'; $aLangPrefOrder['ref'] = 'ref';
$aLangPrefOrder['type'] = 'type'; $aLangPrefOrder['type'] = 'type';
return $aLangPrefOrder; return $aLangPrefOrder;
} }
} }

View File

@ -1,361 +1,361 @@
<?php <?php
class PlaceLookup
{
protected $oDB;
protected $aLangPrefOrder = array(); class PlaceLookup
{
protected $oDB;
protected $bAddressDetails = false; protected $aLangPrefOrder = array();
protected $bExtraTags = false;
protected $bNameDetails = false;
protected $bIncludePolygonAsPoints = false; protected $bAddressDetails = false;
protected $bIncludePolygonAsText = false; protected $bExtraTags = false;
protected $bIncludePolygonAsGeoJSON = false; protected $bNameDetails = false;
protected $bIncludePolygonAsKML = false;
protected $bIncludePolygonAsSVG = false; protected $bIncludePolygonAsPoints = false;
protected $fPolygonSimplificationThreshold = 0.0; protected $bIncludePolygonAsText = false;
protected $bIncludePolygonAsGeoJSON = false;
protected $bIncludePolygonAsKML = false;
protected $bIncludePolygonAsSVG = false;
protected $fPolygonSimplificationThreshold = 0.0;
function PlaceLookup(&$oDB) function PlaceLookup(&$oDB)
{ {
$this->oDB =& $oDB; $this->oDB =& $oDB;
} }
function setLanguagePreference($aLangPrefOrder) function setLanguagePreference($aLangPrefOrder)
{ {
$this->aLangPrefOrder = $aLangPrefOrder; $this->aLangPrefOrder = $aLangPrefOrder;
} }
function setIncludeAddressDetails($bAddressDetails = true) function setIncludeAddressDetails($bAddressDetails = true)
{ {
$this->bAddressDetails = $bAddressDetails; $this->bAddressDetails = $bAddressDetails;
} }
function setIncludeExtraTags($bExtraTags = false) function setIncludeExtraTags($bExtraTags = false)
{ {
$this->bExtraTags = $bExtraTags; $this->bExtraTags = $bExtraTags;
} }
function setIncludeNameDetails($bNameDetails = false) function setIncludeNameDetails($bNameDetails = false)
{ {
$this->bNameDetails = $bNameDetails; $this->bNameDetails = $bNameDetails;
} }
function setIncludePolygonAsPoints($b = true) function setIncludePolygonAsPoints($b = true)
{ {
$this->bIncludePolygonAsPoints = $b; $this->bIncludePolygonAsPoints = $b;
} }
function getIncludePolygonAsPoints() function getIncludePolygonAsPoints()
{ {
return $this->bIncludePolygonAsPoints; return $this->bIncludePolygonAsPoints;
} }
function setIncludePolygonAsText($b = true) function setIncludePolygonAsText($b = true)
{ {
$this->bIncludePolygonAsText = $b; $this->bIncludePolygonAsText = $b;
} }
function getIncludePolygonAsText() function getIncludePolygonAsText()
{ {
return $this->bIncludePolygonAsText; return $this->bIncludePolygonAsText;
} }
function setIncludePolygonAsGeoJSON($b = true) function setIncludePolygonAsGeoJSON($b = true)
{ {
$this->bIncludePolygonAsGeoJSON = $b; $this->bIncludePolygonAsGeoJSON = $b;
} }
function setIncludePolygonAsKML($b = true) function setIncludePolygonAsKML($b = true)
{ {
$this->bIncludePolygonAsKML = $b; $this->bIncludePolygonAsKML = $b;
} }
function setIncludePolygonAsSVG($b = true) function setIncludePolygonAsSVG($b = true)
{ {
$this->bIncludePolygonAsSVG = $b; $this->bIncludePolygonAsSVG = $b;
} }
function setPolygonSimplificationThreshold($f) function setPolygonSimplificationThreshold($f)
{ {
$this->fPolygonSimplificationThreshold = $f; $this->fPolygonSimplificationThreshold = $f;
} }
function lookupOSMID($sType, $iID) function lookupOSMID($sType, $iID)
{ {
$sSQL = "select place_id from placex where osm_type = '".pg_escape_string($sType)."' and osm_id = ".(int)$iID." order by type = 'postcode' asc"; $sSQL = "select place_id from placex where osm_type = '".pg_escape_string($sType)."' and osm_id = ".(int)$iID." order by type = 'postcode' asc";
$iPlaceID = chksql($this->oDB->getOne($sSQL)); $iPlaceID = chksql($this->oDB->getOne($sSQL));
return $this->lookup((int)$iPlaceID); return $this->lookup((int)$iPlaceID);
} }
function lookup($iPlaceID, $sType = '', $fInterpolFraction = 0.0) function lookup($iPlaceID, $sType = '', $fInterpolFraction = 0.0)
{ {
if (!$iPlaceID) return null; if (!$iPlaceID) return null;
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
$bIsTiger = CONST_Use_US_Tiger_Data && $sType == 'tiger'; $bIsTiger = CONST_Use_US_Tiger_Data && $sType == 'tiger';
$bIsInterpolation = $sType == 'interpolation'; $bIsInterpolation = $sType == 'interpolation';
if ($bIsTiger) if ($bIsTiger)
{ {
$sSQL = "select place_id,partition, 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, housenumber, null as street, null as isin, postcode,"; $sSQL = "select place_id,partition, 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, housenumber, null as street, null as isin, postcode,";
$sSQL .= " 'us' as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,"; $sSQL .= " 'us' as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
$sSQL .= " coalesce(null,0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, 'us' as calculated_country_code, "; $sSQL .= " coalesce(null,0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, 'us' as calculated_country_code, ";
$sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,"; $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
$sSQL .= " null as placename,"; $sSQL .= " null as placename,";
$sSQL .= " null as ref,"; $sSQL .= " null as ref,";
if ($this->bExtraTags) $sSQL .= " null as extra,"; if ($this->bExtraTags) $sSQL .= " null as extra,";
if ($this->bNameDetails) $sSQL .= " null as names,"; if ($this->bNameDetails) $sSQL .= " null as names,";
$sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from "; $sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from ";
$sSQL .= " (select *, "; $sSQL .= " (select *, ";
$sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1"; $sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
$sSQL .= " WHEN interpolationtype='even' THEN ((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2"; $sSQL .= " WHEN interpolationtype='even' THEN ((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
$sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int"; $sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
$sSQL .= " END as housenumber"; $sSQL .= " END as housenumber";
$sSQL .= " from location_property_tiger where place_id = ".$iPlaceID.") as blub1) as blub2"; $sSQL .= " from location_property_tiger where place_id = ".$iPlaceID.") as blub1) as blub2";
} }
else if ($bIsInterpolation) else if ($bIsInterpolation)
{ {
$sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,"; $sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,";
$sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,"; $sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
$sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, "; $sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, ";
$sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,"; $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
$sSQL .= " null as placename,"; $sSQL .= " null as placename,";
$sSQL .= " null as ref,"; $sSQL .= " null as ref,";
if ($this->bExtraTags) $sSQL .= " null as extra,"; if ($this->bExtraTags) $sSQL .= " null as extra,";
if ($this->bNameDetails) $sSQL .= " null as names,"; if ($this->bNameDetails) $sSQL .= " null as names,";
$sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from "; $sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from ";
$sSQL .= " (select *, "; $sSQL .= " (select *, ";
$sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1"; $sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
$sSQL .= " WHEN interpolationtype='even' THEN ((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2"; $sSQL .= " WHEN interpolationtype='even' THEN ((".$fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
$sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int"; $sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
$sSQL .= " END as housenumber"; $sSQL .= " END as housenumber";
$sSQL .= " from location_property_osmline where place_id = ".$iPlaceID.") as blub1) as blub2"; $sSQL .= " from location_property_osmline where place_id = ".$iPlaceID.") as blub1) as blub2";
// testcase: interpolationtype=odd, startnumber=1000, endnumber=1006, fInterpolFraction=1 => housenumber=1007 => error in st_lineinterpolatepoint // testcase: interpolationtype=odd, startnumber=1000, endnumber=1006, fInterpolFraction=1 => housenumber=1007 => error in st_lineinterpolatepoint
// but this will never happen, because if the searched point is that close to the endnumber, the endnumber house will be directly taken from placex (in ReverseGeocode.php line 220) // but this will never happen, because if the searched point is that close to the endnumber, the endnumber house will be directly taken from placex (in ReverseGeocode.php line 220)
// and not interpolated // and not interpolated
} }
else else
{ {
$sSQL = "select placex.place_id, partition, osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode, country_code, parent_place_id, linked_place_id, rank_address, rank_search, "; $sSQL = "select placex.place_id, partition, osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode, country_code, parent_place_id, linked_place_id, rank_address, rank_search, ";
$sSQL .= " coalesce(importance,0.75-(rank_search::float/40)) as importance, indexed_status, indexed_date, wikipedia, calculated_country_code, "; $sSQL .= " coalesce(importance,0.75-(rank_search::float/40)) as importance, indexed_status, indexed_date, wikipedia, calculated_country_code, ";
$sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,"; $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
$sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) as placename,"; $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
$sSQL .= " get_name_by_language(name, ARRAY['ref']) as ref,"; $sSQL .= " get_name_by_language(name, ARRAY['ref']) as ref,";
if ($this->bExtraTags) $sSQL .= " hstore_to_json(extratags) as extra,"; if ($this->bExtraTags) $sSQL .= " hstore_to_json(extratags) as extra,";
if ($this->bNameDetails) $sSQL .= " hstore_to_json(name) as names,"; if ($this->bNameDetails) $sSQL .= " hstore_to_json(name) as names,";
$sSQL .= " (case when centroid is null then st_y(st_centroid(geometry)) else st_y(centroid) end) as lat,"; $sSQL .= " (case when centroid is null then st_y(st_centroid(geometry)) else st_y(centroid) end) as lat,";
$sSQL .= " (case when centroid is null then st_x(st_centroid(geometry)) else st_x(centroid) end) as lon"; $sSQL .= " (case when centroid is null then st_x(st_centroid(geometry)) else st_x(centroid) end) as lon";
$sSQL .= " from placex where place_id = ".$iPlaceID; $sSQL .= " from placex where place_id = ".$iPlaceID;
} }
$aPlace = chksql($this->oDB->getRow($sSQL), "Could not lookup place"); $aPlace = chksql($this->oDB->getRow($sSQL), "Could not lookup place");
if (!$aPlace['place_id']) return null; if (!$aPlace['place_id']) return null;
if ($this->bAddressDetails) if ($this->bAddressDetails)
{ {
// to get addressdetails for tiger data, the housenumber is needed // to get addressdetails for tiger data, the housenumber is needed
$iHousenumber = ($bIsTiger || $bIsInterpolation) ? $aPlace['housenumber'] : -1; $iHousenumber = ($bIsTiger || $bIsInterpolation) ? $aPlace['housenumber'] : -1;
$aPlace['aAddress'] = $this->getAddressNames($aPlace['place_id'], $aPlace['aAddress'] = $this->getAddressNames($aPlace['place_id'],
$iHousenumber); $iHousenumber);
} }
if ($this->bExtraTags) if ($this->bExtraTags)
{ {
if ($aPlace['extra']) if ($aPlace['extra'])
{ {
$aPlace['sExtraTags'] = json_decode($aPlace['extra']); $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
} }
else else
{ {
$aPlace['sExtraTags'] = (object) array(); $aPlace['sExtraTags'] = (object) array();
} }
} }
if ($this->bNameDetails) if ($this->bNameDetails)
{ {
if ($aPlace['names']) if ($aPlace['names'])
{ {
$aPlace['sNameDetails'] = json_decode($aPlace['names']); $aPlace['sNameDetails'] = json_decode($aPlace['names']);
} }
else else
{ {
$aPlace['sNameDetails'] = (object) array(); $aPlace['sNameDetails'] = (object) array();
} }
} }
$aClassType = getClassTypes(); $aClassType = getClassTypes();
$sAddressType = ''; $sAddressType = '';
$sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level']; $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
{ {
$sAddressType = $aClassType[$aClassType]['simplelabel']; $sAddressType = $aClassType[$aClassType]['simplelabel'];
} }
else else
{ {
$sClassType = $aPlace['class'].':'.$aPlace['type']; $sClassType = $aPlace['class'].':'.$aPlace['type'];
if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
$sAddressType = $aClassType[$sClassType]['simplelabel']; $sAddressType = $aClassType[$sClassType]['simplelabel'];
else $sAddressType = $aPlace['class']; else $sAddressType = $aPlace['class'];
} }
$aPlace['addresstype'] = $sAddressType; $aPlace['addresstype'] = $sAddressType;
return $aPlace; return $aPlace;
} }
function getAddressDetails($iPlaceID, $bAll = false, $housenumber = -1) function getAddressDetails($iPlaceID, $bAll = false, $housenumber = -1)
{ {
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
$sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$iPlaceID.",".$housenumber.")"; $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$iPlaceID.",".$housenumber.")";
if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'"; if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'";
$sSQL .= " order by rank_address desc,isaddress desc"; $sSQL .= " order by rank_address desc,isaddress desc";
return chksql($this->oDB->getAll($sSQL)); return chksql($this->oDB->getAll($sSQL));
} }
function getAddressNames($iPlaceID, $housenumber = -1) function getAddressNames($iPlaceID, $housenumber = -1)
{ {
$aAddressLines = $this->getAddressDetails($iPlaceID, false, $housenumber); $aAddressLines = $this->getAddressDetails($iPlaceID, false, $housenumber);
$aAddress = array(); $aAddress = array();
$aFallback = array(); $aFallback = array();
$aClassType = getClassTypes(); $aClassType = getClassTypes();
foreach($aAddressLines as $aLine) foreach($aAddressLines as $aLine)
{ {
$bFallback = false; $bFallback = false;
$aTypeLabel = false; $aTypeLabel = false;
if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']]; if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']]; elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
{ {
$aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]; $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
$bFallback = true; $bFallback = true;
} }
else else
{ {
$aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']); $aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
$bFallback = true; $bFallback = true;
} }
if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
{ {
$sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']); $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
$sTypeLabel = str_replace(' ','_',$sTypeLabel); $sTypeLabel = str_replace(' ','_',$sTypeLabel);
if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
{ {
$aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber']; $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
} }
$aFallback[$sTypeLabel] = $bFallback; $aFallback[$sTypeLabel] = $bFallback;
} }
} }
return $aAddress; return $aAddress;
} }
// 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)
{ {
$aOutlineResult = array(); $aOutlineResult = array();
if (!$iPlaceID) return $aOutlineResult; if (!$iPlaceID) return $aOutlineResult;
if (CONST_Search_AreaPolygons) if (CONST_Search_AreaPolygons)
{ {
// Get the bounding box and outline polygon // Get the bounding box and outline polygon
$sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,"; $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
$sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,"; $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
$sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,"; $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
$sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon"; $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson"; if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml"; if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg"; if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext"; if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
$sFrom = " from placex where place_id = ".$iPlaceID; $sFrom = " from placex where place_id = ".$iPlaceID;
if ($this->fPolygonSimplificationThreshold > 0) if ($this->fPolygonSimplificationThreshold > 0)
{ {
$sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx"; $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
} }
else else
{ {
$sSQL .= $sFrom; $sSQL .= $sFrom;
} }
$aPointPolygon = chksql($this->oDB->getRow($sSQL), $aPointPolygon = chksql($this->oDB->getRow($sSQL),
"Could not get outline"); "Could not get outline");
if ($aPointPolygon['place_id']) if ($aPointPolygon['place_id'])
{ {
if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
{ {
$aOutlineResult['lat'] = $aPointPolygon['centrelat']; $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
$aOutlineResult['lon'] = $aPointPolygon['centrelon']; $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
} }
if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson']; if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml']; if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg']; if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext']; if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius); if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
{ {
$aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius; $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
$aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius; $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
} }
if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
{ {
$aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius; $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
$aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius; $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
} }
$aOutlineResult['aBoundingBox'] = array( $aOutlineResult['aBoundingBox'] = array(
(string)$aPointPolygon['minlat'], (string)$aPointPolygon['minlat'],
(string)$aPointPolygon['maxlat'], (string)$aPointPolygon['maxlat'],
(string)$aPointPolygon['minlon'], (string)$aPointPolygon['minlon'],
(string)$aPointPolygon['maxlon'] (string)$aPointPolygon['maxlon']
); );
} }
} // CONST_Search_AreaPolygons } // 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) )
{ {
if ($this->bIncludePolygonAsPoints) if ($this->bIncludePolygonAsPoints)
{ {
$sGeometryText = 'POINT('.$fLon.','.$fLat.')'; $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
$aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius); $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
} }
$aBounds = array(); $aBounds = array();
$aBounds['minlat'] = $fLat - $fRadius; $aBounds['minlat'] = $fLat - $fRadius;
$aBounds['maxlat'] = $fLat + $fRadius; $aBounds['maxlat'] = $fLat + $fRadius;
$aBounds['minlon'] = $fLon - $fRadius; $aBounds['minlon'] = $fLon - $fRadius;
$aBounds['maxlon'] = $fLon + $fRadius; $aBounds['maxlon'] = $fLon + $fRadius;
$aOutlineResult['aBoundingBox'] = array( $aOutlineResult['aBoundingBox'] = array(
(string)$aBounds['minlat'], (string)$aBounds['minlat'],
(string)$aBounds['maxlat'], (string)$aBounds['maxlat'],
(string)$aBounds['minlon'], (string)$aBounds['minlon'],
(string)$aBounds['maxlon'] (string)$aBounds['maxlon']
); );
} }
return $aOutlineResult; return $aOutlineResult;
} }
} }
?>

View File

@ -1,213 +1,213 @@
<?php <?php
class ReverseGeocode
{
protected $oDB;
protected $iMaxRank = 28;
function ReverseGeocode(&$oDB) class ReverseGeocode
{ {
$this->oDB =& $oDB; protected $oDB;
} protected $iMaxRank = 28;
function setZoom($iZoom) function ReverseGeocode(&$oDB)
{ {
// Zoom to rank, this could probably be calculated but a lookup gives fine control $this->oDB =& $oDB;
$aZoomRank = array( }
0 => 2, // Continent / Sea
1 => 2,
2 => 2,
3 => 4, // Country
4 => 4,
5 => 8, // State
6 => 10, // Region
7 => 10,
8 => 12, // County
9 => 12,
10 => 17, // City
11 => 17,
12 => 18, // Town / Village
13 => 18,
14 => 22, // Suburb
15 => 22,
16 => 26, // Street, TODO: major street?
17 => 26,
18 => 30, // or >, Building
19 => 30, // or >, Building
);
$this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
}
// returns { place_id =>, type => '(osm|tiger)' } function setZoom($iZoom)
// fails if no place was found {
function lookup($fLat, $fLon, $bDoInterpolation = true) // Zoom to rank, this could probably be calculated but a lookup gives fine control
{ $aZoomRank = array(
$sPointSQL = 'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)'; 0 => 2, // Continent / Sea
$iMaxRank = $this->iMaxRank; 1 => 2,
2 => 2,
3 => 4, // Country
4 => 4,
5 => 8, // State
6 => 10, // Region
7 => 10,
8 => 12, // County
9 => 12,
10 => 17, // City
11 => 17,
12 => 18, // Town / Village
13 => 18,
14 => 22, // Suburb
15 => 22,
16 => 26, // Street, TODO: major street?
17 => 26,
18 => 30, // or >, Building
19 => 30, // or >, Building
);
$this->iMaxRank = (isset($iZoom) && isset($aZoomRank[$iZoom]))?$aZoomRank[$iZoom]:28;
}
// Find the nearest point // returns { place_id =>, type => '(osm|tiger)' }
$fSearchDiam = 0.0004; // fails if no place was found
$iPlaceID = null; function lookup($fLat, $fLon, $bDoInterpolation = true)
$aArea = false; {
$fMaxAreaDistance = 1; $sPointSQL = 'ST_SetSRID(ST_Point('.$fLon.','.$fLat.'),4326)';
$bIsInUnitedStates = false; $iMaxRank = $this->iMaxRank;
$bPlaceIsTiger = false;
$bPlaceIsLine = false;
while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
{
$fSearchDiam = $fSearchDiam * 2;
// If we have to expand the search area by a large amount then we need a larger feature // Find the nearest point
// then there is a limit to how small the feature should be $fSearchDiam = 0.0004;
if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4; $iPlaceID = null;
if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8; $aArea = false;
if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10; $fMaxAreaDistance = 1;
if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12; $bIsInUnitedStates = false;
if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17; $bPlaceIsTiger = false;
if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18; $bPlaceIsLine = false;
if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22; while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
if ($fSearchDiam > 0.001 && $iMaxRank > 26) $iMaxRank = 26; {
$fSearchDiam = $fSearchDiam * 2;
$sSQL = 'select place_id,parent_place_id,rank_search,calculated_country_code'; // If we have to expand the search area by a large amount then we need a larger feature
$sSQL .= ' FROM placex'; // then there is a limit to how small the feature should be
$sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')'; if ($fSearchDiam > 2 && $iMaxRank > 4) $iMaxRank = 4;
$sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank; if ($fSearchDiam > 1 && $iMaxRank > 9) $iMaxRank = 8;
$sSQL .= ' and (name is not null or housenumber is not null)'; if ($fSearchDiam > 0.8 && $iMaxRank > 10) $iMaxRank = 10;
$sSQL .= ' and class not in (\'waterway\',\'railway\',\'tunnel\',\'bridge\',\'man_made\')'; if ($fSearchDiam > 0.6 && $iMaxRank > 12) $iMaxRank = 12;
$sSQL .= ' and indexed_status = 0 '; if ($fSearchDiam > 0.2 && $iMaxRank > 17) $iMaxRank = 17;
$sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') '; if ($fSearchDiam > 0.1 && $iMaxRank > 18) $iMaxRank = 18;
$sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))'; if ($fSearchDiam > 0.008 && $iMaxRank > 22) $iMaxRank = 22;
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1'; if ($fSearchDiam > 0.001 && $iMaxRank > 26) $iMaxRank = 26;
if (CONST_Debug) var_dump($sSQL);
$aPlace = chksql($this->oDB->getRow($sSQL),
"Could not determine closest place.");
$iPlaceID = $aPlace['place_id'];
$iParentPlaceID = $aPlace['parent_place_id'];
$bIsInUnitedStates = ($aPlace['calculated_country_code'] == 'us');
}
// if a street or house was found, look in interpolation lines table
if ($bDoInterpolation && $this->iMaxRank >= 28 && $aPlace && $aPlace['rank_search'] >= 26)
{
// if a house was found, search the interpolation line that is at least as close as the house
$sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
$sSQL .= ' FROM location_property_osmline';
$sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
$sSQL .= ' and indexed_status = 0 ';
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
if (CONST_Debug)
{
$sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
var_dump($sSQL);
$aAllHouses = chksql($this->oDB->getAll($sSQL)); $sSQL = 'select place_id,parent_place_id,rank_search,calculated_country_code';
foreach($aAllHouses as $i) $sSQL .= ' FROM placex';
{ $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', geometry, '.$fSearchDiam.')';
echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n"; $sSQL .= ' and rank_search != 28 and rank_search >= '.$iMaxRank;
} $sSQL .= ' and (name is not null or housenumber is not null)';
} $sSQL .= ' and class not in (\'waterway\',\'railway\',\'tunnel\',\'bridge\',\'man_made\')';
$aPlaceLine = chksql($this->oDB->getRow($sSQL), $sSQL .= ' and indexed_status = 0 ';
"Could not determine closest housenumber on an osm interpolation line."); $sSQL .= ' and (ST_GeometryType(geometry) not in (\'ST_Polygon\',\'ST_MultiPolygon\') ';
if ($aPlaceLine) $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
{ $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
if (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine); if (CONST_Debug) var_dump($sSQL);
if ($aPlace['rank_search'] == 30) $aPlace = chksql($this->oDB->getRow($sSQL),
{ "Could not determine closest place.");
// if a house was already found in placex, we have to find out, $iPlaceID = $aPlace['place_id'];
// if the placex house or the interpolated house are closer to the searched point $iParentPlaceID = $aPlace['parent_place_id'];
// distance between point and placex house $bIsInUnitedStates = ($aPlace['calculated_country_code'] == 'us');
$sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID; }
$aDistancePlacex = chksql($this->oDB->getRow($sSQL), // if a street or house was found, look in interpolation lines table
"Could not determine distance between searched point and placex house."); if ($bDoInterpolation && $this->iMaxRank >= 28 && $aPlace && $aPlace['rank_search'] >= 26)
$fDistancePlacex = $aDistancePlacex['distance']; {
// distance between point and interpolated house (fraction on interpolation line) // if a house was found, search the interpolation line that is at least as close as the house
$sSQL = 'SELECT ST_distance('.$sPointSQL.', ST_LineInterpolatePoint(linegeo, '.$aPlaceLine['fraction'].')) as distance'; $sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
$sSQL .= ' FROM location_property_osmline WHERE place_id = '.$aPlaceLine['place_id']; $sSQL .= ' FROM location_property_osmline';
$aDistanceInterpolation = chksql($this->oDB->getRow($sSQL), $sSQL .= ' WHERE ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')';
"Could not determine distance between searched point and interpolated house."); $sSQL .= ' and indexed_status = 0 ';
$fDistanceInterpolation = $aDistanceInterpolation['distance']; $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
if ($fDistanceInterpolation < $fDistancePlacex)
{ if (CONST_Debug)
// interpolation is closer to point than placex house {
$bPlaceIsLine = true; $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
$aPlace = $aPlaceLine; var_dump($sSQL);
$iPlaceID = $aPlaceLine['place_id'];
$iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
$fFraction = $aPlaceLine['fraction'];
$iMaxRank = 30;
}
// else: nothing to do, take placex house from above
}
else
{
$bPlaceIsLine = true;
$aPlace = $aPlaceLine;
$iPlaceID = $aPlaceLine['place_id'];
$iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
$fFraction = $aPlaceLine['fraction'];
$iMaxRank = 30;
}
}
}
// Only street found? If it's in the US we can check TIGER data for nearest housenumber
if (CONST_Use_US_Tiger_Data && $bDoInterpolation && $bIsInUnitedStates && $this->iMaxRank >= 28 && $iPlaceID && ($aPlace['rank_search'] == 26 || $aPlace['rank_search'] == 27 ))
{
$fSearchDiam = 0.001;
$sSQL = 'SELECT place_id,parent_place_id,30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
//if (CONST_Debug) { $sSQL .= ', housenumber, ST_distance('.$sPointSQL.', centroid) as distance, st_y(centroid) as lat, st_x(centroid) as lon'; }
$sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$iPlaceID;
$sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')'; //no centroid anymore in Tiger data, now we have lines
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
if (CONST_Debug) $aAllHouses = chksql($this->oDB->getAll($sSQL));
{ foreach($aAllHouses as $i)
$sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL); {
var_dump($sSQL); echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
}
}
$aPlaceLine = chksql($this->oDB->getRow($sSQL),
"Could not determine closest housenumber on an osm interpolation line.");
if ($aPlaceLine)
{
if (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine);
if ($aPlace['rank_search'] == 30)
{
// 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
// distance between point and placex house
$sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID;
$aDistancePlacex = chksql($this->oDB->getRow($sSQL),
"Could not determine distance between searched point and placex house.");
$fDistancePlacex = $aDistancePlacex['distance'];
// distance between point and interpolated house (fraction on interpolation line)
$sSQL = 'SELECT ST_distance('.$sPointSQL.', ST_LineInterpolatePoint(linegeo, '.$aPlaceLine['fraction'].')) as distance';
$sSQL .= ' FROM location_property_osmline WHERE place_id = '.$aPlaceLine['place_id'];
$aDistanceInterpolation = chksql($this->oDB->getRow($sSQL),
"Could not determine distance between searched point and interpolated house.");
$fDistanceInterpolation = $aDistanceInterpolation['distance'];
if ($fDistanceInterpolation < $fDistancePlacex)
{
// interpolation is closer to point than placex house
$bPlaceIsLine = true;
$aPlace = $aPlaceLine;
$iPlaceID = $aPlaceLine['place_id'];
$iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
$fFraction = $aPlaceLine['fraction'];
$iMaxRank = 30;
}
// else: nothing to do, take placex house from above
}
else
{
$bPlaceIsLine = true;
$aPlace = $aPlaceLine;
$iPlaceID = $aPlaceLine['place_id'];
$iParentPlaceID = $aPlaceLine['parent_place_id']; // the street
$fFraction = $aPlaceLine['fraction'];
$iMaxRank = 30;
}
}
}
// Only street found? If it's in the US we can check TIGER data for nearest housenumber
if (CONST_Use_US_Tiger_Data && $bDoInterpolation && $bIsInUnitedStates && $this->iMaxRank >= 28 && $iPlaceID && ($aPlace['rank_search'] == 26 || $aPlace['rank_search'] == 27 ))
{
$fSearchDiam = 0.001;
$sSQL = 'SELECT place_id,parent_place_id,30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
//if (CONST_Debug) { $sSQL .= ', housenumber, ST_distance('.$sPointSQL.', centroid) as distance, st_y(centroid) as lat, st_x(centroid) as lon'; }
$sSQL .= ' FROM location_property_tiger WHERE parent_place_id = '.$iPlaceID;
$sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')'; //no centroid anymore in Tiger data, now we have lines
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
$aAllHouses = chksql($this->oDB->getAll($sSQL)); if (CONST_Debug)
foreach($aAllHouses as $i) {
{ $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n"; var_dump($sSQL);
}
}
$aPlaceTiger = chksql($this->oDB->getRow($sSQL), $aAllHouses = chksql($this->oDB->getAll($sSQL));
"Could not determine closest Tiger place."); foreach($aAllHouses as $i)
if ($aPlaceTiger) {
{ echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger); }
$bPlaceIsTiger = true; }
$aPlace = $aPlaceTiger;
$iPlaceID = $aPlaceTiger['place_id'];
$iParentPlaceID = $aPlaceTiger['parent_place_id']; // the street
$fFraction = $aPlaceTiger['fraction'];
$iMaxRank = 30;
}
}
// The point we found might be too small - use the address to find what it is a child of $aPlaceTiger = chksql($this->oDB->getRow($sSQL),
if ($iPlaceID && $iMaxRank < 28) "Could not determine closest Tiger place.");
{ if ($aPlaceTiger)
if (($aPlace['rank_search'] > 28 || $bPlaceIsTiger || $bPlaceIsLine) && $iParentPlaceID) {
{ if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
$iPlaceID = $iParentPlaceID; $bPlaceIsTiger = true;
} $aPlace = $aPlaceTiger;
$sSQL = 'select address_place_id'; $iPlaceID = $aPlaceTiger['place_id'];
$sSQL .= ' FROM place_addressline'; $iParentPlaceID = $aPlaceTiger['parent_place_id']; // the street
$sSQL .= " WHERE place_id = $iPlaceID"; $fFraction = $aPlaceTiger['fraction'];
$sSQL .= " ORDER BY abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc"; $iMaxRank = 30;
$sSQL .= ' LIMIT 1'; }
$iPlaceID = chksql($this->oDB->getOne($sSQL), }
"Could not get parent for place.");
if (!$iPlaceID) // The point we found might be too small - use the address to find what it is a child of
{ if ($iPlaceID && $iMaxRank < 28)
$iPlaceID = $aPlace['place_id']; {
} if (($aPlace['rank_search'] > 28 || $bPlaceIsTiger || $bPlaceIsLine) && $iParentPlaceID)
} {
return array('place_id' => $iPlaceID, $iPlaceID = $iParentPlaceID;
'type' => $bPlaceIsTiger ? 'tiger' : ($bPlaceIsLine ? 'interpolation' : 'osm'), }
'fraction' => ($bPlaceIsTiger || $bPlaceIsLine) ? $fFraction : -1); $sSQL = 'select address_place_id';
} $sSQL .= ' FROM place_addressline';
$sSQL .= " WHERE place_id = $iPlaceID";
} $sSQL .= " ORDER BY abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc";
?> $sSQL .= ' LIMIT 1';
$iPlaceID = chksql($this->oDB->getOne($sSQL),
"Could not get parent for place.");
if (!$iPlaceID)
{
$iPlaceID = $aPlace['place_id'];
}
}
return array('place_id' => $iPlaceID,
'type' => $bPlaceIsTiger ? 'tiger' : ($bPlaceIsLine ? 'interpolation' : 'osm'),
'fraction' => ($bPlaceIsTiger || $bPlaceIsLine) ? $fFraction : -1);
}
}

View File

@ -1,155 +1,155 @@
<?php <?php
function getCmdOpt($aArg, $aSpec, &$aResult, $bExitOnError = false, $bExitOnUnknown = false) function getCmdOpt($aArg, $aSpec, &$aResult, $bExitOnError = false, $bExitOnUnknown = false)
{ {
$aQuick = array(); $aQuick = array();
$aCounts = array(); $aCounts = array();
foreach($aSpec as $aLine) foreach($aSpec as $aLine)
{ {
if (is_array($aLine)) if (is_array($aLine))
{ {
if ($aLine[0]) $aQuick['--'.$aLine[0]] = $aLine; if ($aLine[0]) $aQuick['--'.$aLine[0]] = $aLine;
if ($aLine[1]) $aQuick['-'.$aLine[1]] = $aLine; if ($aLine[1]) $aQuick['-'.$aLine[1]] = $aLine;
$aCounts[$aLine[0]] = 0; $aCounts[$aLine[0]] = 0;
} }
} }
$aResult = array(); $aResult = array();
$bUnknown = false; $bUnknown = false;
$iSize = sizeof($aArg); $iSize = sizeof($aArg);
for ($i = 1; $i < $iSize; $i++) for ($i = 1; $i < $iSize; $i++)
{ {
if (isset($aQuick[$aArg[$i]])) if (isset($aQuick[$aArg[$i]]))
{ {
$aLine = $aQuick[$aArg[$i]]; $aLine = $aQuick[$aArg[$i]];
$aCounts[$aLine[0]]++; $aCounts[$aLine[0]]++;
$xVal = null; $xVal = null;
if ($aLine[4] == $aLine[5]) if ($aLine[4] == $aLine[5])
{ {
if ($aLine[4]) if ($aLine[4])
{ {
$xVal = array(); $xVal = array();
for($n = $aLine[4]; $i < $iSize && $n; $n--) for($n = $aLine[4]; $i < $iSize && $n; $n--)
{ {
$i++; $i++;
if ($i >= $iSize || $aArg[$i][0] == '-') showUsage($aSpec, $bExitOnError, 'Parameter of \''.$aLine[0].'\' is missing'); if ($i >= $iSize || $aArg[$i][0] == '-') showUsage($aSpec, $bExitOnError, 'Parameter of \''.$aLine[0].'\' is missing');
switch ($aLine[6]) switch ($aLine[6])
{ {
case 'realpath': case 'realpath':
$xVal[] = realpath($aArg[$i]); $xVal[] = realpath($aArg[$i]);
break; break;
case 'realdir': case 'realdir':
$sPath = realpath(dirname($aArg[$i])); $sPath = realpath(dirname($aArg[$i]));
if ($sPath) if ($sPath)
$xVal[] = $sPath . '/' . basename($aArg[$i]); $xVal[] = $sPath . '/' . basename($aArg[$i]);
else else
$xVal[] = $sPath; $xVal[] = $sPath;
break; break;
case 'bool': case 'bool':
$xVal[] = (bool)$aArg[$i]; $xVal[] = (bool)$aArg[$i];
break; break;
case 'int': case 'int':
$xVal[] = (int)$aArg[$i]; $xVal[] = (int)$aArg[$i];
break; break;
case 'float': case 'float':
$xVal[] = (float)$aArg[$i]; $xVal[] = (float)$aArg[$i];
break; break;
default: default:
$xVal[] = $aArg[$i]; $xVal[] = $aArg[$i];
break; break;
} }
} }
if ($aLine[4] == 1) $xVal = $xVal[0]; if ($aLine[4] == 1) $xVal = $xVal[0];
} }
else else
{ {
$xVal = true; $xVal = true;
} }
} }
else else
{ {
fail('Variable numbers of params not yet supported'); fail('Variable numbers of params not yet supported');
} }
if ($aLine[3] > 1) if ($aLine[3] > 1)
{ {
if (!array_key_exists($aLine[0], $aResult)) $aResult[$aLine[0]] = array(); if (!array_key_exists($aLine[0], $aResult)) $aResult[$aLine[0]] = array();
$aResult[$aLine[0]][] = $xVal; $aResult[$aLine[0]][] = $xVal;
} }
else else
{ {
$aResult[$aLine[0]] = $xVal; $aResult[$aLine[0]] = $xVal;
} }
} }
else else
{ {
$bUnknown = $aArg[$i]; $bUnknown = $aArg[$i];
} }
} }
if (array_key_exists('help', $aResult)) showUsage($aSpec); if (array_key_exists('help', $aResult)) showUsage($aSpec);
if ($bUnknown && $bExitOnUnknown) showUsage($aSpec, $bExitOnError, 'Unknown option \''.$bUnknown.'\''); if ($bUnknown && $bExitOnUnknown) showUsage($aSpec, $bExitOnError, 'Unknown option \''.$bUnknown.'\'');
foreach($aSpec as $aLine) foreach($aSpec as $aLine)
{ {
if (is_array($aLine)) if (is_array($aLine))
{ {
if ($aCounts[$aLine[0]] < $aLine[2]) showUsage($aSpec, $bExitOnError, 'Option \''.$aLine[0].'\' is missing'); if ($aCounts[$aLine[0]] < $aLine[2]) showUsage($aSpec, $bExitOnError, 'Option \''.$aLine[0].'\' is missing');
if ($aCounts[$aLine[0]] > $aLine[3]) showUsage($aSpec, $bExitOnError, 'Option \''.$aLine[0].'\' is pressent too many times'); if ($aCounts[$aLine[0]] > $aLine[3]) showUsage($aSpec, $bExitOnError, 'Option \''.$aLine[0].'\' is pressent too many times');
switch ($aLine[6]) switch ($aLine[6])
{ {
case 'bool': case 'bool':
if (!array_key_exists($aLine[0], $aResult)) if (!array_key_exists($aLine[0], $aResult))
$aResult[$aLine[0]] = false; $aResult[$aLine[0]] = false;
break; break;
} }
} }
} }
return $bUnknown; return $bUnknown;
} }
function showUsage($aSpec, $bExit = false, $sError = false) function showUsage($aSpec, $bExit = false, $sError = false)
{ {
if ($sError) if ($sError)
{ {
echo basename($_SERVER['argv'][0]).': '.$sError."\n"; echo basename($_SERVER['argv'][0]).': '.$sError."\n";
echo 'Try `'.basename($_SERVER['argv'][0]).' --help` for more information.'."\n"; echo 'Try `'.basename($_SERVER['argv'][0]).' --help` for more information.'."\n";
exit; exit;
} }
echo "Usage: ".basename($_SERVER['argv'][0])."\n"; echo "Usage: ".basename($_SERVER['argv'][0])."\n";
$bFirst = true; $bFirst = true;
foreach($aSpec as $aLine) foreach($aSpec as $aLine)
{ {
if (is_array($aLine)) if (is_array($aLine))
{ {
if ($bFirst) if ($bFirst)
{ {
$bFirst = false; $bFirst = false;
echo "\n"; echo "\n";
} }
$aNames = array(); $aNames = array();
if ($aLine[1]) $aNames[] = '-'.$aLine[1]; if ($aLine[1]) $aNames[] = '-'.$aLine[1];
if ($aLine[0]) $aNames[] = '--'.$aLine[0]; if ($aLine[0]) $aNames[] = '--'.$aLine[0];
$sName = join(', ',$aNames); $sName = join(', ',$aNames);
echo ' '.$sName.str_repeat(' ',30-strlen($sName)).$aLine[7]."\n"; echo ' '.$sName.str_repeat(' ',30-strlen($sName)).$aLine[7]."\n";
} }
else else
{ {
echo $aLine."\n"; echo $aLine."\n";
} }
} }
echo "\n"; echo "\n";
exit; exit;
} }
function chksql($oSql, $sMsg = false) function chksql($oSql, $sMsg = false)
{ {
if (PEAR::isError($oSql)) if (PEAR::isError($oSql))
{ {
fail($sMsg || $oSql->getMessage(), $oSql->userinfo); fail($sMsg || $oSql->getMessage(), $oSql->userinfo);
} }
return $oSql; return $oSql;
} }

View File

@ -1,34 +1,35 @@
<?php <?php
require_once('DB.php');
function &getDB($bNew = false, $bPersistent = false) require_once('DB.php');
{
// Get the database object
$oDB = chksql(DB::connect(CONST_Database_DSN.($bNew?'?new_link=true':''), $bPersistent),
"Failed to establish database connection");
$oDB->setFetchMode(DB_FETCHMODE_ASSOC);
$oDB->query("SET DateStyle TO 'sql,european'");
$oDB->query("SET client_encoding TO 'utf-8'");
$iMaxExecution = ini_get('max_execution_time') * 1000;
if ($iMaxExecution > 0) $oDB->query("SET statement_timeout TO $iMaxExecution");
return $oDB;
}
function getDBQuoted($s) function &getDB($bNew = false, $bPersistent = false)
{ {
return "'".pg_escape_string($s)."'"; // Get the database object
} $oDB = chksql(DB::connect(CONST_Database_DSN.($bNew?'?new_link=true':''), $bPersistent),
"Failed to establish database connection");
$oDB->setFetchMode(DB_FETCHMODE_ASSOC);
$oDB->query("SET DateStyle TO 'sql,european'");
$oDB->query("SET client_encoding TO 'utf-8'");
$iMaxExecution = ini_get('max_execution_time') * 1000;
if ($iMaxExecution > 0) $oDB->query("SET statement_timeout TO $iMaxExecution");
return $oDB;
}
function getPostgresVersion(&$oDB) function getDBQuoted($s)
{ {
$sVersionString = $oDB->getOne('select version()'); return "'".pg_escape_string($s)."'";
preg_match('#PostgreSQL ([0-9]+)[.]([0-9]+)[^0-9]#', $sVersionString, $aMatches); }
return (float) ($aMatches[1].'.'.$aMatches[2]);
}
function getPostgisVersion(&$oDB) function getPostgresVersion(&$oDB)
{ {
$sVersionString = $oDB->getOne('select postgis_full_version()'); $sVersionString = $oDB->getOne('select version()');
preg_match('#POSTGIS="([0-9]+)[.]([0-9]+)[.]([0-9]+)( r([0-9]+))?"#', $sVersionString, $aMatches); preg_match('#PostgreSQL ([0-9]+)[.]([0-9]+)[^0-9]#', $sVersionString, $aMatches);
return (float) ($aMatches[1].'.'.$aMatches[2]); return (float) ($aMatches[1].'.'.$aMatches[2]);
} }
function getPostgisVersion(&$oDB)
{
$sVersionString = $oDB->getOne('select postgis_full_version()');
preg_match('#POSTGIS="([0-9]+)[.]([0-9]+)[.]([0-9]+)( r([0-9]+))?"#', $sVersionString, $aMatches);
return (float) ($aMatches[1].'.'.$aMatches[2]);
}

View File

@ -1,26 +1,27 @@
<?php <?php
require_once('init.php');
require_once('cmd.php');
// handle http proxy when using file_get_contents require_once('init.php');
if (CONST_HTTP_Proxy) { require_once('cmd.php');
$proxy = 'tcp://' . CONST_HTTP_Proxy_Host . ':' . CONST_HTTP_Proxy_Port;
$aHeaders = array(); // handle http proxy when using file_get_contents
if(CONST_HTTP_Proxy_Login != null && CONST_HTTP_Proxy_Login != '' && CONST_HTTP_Proxy_Password != null && CONST_HTTP_Proxy_Password != '') { if (CONST_HTTP_Proxy) {
$auth = base64_encode(CONST_HTTP_Proxy_Login . ':' . CONST_HTTP_Proxy_Password); $proxy = 'tcp://' . CONST_HTTP_Proxy_Host . ':' . CONST_HTTP_Proxy_Port;
$aHeaders = array("Proxy-Authorization: Basic $auth"); $aHeaders = array();
} if(CONST_HTTP_Proxy_Login != null && CONST_HTTP_Proxy_Login != '' && CONST_HTTP_Proxy_Password != null && CONST_HTTP_Proxy_Password != '') {
$aContext = array( $auth = base64_encode(CONST_HTTP_Proxy_Login . ':' . CONST_HTTP_Proxy_Password);
'http' => array( $aHeaders = array("Proxy-Authorization: Basic $auth");
'proxy' => $proxy, }
'request_fulluri' => true, $aContext = array(
'header' => $aHeaders 'http' => array(
), 'proxy' => $proxy,
'https' => array( 'request_fulluri' => true,
'proxy' => $proxy, 'header' => $aHeaders
'request_fulluri' => true, ),
'header' => $aHeaders 'https' => array(
) 'proxy' => $proxy,
); 'request_fulluri' => true,
stream_context_set_default($aContext); 'header' => $aHeaders
} )
);
stream_context_set_default($aContext);
}

View File

@ -1,104 +1,106 @@
<?php <?php
require_once('init.php');
require_once('ParameterParser.php'); require_once('init.php');
require_once('ParameterParser.php');
/*************************************************************************** /***************************************************************************
* *
* Error handling functions * Error handling functions
* *
*/ */
function chksql($oSql, $sMsg = "Database request failed")
{
if (!PEAR::isError($oSql)) return $oSql;
header('HTTP/1.0 500 Internal Server Error'); function chksql($oSql, $sMsg = "Database request failed")
header('Content-type: text/html; charset=utf-8'); {
if (!PEAR::isError($oSql)) return $oSql;
$sSqlError = $oSql->getMessage(); header('HTTP/1.0 500 Internal Server Error');
header('Content-type: text/html; charset=utf-8');
echo <<<INTERNALFAIL $sSqlError = $oSql->getMessage();
<html>
<head><title>Internal Server Error</title></head> echo <<<INTERNALFAIL
<body> <html>
<h1>Internal Server Error</h1> <head><title>Internal Server Error</title></head>
<p>Nominatim has encountered an internal error while accessing the database. <body>
This may happen because the database is broken or because of a bug in <h1>Internal Server Error</h1>
the software. If you think it is a bug, feel free to report <p>Nominatim has encountered an internal error while accessing the database.
it over on <a href="https://github.com/twain47/Nominatim/issues"> This may happen because the database is broken or because of a bug in
Github</a>. Please include the URL that caused the problem and the the software. If you think it is a bug, feel free to report
complete error details below.</p> it over on <a href="https://github.com/twain47/Nominatim/issues">
<p><b>Message:</b> $sMsg</p> Github</a>. Please include the URL that caused the problem and the
<p><b>SQL Error:</b> $sSqlError</p> complete error details below.</p>
<p><b>Details:</b> <pre> <p><b>Message:</b> $sMsg</p>
<p><b>SQL Error:</b> $sSqlError</p>
<p><b>Details:</b> <pre>
INTERNALFAIL; INTERNALFAIL;
if (CONST_Debug) if (CONST_Debug)
{ {
var_dump($oSql); var_dump($oSql);
} }
else else
{ {
echo "<pre>\n".$oSql->getUserInfo()."</pre>"; echo "<pre>\n".$oSql->getUserInfo()."</pre>";
} }
echo "</pre></p></body></html>"; echo "</pre></p></body></html>";
exit; exit;
} }
function failInternalError($sError, $sSQL = false, $vDumpVar = false) function failInternalError($sError, $sSQL = false, $vDumpVar = false)
{ {
header('HTTP/1.0 500 Internal Server Error'); header('HTTP/1.0 500 Internal Server Error');
header('Content-type: text/html; charset=utf-8'); header('Content-type: text/html; charset=utf-8');
echo "<html><body><h1>Internal Server Error</h1>"; echo "<html><body><h1>Internal Server Error</h1>";
echo '<p>Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.</p>'; echo '<p>Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.</p>';
echo "<p><b>Details:</b> ".$sError,"</p>"; echo "<p><b>Details:</b> ".$sError,"</p>";
echo '<p>Feel free to file an issue on <a href="https://github.com/twain47/Nominatim/issues">Github</a>. Please include the error message above and the URL you used.</p>'; echo '<p>Feel free to file an issue on <a href="https://github.com/twain47/Nominatim/issues">Github</a>. Please include the error message above and the URL you used.</p>';
if (CONST_Debug) if (CONST_Debug)
{ {
echo "<hr><h2>Debugging Information</h2><br>"; echo "<hr><h2>Debugging Information</h2><br>";
if ($sSQL) if ($sSQL)
{ {
echo "<h3>SQL query</h3><code>".$sSQL."</code>"; echo "<h3>SQL query</h3><code>".$sSQL."</code>";
} }
if ($vDumpVar) if ($vDumpVar)
{ {
echo "<h3>Result</h3> <code>"; echo "<h3>Result</h3> <code>";
var_dump($vDumpVar); var_dump($vDumpVar);
echo "</code>"; echo "</code>";
} }
} }
echo "\n</body></html>\n"; echo "\n</body></html>\n";
exit; exit;
} }
function userError($sError) function userError($sError)
{ {
header('HTTP/1.0 400 Bad Request'); header('HTTP/1.0 400 Bad Request');
header('Content-type: text/html; charset=utf-8'); header('Content-type: text/html; charset=utf-8');
echo "<html><body><h1>Bad Request</h1>"; echo "<html><body><h1>Bad Request</h1>";
echo '<p>Nominatim has encountered an error with your request.</p>'; echo '<p>Nominatim has encountered an error with your request.</p>';
echo "<p><b>Details:</b> ".$sError."</p>"; echo "<p><b>Details:</b> ".$sError."</p>";
echo '<p>If you feel this error is incorrect feel file an issue on <a href="https://github.com/twain47/Nominatim/issues">Github</a>. Please include the error message above and the URL you used.</p>'; echo '<p>If you feel this error is incorrect feel file an issue on <a href="https://github.com/twain47/Nominatim/issues">Github</a>. Please include the error message above and the URL you used.</p>';
echo "\n</body></html>\n"; echo "\n</body></html>\n";
exit; exit;
} }
/*************************************************************************** /***************************************************************************
* HTTP Reply header setup * HTTP Reply header setup
*/ */
if (CONST_NoAccessControl) if (CONST_NoAccessControl)
{ {
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: OPTIONS,GET"); header("Access-Control-Allow-Methods: OPTIONS,GET");
if (!empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) if (!empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
{ {
header("Access-Control-Allow-Headers: ".$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']); header("Access-Control-Allow-Headers: ".$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
} }
} }
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,10 +1,10 @@
<?php <?php
require_once(CONST_BasePath.'/lib/lib.php'); require_once(CONST_BasePath.'/lib/lib.php');
require_once(CONST_BasePath.'/lib/db.php'); require_once(CONST_BasePath.'/lib/db.php');
if (get_magic_quotes_gpc()) if (get_magic_quotes_gpc())
{ {
echo "Please disable magic quotes in your php.ini configuration\n"; echo "Please disable magic quotes in your php.ini configuration\n";
exit; exit;
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,74 +1,74 @@
<?php <?php
function logStart(&$oDB, $sType = '', $sQuery = '', $aLanguageList = array()) function logStart(&$oDB, $sType = '', $sQuery = '', $aLanguageList = array())
{ {
$fStartTime = microtime(true); $fStartTime = microtime(true);
$aStartTime = explode('.', $fStartTime); $aStartTime = explode('.', $fStartTime);
if (!isset($aStartTime[1])) $aStartTime[1] = '0'; if (!isset($aStartTime[1])) $aStartTime[1] = '0';
$sOutputFormat = ''; $sOutputFormat = '';
if (isset($_GET['format'])) $sOutputFormat = $_GET['format']; if (isset($_GET['format'])) $sOutputFormat = $_GET['format'];
if ($sType == 'reverse') if ($sType == 'reverse')
{ {
$sOutQuery = (isset($_GET['lat'])?$_GET['lat']:'').'/'; $sOutQuery = (isset($_GET['lat'])?$_GET['lat']:'').'/';
if (isset($_GET['lon'])) $sOutQuery .= $_GET['lon']; if (isset($_GET['lon'])) $sOutQuery .= $_GET['lon'];
if (isset($_GET['zoom'])) $sOutQuery .= '/'.$_GET['zoom']; if (isset($_GET['zoom'])) $sOutQuery .= '/'.$_GET['zoom'];
} }
else else
$sOutQuery = $sQuery; $sOutQuery = $sQuery;
$hLog = array( $hLog = array(
date('Y-m-d H:i:s',$aStartTime[0]).'.'.$aStartTime[1], date('Y-m-d H:i:s',$aStartTime[0]).'.'.$aStartTime[1],
$_SERVER["REMOTE_ADDR"], $_SERVER["REMOTE_ADDR"],
$_SERVER['QUERY_STRING'], $_SERVER['QUERY_STRING'],
$sOutQuery, $sOutQuery,
$sType, $sType,
$fStartTime $fStartTime
); );
if (CONST_Log_DB) if (CONST_Log_DB)
{ {
if (isset($_GET['email'])) if (isset($_GET['email']))
$sUserAgent = $_GET['email']; $sUserAgent = $_GET['email'];
elseif (isset($_SERVER['HTTP_REFERER'])) elseif (isset($_SERVER['HTTP_REFERER']))
$sUserAgent = $_SERVER['HTTP_REFERER']; $sUserAgent = $_SERVER['HTTP_REFERER'];
elseif (isset($_SERVER['HTTP_USER_AGENT'])) elseif (isset($_SERVER['HTTP_USER_AGENT']))
$sUserAgent = $_SERVER['HTTP_USER_AGENT']; $sUserAgent = $_SERVER['HTTP_USER_AGENT'];
else else
$sUserAgent = ''; $sUserAgent = '';
$sSQL = 'insert into new_query_log (type,starttime,query,ipaddress,useragent,language,format,searchterm)'; $sSQL = 'insert into new_query_log (type,starttime,query,ipaddress,useragent,language,format,searchterm)';
$sSQL .= ' values ('.getDBQuoted($sType).','.getDBQuoted($hLog[0]).','.getDBQuoted($hLog[2]); $sSQL .= ' values ('.getDBQuoted($sType).','.getDBQuoted($hLog[0]).','.getDBQuoted($hLog[2]);
$sSQL .= ','.getDBQuoted($hLog[1]).','.getDBQuoted($sUserAgent).','.getDBQuoted(join(',',$aLanguageList)).','.getDBQuoted($sOutputFormat).','.getDBQuoted($hLog[3]).')'; $sSQL .= ','.getDBQuoted($hLog[1]).','.getDBQuoted($sUserAgent).','.getDBQuoted(join(',',$aLanguageList)).','.getDBQuoted($sOutputFormat).','.getDBQuoted($hLog[3]).')';
$oDB->query($sSQL); $oDB->query($sSQL);
} }
return $hLog; return $hLog;
} }
function logEnd(&$oDB, $hLog, $iNumResults) function logEnd(&$oDB, $hLog, $iNumResults)
{ {
$fEndTime = microtime(true); $fEndTime = microtime(true);
if (CONST_Log_DB) if (CONST_Log_DB)
{ {
$aEndTime = explode('.', $fEndTime); $aEndTime = explode('.', $fEndTime);
if (!$aEndTime[1]) $aEndTime[1] = '0'; if (!$aEndTime[1]) $aEndTime[1] = '0';
$sEndTime = date('Y-m-d H:i:s',$aEndTime[0]).'.'.$aEndTime[1]; $sEndTime = date('Y-m-d H:i:s',$aEndTime[0]).'.'.$aEndTime[1];
$sSQL = 'update new_query_log set endtime = '.getDBQuoted($sEndTime).', results = '.$iNumResults; $sSQL = 'update new_query_log set endtime = '.getDBQuoted($sEndTime).', results = '.$iNumResults;
$sSQL .= ' where starttime = '.getDBQuoted($hLog[0]); $sSQL .= ' where starttime = '.getDBQuoted($hLog[0]);
$sSQL .= ' and ipaddress = '.getDBQuoted($hLog[1]); $sSQL .= ' and ipaddress = '.getDBQuoted($hLog[1]);
$sSQL .= ' and query = '.getDBQuoted($hLog[2]); $sSQL .= ' and query = '.getDBQuoted($hLog[2]);
$oDB->query($sSQL); $oDB->query($sSQL);
} }
if (CONST_Log_File) if (CONST_Log_File)
{ {
$aOutdata = sprintf("[%s] %.4f %d %s \"%s\"\n", $aOutdata = sprintf("[%s] %.4f %d %s \"%s\"\n",
$hLog[0], $fEndTime-$hLog[5], $iNumResults, $hLog[0], $fEndTime-$hLog[5], $iNumResults,
$hLog[4], $hLog[2]); $hLog[4], $hLog[2]);
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,43 +1,43 @@
<?php <?php
function formatOSMType($sType, $bIncludeExternal=true) function formatOSMType($sType, $bIncludeExternal=true)
{ {
if ($sType == 'N') return 'node'; if ($sType == 'N') return 'node';
if ($sType == 'W') return 'way'; if ($sType == 'W') return 'way';
if ($sType == 'R') return 'relation'; if ($sType == 'R') return 'relation';
if (!$bIncludeExternal) return ''; if (!$bIncludeExternal) return '';
if ($sType == 'T') return 'tiger'; if ($sType == 'T') return 'tiger';
if ($sType == 'I') return 'way'; if ($sType == 'I') return 'way';
return ''; return '';
} }
function osmLink($aFeature, $sRefText=false) function osmLink($aFeature, $sRefText=false)
{ {
$sOSMType = formatOSMType($aFeature['osm_type'], false); $sOSMType = formatOSMType($aFeature['osm_type'], false);
if ($sOSMType) if ($sOSMType)
{ {
return '<a href="//www.openstreetmap.org/'.$sOSMType.'/'.$aFeature['osm_id'].'">'.$sOSMType.' '.($sRefText?$sRefText:$aFeature['osm_id']).'</a>'; return '<a href="//www.openstreetmap.org/'.$sOSMType.'/'.$aFeature['osm_id'].'">'.$sOSMType.' '.($sRefText?$sRefText:$aFeature['osm_id']).'</a>';
} }
return ''; return '';
} }
function wikipediaLink($aFeature) function wikipediaLink($aFeature)
{ {
if ($aFeature['wikipedia']) if ($aFeature['wikipedia'])
{ {
list($sLanguage, $sArticle) = explode(':',$aFeature['wikipedia']); list($sLanguage, $sArticle) = explode(':',$aFeature['wikipedia']);
return '<a href="https://'.$sLanguage.'.wikipedia.org/wiki/'.urlencode($sArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>'; return '<a href="https://'.$sLanguage.'.wikipedia.org/wiki/'.urlencode($sArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>';
} }
return ''; return '';
} }
function detailsLink($aFeature, $sTitle=false) function detailsLink($aFeature, $sTitle=false)
{ {
if (!$aFeature['place_id']) return ''; if (!$aFeature['place_id']) return '';
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

@ -1,109 +1,109 @@
<?php <?php
header("content-type: text/html; charset=UTF-8"); header("content-type: text/html; charset=UTF-8");
?> ?>
<?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?>
<link href="css/common.css" rel="stylesheet" type="text/css" /> <link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/search.css" rel="stylesheet" type="text/css" /> <link href="css/search.css" rel="stylesheet" type="text/css" />
</head> </head>
<body id="reverse-page"> <body id="reverse-page">
<?php include(CONST_BasePath.'/lib/template/includes/html-top-navigation.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-top-navigation.php'); ?>
<form class="form-inline" role="search" accept-charset="UTF-8" action="<?php echo CONST_Website_BaseURL; ?>reverse.php"> <form class="form-inline" role="search" accept-charset="UTF-8" action="<?php echo CONST_Website_BaseURL; ?>reverse.php">
<div class="form-group"> <div class="form-group">
<input name="format" type="hidden" value="html"> <input name="format" type="hidden" value="html">
<input name="lat" type="text" class="form-control input-sm" placeholder="latitude" value="<?php echo htmlspecialchars($_GET['lat']); ?>" > <input name="lat" type="text" class="form-control input-sm" placeholder="latitude" value="<?php echo htmlspecialchars($_GET['lat']); ?>" >
<input name="lon" type="text" class="form-control input-sm" placeholder="longitude" value="<?php echo htmlspecialchars($_GET['lon']); ?>" > <input name="lon" type="text" class="form-control input-sm" placeholder="longitude" value="<?php echo htmlspecialchars($_GET['lon']); ?>" >
max zoom max zoom
<select name="zoom" class="form-control input-sm" value="<?php echo htmlspecialchars($_GET['zoom']); ?>"> <select name="zoom" class="form-control input-sm" value="<?php echo htmlspecialchars($_GET['zoom']); ?>">
<option value="" <?php echo $_GET['zoom']==''?'selected':'' ?> >--</option> <option value="" <?php echo $_GET['zoom']==''?'selected':'' ?> >--</option>
<?php <?php
$aZoomLevels = array( $aZoomLevels = array(
0 => "Continent / Sea", 0 => "Continent / Sea",
1 => "", 1 => "",
2 => "", 2 => "",
3 => "Country", 3 => "Country",
4 => "", 4 => "",
5 => "State", 5 => "State",
6 => "Region", 6 => "Region",
7 => "", 7 => "",
8 => "County", 8 => "County",
9 => "", 9 => "",
10 => "City", 10 => "City",
11 => "", 11 => "",
12 => "Town / Village", 12 => "Town / Village",
13 => "", 13 => "",
14 => "Suburb", 14 => "Suburb",
15 => "", 15 => "",
16 => "Street", 16 => "Street",
17 => "", 17 => "",
18 => "Building", 18 => "Building",
19 => "", 19 => "",
20 => "", 20 => "",
21 => "", 21 => "",
); );
foreach($aZoomLevels as $iZoomLevel => $sLabel) foreach($aZoomLevels as $iZoomLevel => $sLabel)
{ {
$bSel = isset($_GET['zoom']) && ($_GET['zoom'] == (string)$iZoomLevel); $bSel = isset($_GET['zoom']) && ($_GET['zoom'] == (string)$iZoomLevel);
echo '<option value="'.$iZoomLevel.'"'.($bSel?'selected':'').'>'.$iZoomLevel.' '.$sLabel.'</option>'."\n"; echo '<option value="'.$iZoomLevel.'"'.($bSel?'selected':'').'>'.$iZoomLevel.' '.$sLabel.'</option>'."\n";
} }
?> ?>
</select> </select>
</div> </div>
<div class="form-group search-button-group"> <div class="form-group search-button-group">
<button type="submit" class="btn btn-primary btn-sm">Search</button> <button type="submit" class="btn btn-primary btn-sm">Search</button>
</div> </div>
<div class="search-type-link"> <div class="search-type-link">
<a href="<?php echo CONST_Website_BaseURL; ?>search.php">forward search</a> <a href="<?php echo CONST_Website_BaseURL; ?>search.php">forward search</a>
</div> </div>
</form> </form>
<div id="content"> <div id="content">
<?php if ($aPlace) { ?> <?php if ($aPlace) { ?>
<div id="searchresults" class="sidebar"> <div id="searchresults" class="sidebar">
<?php <?php
$aResult = $aPlace; $aResult = $aPlace;
echo '<div class="result" data-position="0">'; echo '<div class="result" data-position="0">';
echo (isset($aResult['icon'])?'<img alt="icon" src="'.$aResult['icon'].'"/>':''); echo (isset($aResult['icon'])?'<img alt="icon" src="'.$aResult['icon'].'"/>':'');
echo ' <span class="name">'.htmlspecialchars($aResult['langaddress']).'</span>'; echo ' <span class="name">'.htmlspecialchars($aResult['langaddress']).'</span>';
if (isset($aResult['label'])) if (isset($aResult['label']))
echo ' <span class="type">('.$aResult['label'].')</span>'; echo ' <span class="type">('.$aResult['label'].')</span>';
else if ($aResult['type'] == 'yes') else if ($aResult['type'] == 'yes')
echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['class'])).')</span>'; echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['class'])).')</span>';
else else
echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['type'])).')</span>'; echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['type'])).')</span>';
echo '<p>'.$aResult['lat'].','.$aResult['lon'].'</p>'; echo '<p>'.$aResult['lat'].','.$aResult['lon'].'</p>';
echo ' <a class="btn btn-default btn-xs details" href="details.php?place_id='.$aResult['place_id'].'">details</a>'; echo ' <a class="btn btn-default btn-xs details" href="details.php?place_id='.$aResult['place_id'].'">details</a>';
echo '</div>'; echo '</div>';
?> ?>
</div> </div>
<?php } else { ?> <?php } else { ?>
<div id="intro" class="sidebar"> <div id="intro" class="sidebar">
Search for coordinates or click anywhere on the map. Search for coordinates or click anywhere on the map.
</div> </div>
<?php } ?> <?php } ?>
<div id="map-wrapper"> <div id="map-wrapper">
<div id="map-position"> <div id="map-position">
<div id="map-position-inner"></div> <div id="map-position-inner"></div>
<div id="map-position-close"><a href="#">hide</a></div> <div id="map-position-close"><a href="#">hide</a></div>
</div> </div>
<div id="map"></div> <div id="map"></div>
</div> </div>
</div> <!-- /content --> </div> <!-- /content -->
@ -111,22 +111,22 @@
<script type="text/javascript"> <script type="text/javascript">
<?php <?php
$aNominatimMapInit = array( $aNominatimMapInit = array(
'zoom' => isset($_GET['zoom']) ? htmlspecialchars($_GET['zoom']) : CONST_Default_Zoom, 'zoom' => isset($_GET['zoom']) ? htmlspecialchars($_GET['zoom']) : CONST_Default_Zoom,
'lat' => isset($_GET['lat']) ? htmlspecialchars($_GET['lat']) : CONST_Default_Lat, 'lat' => isset($_GET['lat']) ? htmlspecialchars($_GET['lat']) : CONST_Default_Lat,
'lon' => isset($_GET['lon']) ? htmlspecialchars($_GET['lon']) : CONST_Default_Lon, 'lon' => isset($_GET['lon']) ? htmlspecialchars($_GET['lon']) : CONST_Default_Lon,
'tile_url' => $sTileURL, 'tile_url' => $sTileURL,
'tile_attribution' => $sTileAttribution 'tile_attribution' => $sTileAttribution
); );
echo 'var nominatim_map_init = ' . json_encode($aNominatimMapInit, JSON_PRETTY_PRINT) . ';'; echo 'var nominatim_map_init = ' . json_encode($aNominatimMapInit, JSON_PRETTY_PRINT) . ';';
echo 'var nominatim_results = ' . json_encode([$aPlace], JSON_PRETTY_PRINT) . ';'; echo 'var nominatim_results = ' . json_encode([$aPlace], JSON_PRETTY_PRINT) . ';';
?> ?>
</script> </script>
<?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?>
</body> </body>
</html> </html>

View File

@ -1,55 +1,56 @@
<?php <?php
$aFilteredPlaces = array();
if (!sizeof($aPlace)) $aFilteredPlaces = array();
{
if (isset($sError))
$aFilteredPlaces['error'] = $sError;
else
$aFilteredPlaces['error'] = 'Unable to geocode';
}
else
{
if (isset($aPlace['place_id'])) $aFilteredPlaces['place_id'] = $aPlace['place_id'];
$aFilteredPlaces['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright";
$sOSMType = formatOSMType($aPlace['osm_type']);
if ($sOSMType)
{
$aFilteredPlaces['osm_type'] = $sOSMType;
$aFilteredPlaces['osm_id'] = $aPlace['osm_id'];
}
if (isset($aPlace['lat'])) $aFilteredPlaces['lat'] = $aPlace['lat'];
if (isset($aPlace['lon'])) $aFilteredPlaces['lon'] = $aPlace['lon'];
$aFilteredPlaces['display_name'] = $aPlace['langaddress'];
if (isset($aPlace['aAddress'])) $aFilteredPlaces['address'] = $aPlace['aAddress'];
if (isset($aPlace['sExtraTags'])) $aFilteredPlaces['extratags'] = $aPlace['sExtraTags'];
if (isset($aPlace['sNameDetails'])) $aFilteredPlaces['namedetails'] = $aPlace['sNameDetails'];
if (isset($aPlace['aBoundingBox'])) if (!sizeof($aPlace))
{ {
$aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox']; if (isset($sError))
} $aFilteredPlaces['error'] = $sError;
else
$aFilteredPlaces['error'] = 'Unable to geocode';
}
else
{
if (isset($aPlace['place_id'])) $aFilteredPlaces['place_id'] = $aPlace['place_id'];
$aFilteredPlaces['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright";
$sOSMType = formatOSMType($aPlace['osm_type']);
if ($sOSMType)
{
$aFilteredPlaces['osm_type'] = $sOSMType;
$aFilteredPlaces['osm_id'] = $aPlace['osm_id'];
}
if (isset($aPlace['lat'])) $aFilteredPlaces['lat'] = $aPlace['lat'];
if (isset($aPlace['lon'])) $aFilteredPlaces['lon'] = $aPlace['lon'];
$aFilteredPlaces['display_name'] = $aPlace['langaddress'];
if (isset($aPlace['aAddress'])) $aFilteredPlaces['address'] = $aPlace['aAddress'];
if (isset($aPlace['sExtraTags'])) $aFilteredPlaces['extratags'] = $aPlace['sExtraTags'];
if (isset($aPlace['sNameDetails'])) $aFilteredPlaces['namedetails'] = $aPlace['sNameDetails'];
if (isset($aPlace['asgeojson'])) if (isset($aPlace['aBoundingBox']))
{ {
$aFilteredPlaces['geojson'] = json_decode($aPlace['asgeojson']); $aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox'];
} }
if (isset($aPlace['assvg'])) if (isset($aPlace['asgeojson']))
{ {
$aFilteredPlaces['svg'] = $aPlace['assvg']; $aFilteredPlaces['geojson'] = json_decode($aPlace['asgeojson']);
} }
if (isset($aPlace['astext'])) if (isset($aPlace['assvg']))
{ {
$aFilteredPlaces['geotext'] = $aPlace['astext']; $aFilteredPlaces['svg'] = $aPlace['assvg'];
} }
if (isset($aPlace['askml'])) if (isset($aPlace['astext']))
{ {
$aFilteredPlaces['geokml'] = $aPlace['askml']; $aFilteredPlaces['geotext'] = $aPlace['astext'];
} }
}
javascript_renderData($aFilteredPlaces); if (isset($aPlace['askml']))
{
$aFilteredPlaces['geokml'] = $aPlace['askml'];
}
}
javascript_renderData($aFilteredPlaces);

View File

@ -1,67 +1,68 @@
<?php <?php
$aFilteredPlaces = array();
if (!sizeof($aPlace)) $aFilteredPlaces = array();
{
if (isset($sError))
$aFilteredPlaces['error'] = $sError;
else
$aFilteredPlaces['error'] = 'Unable to geocode';
}
else
{
if ($aPlace['place_id']) $aFilteredPlaces['place_id'] = $aPlace['place_id'];
$aFilteredPlaces['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright";
$sOSMType = formatOSMType($aPlace['osm_type']);
if ($sOSMType)
{
$aFilteredPlaces['osm_type'] = $sOSMType;
$aFilteredPlaces['osm_id'] = $aPlace['osm_id'];
}
if (isset($aPlace['lat'])) $aFilteredPlaces['lat'] = $aPlace['lat'];
if (isset($aPlace['lon'])) $aFilteredPlaces['lon'] = $aPlace['lon'];
$aFilteredPlaces['place_rank'] = $aPlace['rank_search']; if (!sizeof($aPlace))
{
if (isset($sError))
$aFilteredPlaces['error'] = $sError;
else
$aFilteredPlaces['error'] = 'Unable to geocode';
}
else
{
if ($aPlace['place_id']) $aFilteredPlaces['place_id'] = $aPlace['place_id'];
$aFilteredPlaces['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright";
$sOSMType = formatOSMType($aPlace['osm_type']);
if ($sOSMType)
{
$aFilteredPlaces['osm_type'] = $sOSMType;
$aFilteredPlaces['osm_id'] = $aPlace['osm_id'];
}
if (isset($aPlace['lat'])) $aFilteredPlaces['lat'] = $aPlace['lat'];
if (isset($aPlace['lon'])) $aFilteredPlaces['lon'] = $aPlace['lon'];
$aFilteredPlaces['category'] = $aPlace['class']; $aFilteredPlaces['place_rank'] = $aPlace['rank_search'];
$aFilteredPlaces['type'] = $aPlace['type'];
$aFilteredPlaces['importance'] = $aPlace['importance']; $aFilteredPlaces['category'] = $aPlace['class'];
$aFilteredPlaces['type'] = $aPlace['type'];
$aFilteredPlaces['addresstype'] = strtolower($aPlace['addresstype']); $aFilteredPlaces['importance'] = $aPlace['importance'];
$aFilteredPlaces['display_name'] = $aPlace['langaddress']; $aFilteredPlaces['addresstype'] = strtolower($aPlace['addresstype']);
$aFilteredPlaces['name'] = $aPlace['placename'];
if (isset($aPlace['aAddress'])) $aFilteredPlaces['address'] = $aPlace['aAddress']; $aFilteredPlaces['display_name'] = $aPlace['langaddress'];
if (isset($aPlace['sExtraTags'])) $aFilteredPlaces['extratags'] = $aPlace['sExtraTags']; $aFilteredPlaces['name'] = $aPlace['placename'];
if (isset($aPlace['sNameDetails'])) $aFilteredPlaces['namedetails'] = $aPlace['sNameDetails'];
if (isset($aPlace['aBoundingBox'])) if (isset($aPlace['aAddress'])) $aFilteredPlaces['address'] = $aPlace['aAddress'];
{ if (isset($aPlace['sExtraTags'])) $aFilteredPlaces['extratags'] = $aPlace['sExtraTags'];
$aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox']; if (isset($aPlace['sNameDetails'])) $aFilteredPlaces['namedetails'] = $aPlace['sNameDetails'];
}
if (isset($aPlace['asgeojson'])) if (isset($aPlace['aBoundingBox']))
{ {
$aFilteredPlaces['geojson'] = json_decode($aPlace['asgeojson']); $aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox'];
} }
if (isset($aPlace['assvg'])) if (isset($aPlace['asgeojson']))
{ {
$aFilteredPlaces['svg'] = $aPlace['assvg']; $aFilteredPlaces['geojson'] = json_decode($aPlace['asgeojson']);
} }
if (isset($aPlace['astext'])) if (isset($aPlace['assvg']))
{ {
$aFilteredPlaces['geotext'] = $aPlace['astext']; $aFilteredPlaces['svg'] = $aPlace['assvg'];
} }
if (isset($aPlace['askml'])) if (isset($aPlace['astext']))
{ {
$aFilteredPlaces['geokml'] = $aPlace['askml']; $aFilteredPlaces['geotext'] = $aPlace['astext'];
} }
} if (isset($aPlace['askml']))
{
$aFilteredPlaces['geokml'] = $aPlace['askml'];
}
javascript_renderData($aFilteredPlaces); }
javascript_renderData($aFilteredPlaces);

View File

@ -1,103 +1,103 @@
<?php <?php
header("content-type: text/xml; charset=UTF-8"); header("content-type: text/xml; charset=UTF-8");
echo "<"; echo "<";
echo "?xml version=\"1.0\" encoding=\"UTF-8\" ?"; echo "?xml version=\"1.0\" encoding=\"UTF-8\" ?";
echo ">\n"; echo ">\n";
echo "<reversegeocode"; echo "<reversegeocode";
echo " timestamp='".date(DATE_RFC822)."'"; echo " timestamp='".date(DATE_RFC822)."'";
echo " attribution='Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'"; echo " attribution='Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'";
echo " querystring='".htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES)."'"; echo " querystring='".htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES)."'";
echo ">\n"; echo ">\n";
if (!sizeof($aPlace)) if (!sizeof($aPlace))
{ {
if (isset($sError)) if (isset($sError))
echo "<error>$sError</error>"; echo "<error>$sError</error>";
else else
echo "<error>Unable to geocode</error>"; echo "<error>Unable to geocode</error>";
} }
else else
{ {
echo "<result"; echo "<result";
if ($aPlace['place_id']) echo ' place_id="'.$aPlace['place_id'].'"'; if ($aPlace['place_id']) echo ' place_id="'.$aPlace['place_id'].'"';
$sOSMType = formatOSMType($aPlace['osm_type']); $sOSMType = formatOSMType($aPlace['osm_type']);
if ($sOSMType) echo ' osm_type="'.$sOSMType.'"'.' osm_id="'.$aPlace['osm_id'].'"'; if ($sOSMType) echo ' osm_type="'.$sOSMType.'"'.' osm_id="'.$aPlace['osm_id'].'"';
if ($aPlace['ref']) echo ' ref="'.htmlspecialchars($aPlace['ref']).'"'; if ($aPlace['ref']) echo ' ref="'.htmlspecialchars($aPlace['ref']).'"';
if (isset($aPlace['lat'])) echo ' lat="'.htmlspecialchars($aPlace['lat']).'"'; if (isset($aPlace['lat'])) echo ' lat="'.htmlspecialchars($aPlace['lat']).'"';
if (isset($aPlace['lon'])) echo ' lon="'.htmlspecialchars($aPlace['lon']).'"'; if (isset($aPlace['lon'])) echo ' lon="'.htmlspecialchars($aPlace['lon']).'"';
if (isset($aPlace['aBoundingBox'])) if (isset($aPlace['aBoundingBox']))
{ {
echo ' boundingbox="'; echo ' boundingbox="';
echo join(',', $aPlace['aBoundingBox']); echo join(',', $aPlace['aBoundingBox']);
echo '"'; echo '"';
} }
if (isset($aPlace['asgeojson'])) if (isset($aPlace['asgeojson']))
{ {
echo ' geojson=\''; echo ' geojson=\'';
echo $aPlace['asgeojson']; echo $aPlace['asgeojson'];
echo '\''; echo '\'';
} }
if (isset($aPlace['assvg'])) if (isset($aPlace['assvg']))
{ {
echo ' geosvg=\''; echo ' geosvg=\'';
echo $aPlace['assvg']; echo $aPlace['assvg'];
echo '\''; echo '\'';
} }
if (isset($aPlace['astext'])) if (isset($aPlace['astext']))
{ {
echo ' geotext=\''; echo ' geotext=\'';
echo $aPlace['astext']; echo $aPlace['astext'];
echo '\''; echo '\'';
} }
echo ">".htmlspecialchars($aPlace['langaddress'])."</result>"; echo ">".htmlspecialchars($aPlace['langaddress'])."</result>";
if (isset($aPlace['aAddress'])) if (isset($aPlace['aAddress']))
{ {
echo "<addressparts>"; echo "<addressparts>";
foreach($aPlace['aAddress'] as $sKey => $sValue) foreach($aPlace['aAddress'] as $sKey => $sValue)
{ {
$sKey = str_replace(' ','_',$sKey); $sKey = str_replace(' ','_',$sKey);
echo "<$sKey>"; echo "<$sKey>";
echo htmlspecialchars($sValue); echo htmlspecialchars($sValue);
echo "</$sKey>"; echo "</$sKey>";
} }
echo "</addressparts>"; echo "</addressparts>";
} }
if (isset($aPlace['sExtraTags'])) if (isset($aPlace['sExtraTags']))
{ {
echo "<extratags>"; echo "<extratags>";
foreach ($aPlace['sExtraTags'] as $sKey => $sValue) foreach ($aPlace['sExtraTags'] as $sKey => $sValue)
{ {
echo '<tag key="'.htmlspecialchars($sKey).'" value="'.htmlspecialchars($sValue).'"/>'; echo '<tag key="'.htmlspecialchars($sKey).'" value="'.htmlspecialchars($sValue).'"/>';
} }
echo "</extratags>"; echo "</extratags>";
} }
if (isset($aPlace['sNameDetails'])) if (isset($aPlace['sNameDetails']))
{ {
echo "<namedetails>"; echo "<namedetails>";
foreach ($aPlace['sNameDetails'] as $sKey => $sValue) foreach ($aPlace['sNameDetails'] as $sKey => $sValue)
{ {
echo '<name desc="'.htmlspecialchars($sKey).'">'; echo '<name desc="'.htmlspecialchars($sKey).'">';
echo htmlspecialchars($sValue); echo htmlspecialchars($sValue);
echo "</name>"; echo "</name>";
} }
echo "</namedetails>"; echo "</namedetails>";
} }
if (isset($aPlace['askml'])) if (isset($aPlace['askml']))
{ {
echo "\n<geokml>"; echo "\n<geokml>";
echo $aPlace['askml']; echo $aPlace['askml'];
echo "</geokml>"; echo "</geokml>";
} }
} }
echo "</reversegeocode>"; echo "</reversegeocode>";

View File

@ -1,122 +1,122 @@
<?php <?php
header("content-type: text/html; charset=UTF-8"); header("content-type: text/html; charset=UTF-8");
?> ?>
<?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?>
<link href="css/common.css" rel="stylesheet" type="text/css" /> <link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/details.css" rel="stylesheet" type="text/css" /> <link href="css/details.css" rel="stylesheet" type="text/css" />
</head> </head>
<?php <?php
function osmMapUrl($aFeature) function osmMapUrl($aFeature)
{ {
if (isset($sFeature['error_x']) && isset($sFeature['error_y'])) if (isset($sFeature['error_x']) && isset($sFeature['error_y']))
{ {
$sBaseUrl = '//www.openstreetmap.org/'; $sBaseUrl = '//www.openstreetmap.org/';
$sOSMType = formatOSMType($aFeature['osm_type'], false); $sOSMType = formatOSMType($aFeature['osm_type'], false);
if ($sOSMType) if ($sOSMType)
{ {
$sBaseUrl += $sOSMType.'/'.$aFeature['osm_id']; $sBaseUrl += $sOSMType.'/'.$aFeature['osm_id'];
} }
return '<a href="'.$sBaseUrl.'?mlat='.$aFeature['error_y'].'&mlon='.$aFeature['error_x'].'">view on osm.org</a>'; return '<a href="'.$sBaseUrl.'?mlat='.$aFeature['error_y'].'&mlon='.$aFeature['error_x'].'">view on osm.org</a>';
} }
return ''; return '';
} }
function josm_edit_url($aFeature) function josm_edit_url($aFeature)
{ {
$fWidth = 0.0002; $fWidth = 0.0002;
$sLon = $aFeature['error_x']; $sLon = $aFeature['error_x'];
$sLat = $aFeature['error_y']; $sLat = $aFeature['error_y'];
if (isset($sLat)) if (isset($sLat))
{ {
return "http://localhost:8111/load_and_zoom?left=".($sLon-$fWidth)."&right=".($sLon+$fWidth)."&top=".($sLat+$fWidth)."&bottom=".($sLat-$fWidth); return "http://localhost:8111/load_and_zoom?left=".($sLon-$fWidth)."&right=".($sLon+$fWidth)."&top=".($sLat+$fWidth)."&bottom=".($sLat-$fWidth);
} }
$sOSMType = formatOSMType($aFeature['osm_type'], false); $sOSMType = formatOSMType($aFeature['osm_type'], false);
if ($sOSMType) if ($sOSMType)
{ {
return 'http://localhost:8111/import?url=http://www.openstreetmap.org/api/0.6/'.$sOSMType.'/'.$aFeature['osm_id'].'/full'; return 'http://localhost:8111/import?url=http://www.openstreetmap.org/api/0.6/'.$sOSMType.'/'.$aFeature['osm_id'].'/full';
// Should be better to load by object id - but this doesn't seem to zoom correctly // Should be better to load by object id - but this doesn't seem to zoom correctly
// return " <a href=\"http://localhost:8111/load_object?new_layer=true&objects=".strtolower($aFeature['osm_type']).$sOSMID."\" target=\"josm\">Remote Control (JOSM / Merkaartor)</a>"; // return " <a href=\"http://localhost:8111/load_object?new_layer=true&objects=".strtolower($aFeature['osm_type']).$sOSMID."\" target=\"josm\">Remote Control (JOSM / Merkaartor)</a>";
} }
return ''; return '';
} }
function potlach_edit_url($aFeature) function potlach_edit_url($aFeature)
{ {
$fWidth = 0.0002; $fWidth = 0.0002;
$sLat = $aFeature['error_y']; $sLat = $aFeature['error_y'];
$sLon = $aFeature['error_x']; $sLon = $aFeature['error_x'];
if (isset($sLat)) if (isset($sLat))
{ {
return "//www.openstreetmap.org/edit?editor=potlatch2&bbox=".($sLon-$fWidth).",".($sLat-$fWidth).",".($sLon+$fWidth).",".($sLat+$fWidth); return "//www.openstreetmap.org/edit?editor=potlatch2&bbox=".($sLon-$fWidth).",".($sLat-$fWidth).",".($sLon+$fWidth).",".($sLat+$fWidth);
} }
return ''; return '';
} }
?> ?>
<body id="details-page"> <body id="details-page">
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<h1><?php echo $aPointDetails['localname'] ?></h1> <h1><?php echo $aPointDetails['localname'] ?></h1>
<div class="locationdetails"> <div class="locationdetails">
<h2 class="bg-danger">This object has an invalid geometry.</h2> <h2 class="bg-danger">This object has an invalid geometry.</h2>
<div> <div>
Type: <span class="type"><?php echo $aPointDetails['class'].':'.$aPointDetails['type'];?></span> Type: <span class="type"><?php echo $aPointDetails['class'].':'.$aPointDetails['type'];?></span>
</div> </div>
<div> <div>
OSM: <span class="label"><?php echo osmLink($aPointDetails); ?><span> OSM: <span class="label"><?php echo osmLink($aPointDetails); ?><span>
</div> </div>
<h4>Error</h4> <h4>Error</h4>
<p> <p>
<?php echo $aPointDetails['errormessage']?$aPointDetails['errormessage']:'unknown'; ?> <?php echo $aPointDetails['errormessage']?$aPointDetails['errormessage']:'unknown'; ?>
</p> </p>
<?php echo osmMapUrl($aPointDetails); ?> <?php echo osmMapUrl($aPointDetails); ?>
<h4>Edit</h4> <h4>Edit</h4>
<ul> <ul>
<?php if (josm_edit_url($aPointDetails)) { ?> <?php if (josm_edit_url($aPointDetails)) { ?>
<li><a href="<?php echo josm_edit_url($aPointDetails); ?>" target="josm">Remote Control (JOSM / Merkaartor)</a></li> <li><a href="<?php echo josm_edit_url($aPointDetails); ?>" target="josm">Remote Control (JOSM / Merkaartor)</a></li>
<?php } ?> <?php } ?>
<?php if (potlach_edit_url($aPointDetails)) { ?> <?php if (potlach_edit_url($aPointDetails)) { ?>
<li><a href="<?php echo potlach_edit_url($aPointDetails); ?>" target="potlatch2">Potlatch 2</a></li> <li><a href="<?php echo potlach_edit_url($aPointDetails); ?>" target="potlatch2">Potlatch 2</a></li>
<?php } ?> <?php } ?>
</ul> </ul>
</div> </div>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<div id="map"></div> <div id="map"></div>
</div> </div>
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
var nominatim_result = { var nominatim_result = {
outlinestring: '<?php echo $aPointDetails['outlinestring'];?>', outlinestring: '<?php echo $aPointDetails['outlinestring'];?>',
lon: <?php echo isset($aPointDetails['error_x']) ? $aPointDetails['error_x'] : 0; ?>, lon: <?php echo isset($aPointDetails['error_x']) ? $aPointDetails['error_x'] : 0; ?>,
lat: <?php echo isset($aPointDetails['error_y']) ? $aPointDetails['error_y'] : 0; ?> lat: <?php echo isset($aPointDetails['error_y']) ? $aPointDetails['error_y'] : 0; ?>
}; };
</script> </script>
<?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?>
</body> </body>
</html> </html>

View File

@ -1,258 +1,258 @@
<?php <?php
header("content-type: text/html; charset=UTF-8"); header("content-type: text/html; charset=UTF-8");
?> ?>
<?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?>
<link href="css/common.css" rel="stylesheet" type="text/css" /> <link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/details.css" rel="stylesheet" type="text/css" /> <link href="css/details.css" rel="stylesheet" type="text/css" />
</head> </head>
<?php <?php
function headline($sTitle) function headline($sTitle)
{ {
echo "<tr class='all-columns'><td colspan='6'><h2>".$sTitle."</h2></td></tr>\n"; echo "<tr class='all-columns'><td colspan='6'><h2>".$sTitle."</h2></td></tr>\n";
} }
function headline3($sTitle) function headline3($sTitle)
{ {
echo "<tr class='all-columns'><td colspan='6'><h3>".$sTitle."</h3></td></tr>\n"; echo "<tr class='all-columns'><td colspan='6'><h3>".$sTitle."</h3></td></tr>\n";
} }
function format_distance($fDistance) function format_distance($fDistance)
{ {
// $fDistance is in meters // $fDistance is in meters
if ($fDistance < 1) if ($fDistance < 1)
{ {
return '0'; return '0';
} }
elseif ($fDistance < 1000) elseif ($fDistance < 1000)
{ {
return'<abbr class="distance" title="'.$fDistance.'">~'.(round($fDistance,0)).' m</abbr>'; return'<abbr class="distance" title="'.$fDistance.'">~'.(round($fDistance,0)).' m</abbr>';
} }
else else
{ {
return'<abbr class="distance" title="'.$fDistance.'">~'.(round($fDistance/1000,1)).' km</abbr>'; return'<abbr class="distance" title="'.$fDistance.'">~'.(round($fDistance/1000,1)).' km</abbr>';
} }
} }
function kv($sKey,$sValue) function kv($sKey,$sValue)
{ {
echo ' <tr><td>' . $sKey . '</td><td>'.$sValue.'</td></tr>'. "\n"; echo ' <tr><td>' . $sKey . '</td><td>'.$sValue.'</td></tr>'. "\n";
} }
function hash_to_subtable($aAssociatedList) function hash_to_subtable($aAssociatedList)
{ {
$sHTML = ''; $sHTML = '';
foreach($aAssociatedList as $sKey => $sValue) foreach($aAssociatedList as $sKey => $sValue)
{ {
$sHTML = $sHTML.' <div class="line"><span class="name">'.$sValue.'</span> ('.$sKey.')</div>'."\n"; $sHTML = $sHTML.' <div class="line"><span class="name">'.$sValue.'</span> ('.$sKey.')</div>'."\n";
} }
return $sHTML; return $sHTML;
} }
function map_icon($sIcon) function map_icon($sIcon)
{ {
if ($sIcon){ if ($sIcon){
echo '<img id="mapicon" src="'.CONST_Website_BaseURL.'images/mapicons/'.$sIcon.'.n.32.png'.'" alt="'.$sIcon.'" />'; echo '<img id="mapicon" src="'.CONST_Website_BaseURL.'images/mapicons/'.$sIcon.'.n.32.png'.'" alt="'.$sIcon.'" />';
} }
} }
function _one_row($aAddressLine){ function _one_row($aAddressLine){
$bNotUsed = (isset($aAddressLine['isaddress']) && $aAddressLine['isaddress'] == 'f'); $bNotUsed = (isset($aAddressLine['isaddress']) && $aAddressLine['isaddress'] == 'f');
echo '<tr class="' . ($bNotUsed?'notused':'') . '">'."\n"; echo '<tr class="' . ($bNotUsed?'notused':'') . '">'."\n";
echo ' <td class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>')."</td>\n"; echo ' <td class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>')."</td>\n";
echo ' <td>' . $aAddressLine['class'].':'.$aAddressLine['type'] . "</td>\n"; echo ' <td>' . $aAddressLine['class'].':'.$aAddressLine['type'] . "</td>\n";
echo ' <td>' . osmLink($aAddressLine) . "</td>\n"; echo ' <td>' . osmLink($aAddressLine) . "</td>\n";
echo ' <td>' . (isset($aAddressLine['admin_level']) ? $aAddressLine['admin_level'] : '') . "</td>\n"; echo ' <td>' . (isset($aAddressLine['admin_level']) ? $aAddressLine['admin_level'] : '') . "</td>\n";
echo ' <td>' . format_distance($aAddressLine['distance'])."</td>\n"; echo ' <td>' . format_distance($aAddressLine['distance'])."</td>\n";
echo ' <td>' . detailsLink($aAddressLine,'details &gt;') . "</td>\n"; echo ' <td>' . detailsLink($aAddressLine,'details &gt;') . "</td>\n";
echo "</tr>\n"; echo "</tr>\n";
} }
function _one_keyword_row($keyword_token,$word_id){ function _one_keyword_row($keyword_token,$word_id){
echo "<tr>\n"; echo "<tr>\n";
echo '<td>'; echo '<td>';
// mark partial tokens (those starting with a space) with a star for readability // mark partial tokens (those starting with a space) with a star for readability
echo ($keyword_token[0]==' '?'*':''); echo ($keyword_token[0]==' '?'*':'');
echo $keyword_token; echo $keyword_token;
if (isset($word_id)) if (isset($word_id))
{ {
echo '</td><td>word id: '.$word_id; echo '</td><td>word id: '.$word_id;
} }
echo "</td></tr>\n"; echo "</td></tr>\n";
} }
?> ?>
<body id="details-page"> <body id="details-page">
<?php include(CONST_BasePath.'/lib/template/includes/html-top-navigation.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-top-navigation.php'); ?>
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-sm-10"> <div class="col-sm-10">
<h1><?php echo $aPointDetails['localname'] ?></h1> <h1><?php echo $aPointDetails['localname'] ?></h1>
</div> </div>
<div class="col-sm-2 text-right"> <div class="col-sm-2 text-right">
<?php map_icon($aPointDetails['icon']) ?> <?php map_icon($aPointDetails['icon']) ?>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<table id="locationdetails" class="table table-striped"> <table id="locationdetails" class="table table-striped">
<?php <?php
kv('Name' , hash_to_subtable($aPointDetails['aNames']) ); kv('Name' , hash_to_subtable($aPointDetails['aNames']) );
kv('Type' , $aPointDetails['class'].':'.$aPointDetails['type'] ); kv('Type' , $aPointDetails['class'].':'.$aPointDetails['type'] );
kv('Last Updated' , $aPointDetails['indexed_date'] ); kv('Last Updated' , $aPointDetails['indexed_date'] );
kv('Admin Level' , $aPointDetails['admin_level'] ); kv('Admin Level' , $aPointDetails['admin_level'] );
kv('Rank' , $aPointDetails['rank_search_label'] ); kv('Rank' , $aPointDetails['rank_search_label'] );
if ($aPointDetails['calculated_importance']) { if ($aPointDetails['calculated_importance']) {
kv('Importance' , $aPointDetails['calculated_importance'].($aPointDetails['importance']?'':' (estimated)') ); kv('Importance' , $aPointDetails['calculated_importance'].($aPointDetails['importance']?'':' (estimated)') );
} }
kv('Coverage' , ($aPointDetails['isarea']=='t'?'Polygon':'Point') ); kv('Coverage' , ($aPointDetails['isarea']=='t'?'Polygon':'Point') );
kv('Centre Point' , $aPointDetails['lat'].','.$aPointDetails['lon'] ); kv('Centre Point' , $aPointDetails['lat'].','.$aPointDetails['lon'] );
kv('OSM' , osmLink($aPointDetails) ); kv('OSM' , osmLink($aPointDetails) );
if ($aPointDetails['wikipedia']) if ($aPointDetails['wikipedia'])
{ {
kv('Wikipedia Calculated' , wikipediaLink($aPointDetails) ); kv('Wikipedia Calculated' , wikipediaLink($aPointDetails) );
} }
kv('Extra Tags' , hash_to_subtable($aPointDetails['aExtraTags']) ); kv('Extra Tags' , hash_to_subtable($aPointDetails['aExtraTags']) );
?> ?>
</table> </table>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<div id="map"></div> <div id="map"></div>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<h2>Address</h2> <h2>Address</h2>
<table id="address" class="table table-striped table-responsive"> <table id="address" class="table table-striped table-responsive">
<thead> <thead>
<tr> <tr>
<td>Local name</td> <td>Local name</td>
<td>Type</td> <td>Type</td>
<td>OSM</td> <td>OSM</td>
<td>Admin level</td> <td>Admin level</td>
<td>Distance</td> <td>Distance</td>
<td></td> <td></td>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php <?php
foreach($aAddressLines as $aAddressLine) foreach($aAddressLines as $aAddressLine)
{ {
_one_row($aAddressLine); _one_row($aAddressLine);
} }
?> ?>
<?php <?php
if ($aLinkedLines) if ($aLinkedLines)
{ {
headline('Linked Places'); headline('Linked Places');
foreach($aLinkedLines as $aAddressLine) foreach($aLinkedLines as $aAddressLine)
{ {
_one_row($aAddressLine); _one_row($aAddressLine);
} }
} }
if ($aPlaceSearchNameKeywords) if ($aPlaceSearchNameKeywords)
{ {
headline('Name Keywords'); headline('Name Keywords');
foreach($aPlaceSearchNameKeywords as $aRow) foreach($aPlaceSearchNameKeywords as $aRow)
{ {
_one_keyword_row($aRow['word_token'], $aRow['word_id']); _one_keyword_row($aRow['word_token'], $aRow['word_id']);
} }
} }
if ($aPlaceSearchAddressKeywords) if ($aPlaceSearchAddressKeywords)
{ {
headline('Address Keywords'); headline('Address Keywords');
foreach($aPlaceSearchAddressKeywords as $aRow) foreach($aPlaceSearchAddressKeywords as $aRow)
{ {
_one_keyword_row($aRow['word_token'], $aRow['word_id']); _one_keyword_row($aRow['word_token'], $aRow['word_id']);
} }
} }
if (sizeof($aParentOfLines)) if (sizeof($aParentOfLines))
{ {
headline('Parent Of'); headline('Parent Of');
$aGroupedAddressLines = array(); $aGroupedAddressLines = array();
foreach($aParentOfLines as $aAddressLine) foreach($aParentOfLines as $aAddressLine)
{ {
if ($aAddressLine['type'] == 'yes') $sType = $aAddressLine['class']; if ($aAddressLine['type'] == 'yes') $sType = $aAddressLine['class'];
else $sType = $aAddressLine['type']; else $sType = $aAddressLine['type'];
if (!isset($aGroupedAddressLines[$sType])) if (!isset($aGroupedAddressLines[$sType]))
$aGroupedAddressLines[$sType] = array(); $aGroupedAddressLines[$sType] = array();
$aGroupedAddressLines[$sType][] = $aAddressLine; $aGroupedAddressLines[$sType][] = $aAddressLine;
} }
foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines) foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines)
{ {
$sGroupHeading = ucwords($sGroupHeading); $sGroupHeading = ucwords($sGroupHeading);
headline3($sGroupHeading); headline3($sGroupHeading);
foreach($aParentOfLines as $aAddressLine) foreach($aParentOfLines as $aAddressLine)
{ {
_one_row($aAddressLine); _one_row($aAddressLine);
} }
} }
if (sizeof($aParentOfLines) >= 500) { if (sizeof($aParentOfLines) >= 500) {
echo '<p>There are more child objects which are not shown.</p>'; echo '<p>There are more child objects which are not shown.</p>';
} }
} }
echo "</table>\n"; echo "</table>\n";
?> ?>
</div> </div>
</div> </div>
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
<?php <?php
$aNominatimMapInit = array( $aNominatimMapInit = array(
'tile_url' => $sTileURL, 'tile_url' => $sTileURL,
'tile_attribution' => $sTileAttribution 'tile_attribution' => $sTileAttribution
); );
echo 'var nominatim_map_init = ' . json_encode($aNominatimMapInit, JSON_PRETTY_PRINT) . ';'; echo 'var nominatim_map_init = ' . json_encode($aNominatimMapInit, JSON_PRETTY_PRINT) . ';';
$aPlace = array( $aPlace = array(
'outlinestring' => $aPointDetails['outlinestring'], 'outlinestring' => $aPointDetails['outlinestring'],
'lon' => $aPointDetails['lon'], 'lon' => $aPointDetails['lon'],
'lat' => $aPointDetails['lat'], 'lat' => $aPointDetails['lat'],
); );
echo 'var nominatim_result = ' . json_encode($aPlace, JSON_PRETTY_PRINT) . ';'; echo 'var nominatim_result = ' . json_encode($aPlace, JSON_PRETTY_PRINT) . ';';
?> ?>
</script> </script>
<?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?>
</body> </body>
</html> </html>

View File

@ -1,10 +1,10 @@
<footer> <footer>
<p class="disclaimer"> <p class="disclaimer">
Addresses and postcodes are approximate Addresses and postcodes are approximate
</p> </p>
<p class="copyright"> <p class="copyright">
&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors &copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors
</p> </p>
</footer> </footer>
<script src="js/jquery.min.js"></script> <script src="js/jquery.min.js"></script>

View File

@ -1,11 +1,11 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<title>OpenStreetMap Nominatim: Search</title> <title>OpenStreetMap Nominatim: Search</title>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<base href="<?php echo CONST_Website_BaseURL;?>" /> <base href="<?php echo CONST_Website_BaseURL;?>" />
<link href="nominatim.xml" rel="search" title="Nominatim Search" type="application/opensearchdescription+xml" /> <link href="nominatim.xml" rel="search" title="Nominatim Search" type="application/opensearchdescription+xml" />
<link href="css/leaflet.css" rel="stylesheet" /> <link href="css/leaflet.css" rel="stylesheet" />
<link href="css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="css/bootstrap.min.css" rel="stylesheet" /> <link href="css/bootstrap.min.css" rel="stylesheet" />

View File

@ -1,49 +1,49 @@
<header class="container-fluid"> <header class="container-fluid">
<div class="row"> <div class="row">
<div class="col-xs-4"> <div class="col-xs-4">
<div class="brand"> <div class="brand">
<a href="<?php echo CONST_Website_BaseURL;?>"> <a href="<?php echo CONST_Website_BaseURL;?>">
<img alt="logo" src="images/osm_logo.120px.png" width="30" height="30"/> <img alt="logo" src="images/osm_logo.120px.png" width="30" height="30"/>
<h1>Nominatim</h1> <h1>Nominatim</h1>
</a> </a>
</div> </div>
</div> </div>
<div id="last-updated" class="col-xs-4 text-center"> <div id="last-updated" class="col-xs-4 text-center">
<?php if (isset($sDataDate)){ ?> <?php if (isset($sDataDate)){ ?>
Data last updated: Data last updated:
<br> <br>
<?php echo $sDataDate; ?> <?php echo $sDataDate; ?>
<?php } ?> <?php } ?>
</div> </div>
<div class="col-xs-4 text-right"> <div class="col-xs-4 text-right">
<div class="btn-group"> <div class="btn-group">
<button class="dropdown-toggle btn btn-sm btn-default" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <button class="dropdown-toggle btn btn-sm btn-default" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
About &amp; Help <span class="caret"></span> About &amp; Help <span class="caret"></span>
</button> </button>
<ul class="dropdown-menu dropdown-menu-right"> <ul class="dropdown-menu dropdown-menu-right">
<li><a href="http://wiki.openstreetmap.org/wiki/Nominatim" target="_blank">Documentation</a></li> <li><a href="http://wiki.openstreetmap.org/wiki/Nominatim" target="_blank">Documentation</a></li>
<li><a href="http://wiki.openstreetmap.org/wiki/Nominatim/FAQ" target="_blank">FAQ</a></li> <li><a href="http://wiki.openstreetmap.org/wiki/Nominatim/FAQ" target="_blank">FAQ</a></li>
<li role="separator" class="divider"></li> <li role="separator" class="divider"></li>
<li><a href="#" class="" data-toggle="modal" data-target="#report-modal">Report problem with results</a></li> <li><a href="#" class="" data-toggle="modal" data-target="#report-modal">Report problem with results</a></li>
</ul> </ul>
</div> </div>
</div> </div>
</div> </div>
</header> </header>
<div class="modal fade" id="report-modal"> <div class="modal fade" id="report-modal">
<div class="modal-dialog"> <div class="modal-dialog">
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Report a problem</h4> <h4 class="modal-title">Report a problem</h4>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<?php include(CONST_BasePath.'/lib/template/includes/report-errors.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/report-errors.php'); ?>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button> <button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,24 +1,24 @@
<p> <p>
Before reporting problems please read the <a target="_blank" href="http://wiki.openstreetmap.org/wiki/Nominatim">user documentation</a> Before reporting problems please read the <a target="_blank" href="http://wiki.openstreetmap.org/wiki/Nominatim">user documentation</a>
and and
<a target="_blank" href="http://wiki.openstreetmap.org/wiki/Nominatim/FAQ">FAQ</a>. <a target="_blank" href="http://wiki.openstreetmap.org/wiki/Nominatim/FAQ">FAQ</a>.
If your problem relates to the address of a particular search result please use the 'details' link If your problem relates to the address of a particular search result please use the 'details' link
to check how the address was generated before reporting a problem. to check how the address was generated before reporting a problem.
</p> </p>
<p> <p>
Use <a target="_blank" href="https://github.com/twain47/nominatim/issues">Nominatim issues on github</a> Use <a target="_blank" href="https://github.com/twain47/nominatim/issues">Nominatim issues on github</a>
to report problems. to report problems.
<!-- You can search for existing bug reports <!-- You can search for existing bug reports
<a href="http://trac.openstreetmap.org/query?status=new&amp;status=assigned&amp;status=reopened&amp;component=nominatim&amp;order=priority">here</a>.</p> <a href="http://trac.openstreetmap.org/query?status=new&amp;status=assigned&amp;status=reopened&amp;component=nominatim&amp;order=priority">here</a>.</p>
--> -->
</p> </p>
<p> <p>
Please ensure that you include a full description of the problem, including the search Please ensure that you include a full description of the problem, including the search
query that you used, the problem with the result and, if the problem relates to missing data, query that you used, the problem with the result and, if the problem relates to missing data,
the osm type (node, way, relation) and id of the item that is missing. the osm type (node, way, relation) and id of the item that is missing.
</p> </p>
<p> <p>
Problems that contain enough detail are likely to get looked at before ones that require Problems that contain enough detail are likely to get looked at before ones that require
significant research. significant research.
</p> </p>

View File

@ -1,88 +1,88 @@
<?php <?php
$aOutput = array(); $aOutput = array();
$aOutput['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright"; $aOutput['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright";
$aOutput['batch'] = array(); $aOutput['batch'] = array();
foreach($aBatchResults as $aSearchResults) foreach($aBatchResults as $aSearchResults)
{ {
if (!$aSearchResults) $aSearchResults = array(); if (!$aSearchResults) $aSearchResults = array();
$aFilteredPlaces = array(); $aFilteredPlaces = array();
foreach($aSearchResults as $iResNum => $aPointDetails) foreach($aSearchResults as $iResNum => $aPointDetails)
{ {
$aPlace = array( $aPlace = array(
'place_id'=>$aPointDetails['place_id'], 'place_id'=>$aPointDetails['place_id'],
); );
$sOSMType = formatOSMType($aPointDetails['osm_type']); $sOSMType = formatOSMType($aPointDetails['osm_type']);
if ($sOSMType) if ($sOSMType)
{ {
$aPlace['osm_type'] = $sOSMType; $aPlace['osm_type'] = $sOSMType;
$aPlace['osm_id'] = $aPointDetails['osm_id']; $aPlace['osm_id'] = $aPointDetails['osm_id'];
} }
if (isset($aPointDetails['aBoundingBox'])) if (isset($aPointDetails['aBoundingBox']))
{ {
$aPlace['boundingbox'] = array( $aPlace['boundingbox'] = array(
$aPointDetails['aBoundingBox'][0], $aPointDetails['aBoundingBox'][0],
$aPointDetails['aBoundingBox'][1], $aPointDetails['aBoundingBox'][1],
$aPointDetails['aBoundingBox'][2], $aPointDetails['aBoundingBox'][2],
$aPointDetails['aBoundingBox'][3]); $aPointDetails['aBoundingBox'][3]);
if (isset($aPointDetails['aPolyPoints']) && $bShowPolygons) if (isset($aPointDetails['aPolyPoints']) && $bShowPolygons)
{ {
$aPlace['polygonpoints'] = $aPointDetails['aPolyPoints']; $aPlace['polygonpoints'] = $aPointDetails['aPolyPoints'];
} }
} }
if (isset($aPointDetails['zoom'])) if (isset($aPointDetails['zoom']))
{ {
$aPlace['zoom'] = $aPointDetails['zoom']; $aPlace['zoom'] = $aPointDetails['zoom'];
} }
$aPlace['lat'] = $aPointDetails['lat']; $aPlace['lat'] = $aPointDetails['lat'];
$aPlace['lon'] = $aPointDetails['lon']; $aPlace['lon'] = $aPointDetails['lon'];
$aPlace['display_name'] = $aPointDetails['name']; $aPlace['display_name'] = $aPointDetails['name'];
$aPlace['place_rank'] = $aPointDetails['rank_search']; $aPlace['place_rank'] = $aPointDetails['rank_search'];
$aPlace['category'] = $aPointDetails['class']; $aPlace['category'] = $aPointDetails['class'];
$aPlace['type'] = $aPointDetails['type']; $aPlace['type'] = $aPointDetails['type'];
$aPlace['importance'] = $aPointDetails['importance']; $aPlace['importance'] = $aPointDetails['importance'];
if (isset($aPointDetails['icon'])) if (isset($aPointDetails['icon']))
{ {
$aPlace['icon'] = $aPointDetails['icon']; $aPlace['icon'] = $aPointDetails['icon'];
} }
if (isset($aPointDetails['address']) && sizeof($aPointDetails['address'])>0) if (isset($aPointDetails['address']) && sizeof($aPointDetails['address'])>0)
{ {
$aPlace['address'] = $aPointDetails['address']; $aPlace['address'] = $aPointDetails['address'];
} }
if (isset($aPointDetails['asgeojson'])) if (isset($aPointDetails['asgeojson']))
{ {
$aPlace['geojson'] = json_decode($aPointDetails['asgeojson']); $aPlace['geojson'] = json_decode($aPointDetails['asgeojson']);
} }
if (isset($aPointDetails['assvg'])) if (isset($aPointDetails['assvg']))
{ {
$aPlace['svg'] = $aPointDetails['assvg']; $aPlace['svg'] = $aPointDetails['assvg'];
} }
if (isset($aPointDetails['astext'])) if (isset($aPointDetails['astext']))
{ {
$aPlace['geotext'] = $aPointDetails['astext']; $aPlace['geotext'] = $aPointDetails['astext'];
} }
if (isset($aPointDetails['askml'])) if (isset($aPointDetails['askml']))
{ {
$aPlace['geokml'] = $aPointDetails['askml']; $aPlace['geokml'] = $aPointDetails['askml'];
} }
$aFilteredPlaces[] = $aPlace; $aFilteredPlaces[] = $aPlace;
} }
$aOutput['batch'][] = $aFilteredPlaces; $aOutput['batch'][] = $aFilteredPlaces;
} }
javascript_renderData($aOutput, array('geojson')); javascript_renderData($aOutput, array('geojson'));

View File

@ -1,94 +1,94 @@
<?php <?php
header("content-type: text/html; charset=UTF-8"); header("content-type: text/html; charset=UTF-8");
?> ?>
<?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-header.php'); ?>
<link href="css/common.css" rel="stylesheet" type="text/css" /> <link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/search.css" rel="stylesheet" type="text/css" /> <link href="css/search.css" rel="stylesheet" type="text/css" />
</head> </head>
<body id="search-page"> <body id="search-page">
<?php include(CONST_BasePath.'/lib/template/includes/html-top-navigation.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-top-navigation.php'); ?>
<form class="form-inline" role="search" accept-charset="UTF-8" action="<?php echo CONST_Website_BaseURL; ?>search.php"> <form class="form-inline" role="search" accept-charset="UTF-8" action="<?php echo CONST_Website_BaseURL; ?>search.php">
<div class="form-group"> <div class="form-group">
<input id="q" name="q" type="text" class="form-control input-sm" placeholder="Search" value="<?php echo htmlspecialchars($sQuery); ?>" > <input id="q" name="q" type="text" class="form-control input-sm" placeholder="Search" value="<?php echo htmlspecialchars($sQuery); ?>" >
</div> </div>
<div class="form-group search-button-group"> <div class="form-group search-button-group">
<button type="submit" class="btn btn-primary btn-sm">Search</button> <button type="submit" class="btn btn-primary btn-sm">Search</button>
<?php if (CONST_Search_AreaPolygons) { ?> <?php if (CONST_Search_AreaPolygons) { ?>
<!-- <input type="checkbox" value="1" name="polygon" <?php if ($bAsText) echo "checked='checked'"; ?>/> Highlight --> <!-- <input type="checkbox" value="1" name="polygon" <?php if ($bAsText) echo "checked='checked'"; ?>/> Highlight -->
<input type="hidden" value="1" name="polygon" /> <input type="hidden" value="1" name="polygon" />
<?php } ?> <?php } ?>
<input type="hidden" name="viewbox" value="<?php echo $sViewBox; ?>" /> <input type="hidden" name="viewbox" value="<?php echo $sViewBox; ?>" />
<div class="checkbox-inline"> <div class="checkbox-inline">
<label> <label>
<input type="checkbox" id="use_viewbox" <?php if ($sViewBox) echo "checked='checked'"; ?>> <input type="checkbox" id="use_viewbox" <?php if ($sViewBox) echo "checked='checked'"; ?>>
apply viewbox apply viewbox
</label> </label>
</div> </div>
</div> </div>
<div class="search-type-link"> <div class="search-type-link">
<a href="<?php echo CONST_Website_BaseURL; ?>reverse.php?format=html">reverse search</a> <a href="<?php echo CONST_Website_BaseURL; ?>reverse.php?format=html">reverse search</a>
</div> </div>
</form> </form>
<div id="content"> <div id="content">
<?php if ($sQuery) { ?> <?php if ($sQuery) { ?>
<div id="searchresults" class="sidebar"> <div id="searchresults" class="sidebar">
<?php <?php
$i = 0; $i = 0;
foreach($aSearchResults as $iResNum => $aResult) foreach($aSearchResults as $iResNum => $aResult)
{ {
echo '<div class="result" data-position=' . $i . '>'; echo '<div class="result" data-position=' . $i . '>';
echo (isset($aResult['icon'])?'<img alt="icon" src="'.$aResult['icon'].'"/>':''); echo (isset($aResult['icon'])?'<img alt="icon" src="'.$aResult['icon'].'"/>':'');
echo ' <span class="name">'.htmlspecialchars($aResult['name']).'</span>'; echo ' <span class="name">'.htmlspecialchars($aResult['name']).'</span>';
// echo ' <span class="latlon">'.round($aResult['lat'],3).','.round($aResult['lon'],3).'</span>'; // echo ' <span class="latlon">'.round($aResult['lat'],3).','.round($aResult['lon'],3).'</span>';
// echo ' <span class="place_id">'.$aResult['place_id'].'</span>'; // echo ' <span class="place_id">'.$aResult['place_id'].'</span>';
if (isset($aResult['label'])) if (isset($aResult['label']))
echo ' <span class="type">('.$aResult['label'].')</span>'; echo ' <span class="type">('.$aResult['label'].')</span>';
else if ($aResult['type'] == 'yes') else if ($aResult['type'] == 'yes')
echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['class'])).')</span>'; echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['class'])).')</span>';
else else
echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['type'])).')</span>'; echo ' <span class="type">('.ucwords(str_replace('_',' ',$aResult['type'])).')</span>';
echo ' <a class="btn btn-default btn-xs details" href="details.php?place_id='.$aResult['place_id'].'">details</a>'; echo ' <a class="btn btn-default btn-xs details" href="details.php?place_id='.$aResult['place_id'].'">details</a>';
echo '</div>'; echo '</div>';
$i = $i+1; $i = $i+1;
} }
if (sizeof($aSearchResults) && $sMoreURL) if (sizeof($aSearchResults) && $sMoreURL)
{ {
echo '<div class="more"><a class="btn btn-primary" href="'.htmlentities($sMoreURL).'">Search for more results</a></div>'; echo '<div class="more"><a class="btn btn-primary" href="'.htmlentities($sMoreURL).'">Search for more results</a></div>';
} }
else else
{ {
echo '<div class="noresults">No search results found</div>'; echo '<div class="noresults">No search results found</div>';
} }
?> ?>
</div> </div>
<?php } else { ?> <?php } else { ?>
<div id="intro" class="sidebar"> <div id="intro" class="sidebar">
<?php include(CONST_BasePath.'/lib/template/includes/introduction.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/introduction.php'); ?>
</div> </div>
<?php } ?> <?php } ?>
<div id="map-wrapper"> <div id="map-wrapper">
<div id="map-position"> <div id="map-position">
<div id="map-position-inner"></div> <div id="map-position-inner"></div>
<div id="map-position-close"><a href="#">hide</a></div> <div id="map-position-close"><a href="#">hide</a></div>
</div> </div>
<div id="map"></div> <div id="map"></div>
</div> </div>
</div> <!-- /content --> </div> <!-- /content -->
@ -96,22 +96,22 @@
<script type="text/javascript"> <script type="text/javascript">
<?php <?php
$aNominatimMapInit = array( $aNominatimMapInit = array(
'zoom' => CONST_Default_Zoom, 'zoom' => CONST_Default_Zoom,
'lat' => CONST_Default_Lat, 'lat' => CONST_Default_Lat,
'lon' => CONST_Default_Lon, 'lon' => CONST_Default_Lon,
'tile_url' => CONST_Map_Tile_URL, 'tile_url' => CONST_Map_Tile_URL,
'tile_attribution' => CONST_Map_Tile_Attribution 'tile_attribution' => CONST_Map_Tile_Attribution
); );
echo 'var nominatim_map_init = ' . json_encode($aNominatimMapInit, JSON_PRETTY_PRINT) . ';'; echo 'var nominatim_map_init = ' . json_encode($aNominatimMapInit, JSON_PRETTY_PRINT) . ';';
echo 'var nominatim_results = ' . json_encode($aSearchResults, JSON_PRETTY_PRINT) . ';'; echo 'var nominatim_results = ' . json_encode($aSearchResults, JSON_PRETTY_PRINT) . ';';
?> ?>
</script> </script>
<?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?> <?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?>
</body> </body>
</html> </html>

View File

@ -1,79 +1,79 @@
<?php <?php
header("content-type: application/json; charset=UTF-8"); header("content-type: application/json; charset=UTF-8");
$aFilteredPlaces = array(); $aFilteredPlaces = array();
foreach($aSearchResults as $iResNum => $aPointDetails) foreach($aSearchResults as $iResNum => $aPointDetails)
{ {
$aPlace = array( $aPlace = array(
'place_id'=>$aPointDetails['place_id'], 'place_id'=>$aPointDetails['place_id'],
'licence'=>"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright", 'licence'=>"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
); );
$sOSMType = formatOSMType($aPointDetails['osm_type']); $sOSMType = formatOSMType($aPointDetails['osm_type']);
if ($sOSMType) if ($sOSMType)
{ {
$aPlace['osm_type'] = $sOSMType; $aPlace['osm_type'] = $sOSMType;
$aPlace['osm_id'] = $aPointDetails['osm_id']; $aPlace['osm_id'] = $aPointDetails['osm_id'];
} }
if (isset($aPointDetails['aBoundingBox'])) if (isset($aPointDetails['aBoundingBox']))
{ {
$aPlace['boundingbox'] = $aPointDetails['aBoundingBox']; $aPlace['boundingbox'] = $aPointDetails['aBoundingBox'];
if (isset($aPointDetails['aPolyPoints']) && $bShowPolygons) if (isset($aPointDetails['aPolyPoints']) && $bShowPolygons)
{ {
$aPlace['polygonpoints'] = $aPointDetails['aPolyPoints']; $aPlace['polygonpoints'] = $aPointDetails['aPolyPoints'];
} }
} }
if (isset($aPointDetails['zoom'])) if (isset($aPointDetails['zoom']))
{ {
$aPlace['zoom'] = $aPointDetails['zoom']; $aPlace['zoom'] = $aPointDetails['zoom'];
} }
$aPlace['lat'] = $aPointDetails['lat']; $aPlace['lat'] = $aPointDetails['lat'];
$aPlace['lon'] = $aPointDetails['lon']; $aPlace['lon'] = $aPointDetails['lon'];
$aPlace['display_name'] = $aPointDetails['name']; $aPlace['display_name'] = $aPointDetails['name'];
$aPlace['class'] = $aPointDetails['class']; $aPlace['class'] = $aPointDetails['class'];
$aPlace['type'] = $aPointDetails['type']; $aPlace['type'] = $aPointDetails['type'];
$aPlace['importance'] = $aPointDetails['importance']; $aPlace['importance'] = $aPointDetails['importance'];
if (isset($aPointDetails['icon']) && $aPointDetails['icon']) if (isset($aPointDetails['icon']) && $aPointDetails['icon'])
{ {
$aPlace['icon'] = $aPointDetails['icon']; $aPlace['icon'] = $aPointDetails['icon'];
} }
if (isset($aPointDetails['address'])) if (isset($aPointDetails['address']))
{ {
$aPlace['address'] = $aPointDetails['address']; $aPlace['address'] = $aPointDetails['address'];
} }
if (isset($aPointDetails['asgeojson'])) if (isset($aPointDetails['asgeojson']))
{ {
$aPlace['geojson'] = json_decode($aPointDetails['asgeojson']); $aPlace['geojson'] = json_decode($aPointDetails['asgeojson']);
} }
if (isset($aPointDetails['assvg'])) if (isset($aPointDetails['assvg']))
{ {
$aPlace['svg'] = $aPointDetails['assvg']; $aPlace['svg'] = $aPointDetails['assvg'];
} }
if (isset($aPointDetails['astext'])) if (isset($aPointDetails['astext']))
{ {
$aPlace['geotext'] = $aPointDetails['astext']; $aPlace['geotext'] = $aPointDetails['astext'];
} }
if (isset($aPointDetails['askml'])) if (isset($aPointDetails['askml']))
{ {
$aPlace['geokml'] = $aPointDetails['askml']; $aPlace['geokml'] = $aPointDetails['askml'];
} }
if (isset($aPointDetails['sExtraTags'])) $aPlace['extratags'] = $aPointDetails['sExtraTags']; if (isset($aPointDetails['sExtraTags'])) $aPlace['extratags'] = $aPointDetails['sExtraTags'];
if (isset($aPointDetails['sNameDetails'])) $aPlace['namedetails'] = $aPointDetails['sNameDetails']; if (isset($aPointDetails['sNameDetails'])) $aPlace['namedetails'] = $aPointDetails['sNameDetails'];
$aFilteredPlaces[] = $aPlace; $aFilteredPlaces[] = $aPlace;
} }
javascript_renderData($aFilteredPlaces); javascript_renderData($aFilteredPlaces);

View File

@ -1,78 +1,79 @@
<?php <?php
$aFilteredPlaces = array();
foreach($aSearchResults as $iResNum => $aPointDetails)
{
$aPlace = array(
'place_id'=>$aPointDetails['place_id'],
'licence'=>"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
);
$sOSMType = formatOSMType($aPointDetails['osm_type']); $aFilteredPlaces = array();
if ($sOSMType) foreach($aSearchResults as $iResNum => $aPointDetails)
{ {
$aPlace['osm_type'] = $sOSMType; $aPlace = array(
$aPlace['osm_id'] = $aPointDetails['osm_id']; 'place_id'=>$aPointDetails['place_id'],
} 'licence'=>"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
);
if (isset($aPointDetails['aBoundingBox'])) $sOSMType = formatOSMType($aPointDetails['osm_type']);
{ if ($sOSMType)
$aPlace['boundingbox'] = $aPointDetails['aBoundingBox']; {
$aPlace['osm_type'] = $sOSMType;
$aPlace['osm_id'] = $aPointDetails['osm_id'];
}
if (isset($aPointDetails['aPolyPoints']) && $bShowPolygons) if (isset($aPointDetails['aBoundingBox']))
{ {
$aPlace['polygonpoints'] = $aPointDetails['aPolyPoints']; $aPlace['boundingbox'] = $aPointDetails['aBoundingBox'];
}
}
if (isset($aPointDetails['zoom'])) if (isset($aPointDetails['aPolyPoints']) && $bShowPolygons)
{ {
$aPlace['zoom'] = $aPointDetails['zoom']; $aPlace['polygonpoints'] = $aPointDetails['aPolyPoints'];
} }
}
$aPlace['lat'] = $aPointDetails['lat']; if (isset($aPointDetails['zoom']))
$aPlace['lon'] = $aPointDetails['lon']; {
$aPlace['display_name'] = $aPointDetails['name']; $aPlace['zoom'] = $aPointDetails['zoom'];
$aPlace['place_rank'] = $aPointDetails['rank_search']; }
$aPlace['category'] = $aPointDetails['class']; $aPlace['lat'] = $aPointDetails['lat'];
$aPlace['type'] = $aPointDetails['type']; $aPlace['lon'] = $aPointDetails['lon'];
$aPlace['display_name'] = $aPointDetails['name'];
$aPlace['place_rank'] = $aPointDetails['rank_search'];
$aPlace['importance'] = $aPointDetails['importance']; $aPlace['category'] = $aPointDetails['class'];
$aPlace['type'] = $aPointDetails['type'];
if (isset($aPointDetails['icon'])) $aPlace['importance'] = $aPointDetails['importance'];
{
$aPlace['icon'] = $aPointDetails['icon'];
}
if (isset($aPointDetails['address']) && sizeof($aPointDetails['address'])>0) if (isset($aPointDetails['icon']))
{ {
$aPlace['address'] = $aPointDetails['address']; $aPlace['icon'] = $aPointDetails['icon'];
} }
if (isset($aPointDetails['asgeojson'])) if (isset($aPointDetails['address']) && sizeof($aPointDetails['address'])>0)
{ {
$aPlace['geojson'] = json_decode($aPointDetails['asgeojson']); $aPlace['address'] = $aPointDetails['address'];
} }
if (isset($aPointDetails['assvg'])) if (isset($aPointDetails['asgeojson']))
{ {
$aPlace['svg'] = $aPointDetails['assvg']; $aPlace['geojson'] = json_decode($aPointDetails['asgeojson']);
} }
if (isset($aPointDetails['astext'])) if (isset($aPointDetails['assvg']))
{ {
$aPlace['geotext'] = $aPointDetails['astext']; $aPlace['svg'] = $aPointDetails['assvg'];
} }
if (isset($aPointDetails['askml'])) if (isset($aPointDetails['astext']))
{ {
$aPlace['geokml'] = $aPointDetails['askml']; $aPlace['geotext'] = $aPointDetails['astext'];
} }
if (isset($aPointDetails['sExtraTags'])) $aPlace['extratags'] = $aPointDetails['sExtraTags']; if (isset($aPointDetails['askml']))
if (isset($aPointDetails['sNameDetails'])) $aPlace['namedetails'] = $aPointDetails['sNameDetails']; {
$aPlace['geokml'] = $aPointDetails['askml'];
}
$aFilteredPlaces[] = $aPlace; if (isset($aPointDetails['sExtraTags'])) $aPlace['extratags'] = $aPointDetails['sExtraTags'];
} if (isset($aPointDetails['sNameDetails'])) $aPlace['namedetails'] = $aPointDetails['sNameDetails'];
javascript_renderData($aFilteredPlaces); $aFilteredPlaces[] = $aPlace;
}
javascript_renderData($aFilteredPlaces);

View File

@ -1,161 +1,161 @@
<?php <?php
header("content-type: text/xml; charset=UTF-8"); header("content-type: text/xml; charset=UTF-8");
echo "<"; echo "<";
echo "?xml version=\"1.0\" encoding=\"UTF-8\" ?"; echo "?xml version=\"1.0\" encoding=\"UTF-8\" ?";
echo ">\n"; echo ">\n";
echo "<"; echo "<";
echo (isset($sXmlRootTag)?$sXmlRootTag:'searchresults'); echo (isset($sXmlRootTag)?$sXmlRootTag:'searchresults');
echo " timestamp='".date(DATE_RFC822)."'"; echo " timestamp='".date(DATE_RFC822)."'";
echo " attribution='Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'"; echo " attribution='Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'";
echo " querystring='".htmlspecialchars($sQuery, ENT_QUOTES)."'"; echo " querystring='".htmlspecialchars($sQuery, ENT_QUOTES)."'";
if ($sViewBox) echo " viewbox='".htmlspecialchars($sViewBox, ENT_QUOTES)."'"; if ($sViewBox) echo " viewbox='".htmlspecialchars($sViewBox, ENT_QUOTES)."'";
echo " polygon='".($bShowPolygons?'true':'false')."'"; echo " polygon='".($bShowPolygons?'true':'false')."'";
if (sizeof($aExcludePlaceIDs)) if (sizeof($aExcludePlaceIDs))
{ {
echo " exclude_place_ids='".htmlspecialchars(join(',',$aExcludePlaceIDs))."'"; echo " exclude_place_ids='".htmlspecialchars(join(',',$aExcludePlaceIDs))."'";
} }
if ($sMoreURL) if ($sMoreURL)
{ {
echo " more_url='".htmlspecialchars($sMoreURL)."'"; echo " more_url='".htmlspecialchars($sMoreURL)."'";
} }
echo ">\n"; echo ">\n";
foreach($aSearchResults as $iResNum => $aResult) foreach($aSearchResults as $iResNum => $aResult)
{ {
echo "<place place_id='".$aResult['place_id']."'"; echo "<place place_id='".$aResult['place_id']."'";
$sOSMType = formatOSMType($aResult['osm_type']); $sOSMType = formatOSMType($aResult['osm_type']);
if ($sOSMType) if ($sOSMType)
{ {
echo " osm_type='$sOSMType'"; echo " osm_type='$sOSMType'";
echo " osm_id='".$aResult['osm_id']."'"; echo " osm_id='".$aResult['osm_id']."'";
} }
echo " place_rank='".$aResult['rank_search']."'"; echo " place_rank='".$aResult['rank_search']."'";
if (isset($aResult['aBoundingBox'])) if (isset($aResult['aBoundingBox']))
{ {
echo ' boundingbox="'; echo ' boundingbox="';
echo join(',',$aResult['aBoundingBox']); echo join(',',$aResult['aBoundingBox']);
echo '"'; echo '"';
if ($bShowPolygons && isset($aResult['aPolyPoints'])) if ($bShowPolygons && isset($aResult['aPolyPoints']))
{ {
echo ' polygonpoints=\''; echo ' polygonpoints=\'';
echo json_encode($aResult['aPolyPoints']); echo json_encode($aResult['aPolyPoints']);
echo '\''; echo '\'';
} }
} }
if (isset($aResult['asgeojson'])) if (isset($aResult['asgeojson']))
{ {
echo ' geojson=\''; echo ' geojson=\'';
echo $aResult['asgeojson']; echo $aResult['asgeojson'];
echo '\''; echo '\'';
} }
if (isset($aResult['assvg'])) if (isset($aResult['assvg']))
{ {
echo ' geosvg=\''; echo ' geosvg=\'';
echo $aResult['assvg']; echo $aResult['assvg'];
echo '\''; echo '\'';
} }
if (isset($aResult['astext'])) if (isset($aResult['astext']))
{ {
echo ' geotext=\''; echo ' geotext=\'';
echo $aResult['astext']; echo $aResult['astext'];
echo '\''; echo '\'';
} }
if (isset($aResult['zoom'])) if (isset($aResult['zoom']))
{ {
echo " zoom='".$aResult['zoom']."'"; echo " zoom='".$aResult['zoom']."'";
} }
echo " lat='".$aResult['lat']."'"; echo " lat='".$aResult['lat']."'";
echo " lon='".$aResult['lon']."'"; echo " lon='".$aResult['lon']."'";
echo " display_name='".htmlspecialchars($aResult['name'], ENT_QUOTES)."'"; echo " display_name='".htmlspecialchars($aResult['name'], ENT_QUOTES)."'";
echo " class='".htmlspecialchars($aResult['class'])."'"; echo " class='".htmlspecialchars($aResult['class'])."'";
echo " type='".htmlspecialchars($aResult['type'], ENT_QUOTES)."'"; echo " type='".htmlspecialchars($aResult['type'], ENT_QUOTES)."'";
echo " importance='".htmlspecialchars($aResult['importance'])."'"; echo " importance='".htmlspecialchars($aResult['importance'])."'";
if (isset($aResult['icon']) && $aResult['icon']) if (isset($aResult['icon']) && $aResult['icon'])
{ {
echo " icon='".htmlspecialchars($aResult['icon'], ENT_QUOTES)."'"; echo " icon='".htmlspecialchars($aResult['icon'], ENT_QUOTES)."'";
} }
$bHasDelim = false; $bHasDelim = false;
if (isset($aResult['askml'])) if (isset($aResult['askml']))
{ {
if (!$bHasDelim) if (!$bHasDelim)
{ {
$bHasDelim = true; $bHasDelim = true;
echo ">"; echo ">";
} }
echo "\n<geokml>"; echo "\n<geokml>";
echo $aResult['askml']; echo $aResult['askml'];
echo "</geokml>"; echo "</geokml>";
} }
if (isset($aResult['sExtraTags'])) if (isset($aResult['sExtraTags']))
{ {
if (!$bHasDelim) if (!$bHasDelim)
{ {
$bHasDelim = true; $bHasDelim = true;
echo ">"; echo ">";
} }
echo "\n<extratags>"; echo "\n<extratags>";
foreach ($aResult['sExtraTags'] as $sKey => $sValue) foreach ($aResult['sExtraTags'] as $sKey => $sValue)
{ {
echo '<tag key="'.htmlspecialchars($sKey).'" value="'.htmlspecialchars($sValue).'"/>'; echo '<tag key="'.htmlspecialchars($sKey).'" value="'.htmlspecialchars($sValue).'"/>';
} }
echo "</extratags>"; echo "</extratags>";
} }
if (isset($aResult['sNameDetails'])) if (isset($aResult['sNameDetails']))
{ {
if (!$bHasDelim) if (!$bHasDelim)
{ {
$bHasDelim = true; $bHasDelim = true;
echo ">"; echo ">";
} }
echo "\n<namedetails>"; echo "\n<namedetails>";
foreach ($aResult['sNameDetails'] as $sKey => $sValue) foreach ($aResult['sNameDetails'] as $sKey => $sValue)
{ {
echo '<name desc="'.htmlspecialchars($sKey).'">'; echo '<name desc="'.htmlspecialchars($sKey).'">';
echo htmlspecialchars($sValue); echo htmlspecialchars($sValue);
echo "</name>"; echo "</name>";
} }
echo "</namedetails>"; echo "</namedetails>";
} }
if (isset($aResult['address'])) if (isset($aResult['address']))
{ {
if (!$bHasDelim) if (!$bHasDelim)
{ {
$bHasDelim = true; $bHasDelim = true;
echo ">"; echo ">";
} }
echo "\n"; echo "\n";
foreach($aResult['address'] as $sKey => $sValue) foreach($aResult['address'] as $sKey => $sValue)
{ {
$sKey = str_replace(' ','_',$sKey); $sKey = str_replace(' ','_',$sKey);
echo "<$sKey>"; echo "<$sKey>";
echo htmlspecialchars($sValue); echo htmlspecialchars($sValue);
echo "</$sKey>"; echo "</$sKey>";
} }
} }
if ($bHasDelim) if ($bHasDelim)
{ {
echo "</place>"; echo "</place>";
} }
else else
{ {
echo "/>"; echo "/>";
} }
} }
echo "</" . (isset($sXmlRootTag)?$sXmlRootTag:'searchresults') . ">"; echo "</" . (isset($sXmlRootTag)?$sXmlRootTag:'searchresults') . ">";

View File

@ -1,105 +1,104 @@
<?php <?php
@define('CONST_BasePath', '@CMAKE_SOURCE_DIR@'); @define('CONST_BasePath', '@CMAKE_SOURCE_DIR@');
@define('CONST_InstallPath', '@CMAKE_BINARY_DIR@'); @define('CONST_InstallPath', '@CMAKE_BINARY_DIR@');
if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS')); if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
if (file_exists(CONST_InstallPath.'/settings/local.php')) require_once(CONST_InstallPath.'/settings/local.php'); if (file_exists(CONST_InstallPath.'/settings/local.php')) require_once(CONST_InstallPath.'/settings/local.php');
if (isset($_GET['debug']) && $_GET['debug']) @define('CONST_Debug', true); if (isset($_GET['debug']) && $_GET['debug']) @define('CONST_Debug', true);
// General settings // General settings
@define('CONST_Debug', false); @define('CONST_Debug', false);
@define('CONST_Database_DSN', 'pgsql://@/nominatim'); // <driver>://<username>:<password>@<host>:<port>/<database> @define('CONST_Database_DSN', 'pgsql://@/nominatim'); // <driver>://<username>:<password>@<host>:<port>/<database>
@define('CONST_Database_Web_User', 'www-data'); @define('CONST_Database_Web_User', 'www-data');
@define('CONST_Max_Word_Frequency', '50000'); @define('CONST_Max_Word_Frequency', '50000');
@define('CONST_Limit_Reindexing', true); @define('CONST_Limit_Reindexing', true);
// Set to false to avoid importing extra postcodes for the US. // Set to false to avoid importing extra postcodes for the US.
@define('CONST_Use_Extra_US_Postcodes', true); @define('CONST_Use_Extra_US_Postcodes', true);
// Set to true after importing Tiger house number data for the US. // Set to true after importing Tiger house number data for the US.
// Note: The tables must already exist or queries will throw errors. // Note: The tables must already exist or queries will throw errors.
// After changing this setting run ./utils/setup --create-functions // After changing this setting run ./utils/setup --create-functions
// again. // again.
@define('CONST_Use_US_Tiger_Data', false); @define('CONST_Use_US_Tiger_Data', false);
// Set to true after importing other external house number data. // Set to true after importing other external house number data.
// Note: the aux tables must already exist or queries will throw errors. // Note: the aux tables must already exist or queries will throw errors.
// After changing this setting run ./utils/setup --create-functions // After changing this setting run ./utils/setup --create-functions
// again. // again.
@define('CONST_Use_Aux_Location_data', false); @define('CONST_Use_Aux_Location_data', false);
// Proxy settings // Proxy settings
@define('CONST_HTTP_Proxy', false); @define('CONST_HTTP_Proxy', false);
@define('CONST_HTTP_Proxy_Host', 'proxy.mydomain.com'); @define('CONST_HTTP_Proxy_Host', 'proxy.mydomain.com');
@define('CONST_HTTP_Proxy_Port', '3128'); @define('CONST_HTTP_Proxy_Port', '3128');
@define('CONST_HTTP_Proxy_Login', ''); @define('CONST_HTTP_Proxy_Login', '');
@define('CONST_HTTP_Proxy_Password', ''); @define('CONST_HTTP_Proxy_Password', '');
// Paths // Paths
@define('CONST_Osm2pgsql_Binary', CONST_InstallPath.'/osm2pgsql/osm2pgsql'); @define('CONST_Osm2pgsql_Binary', CONST_InstallPath.'/osm2pgsql/osm2pgsql');
@define('CONST_Osmosis_Binary', '/usr/bin/osmosis'); @define('CONST_Osmosis_Binary', '/usr/bin/osmosis');
@define('CONST_Tiger_Data_Path', CONST_BasePath.'/data/tiger'); @define('CONST_Tiger_Data_Path', CONST_BasePath.'/data/tiger');
// osm2pgsql settings // osm2pgsql settings
@define('CONST_Osm2pgsql_Flatnode_File', null); @define('CONST_Osm2pgsql_Flatnode_File', null);
// tablespace settings // tablespace settings
// osm2pgsql caching tables (aka slim mode tables) - update only // osm2pgsql caching tables (aka slim mode tables) - update only
@define('CONST_Tablespace_Osm2pgsql_Data', false); @define('CONST_Tablespace_Osm2pgsql_Data', false);
@define('CONST_Tablespace_Osm2pgsql_Index', false); @define('CONST_Tablespace_Osm2pgsql_Index', false);
// osm2pgsql output tables (aka main table) - update only // osm2pgsql output tables (aka main table) - update only
@define('CONST_Tablespace_Place_Data', false); @define('CONST_Tablespace_Place_Data', false);
@define('CONST_Tablespace_Place_Index', false); @define('CONST_Tablespace_Place_Index', false);
// address computation tables - update only // address computation tables - update only
@define('CONST_Tablespace_Address_Data', false); @define('CONST_Tablespace_Address_Data', false);
@define('CONST_Tablespace_Address_Index', false); @define('CONST_Tablespace_Address_Index', false);
// search tables - needed for lookups // search tables - needed for lookups
@define('CONST_Tablespace_Search_Data', false); @define('CONST_Tablespace_Search_Data', false);
@define('CONST_Tablespace_Search_Index', false); @define('CONST_Tablespace_Search_Index', false);
// additional data, e.g. TIGER data, type searches - needed for lookups // additional data, e.g. TIGER data, type searches - needed for lookups
@define('CONST_Tablespace_Aux_Data', false); @define('CONST_Tablespace_Aux_Data', false);
@define('CONST_Tablespace_Aux_Index', false); @define('CONST_Tablespace_Aux_Index', false);
// Replication settings // Replication settings
@define('CONST_Replication_Url', 'http://planet.openstreetmap.org/replication/minute'); @define('CONST_Replication_Url', 'http://planet.openstreetmap.org/replication/minute');
@define('CONST_Replication_MaxInterval', '3600'); @define('CONST_Replication_MaxInterval', '3600');
@define('CONST_Replication_Update_Interval', '60'); // How often upstream publishes diffs @define('CONST_Replication_Update_Interval', '60'); // How often upstream publishes diffs
@define('CONST_Replication_Recheck_Interval', '60'); // How long to sleep if no update found yet @define('CONST_Replication_Recheck_Interval', '60'); // How long to sleep if no update found yet
// Website settings // Website settings
@define('CONST_NoAccessControl', true); @define('CONST_NoAccessControl', true);
@define('CONST_Website_BaseURL', 'http://'.php_uname('n').'/'); @define('CONST_Website_BaseURL', 'http://'.php_uname('n').'/');
// Language to assume when none is supplied with the query. // Language to assume when none is supplied with the query.
// When set to false, the local language (i.e. the name tag without suffix) // When set to false, the local language (i.e. the name tag without suffix)
// will be used. // will be used.
@define('CONST_Default_Language', false); @define('CONST_Default_Language', false);
// Appearance of the map in the debug interface. // Appearance of the map in the debug interface.
@define('CONST_Default_Lat', 20.0); @define('CONST_Default_Lat', 20.0);
@define('CONST_Default_Lon', 0.0); @define('CONST_Default_Lon', 0.0);
@define('CONST_Default_Zoom', 2); @define('CONST_Default_Zoom', 2);
@define('CONST_Map_Tile_URL', 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'); @define('CONST_Map_Tile_URL', 'http://{s}.tile.osm.org/{z}/{x}/{y}.png');
@define('CONST_Map_Tile_Attribution', ''); // Set if tile source isn't osm.org @define('CONST_Map_Tile_Attribution', ''); // Set if tile source isn't osm.org
@define('CONST_Search_AreaPolygons', true); @define('CONST_Search_AreaPolygons', true);
@define('CONST_Search_BatchMode', false); @define('CONST_Search_BatchMode', false);
@define('CONST_Search_TryDroppedAddressTerms', false); @define('CONST_Search_TryDroppedAddressTerms', false);
@define('CONST_Search_NameOnlySearchFrequencyThreshold', 500); @define('CONST_Search_NameOnlySearchFrequencyThreshold', 500);
// If set to true, then reverse order of queries will be tried by default. // If set to true, then reverse order of queries will be tried by default.
// When set to false only selected languages alloow reverse search. // When set to false only selected languages alloow reverse search.
@define('CONST_Search_ReversePlanForAll', true); @define('CONST_Search_ReversePlanForAll', true);
// Maximum number of OSM ids that may be queried at once // Maximum number of OSM ids that may be queried at once
// for the places endpoint. // for the places endpoint.
@define('CONST_Places_Max_ID_count', 50); @define('CONST_Places_Max_ID_count', 50);
// Number of different geometry formats that may be queried in parallel. // Number of different geometry formats that may be queried in parallel.
// Set to zero to disable polygon output. // Set to zero to disable polygon output.
@define('CONST_PolygonOutput_MaximumTypes', 1); @define('CONST_PolygonOutput_MaximumTypes', 1);
// Log settings
// Set to true to log into new_query_log table.
// You should set up a cron job that regularly clears out this table.
@define('CONST_Log_DB', false);
// Set to a file name to enable logging to a file.
@define('CONST_Log_File', false);
// Log settings
// Set to true to log into new_query_log table.
// You should set up a cron job that regularly clears out this table.
@define('CONST_Log_DB', false);
// Set to a file name to enable logging to a file.
@define('CONST_Log_File', false);

View File

@ -3,49 +3,49 @@
# Languages to download the special phrases for. # Languages to download the special phrases for.
$aLanguageIn = array( $aLanguageIn = array(
'af', 'af',
'ar', 'ar',
'br', 'br',
'ca', 'ca',
'cs', 'cs',
'de', 'de',
'en', 'en',
'es', 'es',
'et', 'et',
'eu', 'eu',
'fa', 'fa',
'fi', 'fi',
'fr', 'fr',
'gl', 'gl',
'hr', 'hr',
'hu', 'hu',
'ia', 'ia',
'is', 'is',
'it', 'it',
'ja', 'ja',
'mk', 'mk',
'nl', 'nl',
'no', 'no',
'pl', 'pl',
'ps', 'ps',
'pt', 'pt',
'ru', 'ru',
'sk', 'sk',
'sv', 'sv',
'uk', 'uk',
'vi', 'vi',
); );
# class/type combinations to exclude # class/type combinations to exclude
$aTagsBlacklist = array( $aTagsBlacklist = array(
'boundary' => array('administrative'), 'boundary' => array('administrative'),
'place' => array('house', 'houses'), 'place' => array('house', 'houses'),
); );
# If a class is in the white list then all types will # If a class is in the white list then all types will
# be ignored except the ones given in the list. # be ignored except the ones given in the list.
# Also use this list to exclude an entire class from # Also use this list to exclude an entire class from
# special phrases. # special phrases.
$aTagsWhitelist = array( $aTagsWhitelist = array(
'highway' => array('bus_stop', 'rest_area', 'raceway'), 'highway' => array('bus_stop', 'rest_area', 'raceway'),
'building' => array(), 'building' => array(),
); );

View File

@ -1,4 +1,5 @@
<?php <?php
echo "ERROR: Scripts must be run from build directory.\n";
exit; echo "ERROR: Scripts must be run from build directory.\n";
exit;

View File

@ -7,255 +7,255 @@ require '../lib/lib.php';
class NominatimTest extends \PHPUnit_Framework_TestCase class NominatimTest extends \PHPUnit_Framework_TestCase
{ {
protected function setUp() protected function setUp()
{ {
} }
public function test_getClassTypesWithImportance() public function test_getClassTypesWithImportance()
{ {
$aClasses = getClassTypesWithImportance(); $aClasses = getClassTypesWithImportance();
$this->assertGreaterThan( $this->assertGreaterThan(
200, 200,
count($aClasses) count($aClasses)
); );
$this->assertEquals( $this->assertEquals(
array( array(
'label' => "Country", 'label' => "Country",
'frequency' => 0, 'frequency' => 0,
'icon' => "poi_boundary_administrative", 'icon' => "poi_boundary_administrative",
'defzoom' => 6, 'defzoom' => 6,
'defdiameter' => 15, 'defdiameter' => 15,
'importance' => 3 'importance' => 3
), ),
$aClasses['place:country'] $aClasses['place:country']
); );
} }
public function test_getResultDiameter() public function test_getResultDiameter()
{ {
$aResult = array(); $aResult = array();
$this->assertEquals( $this->assertEquals(
0.0001, 0.0001,
getResultDiameter($aResult) getResultDiameter($aResult)
); );
$aResult = array('class' => 'place', 'type' => 'country'); $aResult = array('class' => 'place', 'type' => 'country');
$this->assertEquals( $this->assertEquals(
15, 15,
getResultDiameter($aResult) getResultDiameter($aResult)
); );
$aResult = array('class' => 'boundary', 'type' => 'administrative', 'admin_level' => 6); $aResult = array('class' => 'boundary', 'type' => 'administrative', 'admin_level' => 6);
$this->assertEquals( $this->assertEquals(
0.32, 0.32,
getResultDiameter($aResult) getResultDiameter($aResult)
); );
} }
public function test_addQuotes() public function test_addQuotes()
{ {
// FIXME: not quoting existing quote signs is probably a bug // FIXME: not quoting existing quote signs is probably a bug
$this->assertSame("'St. John's'", addQuotes("St. John's")); $this->assertSame("'St. John's'", addQuotes("St. John's"));
$this->assertSame("''", addQuotes('')); $this->assertSame("''", addQuotes(''));
} }
public function test_looksLikeLatLonPair() public function test_looksLikeLatLonPair()
{ {
// no coordinates expected // no coordinates expected
$this->assertNull(looksLikeLatLonPair('')); $this->assertNull(looksLikeLatLonPair(''));
$this->assertNull(looksLikeLatLonPair('abc')); $this->assertNull(looksLikeLatLonPair('abc'));
$this->assertNull(looksLikeLatLonPair('12 34')); $this->assertNull(looksLikeLatLonPair('12 34'));
$this->assertNull(looksLikeLatLonPair('200.1 89.9')); // because latitude > 180 $this->assertNull(looksLikeLatLonPair('200.1 89.9')); // because latitude > 180
// coordinates expected // coordinates expected
$this->assertNotNull(looksLikeLatLonPair('0.0 -0.0')); $this->assertNotNull(looksLikeLatLonPair('0.0 -0.0'));
$this->assertEquals( $this->assertEquals(
array( 'lat' => 12.456, 'lon' => -78.90, 'query' => 'abc def'), array( 'lat' => 12.456, 'lon' => -78.90, 'query' => 'abc def'),
looksLikeLatLonPair(' abc 12.456 -78.90 def ') looksLikeLatLonPair(' abc 12.456 -78.90 def ')
); );
$this->assertEquals( $this->assertEquals(
array( 'lat' => 12.456, 'lon' => -78.90, 'query' => ''), array( 'lat' => 12.456, 'lon' => -78.90, 'query' => ''),
looksLikeLatLonPair(' [12.456,-78.90] ') looksLikeLatLonPair(' [12.456,-78.90] ')
); );
// http://en.wikipedia.org/wiki/Geographic_coordinate_conversion // http://en.wikipedia.org/wiki/Geographic_coordinate_conversion
// these all represent the same location // these all represent the same location
$aQueries = array( $aQueries = array(
'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',
"40° 26.767' N 79° 58.933' W", "40° 26.767' N 79° 58.933' W",
'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',
"N 40°26.767', W 79°58.933'", "N 40°26.767', W 79°58.933'",
'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',
'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″',
'N 40° 26\' 46", W 79° 58\' 56"', 'N 40° 26\' 46", W 79° 58\' 56"',
'40.446 -79.982', '40.446 -79.982',
'40.446,-79.982', '40.446,-79.982',
'40.446° N 79.982° W', '40.446° N 79.982° W',
'N 40.446° W 79.982°', 'N 40.446° W 79.982°',
'[40.446 -79.982]', '[40.446 -79.982]',
' 40.446 , -79.982 ', ' 40.446 , -79.982 ',
); );
foreach($aQueries as $sQuery){ foreach($aQueries as $sQuery){
$aRes = looksLikeLatLonPair($sQuery); $aRes = looksLikeLatLonPair($sQuery);
$this->assertEquals( 40.446, $aRes['lat'], 'degrees decimal ' . $sQuery, 0.01); $this->assertEquals( 40.446, $aRes['lat'], 'degrees decimal ' . $sQuery, 0.01);
$this->assertEquals(-79.982, $aRes['lon'], 'degrees decimal ' . $sQuery, 0.01); $this->assertEquals(-79.982, $aRes['lon'], 'degrees decimal ' . $sQuery, 0.01);
} }
} }
public function test_getWordSets() public function test_getWordSets()
{ {
// given an array of arrays like // given an array of arrays like
// array( array('a','b'), array('c','d') ) // array( array('a','b'), array('c','d') )
// returns a summary as string: '(a|b),(c|d)' // returns a summary as string: '(a|b),(c|d)'
function serialize_sets($aSets) function serialize_sets($aSets)
{ {
$aParts = array(); $aParts = array();
foreach($aSets as $aSet){ foreach($aSets as $aSet){
$aParts[] = '(' . join('|', $aSet) . ')'; $aParts[] = '(' . join('|', $aSet) . ')';
} }
return join(',', $aParts); return join(',', $aParts);
} }
$this->assertEquals( $this->assertEquals(
array(array('')), array(array('')),
getWordSets(array(),0) getWordSets(array(),0)
); );
$this->assertEquals( $this->assertEquals(
'(a)', '(a)',
serialize_sets( getWordSets(array("a"),0) ) serialize_sets( getWordSets(array("a"),0) )
); );
$this->assertEquals( $this->assertEquals(
'(a b),(a|b)', '(a b),(a|b)',
serialize_sets( getWordSets(array('a','b'),0) ) serialize_sets( getWordSets(array('a','b'),0) )
); );
$this->assertEquals( $this->assertEquals(
'(a b c),(a|b c),(a|b|c),(a b|c)', '(a b c),(a|b c),(a|b|c),(a b|c)',
serialize_sets( getWordSets(array('a','b','c'),0) ) serialize_sets( getWordSets(array('a','b','c'),0) )
); );
$this->assertEquals( $this->assertEquals(
'(a b c d),(a|b c d),(a|b|c d),(a|b|c|d),(a|b c|d),(a b|c d),(a b|c|d),(a b c|d)', '(a b c d),(a|b c d),(a|b|c d),(a|b|c|d),(a|b c|d),(a b|c d),(a b|c|d),(a b c|d)',
serialize_sets( getWordSets(array('a','b','c','d'),0) ) serialize_sets( getWordSets(array('a','b','c','d'),0) )
); );
// Inverse // Inverse
$this->assertEquals( $this->assertEquals(
'(a b c),(c|a b),(c|b|a),(b c|a)', '(a b c),(c|a b),(c|b|a),(b c|a)',
serialize_sets( getInverseWordSets(array('a','b','c'),0) ) serialize_sets( getInverseWordSets(array('a','b','c'),0) )
); );
// make sure we don't create too many sets // make sure we don't create too many sets
// 4 words => 8 sets // 4 words => 8 sets
// 10 words => 511 sets // 10 words => 511 sets
// 15 words => 12911 sets // 15 words => 12911 sets
// 18 words => 65536 sets // 18 words => 65536 sets
// 20 words => 169766 sets // 20 words => 169766 sets
// 22 words => 401930 sets // 22 words => 401930 sets
// 28 words => 3505699 sets (needs more than 4GB via 'phpunit -d memory_limit=' to run) // 28 words => 3505699 sets (needs more than 4GB via 'phpunit -d memory_limit=' to run)
$this->assertEquals( $this->assertEquals(
8, 8,
count( getWordSets(array_fill( 0, 4, 'a'),0) ) count( getWordSets(array_fill( 0, 4, 'a'),0) )
); );
$this->assertEquals( $this->assertEquals(
65536, 65536,
count( getWordSets(array_fill( 0, 18, 'a'),0) ) count( getWordSets(array_fill( 0, 18, 'a'),0) )
); );
} }
// you might say we're creating a circle // you might say we're creating a circle
public function test_createPointsAroundCenter() public function test_createPointsAroundCenter()
{ {
$aPoints = createPointsAroundCenter(0, 0, 2); $aPoints = createPointsAroundCenter(0, 0, 2);
$this->assertEquals( $this->assertEquals(
101, 101,
count($aPoints) count($aPoints)
); );
$this->assertEquals( $this->assertEquals(
array( array(
['', 0, 2], ['', 0, 2],
['', 0.12558103905863, 1.9960534568565], ['', 0.12558103905863, 1.9960534568565],
['', 0.25066646712861, 1.984229402629] ['', 0.25066646712861, 1.984229402629]
), ),
array_splice($aPoints, 0, 3) array_splice($aPoints, 0, 3)
); );
} }
public function test_geometryText2Points() public function test_geometryText2Points()
{ {
$fRadius = 1; $fRadius = 1;
// invalid value // invalid value
$this->assertEquals( $this->assertEquals(
NULL, NULL,
geometryText2Points('', $fRadius) geometryText2Points('', $fRadius)
); );
// POINT // POINT
$aPoints = geometryText2Points('POINT(10 20)', $fRadius); $aPoints = geometryText2Points('POINT(10 20)', $fRadius);
$this->assertEquals( $this->assertEquals(
101, 101,
count($aPoints) count($aPoints)
); );
$this->assertEquals( $this->assertEquals(
array( array(
[10, 21], [10, 21],
[10.062790519529, 20.998026728428], [10.062790519529, 20.998026728428],
[10.125333233564, 20.992114701314] [10.125333233564, 20.992114701314]
), ),
array_splice($aPoints, 0,3) array_splice($aPoints, 0,3)
); );
// POLYGON // POLYGON
$this->assertEquals( $this->assertEquals(
array( array(
['30', '10'], ['30', '10'],
['40', '40'], ['40', '40'],
['20', '40'], ['20', '40'],
['10', '20'], ['10', '20'],
['30', '10'] ['30', '10']
), ),
geometryText2Points('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))', $fRadius) geometryText2Points('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))', $fRadius)
); );
// MULTIPOLYGON // MULTIPOLYGON
$this->assertEquals( $this->assertEquals(
array( array(
['30', '20'], // first polygon only ['30', '20'], // first polygon only
['45', '40'], ['45', '40'],
['10', '40'], ['10', '40'],
['30', '20'], ['30', '20'],
), ),
geometryText2Points('MULTIPOLYGON(((30 20, 45 40, 10 40, 30 20)),((15 5, 40 10, 10 20, 5 10, 15 5)))', $fRadius) geometryText2Points('MULTIPOLYGON(((30 20, 45 40, 10 40, 30 20)),((15 5, 40 10, 10 20, 5 10, 15 5)))', $fRadius)
); );
} }
} }

View File

@ -1,53 +1,53 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
$aCMDOptions = array( $aCMDOptions = array(
"Manage service blocks / restrictions", "Manage service blocks / restrictions",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('list', 'l', 0, 1, 0, 0, 'bool', 'List recent blocks'), array('list', 'l', 0, 1, 0, 0, 'bool', 'List recent blocks'),
array('delete', 'd', 0, 1, 0, 0, 'bool', 'Clear recent blocks list'), array('delete', 'd', 0, 1, 0, 0, 'bool', 'Clear recent blocks list'),
array('flush', '', 0, 1, 0, 0, 'bool', 'Flush all blocks / stats'), array('flush', '', 0, 1, 0, 0, 'bool', 'Flush all blocks / stats'),
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
$m = getBucketMemcache(); $m = getBucketMemcache();
if (!$m) if (!$m)
{ {
echo "ERROR: Bucket memcache is not configured\n"; echo "ERROR: Bucket memcache is not configured\n";
exit; exit;
} }
if ($aResult['list']) if ($aResult['list'])
{ {
$iCurrentSleeping = $m->get('sleepCounter'); $iCurrentSleeping = $m->get('sleepCounter');
echo "\n Sleeping blocks count: $iCurrentSleeping\n"; echo "\n Sleeping blocks count: $iCurrentSleeping\n";
$aBlocks = getBucketBlocks(); $aBlocks = getBucketBlocks();
echo "\n"; echo "\n";
printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", "Key", "Total Blocks", "Current", "Still Blocked", "Last Block Time", "Sleeping"); printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", "Key", "Total Blocks", "Current", "Still Blocked", "Last Block Time", "Sleeping");
printf(" %'--40s-|-%'-12s-|-%'-7s-|-%'-13s-|-%'-31s-|-%'-8s\n", "", "", "", "", "", ""); printf(" %'--40s-|-%'-12s-|-%'-7s-|-%'-13s-|-%'-31s-|-%'-8s\n", "", "", "", "", "", "");
foreach($aBlocks as $sKey => $aDetails) foreach($aBlocks as $sKey => $aDetails)
{ {
printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", $sKey, $aDetails['totalBlocks'], printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", $sKey, $aDetails['totalBlocks'],
(int)$aDetails['currentBucketSize'], $aDetails['currentlyBlocked']?'Y':'N', (int)$aDetails['currentBucketSize'], $aDetails['currentlyBlocked']?'Y':'N',
date("r", $aDetails['lastBlockTimestamp']), $aDetails['isSleeping']?'Y':'N'); date("r", $aDetails['lastBlockTimestamp']), $aDetails['isSleeping']?'Y':'N');
} }
echo "\n"; echo "\n";
} }
if ($aResult['delete']) if ($aResult['delete'])
{ {
$m->set('sleepCounter', 0); $m->set('sleepCounter', 0);
clearBucketBlocks(); clearBucketBlocks();
} }
if ($aResult['flush']) if ($aResult['flush'])
{ {
$m->flush(); $m->flush();
} }

View File

@ -1,36 +1,36 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
ini_set('display_errors', 'stderr'); ini_set('display_errors', 'stderr');
$aCMDOptions = array( $aCMDOptions = array(
"Import country language data from osm wiki", "Import country language data from osm wiki",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
include(CONST_InstallPath.'/settings/phrase_settings.php'); include(CONST_InstallPath.'/settings/phrase_settings.php');
if (true) if (true)
{ {
$sURL = 'http://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Country_Codes'; $sURL = 'http://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Country_Codes';
$sWikiPageXML = file_get_contents($sURL); $sWikiPageXML = file_get_contents($sURL);
if (preg_match_all('#\\| ([a-z]{2}) \\|\\| [^|]+\\|\\| ([a-z,]+)#', $sWikiPageXML, $aMatches, PREG_SET_ORDER)) if (preg_match_all('#\\| ([a-z]{2}) \\|\\| [^|]+\\|\\| ([a-z,]+)#', $sWikiPageXML, $aMatches, PREG_SET_ORDER))
{ {
foreach($aMatches as $aMatch) foreach($aMatches as $aMatch)
{ {
$aLanguages = explode(',', $aMatch[2]); $aLanguages = explode(',', $aMatch[2]);
foreach($aLanguages as $i => $s) foreach($aLanguages as $i => $s)
{ {
$aLanguages[$i] = '"'.pg_escape_string($s).'"'; $aLanguages[$i] = '"'.pg_escape_string($s).'"';
} }
echo "UPDATE country_name set country_default_language_codes = '{".join(',',$aLanguages)."}' where country_code = '".pg_escape_string($aMatch[1])."';\n"; echo "UPDATE country_name set country_default_language_codes = '{".join(',',$aLanguages)."}' where country_code = '".pg_escape_string($aMatch[1])."';\n";
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,32 +11,32 @@ echo "CREATE TABLE wikipedia_redirect (language text, from_title text, to_title
for i in "${language[@]}" for i in "${language[@]}"
do do
wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-page.sql.gz wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-page.sql.gz
wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-pagelinks.sql.gz wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-pagelinks.sql.gz
wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-langlinks.sql.gz wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-langlinks.sql.gz
wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-redirect.sql.gz wget http://dumps.wikimedia.org/${i}wiki/latest/${i}wiki-latest-redirect.sql.gz
done done
for i in "${language[@]}" for i in "${language[@]}"
do do
gzip -dc ${i}wiki-latest-pagelinks.sql.gz | sed "s/\`pagelinks\`/\`${i}pagelinks\`/g" | $mysql2pgsqlcmd | $psqlcmd gzip -dc ${i}wiki-latest-pagelinks.sql.gz | sed "s/\`pagelinks\`/\`${i}pagelinks\`/g" | $mysql2pgsqlcmd | $psqlcmd
gzip -dc ${i}wiki-latest-page.sql.gz | sed "s/\`page\`/\`${i}page\`/g" | $mysql2pgsqlcmd | $psqlcmd gzip -dc ${i}wiki-latest-page.sql.gz | sed "s/\`page\`/\`${i}page\`/g" | $mysql2pgsqlcmd | $psqlcmd
gzip -dc ${i}wiki-latest-langlinks.sql.gz | sed "s/\`langlinks\`/\`${i}langlinks\`/g" | $mysql2pgsqlcmd | $psqlcmd gzip -dc ${i}wiki-latest-langlinks.sql.gz | sed "s/\`langlinks\`/\`${i}langlinks\`/g" | $mysql2pgsqlcmd | $psqlcmd
gzip -dc ${i}wiki-latest-redirect.sql.gz | sed "s/\`redirect\`/\`${i}redirect\`/g" | $mysql2pgsqlcmd | $psqlcmd gzip -dc ${i}wiki-latest-redirect.sql.gz | sed "s/\`redirect\`/\`${i}redirect\`/g" | $mysql2pgsqlcmd | $psqlcmd
done done
for i in "${language[@]}" for i in "${language[@]}"
do do
echo "create table ${i}pagelinkcount as select pl_title as title,count(*) as count from ${i}pagelinks where pl_namespace = 0 group by pl_title;" | $psqlcmd echo "create table ${i}pagelinkcount as select pl_title as title,count(*) as count from ${i}pagelinks where pl_namespace = 0 group by pl_title;" | $psqlcmd
echo "insert into linkcounts select '${i}',pl_title,count(*) from ${i}pagelinks where pl_namespace = 0 group by pl_title;" | $psqlcmd echo "insert into linkcounts select '${i}',pl_title,count(*) from ${i}pagelinks where pl_namespace = 0 group by pl_title;" | $psqlcmd
echo "insert into wikipedia_redirect select '${i}',page_title,rd_title from ${i}redirect join ${i}page on (rd_from = page_id) where page_namespace = 0 and rd_namespace = 0;" | $psqlcmd echo "insert into wikipedia_redirect select '${i}',page_title,rd_title from ${i}redirect join ${i}page on (rd_from = page_id) where page_namespace = 0 and rd_namespace = 0;" | $psqlcmd
echo "alter table ${i}pagelinkcount add column othercount integer;" | $psqlcmd echo "alter table ${i}pagelinkcount add column othercount integer;" | $psqlcmd
echo "update ${i}pagelinkcount set othercount = 0;" | $psqlcmd echo "update ${i}pagelinkcount set othercount = 0;" | $psqlcmd
for j in "${language[@]}" for j in "${language[@]}"
do do
echo "update ${i}pagelinkcount set othercount = ${i}pagelinkcount.othercount + x.count from (select page_title as title,count from ${i}langlinks join ${i}page on (ll_from = page_id) join ${j}pagelinkcount on (ll_lang = '${j}' and ll_title = title)) as x where x.title = ${i}pagelinkcount.title;" | $psqlcmd echo "update ${i}pagelinkcount set othercount = ${i}pagelinkcount.othercount + x.count from (select page_title as title,count from ${i}langlinks join ${i}page on (ll_from = page_id) join ${j}pagelinkcount on (ll_lang = '${j}' and ll_title = title)) as x where x.title = ${i}pagelinkcount.title;" | $psqlcmd
done done
echo "insert into wikipedia_article select '${i}', title, count, othercount, count+othercount from ${i}pagelinkcount;" | $psqlcmd echo "insert into wikipedia_article select '${i}', title, count, othercount, count+othercount from ${i}pagelinkcount;" | $psqlcmd
done done
echo "update wikipedia_article set importance = log(totalcount)/log((select max(totalcount) from wikipedia_article))" | $psqlcmd echo "update wikipedia_article set importance = log(totalcount)/log((select max(totalcount) from wikipedia_article))" | $psqlcmd

View File

@ -1,61 +1,61 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
$aCMDOptions = array( $aCMDOptions = array(
"Create and setup nominatim search system", "Create and setup nominatim search system",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('parse-tiger', '', 0, 1, 1, 1, 'realpath', 'Convert tiger edge files to nominatim sql import - datafiles from 2011 or later (source: edges directory of tiger data)'), array('parse-tiger', '', 0, 1, 1, 1, 'realpath', 'Convert tiger edge files to nominatim sql import - datafiles from 2011 or later (source: edges directory of tiger data)'),
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
if (isset($aCMDResult['parse-tiger'])) if (isset($aCMDResult['parse-tiger']))
{ {
if (!file_exists(CONST_Tiger_Data_Path)) mkdir(CONST_Tiger_Data_Path); if (!file_exists(CONST_Tiger_Data_Path)) mkdir(CONST_Tiger_Data_Path);
$sTempDir = tempnam('/tmp', 'tiger'); $sTempDir = tempnam('/tmp', 'tiger');
unlink($sTempDir); unlink($sTempDir);
mkdir($sTempDir); mkdir($sTempDir);
foreach(glob($aCMDResult['parse-tiger'].'/tl_20??_?????_edges.zip', 0) as $sImportFile) foreach(glob($aCMDResult['parse-tiger'].'/tl_20??_?????_edges.zip', 0) as $sImportFile)
{ {
set_time_limit(30); set_time_limit(30);
preg_match('#([0-9]{5})_(.*)#',basename($sImportFile), $aMatch); preg_match('#([0-9]{5})_(.*)#',basename($sImportFile), $aMatch);
$sCountyID = $aMatch[1]; $sCountyID = $aMatch[1];
echo "Processing ".$sCountyID."...\n"; echo "Processing ".$sCountyID."...\n";
$sUnzipCmd = "unzip -d $sTempDir $sImportFile"; $sUnzipCmd = "unzip -d $sTempDir $sImportFile";
exec($sUnzipCmd); exec($sUnzipCmd);
$sShapeFile = $sTempDir.'/'.basename($sImportFile, '.zip').'.shp'; $sShapeFile = $sTempDir.'/'.basename($sImportFile, '.zip').'.shp';
if (!file_exists($sShapeFile)) if (!file_exists($sShapeFile))
{ {
echo "Failed unzip ($sImportFile)\n"; echo "Failed unzip ($sImportFile)\n";
} }
else else
{ {
$sParseCmd = CONST_BasePath.'/utils/tigerAddressImport.py '.$sShapeFile; $sParseCmd = CONST_BasePath.'/utils/tigerAddressImport.py '.$sShapeFile;
exec($sParseCmd); exec($sParseCmd);
$sOsmFile = $sTempDir.'/'.basename($sImportFile, '.zip').'.osm1.osm'; $sOsmFile = $sTempDir.'/'.basename($sImportFile, '.zip').'.osm1.osm';
if (!file_exists($sOsmFile)) if (!file_exists($sOsmFile))
{ {
echo "Failed parse ($sImportFile)\n"; echo "Failed parse ($sImportFile)\n";
} }
else else
{ {
copy($sOsmFile, CONST_Tiger_Data_Path.'/'.$sCountyID.'.sql'); copy($sOsmFile, CONST_Tiger_Data_Path.'/'.$sCountyID.'.sql');
} }
} }
// Cleanup // Cleanup
foreach(glob($sTempDir.'/*') as $sTmpFile) foreach(glob($sTempDir.'/*') as $sTmpFile)
{ {
unlink($sTmpFile); unlink($sTmpFile);
} }
} }
} }

View File

@ -1,55 +1,52 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
require_once(CONST_BasePath.'/lib/Geocode.php'); require_once(CONST_BasePath.'/lib/Geocode.php');
require_once(CONST_BasePath.'/lib/ParameterParser.php'); require_once(CONST_BasePath.'/lib/ParameterParser.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
$aCMDOptions = array( $aCMDOptions = array(
"Query database from command line. Returns search result as JSON.", "Query database from command line. Returns search result as JSON.",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('search', '', 0, 1, 1, 1, 'string', 'Search for given term or coordinate'), array('search', '', 0, 1, 1, 1, 'string', 'Search for given term or coordinate'),
array('accept-language', '', 0, 1, 1, 1, 'string', 'Preferred language order for showing search results'), array('accept-language', '', 0, 1, 1, 1, 'string', 'Preferred language order for showing search results'),
array('bounded', '', 0, 1, 0, 0, 'bool', 'Restrict results to given viewbox'), array('bounded', '', 0, 1, 0, 0, 'bool', 'Restrict results to given viewbox'),
array('nodedupe', '', 0, 1, 0, 0, 'bool', 'Do not remove duplicate results'), array('nodedupe', '', 0, 1, 0, 0, 'bool', 'Do not remove duplicate results'),
array('limit', '', 0, 1, 1, 1, 'int', 'Maximum number of results returned (default: 10)'), array('limit', '', 0, 1, 1, 1, 'int', 'Maximum number of results returned (default: 10)'),
array('exclude_place_ids', '', 0, 1, 1, 1, 'string', 'Comma-separated list of place ids to exclude from results'), array('exclude_place_ids', '', 0, 1, 1, 1, 'string', 'Comma-separated list of place ids to exclude from results'),
array('featureType', '', 0, 1, 1, 1, 'string', 'Restrict results to certain features (country, state,city,settlement)'), array('featureType', '', 0, 1, 1, 1, 'string', 'Restrict results to certain features (country, state,city,settlement)'),
array('countrycodes', '', 0, 1, 1, 1, 'string', 'Comma-separated list of countries to restrict search to'), array('countrycodes', '', 0, 1, 1, 1, 'string', 'Comma-separated list of countries to restrict search to'),
array('viewbox', '', 0, 1, 1, 1, 'string', 'Prefer results in given view box') array('viewbox', '', 0, 1, 1, 1, 'string', 'Prefer results in given view box')
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
$oDB =& getDB(); $oDB =& getDB();
$oParams = new ParameterParser($aCMDResult); $oParams = new ParameterParser($aCMDResult);
if ($oParams->getBool('search')) if ($oParams->getBool('search'))
{ {
if (isset($aCMDResult['nodedupe'])) $aCMDResult['dedupe'] = 'false'; if (isset($aCMDResult['nodedupe'])) $aCMDResult['dedupe'] = 'false';
$oGeocode = new Geocode($oDB); $oGeocode = new Geocode($oDB);
$oGeocode->setLanguagePreference($oParams->getPreferredLanguages(false));
$oGeocode->loadParamArray($oParams);
$oGeocode->setQuery($aCMDResult['search']);
$aSearchResults = $oGeocode->lookup();
if (version_compare(phpversion(), "5.4.0", '<'))
echo json_encode($aSearchResults);
else
echo json_encode($aSearchResults, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n";
}
else
{
showUsage($aCMDOptions, true);
}
$oGeocode->setLanguagePreference($oParams->getPreferredLanguages(false));
$oGeocode->loadParamArray($oParams);
$oGeocode->setQuery($aCMDResult['search']);
$aSearchResults = $oGeocode->lookup();
if (version_compare(phpversion(), "5.4.0", '<'))
echo json_encode($aSearchResults);
else
echo json_encode($aSearchResults, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n";
}
else
{
showUsage($aCMDOptions, true);
}

View File

@ -1,78 +1,78 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
// Apache log file // Apache log file
$sFile = "sample.log.txt"; $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';
$sHost1Escaped = str_replace('/', '\\/', $sHost1); $sHost1Escaped = str_replace('/', '\\/', $sHost1);
$sHost2Escaped = str_replace('/', '\\/', $sHost2); $sHost2Escaped = str_replace('/', '\\/', $sHost2);
$aToDo = array(251, 293, 328, 399.1, 455.1, 479, 496, 499, 574, 609, 702, 790, 846, 865, 878, 894, 902, 961, 980); $aToDo = array(251, 293, 328, 399.1, 455.1, 479, 496, 499, 574, 609, 702, 790, 846, 865, 878, 894, 902, 961, 980);
$hFile = @fopen($sFile, "r"); $hFile = @fopen($sFile, "r");
if (!$hFile) if (!$hFile)
{ {
echo "Unable to open file: $sFile\n"; echo "Unable to open file: $sFile\n";
exit; exit;
} }
$i = 0; $i = 0;
while (($sLine = fgets($hFile, 10000)) !== false) while (($sLine = fgets($hFile, 10000)) !== false)
{ {
$i++; $i++;
if (!in_array($i, $aToDo)) continue; if (!in_array($i, $aToDo)) continue;
if (preg_match('#"GET (.*) HTTP/1.[01]"#', $sLine, $aResult)) if (preg_match('#"GET (.*) HTTP/1.[01]"#', $sLine, $aResult))
{ {
$sURL1 = $sHost1.$aResult[1]; $sURL1 = $sHost1.$aResult[1];
$sURL2 = $sHost2.$aResult[1]; $sURL2 = $sHost2.$aResult[1];
$sRes1 = ''; $sRes1 = '';
$k = 0; $k = 0;
while(!$sRes1 && $k < 10) while(!$sRes1 && $k < 10)
{ {
$sRes1 = file_get_contents($sURL1); $sRes1 = file_get_contents($sURL1);
$k++; $k++;
if (!$sRes1) sleep(10); if (!$sRes1) sleep(10);
} }
$sRes2 = file_get_contents($sURL2); $sRes2 = file_get_contents($sURL2);
// Strip out the things that will always change // Strip out the things that will always change
$sRes1 = preg_replace('# timestamp=\'[^\']*\'#', '', $sRes1); $sRes1 = preg_replace('# timestamp=\'[^\']*\'#', '', $sRes1);
$sRes1 = str_replace($sHost1, '', $sRes1); $sRes1 = str_replace($sHost1, '', $sRes1);
$sRes1 = str_replace($sHost1Escaped, '', $sRes1); $sRes1 = str_replace($sHost1Escaped, '', $sRes1);
$sRes2 = preg_replace('# timestamp=\'[^\']*\'#', '', $sRes2); $sRes2 = preg_replace('# timestamp=\'[^\']*\'#', '', $sRes2);
$sRes2 = str_replace($sHost2, '', $sRes2); $sRes2 = str_replace($sHost2, '', $sRes2);
$sRes2 = str_replace($sHost2Escaped, '', $sRes2); $sRes2 = str_replace($sHost2Escaped, '', $sRes2);
if ($sRes1 != $sRes2) if ($sRes1 != $sRes2)
{ {
echo "$i:\n"; echo "$i:\n";
var_dump($sURL1, $sURL2); var_dump($sURL1, $sURL2);
$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);
} }
echo ".\n"; echo ".\n";
} }
else else
{ {
var_dump($sLine); var_dump($sLine);
} }
} }
fclose($hFile); fclose($hFile);

File diff suppressed because it is too large Load Diff

View File

@ -1,114 +1,114 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
ini_set('display_errors', 'stderr'); ini_set('display_errors', 'stderr');
$aCMDOptions = array( $aCMDOptions = array(
"Import and export special phrases", "Import and export special phrases",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('countries', '', 0, 1, 0, 0, 'bool', 'Create import script for country codes and names'), array('countries', '', 0, 1, 0, 0, 'bool', 'Create import script for country codes and names'),
array('wiki-import', '', 0, 1, 0, 0, 'bool', 'Create import script for search phrases '), array('wiki-import', '', 0, 1, 0, 0, 'bool', 'Create import script for search phrases '),
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
include(CONST_InstallPath.'/settings/phrase_settings.php'); include(CONST_InstallPath.'/settings/phrase_settings.php');
if ($aCMDResult['countries']) { if ($aCMDResult['countries']) {
echo "select getorcreate_country(make_standard_name('uk'), 'gb');\n"; echo "select getorcreate_country(make_standard_name('uk'), 'gb');\n";
echo "select getorcreate_country(make_standard_name('united states'), 'us');\n"; echo "select getorcreate_country(make_standard_name('united states'), 'us');\n";
echo "select count(*) from (select getorcreate_country(make_standard_name(country_code), country_code) from country_name where country_code is not null) as x;\n"; echo "select count(*) from (select getorcreate_country(make_standard_name(country_code), country_code) from country_name where country_code is not null) as x;\n";
echo "select count(*) from (select getorcreate_country(make_standard_name(get_name_by_language(country_name.name,ARRAY['name'])), country_code) from country_name where get_name_by_language(country_name.name, ARRAY['name']) is not null) as x;\n"; echo "select count(*) from (select getorcreate_country(make_standard_name(get_name_by_language(country_name.name,ARRAY['name'])), country_code) from country_name where get_name_by_language(country_name.name, ARRAY['name']) is not null) as x;\n";
foreach($aLanguageIn as $sLanguage) foreach($aLanguageIn as $sLanguage)
{ {
echo "select count(*) from (select getorcreate_country(make_standard_name(get_name_by_language(country_name.name,ARRAY['name:".$sLanguage."'])), country_code) from country_name where get_name_by_language(country_name.name, ARRAY['name:".$sLanguage."']) is not null) as x;\n"; echo "select count(*) from (select getorcreate_country(make_standard_name(get_name_by_language(country_name.name,ARRAY['name:".$sLanguage."'])), country_code) from country_name where get_name_by_language(country_name.name, ARRAY['name:".$sLanguage."']) is not null) as x;\n";
}
}
if ($aCMDResult['wiki-import'])
{
$aPairs = array();
foreach($aLanguageIn as $sLanguage)
{
$sURL = 'http://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/'.strtoupper($sLanguage);
$sWikiPageXML = file_get_contents($sURL);
if (preg_match_all('#\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([\\-YN])#', $sWikiPageXML, $aMatches, PREG_SET_ORDER))
{
foreach($aMatches as $aMatch)
{
$sLabel = trim($aMatch[1]);
$sClass = trim($aMatch[2]);
$sType = trim($aMatch[3]);
# hack around a bug where building=yes was imported with
# quotes into the wiki
$sType = preg_replace('/&quot;/', '', $sType);
# sanity check, in case somebody added garbage in the wiki
if (preg_match('/^\\w+$/', $sClass) < 1 ||
preg_match('/^\\w+$/', $sType) < 1) {
trigger_error("Bad class/type for language $sLanguage: $sClass=$sType");
exit;
}
# blacklisting: disallow certain class/type combinations
if (isset($aTagsBlacklist[$sClass]) && in_array($sType, $aTagsBlacklist[$sClass])) {
# fwrite(STDERR, "Blacklisted: ".$sClass."/".$sType."\n");
continue;
}
# whitelisting: if class is in whitelist, allow only tags in the list
if (isset($aTagsWhitelist[$sClass]) && !in_array($sType, $aTagsWhitelist[$sClass])) {
# fwrite(STDERR, "Non-Whitelisted: ".$sClass."/".$sType."\n");
continue;
}
$aPairs[$sClass.'|'.$sType] = array($sClass, $sType);
switch(trim($aMatch[4]))
{
case 'near':
echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'near');\n";
break;
case 'in':
echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'in');\n";
break;
default:
echo "select getorcreate_amenity(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType');\n";
break;
}
}
} }
} }
if ($aCMDResult['wiki-import']) echo "create index idx_placex_classtype on placex (class, type);";
{
$aPairs = array();
foreach($aLanguageIn as $sLanguage) foreach($aPairs as $aPair)
{ {
$sURL = 'http://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/'.strtoupper($sLanguage); echo "create table place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1]);
$sWikiPageXML = file_get_contents($sURL); if (CONST_Tablespace_Aux_Data)
if (preg_match_all('#\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([\\-YN])#', $sWikiPageXML, $aMatches, PREG_SET_ORDER)) echo " tablespace ".CONST_Tablespace_Aux_Data;
{ echo " as select place_id as place_id,st_centroid(geometry) as centroid from placex where ";
foreach($aMatches as $aMatch) echo "class = '".pg_escape_string($aPair[0])."' and type = '".pg_escape_string($aPair[1])."'";
{ echo ";\n";
$sLabel = trim($aMatch[1]);
$sClass = trim($aMatch[2]);
$sType = trim($aMatch[3]);
# hack around a bug where building=yes was imported with
# quotes into the wiki
$sType = preg_replace('/&quot;/', '', $sType);
# sanity check, in case somebody added garbage in the wiki
if (preg_match('/^\\w+$/', $sClass) < 1 ||
preg_match('/^\\w+$/', $sType) < 1) {
trigger_error("Bad class/type for language $sLanguage: $sClass=$sType");
exit;
}
# blacklisting: disallow certain class/type combinations
if (isset($aTagsBlacklist[$sClass]) && in_array($sType, $aTagsBlacklist[$sClass])) {
# fwrite(STDERR, "Blacklisted: ".$sClass."/".$sType."\n");
continue;
}
# whitelisting: if class is in whitelist, allow only tags in the list
if (isset($aTagsWhitelist[$sClass]) && !in_array($sType, $aTagsWhitelist[$sClass])) {
# fwrite(STDERR, "Non-Whitelisted: ".$sClass."/".$sType."\n");
continue;
}
$aPairs[$sClass.'|'.$sType] = array($sClass, $sType);
switch(trim($aMatch[4])) echo "CREATE INDEX idx_place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])."_centroid ";
{ echo "ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])." USING GIST (centroid)";
case 'near': if (CONST_Tablespace_Aux_Index)
echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'near');\n"; echo " tablespace ".CONST_Tablespace_Aux_Index;
break; echo ";\n";
case 'in':
echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'in');\n";
break;
default:
echo "select getorcreate_amenity(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType');\n";
break;
}
}
}
}
echo "create index idx_placex_classtype on placex (class, type);"; echo "CREATE INDEX idx_place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])."_place_id ";
echo "ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])." USING btree(place_id)";
if (CONST_Tablespace_Aux_Index)
echo " tablespace ".CONST_Tablespace_Aux_Index;
echo ";\n";
foreach($aPairs as $aPair) echo "GRANT SELECT ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1]).' TO "'.CONST_Database_Web_User."\";\n";
{
echo "create table place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1]);
if (CONST_Tablespace_Aux_Data)
echo " tablespace ".CONST_Tablespace_Aux_Data;
echo " as select place_id as place_id,st_centroid(geometry) as centroid from placex where ";
echo "class = '".pg_escape_string($aPair[0])."' and type = '".pg_escape_string($aPair[1])."'";
echo ";\n";
echo "CREATE INDEX idx_place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])."_centroid "; }
echo "ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])." USING GIST (centroid)";
if (CONST_Tablespace_Aux_Index)
echo " tablespace ".CONST_Tablespace_Aux_Index;
echo ";\n";
echo "CREATE INDEX idx_place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])."_place_id "; echo "drop index idx_placex_classtype;";
echo "ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1])." USING btree(place_id)"; }
if (CONST_Tablespace_Aux_Index)
echo " tablespace ".CONST_Tablespace_Aux_Index;
echo ";\n";
echo "GRANT SELECT ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1]).' TO "'.CONST_Database_Web_User."\";\n";
}
echo "drop index idx_placex_classtype;";
}

View File

@ -1,376 +1,376 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
$aCMDOptions = array( $aCMDOptions = array(
"Import / update / index osm data", "Import / update / index osm data",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import using osmosis'), array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import using osmosis'),
array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import using osmosis forever'), array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import using osmosis forever'),
array('no-npi', '', 0, 1, 0, 0, 'bool', '(obsolate)'), array('no-npi', '', 0, 1, 0, 0, 'bool', '(obsolate)'),
array('no-index', '', 0, 1, 0, 0, 'bool', 'Do not index the new data'), array('no-index', '', 0, 1, 0, 0, 'bool', 'Do not index the new data'),
array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'), array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'),
array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'), array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'), array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'), array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'), array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'), array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'), array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'), array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'),
array('index', '', 0, 1, 0, 0, 'bool', 'Index'), array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'), array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'), array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'), array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1; if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0; if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
date_default_timezone_set('Etc/UTC'); date_default_timezone_set('Etc/UTC');
$oDB =& getDB(); $oDB =& getDB();
$aDSNInfo = DB::parseDSN(CONST_Database_DSN); $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432; if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
// cache memory to be used by osm2pgsql, should not be more than the available memory // cache memory to be used by osm2pgsql, should not be more than the available memory
$iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000); $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
if ($iCacheMemory + 500 > getTotalMemoryMB()) if ($iCacheMemory + 500 > getTotalMemoryMB())
{ {
$iCacheMemory = getCacheMemoryMB(); $iCacheMemory = getCacheMemoryMB();
echo "WARNING: resetting cache memory to $iCacheMemory\n"; echo "WARNING: resetting cache memory to $iCacheMemory\n";
} }
$sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas --number-processes 1 -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port']; $sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas --number-processes 1 -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
if (!is_null(CONST_Osm2pgsql_Flatnode_File)) if (!is_null(CONST_Osm2pgsql_Flatnode_File))
{ {
$sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File; $sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
} }
if (isset($aResult['import-diff'])) if (isset($aResult['import-diff']))
{ {
// import diff directly (e.g. from osmosis --rri) // import diff directly (e.g. from osmosis --rri)
$sNextFile = $aResult['import-diff']; $sNextFile = $aResult['import-diff'];
if (!file_exists($sNextFile)) if (!file_exists($sNextFile))
{ {
fail("Cannot open $sNextFile\n"); fail("Cannot open $sNextFile\n");
} }
// Import the file // Import the file
$sCMD = $sOsm2pgsqlCmd.' '.$sNextFile; $sCMD = $sOsm2pgsqlCmd.' '.$sNextFile;
echo $sCMD."\n"; echo $sCMD."\n";
exec($sCMD, $sJunk, $iErrorLevel); exec($sCMD, $sJunk, $iErrorLevel);
if ($iErrorLevel) if ($iErrorLevel)
{ {
fail("Error from osm2pgsql, $iErrorLevel\n"); fail("Error from osm2pgsql, $iErrorLevel\n");
} }
// Don't update the import status - we don't know what this file contains // Don't update the import status - we don't know what this file contains
} }
$sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc'; $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
$bHaveDiff = false; $bHaveDiff = false;
if (isset($aResult['import-file']) && $aResult['import-file']) if (isset($aResult['import-file']) && $aResult['import-file'])
{ {
$bHaveDiff = true; $bHaveDiff = true;
$sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile; $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
echo $sCMD."\n"; echo $sCMD."\n";
exec($sCMD, $sJunk, $iErrorLevel); exec($sCMD, $sJunk, $iErrorLevel);
if ($iErrorLevel) if ($iErrorLevel)
{ {
fail("Error converting osm to osc, osmosis returned: $iErrorLevel\n"); fail("Error converting osm to osc, osmosis returned: $iErrorLevel\n");
} }
} }
$bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api']; $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
$sContentURL = ''; $sContentURL = '';
if (isset($aResult['import-node']) && $aResult['import-node']) if (isset($aResult['import-node']) && $aResult['import-node'])
{ {
if ($bUseOSMApi) if ($bUseOSMApi)
{ {
$sContentURL = 'http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']; $sContentURL = 'http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
} }
else else
{ {
$sContentURL = 'http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;'; $sContentURL = 'http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
} }
} }
if (isset($aResult['import-way']) && $aResult['import-way']) if (isset($aResult['import-way']) && $aResult['import-way'])
{ {
if ($bUseOSMApi) if ($bUseOSMApi)
{ {
$sContentURL = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full'; $sContentURL = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
} }
else else
{ {
$sContentURL = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;'; $sContentURL = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
} }
} }
if (isset($aResult['import-relation']) && $aResult['import-relation']) if (isset($aResult['import-relation']) && $aResult['import-relation'])
{ {
if ($bUseOSMApi) if ($bUseOSMApi)
{ {
$sContentURLsModifyXMLstr = 'http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full'; $sContentURLsModifyXMLstr = 'http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
} }
else else
{ {
$sContentURL = 'http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;'; $sContentURL = 'http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;';
} }
} }
if ($sContentURL) if ($sContentURL)
{ {
$sModifyXMLstr = file_get_contents($sContentURL); $sModifyXMLstr = file_get_contents($sContentURL);
$bHaveDiff = true; $bHaveDiff = true;
$aSpec = array( $aSpec = array(
0 => array("pipe", "r"), // stdin 0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout 1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr 2 => array("pipe", "w") // stderr
); );
$sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile; $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
echo $sCMD."\n"; echo $sCMD."\n";
$hProc = proc_open($sCMD, $aSpec, $aPipes); $hProc = proc_open($sCMD, $aSpec, $aPipes);
if (!is_resource($hProc)) if (!is_resource($hProc))
{ {
fail("Error converting osm to osc, osmosis failed\n"); fail("Error converting osm to osc, osmosis failed\n");
} }
fwrite($aPipes[0], $sModifyXMLstr); fwrite($aPipes[0], $sModifyXMLstr);
fclose($aPipes[0]); fclose($aPipes[0]);
$sOut = stream_get_contents($aPipes[1]); $sOut = stream_get_contents($aPipes[1]);
if ($aResult['verbose']) echo $sOut; if ($aResult['verbose']) echo $sOut;
fclose($aPipes[1]); fclose($aPipes[1]);
$sErrors = stream_get_contents($aPipes[2]); $sErrors = stream_get_contents($aPipes[2]);
if ($aResult['verbose']) echo $sErrors; if ($aResult['verbose']) echo $sErrors;
fclose($aPipes[2]); fclose($aPipes[2]);
if ($iError = proc_close($hProc)) if ($iError = proc_close($hProc))
{ {
echo $sOut; echo $sOut;
echo $sErrors; echo $sErrors;
fail("Error converting osm to osc, osmosis returned: $iError\n"); fail("Error converting osm to osc, osmosis returned: $iError\n");
} }
} }
if ($bHaveDiff) if ($bHaveDiff)
{ {
// import generated change file // import generated change file
$sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile; $sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile;
echo $sCMD."\n"; echo $sCMD."\n";
exec($sCMD, $sJunk, $iErrorLevel); exec($sCMD, $sJunk, $iErrorLevel);
if ($iErrorLevel) if ($iErrorLevel)
{ {
fail("osm2pgsql exited with error level $iErrorLevel\n"); fail("osm2pgsql exited with error level $iErrorLevel\n");
} }
} }
if ($aResult['deduplicate']) if ($aResult['deduplicate'])
{ {
if (getPostgresVersion() < 9.3) if (getPostgresVersion() < 9.3)
{ {
fail("ERROR: deduplicate is only currently supported in postgresql 9.3"); fail("ERROR: deduplicate is only currently supported in postgresql 9.3");
} }
$oDB =& getDB(); $oDB =& getDB();
$sSQL = 'select partition from country_name order by country_code'; $sSQL = 'select partition from country_name order by country_code';
$aPartitions = chksql($oDB->getCol($sSQL)); $aPartitions = chksql($oDB->getCol($sSQL));
$aPartitions[] = 0; $aPartitions[] = 0;
$sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' ' and class is null and type is null and country_code is null group by word_token having count(*) > 1 order by word_token"; $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' ' and class is null and type is null and country_code is null group by word_token having count(*) > 1 order by word_token";
$aDuplicateTokens = chksql($oDB->getAll($sSQL)); $aDuplicateTokens = chksql($oDB->getAll($sSQL));
foreach($aDuplicateTokens as $aToken) foreach($aDuplicateTokens as $aToken)
{ {
if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue; if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
echo "Deduping ".$aToken['word_token']."\n"; echo "Deduping ".$aToken['word_token']."\n";
$sSQL = "select word_id,(select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num from word where word_token = '".$aToken['word_token']."' and class is null and type is null and country_code is null order by num desc"; $sSQL = "select word_id,(select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num from word where word_token = '".$aToken['word_token']."' and class is null and type is null and country_code is null order by num desc";
$aTokenSet = chksql($oDB->getAll($sSQL)); $aTokenSet = chksql($oDB->getAll($sSQL));
$aKeep = array_shift($aTokenSet); $aKeep = array_shift($aTokenSet);
$iKeepID = $aKeep['word_id']; $iKeepID = $aKeep['word_id'];
foreach($aTokenSet as $aRemove) foreach($aTokenSet as $aRemove)
{ {
$sSQL = "update search_name set"; $sSQL = "update search_name set";
$sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID."),"; $sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID."),";
$sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")"; $sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]"; $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
chksql($oDB->query($sSQL)); chksql($oDB->query($sSQL));
$sSQL = "update search_name set"; $sSQL = "update search_name set";
$sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")"; $sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]"; $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
chksql($oDB->query($sSQL)); chksql($oDB->query($sSQL));
$sSQL = "update location_area_country set"; $sSQL = "update location_area_country set";
$sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")"; $sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]"; $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
chksql($oDB->query($sSQL)); chksql($oDB->query($sSQL));
foreach ($aPartitions as $sPartition) foreach ($aPartitions as $sPartition)
{ {
$sSQL = "update search_name_".$sPartition." set"; $sSQL = "update search_name_".$sPartition." set";
$sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID.")"; $sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]"; $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
chksql($oDB->query($sSQL)); chksql($oDB->query($sSQL));
$sSQL = "update location_area_country set"; $sSQL = "update location_area_country set";
$sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")"; $sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]"; $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
chksql($oDB->query($sSQL)); chksql($oDB->query($sSQL));
} }
$sSQL = "delete from word where word_id = ".$aRemove['word_id']; $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
chksql($oDB->query($sSQL)); chksql($oDB->query($sSQL));
} }
} }
} }
if ($aResult['index']) if ($aResult['index'])
{ {
passthru(CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']); passthru(CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']);
} }
if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
{ {
if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) { if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
fail("Error: Update interval too low for download.geofabrik.de. Please check install documentation (http://wiki.openstreetmap.org/wiki/Nominatim/Installation#Updates)\n"); fail("Error: Update interval too low for download.geofabrik.de. Please check install documentation (http://wiki.openstreetmap.org/wiki/Nominatim/Installation#Updates)\n");
} }
$sImportFile = CONST_BasePath.'/data/osmosischange.osc'; $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
$sOsmosisConfigDirectory = CONST_InstallPath.'/settings'; $sOsmosisConfigDirectory = CONST_InstallPath.'/settings';
$sCMDDownload = CONST_Osmosis_Binary.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile; $sCMDDownload = CONST_Osmosis_Binary.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
$sCMDCheckReplicationLag = CONST_Osmosis_Binary.' -q --read-replication-lag workingDirectory='.$sOsmosisConfigDirectory; $sCMDCheckReplicationLag = CONST_Osmosis_Binary.' -q --read-replication-lag workingDirectory='.$sOsmosisConfigDirectory;
$sCMDImport = $sOsm2pgsqlCmd.' '.$sImportFile; $sCMDImport = $sOsm2pgsqlCmd.' '.$sImportFile;
$sCMDIndex = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances']; $sCMDIndex = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'];
while(true) while(true)
{ {
$fStartTime = time(); $fStartTime = time();
$iFileSize = 1001; $iFileSize = 1001;
if (!file_exists($sImportFile)) if (!file_exists($sImportFile))
{ {
// 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. ";
echo "Re-trying: ".$sCMDCheckReplicationLag." in ".CONST_Replication_Recheck_Interval." secs\n"; echo "Re-trying: ".$sCMDCheckReplicationLag." in ".CONST_Replication_Recheck_Interval." secs\n";
} }
else else
{ {
echo "."; echo ".";
} }
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";
} }
$fStartTime = time(); $fStartTime = time();
$fCMDStartTime = time(); $fCMDStartTime = time();
echo $sCMDDownload."\n"; echo $sCMDDownload."\n";
exec($sCMDDownload, $sJunk, $iErrorLevel); exec($sCMDDownload, $sJunk, $iErrorLevel);
while ($iErrorLevel > 0) while ($iErrorLevel > 0)
{ {
echo "Error: $iErrorLevel\n"; echo "Error: $iErrorLevel\n";
sleep(60); sleep(60);
echo 'Re-trying: '.$sCMDDownload."\n"; echo 'Re-trying: '.$sCMDDownload."\n";
exec($sCMDDownload, $sJunk, $iErrorLevel); exec($sCMDDownload, $sJunk, $iErrorLevel);
} }
$iFileSize = filesize($sImportFile); $iFileSize = filesize($sImportFile);
$sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory); $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')"; $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')";
var_Dump($sSQL); var_Dump($sSQL);
$oDB->query($sSQL); $oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed osmosis step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n"; echo date('Y-m-d H:i:s')." Completed osmosis step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
} }
$iFileSize = filesize($sImportFile); $iFileSize = filesize($sImportFile);
$sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory); $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
// Import the file
$fCMDStartTime = time();
echo $sCMDImport."\n";
exec($sCMDImport, $sJunk, $iErrorLevel);
if ($iErrorLevel)
{
echo "Error: $iErrorLevel\n";
exit($iErrorLevel);
}
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')";
var_Dump($sSQL);
$oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed osm2pgsql step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
// Archive for debug? // Import the file
unlink($sImportFile); $fCMDStartTime = time();
echo $sCMDImport."\n";
exec($sCMDImport, $sJunk, $iErrorLevel);
if ($iErrorLevel)
{
echo "Error: $iErrorLevel\n";
exit($iErrorLevel);
}
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')";
var_Dump($sSQL);
$oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed osm2pgsql step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
$sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory); // Archive for debug?
unlink($sImportFile);
// Index file $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
$sThisIndexCmd = $sCMDIndex;
$fCMDStartTime = time();
if (!$aResult['no-index']) // Index file
{ $sThisIndexCmd = $sCMDIndex;
echo "$sThisIndexCmd\n"; $fCMDStartTime = time();
exec($sThisIndexCmd, $sJunk, $iErrorLevel);
if ($iErrorLevel)
{
echo "Error: $iErrorLevel\n";
exit($iErrorLevel);
}
}
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')"; if (!$aResult['no-index'])
var_Dump($sSQL); {
$oDB->query($sSQL); echo "$sThisIndexCmd\n";
echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n"; exec($sThisIndexCmd, $sJunk, $iErrorLevel);
if ($iErrorLevel)
{
echo "Error: $iErrorLevel\n";
exit($iErrorLevel);
}
}
$sSQL = "update import_status set lastimportdate = '$sBatchEnd'"; $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')";
$oDB->query($sSQL); var_Dump($sSQL);
$oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
$fDuration = time() - $fStartTime; $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n"; $oDB->query($sSQL);
if (!$aResult['import-osmosis-all']) exit(0);
if ( CONST_Replication_Update_Interval > 60 ) $fDuration = time() - $fStartTime;
{ echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n";
$iSleep = max(0,(strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time())); if (!$aResult['import-osmosis-all']) exit(0);
}
else
{
$iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
}
echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
sleep($iSleep);
}
}
function getosmosistimestamp($sOsmosisConfigDirectory) if ( CONST_Replication_Update_Interval > 60 )
{ {
$sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt'); $iSleep = max(0,(strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time()));
preg_match('#timestamp=(.+)#', $sStateFile, $aResult); }
return str_replace('\:',':',$aResult[1]); else
} {
$iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
}
echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
sleep($iSleep);
}
}
function getosmosistimestamp($sOsmosisConfigDirectory)
{
$sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
return str_replace('\:',':',$aResult[1]);
}

View File

@ -1,69 +1,69 @@
#!/usr/bin/php -Cq #!/usr/bin/php -Cq
<?php <?php
require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
require_once(CONST_BasePath.'/lib/init-cmd.php'); require_once(CONST_BasePath.'/lib/init-cmd.php');
ini_set('memory_limit', '800M'); ini_set('memory_limit', '800M');
$aCMDOptions = array( $aCMDOptions = array(
"Tools to warm nominatim db", "Tools to warm nominatim db",
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'), array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'), array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'), array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('reverse-only', '', 0, 1, 0, 0, 'bool', 'Warm reverse only'), array('reverse-only', '', 0, 1, 0, 0, 'bool', 'Warm reverse only'),
array('search-only', '', 0, 1, 0, 0, 'bool', 'Warm reverse only'), array('search-only', '', 0, 1, 0, 0, 'bool', 'Warm reverse only'),
); );
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true); getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/Geocode.php'); require_once(CONST_BasePath.'/lib/Geocode.php');
require_once(CONST_BasePath.'/lib/PlaceLookup.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php');
require_once(CONST_BasePath.'/lib/ReverseGeocode.php'); require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
$oDB =& getDB(); $oDB =& getDB();
$bVerbose = $aResult['verbose']; $bVerbose = $aResult['verbose'];
if (!$aResult['search-only']) { if (!$aResult['search-only']) {
$oReverseGeocode = new ReverseGeocode($oDB); $oReverseGeocode = new ReverseGeocode($oDB);
$oReverseGeocode->setZoom(20); $oReverseGeocode->setZoom(20);
$oPlaceLookup = new PlaceLookup($oDB); $oPlaceLookup = new PlaceLookup($oDB);
$oPlaceLookup->setIncludeAddressDetails(true); $oPlaceLookup->setIncludeAddressDetails(true);
$oPlaceLookup->setLanguagePreference(array('en')); $oPlaceLookup->setLanguagePreference(array('en'));
echo "Warm reverse: "; echo "Warm reverse: ";
if ($bVerbose) echo "\n"; if ($bVerbose) echo "\n";
for($i = 0; $i < 1000; $i++) { for($i = 0; $i < 1000; $i++) {
$fLat = rand(-9000, 9000) / 100; $fLat = rand(-9000, 9000) / 100;
$fLon = rand(-18000, 18000) / 100; $fLon = rand(-18000, 18000) / 100;
if ($bVerbose) echo "$fLat, $fLon = "; if ($bVerbose) echo "$fLat, $fLon = ";
$aLookup = $oReverseGeocode->lookup($fLat, $fLon); $aLookup = $oReverseGeocode->lookup($fLat, $fLon);
if ($aLookup && $aLookup['place_id']) if ($aLookup && $aLookup['place_id'])
{ {
$aDetails = $oPlaceLookup->lookup((int)$aLookup['place_id'], $aDetails = $oPlaceLookup->lookup((int)$aLookup['place_id'],
$aLookup['type'], $aLookup['fraction']); $aLookup['type'], $aLookup['fraction']);
if ($bVerbose) echo $aDetails['langaddress']."\n"; if ($bVerbose) echo $aDetails['langaddress']."\n";
} }
else echo "."; else echo ".";
} }
echo "\n"; echo "\n";
} }
if (!$aResult['reverse-only']) { if (!$aResult['reverse-only']) {
$oGeocode =& new Geocode($oDB); $oGeocode =& new Geocode($oDB);
echo "Warm search: "; echo "Warm search: ";
if ($bVerbose) echo "\n"; if ($bVerbose) echo "\n";
$sSQL = 'select word from word where word is not null order by search_name_count desc limit 1000'; $sSQL = 'select word from word where word is not null order by search_name_count desc limit 1000';
foreach($oDB->getCol($sSQL) as $sWord) { foreach($oDB->getCol($sSQL) as $sWord) {
if ($bVerbose) echo "$sWord = "; if ($bVerbose) echo "$sWord = ";
$oGeocode->setLanguagePreference(array('en')); $oGeocode->setLanguagePreference(array('en'));
$oGeocode->setQuery($sWord); $oGeocode->setQuery($sWord);
$aSearchResults = $oGeocode->lookup(); $aSearchResults = $oGeocode->lookup();
if ($bVerbose) echo $aSearchResults[0]['langaddress']."\n"; if ($bVerbose) echo $aSearchResults[0]['langaddress']."\n";
else echo "."; else echo ".";
} }
} }

View File

@ -1,66 +1,66 @@
<?php <?php
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$sOutputFormat = 'html'; $sOutputFormat = 'html';
$oDB =& getDB(); $oDB =& getDB();
$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"; $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), $aPolygons = chksql($oDB->getAll($sSQL),
"Could not get list of deleted OSM elements."); "Could not get list of deleted OSM elements.");
if (CONST_DEBUG) if (CONST_DEBUG)
{ {
var_dump($aPolygons); var_dump($aPolygons);
exit; exit;
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"/> <meta charset="utf-8"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Nominatim Deleted Data</title> <title>Nominatim Deleted Data</title>
<meta name="description" content="List of OSM data that has been deleted" lang="en-US" /> <meta name="description" content="List of OSM data that has been deleted" lang="en-US" />
</head> </head>
<body> <body>
<style type="text/css"> <style type="text/css">
table { table {
border-width: 1px; border-width: 1px;
border-spacing: 0px; border-spacing: 0px;
border-style: solid; border-style: solid;
border-color: gray; border-color: gray;
border-collapse: collapse; border-collapse: collapse;
background-color: white; background-color: white;
margin: 10px; margin: 10px;
} }
table th { table th {
border-width: 1px; border-width: 1px;
padding: 2px; padding: 2px;
border-style: inset; border-style: inset;
border-color: gray; border-color: gray;
border-left-color: #ddd; border-left-color: #ddd;
border-right-color: #ddd; border-right-color: #ddd;
background-color: #eee; background-color: #eee;
-moz-border-radius: 0px 0px 0px 0px; -moz-border-radius: 0px 0px 0px 0px;
} }
table td { table td {
border-width: 1px; border-width: 1px;
padding: 2px; padding: 2px;
border-style: inset; border-style: inset;
border-color: gray; border-color: gray;
border-left-color: #ddd; border-left-color: #ddd;
border-right-color: #ddd; border-right-color: #ddd;
background-color: white; background-color: white;
-moz-border-radius: 0px 0px 0px 0px; -moz-border-radius: 0px 0px 0px 0px;
} }
</style> </style>
@ -68,34 +68,34 @@ table td {
<table> <table>
<?php <?php
if (!$aPolygons) exit; if (!$aPolygons) exit;
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 "</tr>"; echo "</tr>";
foreach($aPolygons as $aRow) foreach($aPolygons as $aRow)
{ {
echo "<tr>"; echo "<tr>";
foreach($aRow as $sCol => $sVal) foreach($aRow as $sCol => $sVal)
{ {
switch($sCol) switch($sCol)
{ {
case 'osm_id': case 'osm_id':
echo '<td>'.osmLink($aRow).'</td>'; echo '<td>'.osmLink($aRow).'</td>';
break; break;
case 'place_id': case 'place_id':
echo '<td>'.detailsLink($aRow).'</td>'; echo '<td>'.detailsLink($aRow).'</td>';
break; break;
default: default:
echo "<td>".($sVal?$sVal:'&nbsp;')."</td>"; echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
break; break;
} }
} }
echo "</tr>"; echo "</tr>";
} }
?> ?>
</table> </table>

View File

@ -1,164 +1,164 @@
<?php <?php
@define('CONST_ConnectionBucket_PageType', 'Details'); @define('CONST_ConnectionBucket_PageType', 'Details');
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$oParams = new ParameterParser(); $oParams = new ParameterParser();
$sOutputFormat = 'html'; $sOutputFormat = 'html';
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
$sPlaceId = $oParams->getString('place_id'); $sPlaceId = $oParams->getString('place_id');
$sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R')); $sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R'));
$iOsmId = $oParams->getInt('osmid', -1); $iOsmId = $oParams->getInt('osmid', -1);
$oDB =& getDB(); $oDB =& getDB();
if ($sOsmType && $iOsmId > 0) if ($sOsmType && $iOsmId > 0)
{ {
$sPlaceId = chksql($oDB->getOne("select place_id from placex where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by type = 'postcode' asc")); $sPlaceId = chksql($oDB->getOne("select place_id from placex where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by type = 'postcode' asc"));
// Be nice about our error messages for broken geometry // Be nice about our error messages for broken geometry
if (!$sPlaceId) if (!$sPlaceId)
{ {
$aPointDetails = chksql($oDB->getRow("select osm_type, osm_id, errormessage, class, type, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ST_AsText(prevgeometry) as prevgeom, ST_AsText(newgeometry) as newgeom from import_polygon_error where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by updated desc limit 1")); $aPointDetails = chksql($oDB->getRow("select osm_type, osm_id, errormessage, class, type, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ST_AsText(prevgeometry) as prevgeom, ST_AsText(newgeometry) as newgeom from import_polygon_error where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by updated desc limit 1"));
if (!PEAR::isError($aPointDetails) && $aPointDetails) { if (!PEAR::isError($aPointDetails) && $aPointDetails) {
if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches))
{ {
$aPointDetails['error_x'] = $aMatches[1]; $aPointDetails['error_x'] = $aMatches[1];
$aPointDetails['error_y'] = $aMatches[2]; $aPointDetails['error_y'] = $aMatches[2];
} }
else else
{ {
$aPointDetails['error_x'] = 0; $aPointDetails['error_x'] = 0;
$aPointDetails['error_y'] = 0; $aPointDetails['error_y'] = 0;
} }
include(CONST_BasePath.'/lib/template/details-error-'.$sOutputFormat.'.php'); include(CONST_BasePath.'/lib/template/details-error-'.$sOutputFormat.'.php');
exit; exit;
} }
} }
} }
if (!$sPlaceId) userError("Please select a place id"); if (!$sPlaceId) userError("Please select a place id");
$iPlaceID = (int)$sPlaceId; $iPlaceID = (int)$sPlaceId;
if (CONST_Use_US_Tiger_Data) if (CONST_Use_US_Tiger_Data)
{ {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_tiger where place_id = '.$iPlaceID)); $iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_tiger where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID; if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
} }
if (CONST_Use_Aux_Location_data) if (CONST_Use_Aux_Location_data)
{ {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_aux where place_id = '.$iPlaceID)); $iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_aux where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID; if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
} }
$hLog = logStart($oDB, 'details', $_SERVER['QUERY_STRING'], $aLangPrefOrder); $hLog = logStart($oDB, 'details', $_SERVER['QUERY_STRING'], $aLangPrefOrder);
// Get the details for this point // Get the details for this point
$sSQL = "select place_id, osm_type, osm_id, class, type, name, admin_level, housenumber, street, isin, postcode, calculated_country_code as country_code, importance, wikipedia,"; $sSQL = "select place_id, osm_type, osm_id, class, type, name, admin_level, housenumber, street, isin, postcode, calculated_country_code as country_code, importance, wikipedia,";
$sSQL .= " to_char(indexed_date, 'YYYY-MM-DD HH24:MI') as indexed_date, parent_place_id, rank_address, rank_search, get_searchrank_label(rank_search) as rank_search_label, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, "; $sSQL .= " to_char(indexed_date, 'YYYY-MM-DD HH24:MI') as indexed_date, parent_place_id, rank_address, rank_search, get_searchrank_label(rank_search) as rank_search_label, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ";
$sSQL .= " ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, "; $sSQL .= " ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, ";
//$sSQL .= " ST_Area(geometry::geography) as area, "; //$sSQL .= " ST_Area(geometry::geography) as area, ";
$sSQL .= " ST_y(centroid) as lat, ST_x(centroid) as lon,"; $sSQL .= " ST_y(centroid) as lat, ST_x(centroid) as lon,";
$sSQL .= " case when importance = 0 OR importance IS NULL then 0.75-(rank_search::float/40) else importance end as calculated_importance, "; $sSQL .= " case when importance = 0 OR importance IS NULL then 0.75-(rank_search::float/40) else importance end as calculated_importance, ";
$sSQL .= " ST_AsText(CASE WHEN ST_NPoints(geometry) > 5000 THEN ST_SimplifyPreserveTopology(geometry, 0.0001) ELSE geometry END) as outlinestring"; $sSQL .= " ST_AsText(CASE WHEN ST_NPoints(geometry) > 5000 THEN ST_SimplifyPreserveTopology(geometry, 0.0001) ELSE geometry END) as outlinestring";
$sSQL .= " from placex where place_id = $iPlaceID"; $sSQL .= " from placex where place_id = $iPlaceID";
$aPointDetails = chksql($oDB->getRow($sSQL), $aPointDetails = chksql($oDB->getRow($sSQL),
"Could not get details of place object."); "Could not get details of place object.");
$aPointDetails['localname'] = $aPointDetails['localname']?$aPointDetails['localname']:$aPointDetails['housenumber']; $aPointDetails['localname'] = $aPointDetails['localname']?$aPointDetails['localname']:$aPointDetails['housenumber'];
$aClassType = getClassTypesWithImportance(); $aClassType = getClassTypesWithImportance();
$aPointDetails['icon'] = $aClassType[$aPointDetails['class'].':'.$aPointDetails['type']]['icon']; $aPointDetails['icon'] = $aClassType[$aPointDetails['class'].':'.$aPointDetails['type']]['icon'];
// Get all alternative names (languages, etc) // Get all alternative names (languages, etc)
$sSQL = "select (each(name)).key,(each(name)).value from placex where place_id = $iPlaceID order by (each(name)).key"; $sSQL = "select (each(name)).key,(each(name)).value from placex where place_id = $iPlaceID order by (each(name)).key";
$aPointDetails['aNames'] = $oDB->getAssoc($sSQL); $aPointDetails['aNames'] = $oDB->getAssoc($sSQL);
if (PEAR::isError($aPointDetails['aNames'])) // possible timeout if (PEAR::isError($aPointDetails['aNames'])) // possible timeout
{ {
$aPointDetails['aNames'] = []; $aPointDetails['aNames'] = [];
} }
// Extra tags // Extra tags
$sSQL = "select (each(extratags)).key,(each(extratags)).value from placex where place_id = $iPlaceID order by (each(extratags)).key"; $sSQL = "select (each(extratags)).key,(each(extratags)).value from placex where place_id = $iPlaceID order by (each(extratags)).key";
$aPointDetails['aExtraTags'] = $oDB->getAssoc($sSQL); $aPointDetails['aExtraTags'] = $oDB->getAssoc($sSQL);
if (PEAR::isError($aPointDetails['aExtraTags'])) // possible timeout if (PEAR::isError($aPointDetails['aExtraTags'])) // possible timeout
{ {
$aPointDetails['aExtraTags'] = []; $aPointDetails['aExtraTags'] = [];
} }
// Address // Address
$aAddressLines = getAddressDetails($oDB, $sLanguagePrefArraySQL, $iPlaceID, $aPointDetails['country_code'], -1, true); $aAddressLines = getAddressDetails($oDB, $sLanguagePrefArraySQL, $iPlaceID, $aPointDetails['country_code'], -1, true);
// Linked places // Linked places
$sSQL = "select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, ST_Distance_Spheroid(geometry, placegeometry, 'SPHEROID[\"WGS 84\",6378137,298.257223563, AUTHORITY[\"EPSG\",\"7030\"]]') as distance, "; $sSQL = "select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, ST_Distance_Spheroid(geometry, placegeometry, 'SPHEROID[\"WGS 84\",6378137,298.257223563, AUTHORITY[\"EPSG\",\"7030\"]]') as distance, ";
$sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength "; $sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength ";
$sSQL .= " from placex, (select centroid as placegeometry from placex where place_id = $iPlaceID) as x"; $sSQL .= " from placex, (select centroid as placegeometry from placex where place_id = $iPlaceID) as x";
$sSQL .= " where linked_place_id = $iPlaceID"; $sSQL .= " where linked_place_id = $iPlaceID";
$sSQL .= " order by rank_address asc,rank_search asc,get_name_by_language(name,$sLanguagePrefArraySQL),housenumber"; $sSQL .= " order by rank_address asc,rank_search asc,get_name_by_language(name,$sLanguagePrefArraySQL),housenumber";
$aLinkedLines = $oDB->getAll($sSQL); $aLinkedLines = $oDB->getAll($sSQL);
if (PEAR::isError($aLinkedLines)) // possible timeout if (PEAR::isError($aLinkedLines)) // possible timeout
{ {
$aLinkedLines = []; $aLinkedLines = [];
} }
// All places this is an imediate parent of // All places this is an imediate parent of
$sSQL = "select obj.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, ST_Distance_Spheroid(geometry, placegeometry, 'SPHEROID[\"WGS 84\",6378137,298.257223563, AUTHORITY[\"EPSG\",\"7030\"]]') as distance, "; $sSQL = "select obj.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, ST_Distance_Spheroid(geometry, placegeometry, 'SPHEROID[\"WGS 84\",6378137,298.257223563, AUTHORITY[\"EPSG\",\"7030\"]]') as distance, ";
$sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength "; $sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength ";
$sSQL .= " from (select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, geometry, name from placex "; $sSQL .= " from (select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, geometry, name from placex ";
$sSQL .= " where parent_place_id = $iPlaceID order by rank_address asc,rank_search asc limit 500) as obj,"; $sSQL .= " where parent_place_id = $iPlaceID order by rank_address asc,rank_search asc limit 500) as obj,";
$sSQL .= " (select centroid as placegeometry from placex where place_id = $iPlaceID) as x"; $sSQL .= " (select centroid as placegeometry from placex where place_id = $iPlaceID) as x";
$sSQL .= " order by rank_address asc,rank_search asc,localname,housenumber"; $sSQL .= " order by rank_address asc,rank_search asc,localname,housenumber";
$aParentOfLines = $oDB->getAll($sSQL); $aParentOfLines = $oDB->getAll($sSQL);
if (PEAR::isError($aParentOfLines)) // possible timeout if (PEAR::isError($aParentOfLines)) // possible timeout
{ {
$aParentOfLines = []; $aParentOfLines = [];
} }
$aPlaceSearchNameKeywords = false; $aPlaceSearchNameKeywords = false;
$aPlaceSearchAddressKeywords = false; $aPlaceSearchAddressKeywords = false;
if ($oParams->getBool('keywords')) if ($oParams->getBool('keywords'))
{ {
$sSQL = "select * from search_name where place_id = $iPlaceID"; $sSQL = "select * from search_name where place_id = $iPlaceID";
$aPlaceSearchName = $oDB->getRow($sSQL); $aPlaceSearchName = $oDB->getRow($sSQL);
if (PEAR::isError($aPlaceSearchName)) // possible timeout if (PEAR::isError($aPlaceSearchName)) // possible timeout
{ {
$aPlaceSearchName = []; $aPlaceSearchName = [];
} }
$sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['name_vector'],1,-1).")"; $sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['name_vector'],1,-1).")";
$aPlaceSearchNameKeywords = $oDB->getAll($sSQL); $aPlaceSearchNameKeywords = $oDB->getAll($sSQL);
if (PEAR::isError($aPlaceSearchNameKeywords)) // possible timeout if (PEAR::isError($aPlaceSearchNameKeywords)) // possible timeout
{ {
$aPlaceSearchNameKeywords = []; $aPlaceSearchNameKeywords = [];
} }
$sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['nameaddress_vector'],1,-1).")"; $sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['nameaddress_vector'],1,-1).")";
$aPlaceSearchAddressKeywords = $oDB->getAll($sSQL); $aPlaceSearchAddressKeywords = $oDB->getAll($sSQL);
if (PEAR::isError($aPlaceSearchAddressKeywords)) // possible timeout if (PEAR::isError($aPlaceSearchAddressKeywords)) // possible timeout
{ {
$aPlaceSearchAddressKeywords = []; $aPlaceSearchAddressKeywords = [];
} }
} }
logEnd($oDB, $hLog, 1); logEnd($oDB, $hLog, 1);
if ($sOutputFormat=='html') if ($sOutputFormat=='html')
{ {
$sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1")); $sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1"));
$sTileURL = CONST_Map_Tile_URL; $sTileURL = CONST_Map_Tile_URL;
$sTileAttribution = CONST_Map_Tile_Attribution; $sTileAttribution = CONST_Map_Tile_Attribution;
} }
include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php'); include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php');

View File

@ -1,149 +1,149 @@
<?php <?php
@define('CONST_ConnectionBucket_PageType', 'Details'); @define('CONST_ConnectionBucket_PageType', 'Details');
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/PlaceLookup.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$oParams = new ParameterParser(); $oParams = new ParameterParser();
$sOutputFormat = $oParams->getSet('format', array('html', 'json'), 'html'); $sOutputFormat = $oParams->getSet('format', array('html', 'json'), 'html');
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
$sPlaceId = $oParams->getString('place_id'); $sPlaceId = $oParams->getString('place_id');
$sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R')); $sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R'));
$iOsmId = $oParams->getInt('osmid', -1); $iOsmId = $oParams->getInt('osmid', -1);
$oDB =& getDB(); $oDB =& getDB();
if ($sOsmType && $iOsmId > 0) if ($sOsmType && $iOsmId > 0)
{ {
$sPlaceId = chksql($oDB->getOne("select place_id from placex where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by type = 'postcode' asc")); $sPlaceId = chksql($oDB->getOne("select place_id from placex where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by type = 'postcode' asc"));
// Be nice about our error messages for broken geometry // Be nice about our error messages for broken geometry
if (!$sPlaceId) if (!$sPlaceId)
{ {
$aPointDetails = chksql($oDB->getRow("select osm_type, osm_id, errormessage, class, type, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ST_AsText(prevgeometry) as prevgeom, ST_AsText(newgeometry) as newgeom from import_polygon_error where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by updated desc limit 1")); $aPointDetails = chksql($oDB->getRow("select osm_type, osm_id, errormessage, class, type, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ST_AsText(prevgeometry) as prevgeom, ST_AsText(newgeometry) as newgeom from import_polygon_error where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by updated desc limit 1"));
if ($aPointDetails) { if ($aPointDetails) {
if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches))
{ {
$aPointDetails['error_x'] = $aMatches[1]; $aPointDetails['error_x'] = $aMatches[1];
$aPointDetails['error_y'] = $aMatches[2]; $aPointDetails['error_y'] = $aMatches[2];
} }
include(CONST_BasePath.'/lib/template/details-error-'.$sOutputFormat.'.php'); include(CONST_BasePath.'/lib/template/details-error-'.$sOutputFormat.'.php');
exit; exit;
} }
} }
} }
if (!$sPlaceId) userError("Please select a place id"); if (!$sPlaceId) userError("Please select a place id");
$iPlaceID = (int)$sPlaceId; $iPlaceID = (int)$sPlaceId;
if (CONST_Use_US_Tiger_Data) if (CONST_Use_US_Tiger_Data)
{ {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_tiger where place_id = '.$iPlaceID)); $iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_tiger where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID; if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
} }
if (CONST_Use_Aux_Location_data) if (CONST_Use_Aux_Location_data)
{ {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_aux where place_id = '.$iPlaceID)); $iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_aux where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID; if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
} }
$oPlaceLookup = new PlaceLookup($oDB); $oPlaceLookup = new PlaceLookup($oDB);
$oPlaceLookup->setLanguagePreference($aLangPrefOrder); $oPlaceLookup->setLanguagePreference($aLangPrefOrder);
$oPlaceLookup->setIncludeAddressDetails(true); $oPlaceLookup->setIncludeAddressDetails(true);
$aPlaceAddress = array_reverse($oPlaceLookup->getAddressDetails($iPlaceID)); $aPlaceAddress = array_reverse($oPlaceLookup->getAddressDetails($iPlaceID));
if (!sizeof($aPlaceAddress)) userError("Unknown place id."); if (!sizeof($aPlaceAddress)) userError("Unknown place id.");
$aBreadcrums = array(); $aBreadcrums = array();
foreach($aPlaceAddress as $i => $aPlace) foreach($aPlaceAddress as $i => $aPlace)
{ {
if (!$aPlace['place_id']) continue; if (!$aPlace['place_id']) continue;
$aBreadcrums[] = array('placeId' => $aPlace['place_id'], $aBreadcrums[] = array('placeId' => $aPlace['place_id'],
'osmType' => $aPlace['osm_type'], 'osmType' => $aPlace['osm_type'],
'osmId' => $aPlace['osm_id'], 'osmId' => $aPlace['osm_id'],
'localName' => $aPlace['localname']); 'localName' => $aPlace['localname']);
if ($sOutputFormat == 'html') if ($sOutputFormat == 'html')
{ {
$sPlaceUrl = 'hierarchy.php?place_id='.$aPlace['place_id']; $sPlaceUrl = 'hierarchy.php?place_id='.$aPlace['place_id'];
if ($i) echo " &gt; "; if ($i) echo " &gt; ";
echo '<a href="'.$sPlaceUrl.'">'.$aPlace['localname'].'</a> ('.osmLink($aPlace).')'; echo '<a href="'.$sPlaceUrl.'">'.$aPlace['localname'].'</a> ('.osmLink($aPlace).')';
} }
} }
if ($sOutputFormat == 'json') if ($sOutputFormat == 'json')
{ {
header("content-type: application/json; charset=UTF-8"); header("content-type: application/json; charset=UTF-8");
$aDetails = array(); $aDetails = array();
$aDetails['breadcrumbs'] = $aBreadcrums; $aDetails['breadcrumbs'] = $aBreadcrums;
javascript_renderData($aDetails); javascript_renderData($aDetails);
exit; exit;
} }
$aRelatedPlaceIDs = chksql($oDB->getCol($sSQL = "select place_id from placex where linked_place_id = $iPlaceID or place_id = $iPlaceID")); $aRelatedPlaceIDs = chksql($oDB->getCol($sSQL = "select place_id from placex where linked_place_id = $iPlaceID or place_id = $iPlaceID"));
$sSQL = "select obj.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, st_area(geometry) as area, "; $sSQL = "select obj.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, st_area(geometry) as area, ";
$sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength "; $sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength ";
$sSQL .= " from (select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, geometry, name from placex "; $sSQL .= " from (select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, geometry, name from placex ";
$sSQL .= " where parent_place_id in (".join(',',$aRelatedPlaceIDs).") and name is not null order by rank_address asc,rank_search asc limit 500) as obj"; $sSQL .= " where parent_place_id in (".join(',',$aRelatedPlaceIDs).") and name is not null order by rank_address asc,rank_search asc limit 500) as obj";
$sSQL .= " order by rank_address asc,rank_search asc,localname,class, type,housenumber"; $sSQL .= " order by rank_address asc,rank_search asc,localname,class, type,housenumber";
$aParentOfLines = chksql($oDB->getAll($sSQL)); $aParentOfLines = chksql($oDB->getAll($sSQL));
if (sizeof($aParentOfLines)) if (sizeof($aParentOfLines))
{ {
echo '<h2>Parent Of:</h2>'; echo '<h2>Parent Of:</h2>';
$aClassType = getClassTypesWithImportance(); $aClassType = getClassTypesWithImportance();
$aGroupedAddressLines = array(); $aGroupedAddressLines = array();
foreach($aParentOfLines as $aAddressLine) foreach($aParentOfLines as $aAddressLine)
{ {
if (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']) if (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'])
&& $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']) && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'])
{ {
$aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']; $aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'];
} }
elseif (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']) elseif (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'])
&& $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']) && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'])
{ {
$aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']; $aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'];
} }
else $aAddressLine['label'] = ucwords($aAddressLine['type']); else $aAddressLine['label'] = ucwords($aAddressLine['type']);
if (!isset($aGroupedAddressLines[$aAddressLine['label']])) $aGroupedAddressLines[$aAddressLine['label']] = array(); if (!isset($aGroupedAddressLines[$aAddressLine['label']])) $aGroupedAddressLines[$aAddressLine['label']] = array();
$aGroupedAddressLines[$aAddressLine['label']][] = $aAddressLine; $aGroupedAddressLines[$aAddressLine['label']][] = $aAddressLine;
} }
foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines) foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines)
{ {
echo "<h3>$sGroupHeading</h3>"; echo "<h3>$sGroupHeading</h3>";
foreach($aParentOfLines as $aAddressLine) foreach($aParentOfLines as $aAddressLine)
{ {
$aAddressLine['localname'] = $aAddressLine['localname']?$aAddressLine['localname']:$aAddressLine['housenumber']; $aAddressLine['localname'] = $aAddressLine['localname']?$aAddressLine['localname']:$aAddressLine['housenumber'];
$sOSMType = formatOSMType($aAddressLine['osm_type'], false); $sOSMType = formatOSMType($aAddressLine['osm_type'], false);
echo '<div class="line">'; echo '<div class="line">';
echo '<span class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>').'</span>'; echo '<span class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>').'</span>';
echo ' ('; echo ' (';
echo '<span class="area">'.($aAddressLine['isarea']=='t'?'Polygon':'Point').'</span>'; echo '<span class="area">'.($aAddressLine['isarea']=='t'?'Polygon':'Point').'</span>';
if ($sOSMType) echo ', <span class="osm"><span class="label"></span>'.$sOSMType.' '.osmLink($aAddressLine).'</span>'; if ($sOSMType) echo ', <span class="osm"><span class="label"></span>'.$sOSMType.' '.osmLink($aAddressLine).'</span>';
echo ', <a href="hierarchy.php?place_id='.$aAddressLine['place_id'].'">GOTO</a>'; echo ', <a href="hierarchy.php?place_id='.$aAddressLine['place_id'].'">GOTO</a>';
echo ', '.$aAddressLine['area']; echo ', '.$aAddressLine['area'];
echo ')'; echo ')';
echo '</div>'; echo '</div>';
} }
} }
if (sizeof($aParentOfLines) >= 500) { if (sizeof($aParentOfLines) >= 500) {
echo '<p>There are more child objects which are not shown.</p>'; echo '<p>There are more child objects which are not shown.</p>';
} }
echo '</div>'; echo '</div>';
} }

View File

@ -3,201 +3,201 @@ var last_click_latlng;
jQuery(document).on('ready', function(){ jQuery(document).on('ready', function(){
if ( !$('#search-page,#reverse-page').length ){ return; } if ( !$('#search-page,#reverse-page').length ){ return; }
var is_reverse_search = !!( $('#reverse-page').length ); var is_reverse_search = !!( $('#reverse-page').length );
$('#q').focus(); $('#q').focus();
map = new L.map('map', { map = new L.map('map', {
attributionControl: (nominatim_map_init.tile_attribution && nominatim_map_init.tile_attribution.length), attributionControl: (nominatim_map_init.tile_attribution && nominatim_map_init.tile_attribution.length),
scrollWheelZoom: !L.Browser.touch, scrollWheelZoom: !L.Browser.touch,
touchZoom: false touchZoom: false
}); });
L.tileLayer(nominatim_map_init.tile_url, { L.tileLayer(nominatim_map_init.tile_url, {
noWrap: true, // otherwise we end up with click coordinates like latitude -728 noWrap: true, // otherwise we end up with click coordinates like latitude -728
// moved to footer // moved to footer
attribution: (nominatim_map_init.tile_attribution || null ) //'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' attribution: (nominatim_map_init.tile_attribution || null ) //'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map); }).addTo(map);
map.setView([nominatim_map_init.lat, nominatim_map_init.lon], nominatim_map_init.zoom); map.setView([nominatim_map_init.lat, nominatim_map_init.lon], nominatim_map_init.zoom);
if ( is_reverse_search ){ if ( is_reverse_search ){
// We don't need a marker, but an L.circle instance changes radius once you zoom in/out // We don't need a marker, but an L.circle instance changes radius once you zoom in/out
var cm = L.circleMarker([nominatim_map_init.lat,nominatim_map_init.lon], { radius: 5, weight: 2, fillColor: '#ff7800', color: 'red', opacity: 0.75, clickable: false}); var cm = L.circleMarker([nominatim_map_init.lat,nominatim_map_init.lon], { radius: 5, weight: 2, fillColor: '#ff7800', color: 'red', opacity: 0.75, clickable: false});
cm.addTo(map); cm.addTo(map);
} }
var MapPositionControl = L.Control.extend({ var MapPositionControl = L.Control.extend({
options: { options: {
position: 'topright' position: 'topright'
}, },
onAdd: function (map) { onAdd: function (map) {
var container = L.DomUtil.create('div', 'my-custom-control'); var container = L.DomUtil.create('div', 'my-custom-control');
$(container).text('show map bounds').addClass('leaflet-bar btn btn-sm btn-default').on('click', function(e){ $(container).text('show map bounds').addClass('leaflet-bar btn btn-sm btn-default').on('click', function(e){
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
$('#map-position').show(); $('#map-position').show();
$(container).hide(); $(container).hide();
}); });
$('#map-position-close a').on('click', function(e){ $('#map-position-close a').on('click', function(e){
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
$('#map-position').hide(); $('#map-position').hide();
$(container).show(); $(container).show();
}); });
return container; return container;
} }
}); });
map.addControl(new MapPositionControl()); map.addControl(new MapPositionControl());
function display_map_position(mouse_lat_lng){ function display_map_position(mouse_lat_lng){
html_mouse = "mouse position " + (mouse_lat_lng ? [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',') : '-'); html_mouse = "mouse position " + (mouse_lat_lng ? [mouse_lat_lng.lat.toFixed(5), mouse_lat_lng.lng.toFixed(5)].join(',') : '-');
html_click = "last click: " + (last_click_latlng ? [last_click_latlng.lat.toFixed(5),last_click_latlng.lng.toFixed(5)].join(',') : '-'); html_click = "last click: " + (last_click_latlng ? [last_click_latlng.lat.toFixed(5),last_click_latlng.lng.toFixed(5)].join(',') : '-');
html_center = html_center =
"map center: " + "map center: " +
map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5) + map.getCenter().lat.toFixed(5) + ',' + map.getCenter().lng.toFixed(5) +
" <a target='_blank' href='" + map_link_to_osm() + "'>view on osm.org</a>"; " <a target='_blank' href='" + map_link_to_osm() + "'>view on osm.org</a>";
html_zoom = "map zoom: " + map.getZoom(); html_zoom = "map zoom: " + map.getZoom();
html_viewbox = "viewbox: " + map_viewbox_as_string(); html_viewbox = "viewbox: " + map_viewbox_as_string();
$('#map-position-inner').html([html_center,html_zoom,html_viewbox,html_click,html_mouse].join('<br/>')); $('#map-position-inner').html([html_center,html_zoom,html_viewbox,html_click,html_mouse].join('<br/>'));
$('input#use_viewbox').trigger('change'); $('input#use_viewbox').trigger('change');
} }
map.on('move', function(e) { map.on('move', function(e) {
display_map_position(); display_map_position();
}); });
map.on('mousemove', function(e) { map.on('mousemove', function(e) {
display_map_position(e.latlng); display_map_position(e.latlng);
}); });
map.on('click', function(e) { map.on('click', function(e) {
last_click_latlng = e.latlng; last_click_latlng = e.latlng;
display_map_position(); display_map_position();
}); });
map.on('load', function(e){ map.on('load', function(e){
display_map_position(); display_map_position();
}); });
$('input#use_viewbox').on('change', function(){ $('input#use_viewbox').on('change', function(){
$('input[name=viewbox]').val( $(this).prop('checked') ? map_viewbox_as_string() : ''); $('input[name=viewbox]').val( $(this).prop('checked') ? map_viewbox_as_string() : '');
}); });
function map_viewbox_as_string() { function map_viewbox_as_string() {
// since .toBBoxString() doesn't round numbers // since .toBBoxString() doesn't round numbers
return [ return [
map.getBounds().getSouthWest().lat.toFixed(5), map.getBounds().getSouthWest().lat.toFixed(5),
map.getBounds().getSouthWest().lng.toFixed(5), map.getBounds().getSouthWest().lng.toFixed(5),
map.getBounds().getNorthEast().lat.toFixed(5), map.getBounds().getNorthEast().lat.toFixed(5),
map.getBounds().getNorthEast().lng.toFixed(5) ].join(','); map.getBounds().getNorthEast().lng.toFixed(5) ].join(',');
} }
function map_link_to_osm(){ function map_link_to_osm(){
return "http://openstreetmap.org/#map=" + map.getZoom() + "/" + map.getCenter().lat + "/" + map.getCenter().lng; return "http://openstreetmap.org/#map=" + map.getZoom() + "/" + map.getCenter().lat + "/" + map.getCenter().lng;
} }
function get_result_element(position){ function get_result_element(position){
return $('.result').eq(position); return $('.result').eq(position);
} }
function marker_for_result(result){ function marker_for_result(result){
return L.marker([result.lat,result.lon], {riseOnHover:true,title:result.name }); return L.marker([result.lat,result.lon], {riseOnHover:true,title:result.name });
} }
function circle_for_result(result){ function circle_for_result(result){
return L.circleMarker([result.lat,result.lon], { radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75, clickable: !is_reverse_search}); return L.circleMarker([result.lat,result.lon], { radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75, clickable: !is_reverse_search});
} }
var layerGroup = new L.layerGroup().addTo(map); var layerGroup = new L.layerGroup().addTo(map);
function highlight_result(position, bool_focus){ function highlight_result(position, bool_focus){
var result = nominatim_results[position]; var result = nominatim_results[position];
if (!result){ return } if (!result){ return }
var result_el = get_result_element(position); var result_el = get_result_element(position);
$('.result').removeClass('highlight'); $('.result').removeClass('highlight');
result_el.addClass('highlight'); result_el.addClass('highlight');
layerGroup.clearLayers(); layerGroup.clearLayers();
if (result.lat){ if (result.lat){
var circle = circle_for_result(result); var circle = circle_for_result(result);
circle.on('click', function(){ circle.on('click', function(){
highlight_result(position); highlight_result(position);
}); });
layerGroup.addLayer(circle); layerGroup.addLayer(circle);
} }
if (result.aBoundingBox){ if (result.aBoundingBox){
var bounds = [[result.aBoundingBox[0]*1,result.aBoundingBox[2]*1], [result.aBoundingBox[1]*1,result.aBoundingBox[3]*1]]; var bounds = [[result.aBoundingBox[0]*1,result.aBoundingBox[2]*1], [result.aBoundingBox[1]*1,result.aBoundingBox[3]*1]];
map.fitBounds(bounds); map.fitBounds(bounds);
if (result.astext && result.astext.match(/(POLY)|(LINE)/) ){ if (result.astext && result.astext.match(/(POLY)|(LINE)/) ){
var geojson_layer = L.geoJson(null, { var geojson_layer = L.geoJson(null, {
// http://leafletjs.com/reference.html#geojson-style // http://leafletjs.com/reference.html#geojson-style
style: function(feature) { return { clickable: false, color: 'blue' }; } style: function(feature) { return { clickable: false, color: 'blue' }; }
}); });
omnivore.wkt.parse(result.astext,null,geojson_layer); omnivore.wkt.parse(result.astext,null,geojson_layer);
layerGroup.addLayer(geojson_layer); layerGroup.addLayer(geojson_layer);
} }
else { else {
// var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} ); // var layer = L.rectangle(bounds, {color: "#ff7800", weight: 1} );
// layerGroup.addLayer(layer); // layerGroup.addLayer(layer);
} }
} }
else { else {
if ( is_reverse_search ){ if ( is_reverse_search ){
// make sure the search coordinates are in the map view as well // make sure the search coordinates are in the map view as well
map.fitBounds([[result.lat,result.lon], [nominatim_map_init.lat,nominatim_map_init.lon]], {padding: [50,50], maxZoom: map.getZoom()}); map.fitBounds([[result.lat,result.lon], [nominatim_map_init.lat,nominatim_map_init.lon]], {padding: [50,50], maxZoom: map.getZoom()});
// better, but causes a leaflet warning // better, but causes a leaflet warning
// map.panInsideBounds([[result.lat,result.lon], [nominatim_map_init.lat,nominatim_map_init.lon]], {animate: false}); // map.panInsideBounds([[result.lat,result.lon], [nominatim_map_init.lat,nominatim_map_init.lon]], {animate: false});
} }
else { else {
map.panTo([result.lat,result.lon], result.zoom || nominatim_map_init.zoom); map.panTo([result.lat,result.lon], result.zoom || nominatim_map_init.zoom);
} }
} }
// var crosshairIcon = L.icon({ // var crosshairIcon = L.icon({
// iconUrl: 'images/crosshair.png', // iconUrl: 'images/crosshair.png',
// iconSize: [12, 12], // iconSize: [12, 12],
// iconAnchor: [6, 6], // iconAnchor: [6, 6],
// }); // });
// var crossMarker = new L.Marker([result.lat,result.lon], { icon: crosshairIcon, clickable: false}); // var crossMarker = new L.Marker([result.lat,result.lon], { icon: crosshairIcon, clickable: false});
// layerGroup.addLayer(crossMarker); // layerGroup.addLayer(crossMarker);
if (bool_focus){ if (bool_focus){
$('#map').focus(); $('#map').focus();
} }
} }
$('.result').on('click', function(e){ $('.result').on('click', function(e){
highlight_result($(this).data('position'), true); highlight_result($(this).data('position'), true);
}); });
if ( is_reverse_search ){ if ( is_reverse_search ){
map.on('click', function(e){ map.on('click', function(e){
$('form input[name=lat]').val( e.latlng.lat); $('form input[name=lat]').val( e.latlng.lat);
$('form input[name=lon]').val( e.latlng.lng); $('form input[name=lon]').val( e.latlng.lng);
$('form').submit(); $('form').submit();
}); });
} }
highlight_result(0, false); highlight_result(0, false);
}); });
@ -205,41 +205,41 @@ jQuery(document).on('ready', function(){
jQuery(document).on('ready', function(){ jQuery(document).on('ready', function(){
if ( !$('#details-page').length ){ return; } if ( !$('#details-page').length ){ return; }
map = new L.map('map', { map = new L.map('map', {
// center: [nominatim_map_init.lat, nominatim_map_init.lon], // center: [nominatim_map_init.lat, nominatim_map_init.lon],
// zoom: nominatim_map_init.zoom, // zoom: nominatim_map_init.zoom,
attributionControl: (nominatim_map_init.tile_attribution && nominatim_map_init.tile_attribution.length), attributionControl: (nominatim_map_init.tile_attribution && nominatim_map_init.tile_attribution.length),
scrollWheelZoom: false, scrollWheelZoom: false,
touchZoom: false, touchZoom: false,
}); });
L.tileLayer(nominatim_map_init.tile_url, { L.tileLayer(nominatim_map_init.tile_url, {
// moved to footer // moved to footer
attribution: (nominatim_map_init.tile_attribution || null ) //'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' attribution: (nominatim_map_init.tile_attribution || null ) //'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map); }).addTo(map);
var layerGroup = new L.layerGroup().addTo(map); var layerGroup = new L.layerGroup().addTo(map);
var circle = L.circleMarker([nominatim_result.lat,nominatim_result.lon], { radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75}); var circle = L.circleMarker([nominatim_result.lat,nominatim_result.lon], { radius: 10, weight: 2, fillColor: '#ff7800', color: 'blue', opacity: 0.75});
map.addLayer(circle); map.addLayer(circle);
if ( nominatim_result.outlinestring ){ if ( nominatim_result.outlinestring ){
var geojson_layer = L.geoJson(null, { var geojson_layer = L.geoJson(null, {
// http://leafletjs.com/reference.html#geojson-style // http://leafletjs.com/reference.html#geojson-style
style: function(feature) { return { clickable: false, color: 'blue' }; } style: function(feature) { return { clickable: false, color: 'blue' }; }
}); });
omnivore.wkt.parse(nominatim_result.outlinestring,null,geojson_layer); omnivore.wkt.parse(nominatim_result.outlinestring,null,geojson_layer);
layerGroup.addLayer(geojson_layer); layerGroup.addLayer(geojson_layer);
map.fitBounds(geojson_layer.getBounds()); map.fitBounds(geojson_layer.getBounds());
} else { } else {
map.setView([nominatim_result.lat,nominatim_result.lon],10); map.setView([nominatim_result.lat,nominatim_result.lon],10);
} }

View File

@ -1,5 +1,5 @@
div.olMap { div.olMap {
z-index: 0; z-index: 0;
padding: 0px!important; padding: 0px!important;
margin: 0px!important; margin: 0px!important;
cursor: default; cursor: default;

View File

@ -1,75 +1,75 @@
<?php <?php
@define('CONST_ConnectionBucket_PageType', 'Reverse'); @define('CONST_ConnectionBucket_PageType', 'Reverse');
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/PlaceLookup.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$oParams = new ParameterParser(); $oParams = new ParameterParser();
// Format for output // Format for output
$sOutputFormat = $oParams->getSet('format', array('xml', 'json'), 'xml'); $sOutputFormat = $oParams->getSet('format', array('xml', 'json'), 'xml');
// Preferred language // Preferred language
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$oDB =& getDB(); $oDB =& getDB();
$hLog = logStart($oDB, 'place', $_SERVER['QUERY_STRING'], $aLangPrefOrder); $hLog = logStart($oDB, 'place', $_SERVER['QUERY_STRING'], $aLangPrefOrder);
$aSearchResults = array(); $aSearchResults = array();
$aCleanedQueryParts = array(); $aCleanedQueryParts = array();
$oPlaceLookup = new PlaceLookup($oDB); $oPlaceLookup = new PlaceLookup($oDB);
$oPlaceLookup->setLanguagePreference($aLangPrefOrder); $oPlaceLookup->setLanguagePreference($aLangPrefOrder);
$oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', true)); $oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', true));
$oPlaceLookup->setIncludeExtraTags($oParams->getBool('extratags', false)); $oPlaceLookup->setIncludeExtraTags($oParams->getBool('extratags', false));
$oPlaceLookup->setIncludeNameDetails($oParams->getBool('namedetails', false)); $oPlaceLookup->setIncludeNameDetails($oParams->getBool('namedetails', false));
$aOsmIds = explode(',', $oParams->getString('osm_ids', '')); $aOsmIds = explode(',', $oParams->getString('osm_ids', ''));
if (count($aOsmIds) > CONST_Places_Max_ID_count) 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;
$sType = $sItem[0]; $sType = $sItem[0];
$iId = (int) substr($sItem, 1); $iId = (int) substr($sItem, 1);
if ( $iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R') ) if ( $iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R') )
{ {
$aCleanedQueryParts[] = $sType . $iId; $aCleanedQueryParts[] = $sType . $iId;
$oPlace = $oPlaceLookup->lookupOSMID($sType, $iId); $oPlace = $oPlaceLookup->lookupOSMID($sType, $iId);
if ($oPlace){ if ($oPlace){
// we want to use the search-* output templates, so we need to fill // we want to use the search-* output templates, so we need to fill
// $aSearchResults and slightly change the (reverse search) oPlace // $aSearchResults and slightly change the (reverse search) oPlace
// key names // key names
$oResult = $oPlace; $oResult = $oPlace;
unset($oResult['aAddress']); unset($oResult['aAddress']);
if (isset($oPlace['aAddress'])) $oResult['address'] = $oPlace['aAddress']; if (isset($oPlace['aAddress'])) $oResult['address'] = $oPlace['aAddress'];
unset($oResult['langaddress']); unset($oResult['langaddress']);
$oResult['name'] = $oPlace['langaddress']; $oResult['name'] = $oPlace['langaddress'];
$aSearchResults[] = $oResult; $aSearchResults[] = $oResult;
} }
} }
} }
if (CONST_Debug) exit; if (CONST_Debug) exit;
$sXmlRootTag = 'lookupresults'; $sXmlRootTag = 'lookupresults';
$sQuery = join(',',$aCleanedQueryParts); $sQuery = join(',',$aCleanedQueryParts);
// we initialize these to avoid warnings in our logfile // we initialize these to avoid warnings in our logfile
$sViewBox = ''; $sViewBox = '';
$bShowPolygons = ''; $bShowPolygons = '';
$aExcludePlaceIDs = []; $aExcludePlaceIDs = [];
$sMoreURL = ''; $sMoreURL = '';
include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php'); include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');

View File

@ -1,143 +1,143 @@
<?php <?php
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$oParams = new ParameterParser(); $oParams = new ParameterParser();
$sOutputFormat = 'html'; $sOutputFormat = 'html';
$iDays = $oParams->getInt('days', 1); $iDays = $oParams->getInt('days', 1);
$bReduced = $oParams->getBool('reduced', false); $bReduced = $oParams->getBool('reduced', false);
$sClass = $oParams->getString('class', false); $sClass = $oParams->getString('class', false);
$oDB =& getDB(); $oDB =& getDB();
$iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error')); $iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error'));
$aPolygons = array(); $aPolygons = array();
while($iTotalBroken && !sizeof($aPolygons)) 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 = '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 .= 'country_code as "country",errormessage as "error message",updated';
$sSQL .= " from import_polygon_error"; $sSQL .= " from import_polygon_error";
$sSQL .= " where updated > 'now'::timestamp - '".$iDays." day'::interval"; $sSQL .= " where updated > 'now'::timestamp - '".$iDays." day'::interval";
$iDays++; $iDays++;
if ($bReduced) $sSQL .= " and errormessage like 'Area reduced%'"; if ($bReduced) $sSQL .= " and errormessage like 'Area reduced%'";
if ($sClass) $sSQL .= " and class = '".pg_escape_string($sClass)."'"; if ($sClass) $sSQL .= " and class = '".pg_escape_string($sClass)."'";
$sSQL .= " order by updated desc limit 1000"; $sSQL .= " order by updated desc limit 1000";
$aPolygons = chksql($oDB->getAll($sSQL)); $aPolygons = chksql($oDB->getAll($sSQL));
} }
if (CONST_Debug) if (CONST_Debug)
{ {
var_dump($aPolygons); var_dump($aPolygons);
exit; exit;
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"/> <meta charset="utf-8"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Nominatim Broken Polygon Data</title> <title>Nominatim Broken Polygon Data</title>
<meta name="description" content="List of broken OSM polygon data by date" lang="en-US" /> <meta name="description" content="List of broken OSM polygon data by date" lang="en-US" />
</head> </head>
<body> <body>
<style type="text/css"> <style type="text/css">
table { table {
border-width: 1px; border-width: 1px;
border-spacing: 0px; border-spacing: 0px;
border-style: solid; border-style: solid;
border-color: gray; border-color: gray;
border-collapse: collapse; border-collapse: collapse;
background-color: white; background-color: white;
margin: 10px; margin: 10px;
} }
table th { table th {
border-width: 1px; border-width: 1px;
padding: 2px; padding: 2px;
border-style: inset; border-style: inset;
border-color: gray; border-color: gray;
border-left-color: #ddd; border-left-color: #ddd;
border-right-color: #ddd; border-right-color: #ddd;
background-color: #eee; background-color: #eee;
-moz-border-radius: 0px 0px 0px 0px; -moz-border-radius: 0px 0px 0px 0px;
} }
table td { table td {
border-width: 1px; border-width: 1px;
padding: 2px; padding: 2px;
border-style: inset; border-style: inset;
border-color: gray; border-color: gray;
border-left-color: #ddd; border-left-color: #ddd;
border-right-color: #ddd; border-right-color: #ddd;
background-color: white; background-color: white;
-moz-border-radius: 0px 0px 0px 0px; -moz-border-radius: 0px 0px 0px 0px;
} }
</style> </style>
<?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];
$aRow['lon'] = $aMatch[1]; $aRow['lon'] = $aMatch[1];
echo "<td><a href=\"http://www.openstreetmap.org/?lat=".$aMatch[2]."&lon=".$aMatch[1]."&zoom=18&layers=M&".$sOSMType."=".$aRow['id']."\">".($sVal?$sVal:'&nbsp;')."</a></td>"; echo "<td><a href=\"http://www.openstreetmap.org/?lat=".$aMatch[2]."&lon=".$aMatch[1]."&zoom=18&layers=M&".$sOSMType."=".$aRow['id']."\">".($sVal?$sVal:'&nbsp;')."</a></td>";
} }
else else
{ {
echo "<td>".($sVal?$sVal:'&nbsp;')."</td>"; echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
} }
break; break;
case 'id': case 'id':
echo '<td>'.osmLink($aRow).'</td>'; echo '<td>'.osmLink($aRow).'</td>';
break; break;
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>"; 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'])) 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>"; 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 else
{ {
echo "<td>&nbsp;</td>"; echo "<td>&nbsp;</td>";
} }
echo "</tr>"; echo "</tr>";
} }
echo "</table>"; echo "</table>";
?> ?>
</body> </body>
</html> </html>

View File

@ -1,108 +1,108 @@
<?php <?php
@define('CONST_ConnectionBucket_PageType', 'Reverse'); @define('CONST_ConnectionBucket_PageType', 'Reverse');
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/PlaceLookup.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php');
require_once(CONST_BasePath.'/lib/ReverseGeocode.php'); require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$oParams = new ParameterParser(); $oParams = new ParameterParser();
$bAsGeoJSON = $oParams->getBool('polygon_geojson'); $bAsGeoJSON = $oParams->getBool('polygon_geojson');
$bAsKML = $oParams->getBool('polygon_kml'); $bAsKML = $oParams->getBool('polygon_kml');
$bAsSVG = $oParams->getBool('polygon_svg'); $bAsSVG = $oParams->getBool('polygon_svg');
$bAsText = $oParams->getBool('polygon_text'); $bAsText = $oParams->getBool('polygon_text');
if ((($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0) if ((($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0)
+ ($bAsText?1:0)) > CONST_PolygonOutput_MaximumTypes) + ($bAsText?1:0)) > CONST_PolygonOutput_MaximumTypes)
{ {
if (CONST_PolygonOutput_MaximumTypes) if (CONST_PolygonOutput_MaximumTypes)
{ {
userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option"); userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
} }
else else
{ {
userError("Polygon output is disabled"); userError("Polygon output is disabled");
} }
} }
// Polygon simplification threshold (optional) // Polygon simplification threshold (optional)
$fThreshold = $oParams->getFloat('polygon_threshold', 0.0); $fThreshold = $oParams->getFloat('polygon_threshold', 0.0);
// Format for output // Format for output
$sOutputFormat = $oParams->getSet('format', array('html', 'xml', 'json', 'jsonv2'), 'xml'); $sOutputFormat = $oParams->getSet('format', array('html', 'xml', 'json', 'jsonv2'), 'xml');
// Preferred language // Preferred language
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$oDB =& getDB(); $oDB =& getDB();
$hLog = logStart($oDB, 'reverse', $_SERVER['QUERY_STRING'], $aLangPrefOrder); $hLog = logStart($oDB, 'reverse', $_SERVER['QUERY_STRING'], $aLangPrefOrder);
$oPlaceLookup = new PlaceLookup($oDB); $oPlaceLookup = new PlaceLookup($oDB);
$oPlaceLookup->setLanguagePreference($aLangPrefOrder); $oPlaceLookup->setLanguagePreference($aLangPrefOrder);
$oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', true)); $oPlaceLookup->setIncludeAddressDetails($oParams->getBool('addressdetails', true));
$oPlaceLookup->setIncludeExtraTags($oParams->getBool('extratags', false)); $oPlaceLookup->setIncludeExtraTags($oParams->getBool('extratags', false));
$oPlaceLookup->setIncludeNameDetails($oParams->getBool('namedetails', false)); $oPlaceLookup->setIncludeNameDetails($oParams->getBool('namedetails', false));
$sOsmType = $oParams->getSet('osm_type', array('N', 'W', 'R')); $sOsmType = $oParams->getSet('osm_type', array('N', 'W', 'R'));
$iOsmId = $oParams->getInt('osm_id', -1); $iOsmId = $oParams->getInt('osm_id', -1);
$fLat = $oParams->getFloat('lat'); $fLat = $oParams->getFloat('lat');
$fLon = $oParams->getFloat('lon'); $fLon = $oParams->getFloat('lon');
if ($sOsmType && $iOsmId > 0) if ($sOsmType && $iOsmId > 0)
{ {
$aPlace = $oPlaceLookup->lookupOSMID($sOsmType, $iOsmId); $aPlace = $oPlaceLookup->lookupOSMID($sOsmType, $iOsmId);
} }
else if ($fLat !== false && $fLon !== false) else if ($fLat !== false && $fLon !== false)
{ {
$oReverseGeocode = new ReverseGeocode($oDB); $oReverseGeocode = new ReverseGeocode($oDB);
$oReverseGeocode->setZoom($oParams->getInt('zoom', 18)); $oReverseGeocode->setZoom($oParams->getInt('zoom', 18));
$aLookup = $oReverseGeocode->lookup($fLat, $fLon); $aLookup = $oReverseGeocode->lookup($fLat, $fLon);
if (CONST_Debug) var_dump($aLookup); if (CONST_Debug) var_dump($aLookup);
$aPlace = $oPlaceLookup->lookup((int)$aLookup['place_id'], $aPlace = $oPlaceLookup->lookup((int)$aLookup['place_id'],
$aLookup['type'], $aLookup['fraction']); $aLookup['type'], $aLookup['fraction']);
} }
else if ($sOutputFormat != 'html') else if ($sOutputFormat != 'html')
{ {
userError("Need coordinates or OSM object to lookup."); userError("Need coordinates or OSM object to lookup.");
} }
if ($aPlace) if ($aPlace)
{ {
$oPlaceLookup->setIncludePolygonAsPoints(false); $oPlaceLookup->setIncludePolygonAsPoints(false);
$oPlaceLookup->setIncludePolygonAsText($bAsText); $oPlaceLookup->setIncludePolygonAsText($bAsText);
$oPlaceLookup->setIncludePolygonAsGeoJSON($bAsGeoJSON); $oPlaceLookup->setIncludePolygonAsGeoJSON($bAsGeoJSON);
$oPlaceLookup->setIncludePolygonAsKML($bAsKML); $oPlaceLookup->setIncludePolygonAsKML($bAsKML);
$oPlaceLookup->setIncludePolygonAsSVG($bAsSVG); $oPlaceLookup->setIncludePolygonAsSVG($bAsSVG);
$oPlaceLookup->setPolygonSimplificationThreshold($fThreshold); $oPlaceLookup->setPolygonSimplificationThreshold($fThreshold);
$fRadius = $fDiameter = getResultDiameter($aPlace); $fRadius = $fDiameter = getResultDiameter($aPlace);
$aOutlineResult = $oPlaceLookup->getOutlines($aPlace['place_id'], $aOutlineResult = $oPlaceLookup->getOutlines($aPlace['place_id'],
$aPlace['lon'], $aPlace['lat'], $aPlace['lon'], $aPlace['lat'],
$fRadius); $fRadius);
if ($aOutlineResult) if ($aOutlineResult)
{ {
$aPlace = array_merge($aPlace, $aOutlineResult); $aPlace = array_merge($aPlace, $aOutlineResult);
} }
} }
if (CONST_Debug) if (CONST_Debug)
{ {
var_dump($aPlace); var_dump($aPlace);
exit; exit;
} }
if ($sOutputFormat=='html') if ($sOutputFormat=='html')
{ {
$sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1")); $sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1"));
$sTileURL = CONST_Map_Tile_URL; $sTileURL = CONST_Map_Tile_URL;
$sTileAttribution = CONST_Map_Tile_Attribution; $sTileAttribution = CONST_Map_Tile_Attribution;
} }
include(CONST_BasePath.'/lib/template/address-'.$sOutputFormat.'.php'); include(CONST_BasePath.'/lib/template/address-'.$sOutputFormat.'.php');

View File

@ -1,132 +1,132 @@
<?php <?php
@define('CONST_ConnectionBucket_PageType', 'Search'); @define('CONST_ConnectionBucket_PageType', 'Search');
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');
require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/log.php');
require_once(CONST_BasePath.'/lib/Geocode.php'); require_once(CONST_BasePath.'/lib/Geocode.php');
require_once(CONST_BasePath.'/lib/output.php'); require_once(CONST_BasePath.'/lib/output.php');
ini_set('memory_limit', '200M'); ini_set('memory_limit', '200M');
$oDB =& getDB(); $oDB =& getDB();
$oParams = new ParameterParser(); $oParams = new ParameterParser();
$oGeocode = new Geocode($oDB); $oGeocode = new Geocode($oDB);
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$oGeocode->setLanguagePreference($aLangPrefOrder); $oGeocode->setLanguagePreference($aLangPrefOrder);
if (CONST_Search_ReversePlanForAll if (CONST_Search_ReversePlanForAll
|| isset($aLangPrefOrder['name:de']) || isset($aLangPrefOrder['name:de'])
|| isset($aLangPrefOrder['name:ru']) || isset($aLangPrefOrder['name:ru'])
|| isset($aLangPrefOrder['name:ja']) || isset($aLangPrefOrder['name:ja'])
|| isset($aLangPrefOrder['name:pl'])) || isset($aLangPrefOrder['name:pl']))
{ {
$oGeocode->setReverseInPlan(true); $oGeocode->setReverseInPlan(true);
} }
// Format for output // Format for output
$sOutputFormat = $oParams->getSet('format', array('html', 'xml', 'json', 'jsonv2'), 'html'); $sOutputFormat = $oParams->getSet('format', array('html', 'xml', 'json', 'jsonv2'), 'html');
// Show / use polygons // Show / use polygons
if ($sOutputFormat == 'html') if ($sOutputFormat == 'html')
{ {
$oGeocode->setIncludePolygonAsText($oParams->getBool('polygon')); $oGeocode->setIncludePolygonAsText($oParams->getBool('polygon'));
$bAsText = false; $bAsText = false;
} }
else else
{ {
$bAsPoints = $oParams->getBool('polygon'); $bAsPoints = $oParams->getBool('polygon');
$bAsGeoJSON = $oParams->getBool('polygon_geojson'); $bAsGeoJSON = $oParams->getBool('polygon_geojson');
$bAsKML = $oParams->getBool('polygon_kml'); $bAsKML = $oParams->getBool('polygon_kml');
$bAsSVG = $oParams->getBool('polygon_svg'); $bAsSVG = $oParams->getBool('polygon_svg');
$bAsText = $oParams->getBool('polygon_text'); $bAsText = $oParams->getBool('polygon_text');
if ( ( ($bAsGeoJSON?1:0) if ( ( ($bAsGeoJSON?1:0)
+ ($bAsKML?1:0) + ($bAsKML?1:0)
+ ($bAsSVG?1:0) + ($bAsSVG?1:0)
+ ($bAsText?1:0) + ($bAsText?1:0)
+ ($bAsPoints?1:0) + ($bAsPoints?1:0)
) > CONST_PolygonOutput_MaximumTypes) ) > CONST_PolygonOutput_MaximumTypes)
{ {
if (CONST_PolygonOutput_MaximumTypes) if (CONST_PolygonOutput_MaximumTypes)
{ {
userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option"); userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
} }
else else
{ {
userError("Polygon output is disabled"); userError("Polygon output is disabled");
} }
exit; exit;
} }
$oGeocode->setIncludePolygonAsPoints($bAsPoints); $oGeocode->setIncludePolygonAsPoints($bAsPoints);
$oGeocode->setIncludePolygonAsText($bAsText); $oGeocode->setIncludePolygonAsText($bAsText);
$oGeocode->setIncludePolygonAsGeoJSON($bAsGeoJSON); $oGeocode->setIncludePolygonAsGeoJSON($bAsGeoJSON);
$oGeocode->setIncludePolygonAsKML($bAsKML); $oGeocode->setIncludePolygonAsKML($bAsKML);
$oGeocode->setIncludePolygonAsSVG($bAsSVG); $oGeocode->setIncludePolygonAsSVG($bAsSVG);
} }
// Polygon simplification threshold (optional) // Polygon simplification threshold (optional)
$oGeocode->setPolygonSimplificationThreshold($oParams->getFloat('polygon_threshold', 0.0)); $oGeocode->setPolygonSimplificationThreshold($oParams->getFloat('polygon_threshold', 0.0));
$oGeocode->loadParamArray($oParams); $oGeocode->loadParamArray($oParams);
if (CONST_Search_BatchMode && isset($_GET['batch'])) if (CONST_Search_BatchMode && isset($_GET['batch']))
{ {
$aBatch = json_decode($_GET['batch'], true); $aBatch = json_decode($_GET['batch'], true);
$aBatchResults = array(); $aBatchResults = array();
foreach($aBatch as $aBatchParams) foreach($aBatch as $aBatchParams)
{ {
$oBatchGeocode = clone $oGeocode; $oBatchGeocode = clone $oGeocode;
$oBatchParams = new ParameterParser($aBatchParams); $oBatchParams = new ParameterParser($aBatchParams);
$oBatchGeocode->loadParamArray($oBatchParams); $oBatchGeocode->loadParamArray($oBatchParams);
$oBatchGeocode->setQueryFromParams($oBatchParams); $oBatchGeocode->setQueryFromParams($oBatchParams);
$aSearchResults = $oBatchGeocode->lookup(); $aSearchResults = $oBatchGeocode->lookup();
$aBatchResults[] = $aSearchResults; $aBatchResults[] = $aSearchResults;
} }
include(CONST_BasePath.'/lib/template/search-batch-json.php'); include(CONST_BasePath.'/lib/template/search-batch-json.php');
exit; exit;
} }
$oGeocode->setQueryFromParams($oParams); $oGeocode->setQueryFromParams($oParams);
if (!$oGeocode->getQueryString() if (!$oGeocode->getQueryString()
&& isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/') && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
{ {
$sQuery = substr(rawurldecode($_SERVER['PATH_INFO']), 1); $sQuery = substr(rawurldecode($_SERVER['PATH_INFO']), 1);
// reverse order of '/' separated string // reverse order of '/' separated string
$aPhrases = explode('/', $sQuery); $aPhrases = explode('/', $sQuery);
$aPhrases = array_reverse($aPhrases); $aPhrases = array_reverse($aPhrases);
$sQuery = join(', ',$aPhrases); $sQuery = join(', ',$aPhrases);
$oGeocode->setQuery($sQuery); $oGeocode->setQuery($sQuery);
} }
$hLog = logStart($oDB, 'search', $oGeocode->getQueryString(), $aLangPrefOrder); $hLog = logStart($oDB, 'search', $oGeocode->getQueryString(), $aLangPrefOrder);
$aSearchResults = $oGeocode->lookup(); $aSearchResults = $oGeocode->lookup();
if ($aSearchResults === false) $aSearchResults = array(); if ($aSearchResults === false) $aSearchResults = array();
if ($sOutputFormat=='html') if ($sOutputFormat=='html')
{ {
$sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1")); $sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1"));
} }
logEnd($oDB, $hLog, sizeof($aSearchResults)); logEnd($oDB, $hLog, sizeof($aSearchResults));
$sQuery = $oGeocode->getQueryString(); $sQuery = $oGeocode->getQueryString();
$sViewBox = $oGeocode->getViewBoxString(); $sViewBox = $oGeocode->getViewBoxString();
$bShowPolygons = (isset($_GET['polygon']) && $_GET['polygon']); $bShowPolygons = (isset($_GET['polygon']) && $_GET['polygon']);
$aExcludePlaceIDs = $oGeocode->getExcludedPlaceIDs(); $aExcludePlaceIDs = $oGeocode->getExcludedPlaceIDs();
$sMoreURL = CONST_Website_BaseURL.'search.php?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs); $sMoreURL = CONST_Website_BaseURL.'search.php?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"]; if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
if ($bShowPolygons) $sMoreURL .= '&polygon=1'; if ($bShowPolygons) $sMoreURL .= '&polygon=1';
if ($oGeocode->getIncludeAddressDetails()) $sMoreURL .= '&addressdetails=1'; if ($oGeocode->getIncludeAddressDetails()) $sMoreURL .= '&addressdetails=1';
if ($oGeocode->getIncludeExtraTags()) $sMoreURL .= '&extratags=1'; if ($oGeocode->getIncludeExtraTags()) $sMoreURL .= '&extratags=1';
if ($oGeocode->getIncludeNameDetails()) $sMoreURL .= '&namedetails=1'; if ($oGeocode->getIncludeNameDetails()) $sMoreURL .= '&namedetails=1';
if ($sViewBox) $sMoreURL .= '&viewbox='.urlencode($sViewBox); if ($sViewBox) $sMoreURL .= '&viewbox='.urlencode($sViewBox);
if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon']; if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
$sMoreURL .= '&q='.urlencode($sQuery); $sMoreURL .= '&q='.urlencode($sQuery);
if (CONST_Debug) exit; if (CONST_Debug) exit;
include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php'); include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');

View File

@ -1,42 +1,42 @@
<?php <?php
@define('CONST_ConnectionBucket_PageType', 'Status'); @define('CONST_ConnectionBucket_PageType', 'Status');
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");
echo "ERROR: ".$sMsg; echo "ERROR: ".$sMsg;
exit; exit;
} }
$oDB =& DB::connect(CONST_Database_DSN, false); $oDB =& DB::connect(CONST_Database_DSN, false);
if (!$oDB || PEAR::isError($oDB)) if (!$oDB || PEAR::isError($oDB))
{ {
statusError("No database"); statusError("No database");
} }
$sStandardWord = $oDB->getOne("select make_standard_name('a')"); $sStandardWord = $oDB->getOne("select make_standard_name('a')");
if (PEAR::isError($sStandardWord)) if (PEAR::isError($sStandardWord))
{ {
statusError("Module failed"); statusError("Module failed");
} }
if ($sStandardWord != 'a') if ($sStandardWord != 'a')
{ {
statusError("Module call failed"); statusError("Module call failed");
} }
$iWordID = $oDB->getOne("select word_id,word_token, word, class, type, country_code, operator, search_name_count from word where word_token in (' a')"); $iWordID = $oDB->getOne("select word_id,word_token, word, class, type, country_code, operator, search_name_count from word where word_token in (' a')");
if (PEAR::isError($iWordID)) if (PEAR::isError($iWordID))
{ {
statusError("Query failed"); statusError("Query failed");
} }
if (!$iWordID) if (!$iWordID)
{ {
statusError("No value"); statusError("No value");
} }
echo "OK"; echo "OK";
exit; exit;

View File

@ -17,172 +17,172 @@ $iNS = false;
$iID = false; $iID = false;
if ($hFile) { if ($hFile) {
while (($sLine = fgets($hFile, 4000000)) !== false) { while (($sLine = fgets($hFile, 4000000)) !== false) {
if (substr($sLine, 0, 11) == ' <title>') { if (substr($sLine, 0, 11) == ' <title>') {
$sTitle = substr($sLine, 11, -9); $sTitle = substr($sLine, 11, -9);
} }
else if (substr($sLine, 0, 8) == ' <ns>') { else if (substr($sLine, 0, 8) == ' <ns>') {
$iNS = (int)substr($sLine, 8, -6); $iNS = (int)substr($sLine, 8, -6);
} }
else if (substr($sLine, 0, 8) == ' <id>') { else if (substr($sLine, 0, 8) == ' <id>') {
$iID = (int)substr($sLine, 8, -6); $iID = (int)substr($sLine, 8, -6);
} }
else if (substr($sLine, 0, 33) == ' <text xml:space="preserve">') { else if (substr($sLine, 0, 33) == ' <text xml:space="preserve">') {
if ($iNS == -2) continue; if ($iNS == -2) continue;
if ($iNS == -1) continue; if ($iNS == -1) continue;
if ($iNS == 1) continue; if ($iNS == 1) continue;
if ($iNS == 2) continue; if ($iNS == 2) continue;
if ($iNS == 3) continue; if ($iNS == 3) continue;
if ($iNS == 4) continue; if ($iNS == 4) continue;
if ($iNS == 5) continue; if ($iNS == 5) continue;
if ($iNS == 6) continue; if ($iNS == 6) continue;
if ($iNS == 7) continue; if ($iNS == 7) continue;
if ($iNS == 8) continue; if ($iNS == 8) continue;
if ($iNS == 9) continue; if ($iNS == 9) continue;
if ($iNS == 10) continue; if ($iNS == 10) continue;
if ($iNS == 11) continue; if ($iNS == 11) continue;
if ($iNS == 12) continue; if ($iNS == 12) continue;
if ($iNS == 13) continue; if ($iNS == 13) continue;
if ($iNS == 14) continue; if ($iNS == 14) continue;
if ($iNS == 15) continue; if ($iNS == 15) continue;
if ($iNS == 121) continue; if ($iNS == 121) continue;
if ($iNS == 123) continue; if ($iNS == 123) continue;
if ($iNS == 829) continue; if ($iNS == 829) continue;
if ($iNS == 1198) continue; if ($iNS == 1198) continue;
if ($iNS == 1199) continue; if ($iNS == 1199) continue;
$sText = html_entity_decode(substr($sLine, 33, -8), ENT_COMPAT, 'UTF-8'); $sText = html_entity_decode(substr($sLine, 33, -8), ENT_COMPAT, 'UTF-8');
$aArticle = json_decode($sText, true); $aArticle = json_decode($sText, true);
if (array_diff(array_keys($aArticle), array("label", "description", "aliases", "links", "entity", "claims", "datatype")) != array()) { if (array_diff(array_keys($aArticle), array("label", "description", "aliases", "links", "entity", "claims", "datatype")) != array()) {
// DEBUG // DEBUG
var_dump($sTitle); var_dump($sTitle);
var_dump(array_keys($aArticle)); var_dump(array_keys($aArticle));
var_dump($aArticle); var_dump($aArticle);
exit; exit;
} }
$iPID = $iQID = null; $iPID = $iQID = null;
if ($aArticle['entity'][0] == 'p') { if ($aArticle['entity'][0] == 'p') {
$iPID = (int)substr($aArticle['entity'], 1); $iPID = (int)substr($aArticle['entity'], 1);
} else if ($aArticle['entity'][0] == 'q') { } else if ($aArticle['entity'][0] == 'q') {
$iQID = (int)substr($aArticle['entity'], 1); $iQID = (int)substr($aArticle['entity'], 1);
} else { } else {
continue; continue;
} }
echo "."; echo ".";
fputcsv($hFileEntity, array($iID,$sTitle,$iPID,$iQID,@$aArticle['datatype'])); fputcsv($hFileEntity, array($iID,$sTitle,$iPID,$iQID,@$aArticle['datatype']));
foreach($aArticle['label'] as $sLang => $sLabel) { foreach($aArticle['label'] as $sLang => $sLabel) {
fputcsv($hFileEntityLabel, array($iID,$sLang,$sLabel)); fputcsv($hFileEntityLabel, array($iID,$sLang,$sLabel));
// echo "insert into entity_label values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n"; // echo "insert into entity_label values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n";
} }
foreach($aArticle['description'] as $sLang => $sLabel) { foreach($aArticle['description'] as $sLang => $sLabel) {
fputcsv($hFileEntityDescription, array($iID,$sLang,$sLabel)); fputcsv($hFileEntityDescription, array($iID,$sLang,$sLabel));
// echo "insert into entity_description values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n"; // echo "insert into entity_description values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n";
} }
foreach($aArticle['aliases'] as $sLang => $aLabels) { foreach($aArticle['aliases'] as $sLang => $aLabels) {
$aUniqueAlias = array(); $aUniqueAlias = array();
foreach($aLabels as $sLabel) { foreach($aLabels as $sLabel) {
if (!isset($aUniqueAlias[$sLabel]) && $sLabel) { if (!isset($aUniqueAlias[$sLabel]) && $sLabel) {
fputcsv($hFileEntityAlias, array($iID,$sLang,$sLabel)); fputcsv($hFileEntityAlias, array($iID,$sLang,$sLabel));
// echo "insert into entity_alias values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n"; // echo "insert into entity_alias values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n";
$aUniqueAlias[$sLabel] = true; $aUniqueAlias[$sLabel] = true;
} }
} }
} }
foreach($aArticle['links'] as $sLang => $sLabel) { foreach($aArticle['links'] as $sLang => $sLabel) {
fputcsv($hFileEntityLink, array($iID,$sLang,$sLabel)); fputcsv($hFileEntityLink, array($iID,$sLang,$sLabel));
// echo "insert into entity_link values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n"; // echo "insert into entity_link values (".$iID.",'".pg_escape_string($sLang)."','".pg_escape_string($sLabel)."');\n";
} }
if (isset($aArticle['claims'])) { if (isset($aArticle['claims'])) {
foreach($aArticle['claims'] as $iClaim => $aClaim) { foreach($aArticle['claims'] as $iClaim => $aClaim) {
$bFail = false; $bFail = false;
if ($aClaim['m'][0] == 'novalue') continue; if ($aClaim['m'][0] == 'novalue') continue;
if ($aClaim['m'][0] == 'somevalue') continue; if ($aClaim['m'][0] == 'somevalue') continue;
$iPID = (int)$aClaim['m'][1]; $iPID = (int)$aClaim['m'][1];
if ($aClaim['m'][0] != 'value') $bFail = true; if ($aClaim['m'][0] != 'value') $bFail = true;
if ($aClaim['m'][2]== 'wikibase-entityid') { if ($aClaim['m'][2]== 'wikibase-entityid') {
if ($aClaim['m'][3]['entity-type'] != 'item') $bFail = true; if ($aClaim['m'][3]['entity-type'] != 'item') $bFail = true;
fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,null,$aClaim['m'][3]['numeric-id'],null,null)); fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,null,$aClaim['m'][3]['numeric-id'],null,null));
// echo "insert into entity_property values (nextval('seq_entity_property'),".$iID.",".$iPID.",null,".$aClaim['m'][3]['numeric-id'].",null);\n"; // echo "insert into entity_property values (nextval('seq_entity_property'),".$iID.",".$iPID.",null,".$aClaim['m'][3]['numeric-id'].",null);\n";
} elseif ($aClaim['m'][2] == 'globecoordinate') { } elseif ($aClaim['m'][2] == 'globecoordinate') {
if ($aClaim['m'][3]['globe'] != 'http://www.wikidata.org/entity/Q2') $bFail = true; if ($aClaim['m'][3]['globe'] != 'http://www.wikidata.org/entity/Q2') $bFail = true;
fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,null,null,"SRID=4326;POINT(".((float)$aClaim['m'][3]['longitude'])." ".((float)$aClaim['m'][3]['latitude']).")",null)); fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,null,null,"SRID=4326;POINT(".((float)$aClaim['m'][3]['longitude'])." ".((float)$aClaim['m'][3]['latitude']).")",null));
// echo "insert into entity_property values (nextval('seq_entity_property'),".$iID.",".$iPID.",null,null,ST_SetSRID(ST_MakePoint(".((float)$aClaim['m'][3]['longitude']).", ".((float)$aClaim['m'][3]['latitude'])."),4326));\n"; // echo "insert into entity_property values (nextval('seq_entity_property'),".$iID.",".$iPID.",null,null,ST_SetSRID(ST_MakePoint(".((float)$aClaim['m'][3]['longitude']).", ".((float)$aClaim['m'][3]['latitude'])."),4326));\n";
} elseif ($aClaim['m'][2] == 'time') { } elseif ($aClaim['m'][2] == 'time') {
// TODO! // TODO!
/* /*
if ($aClaim['m'][3]['calendarmodel'] == 'http://www.wikidata.org/entity/Q1985727') { if ($aClaim['m'][3]['calendarmodel'] == 'http://www.wikidata.org/entity/Q1985727') {
// Gregorian // Gregorian
if (preg_match('#(\\+|-)0*([0-9]{4})-([0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})Z#', $aClaim['m'][3]['time'], $aMatch)) { if (preg_match('#(\\+|-)0*([0-9]{4})-([0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})Z#', $aClaim['m'][3]['time'], $aMatch)) {
if ((int)$aMatch[2] < 4700 && ) { if ((int)$aMatch[2] < 4700 && ) {
$sDateString = $aMatch[2].'-'.$aMatch[3].($aClaim['m'][3]['timezone']>=0?'+':'').$aClaim['m'][3]['timezone'].($aMatch[1]=='-'?' bc':''); $sDateString = $aMatch[2].'-'.$aMatch[3].($aClaim['m'][3]['timezone']>=0?'+':'').$aClaim['m'][3]['timezone'].($aMatch[1]=='-'?' bc':'');
fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,null,null,null,$sDateString)); fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,null,null,null,$sDateString));
} }
} else { } else {
// $bFail = true; // $bFail = true;
} }
} elseif ( $aClaim['m'][3]['calendarmodel'] != 'http://www.wikidata.org/entity/Q1985786') { } elseif ( $aClaim['m'][3]['calendarmodel'] != 'http://www.wikidata.org/entity/Q1985786') {
/ * / *
// Julian // Julian
if (preg_match('#(\\+|-)0*([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}:[0-9]{2}:[0-9]{2})Z#', $aClaim['m'][3]['time'], $aMatch)) { if (preg_match('#(\\+|-)0*([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}:[0-9]{2}:[0-9]{2})Z#', $aClaim['m'][3]['time'], $aMatch)) {
var_dump($aMatch); var_dump($aMatch);
exit; exit;
$iDayCount = juliantojd(2, 11, 1732); $iDayCount = juliantojd(2, 11, 1732);
var_dump($iDayCount, jdtogregorian($iDayCount)); var_dump($iDayCount, jdtogregorian($iDayCount));
} else { } else {
$bFail = true; $bFail = true;
exit; exit;
} }
exit; exit;
* / * /
} else { } else {
// $bFail = true; // $bFail = true;
} }
*/ */
} elseif ($aClaim['m'][2] == 'string') { } elseif ($aClaim['m'][2] == 'string') {
// echo "insert into entity_property values (nextval('seq_entity_property'),".$iID.",".$iPID.",'".pg_escape_string($aClaim['m'][3])."',null,null);\n"; // echo "insert into entity_property values (nextval('seq_entity_property'),".$iID.",".$iPID.",'".pg_escape_string($aClaim['m'][3])."',null,null);\n";
fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,$aClaim['m'][3],null,null,null)); fputcsv($hFileEntityProperty, array($iID,$iClaim,$iPID,$aClaim['m'][3],null,null,null));
} else { } else {
$bFail = true; $bFail = true;
} }
// Don't care about sources: if ($aClaim['refs'] != array()) $bFail = true; // Don't care about sources: if ($aClaim['refs'] != array()) $bFail = true;
if ($bFail) { if ($bFail) {
var_dump($sTitle); var_dump($sTitle);
var_dump($aClaim); var_dump($aClaim);
} else { } else {
// process // process
} }
} }
} }
} }
} }
fclose($hFile); fclose($hFile);
fclose($hFileEntity); fclose($hFileEntity);
fclose($hFileEntityLabel); fclose($hFileEntityLabel);
fclose($hFileEntityDescription); fclose($hFileEntityDescription);
fclose($hFileEntityAlias); fclose($hFileEntityAlias);
fclose($hFileEntityLink); fclose($hFileEntityLink);
fclose($hFileEntityProperty); fclose($hFileEntityProperty);
} }

View File

@ -1,91 +1,91 @@
<?php <?php
for($iTimestamp = mktime(0, 0, 0, 5, 1, 2013); $iTimestamp < mktime(0, 0, 0, 6, 15, 2013); $iTimestamp += 24*60*60) for($iTimestamp = mktime(0, 0, 0, 5, 1, 2013); $iTimestamp < mktime(0, 0, 0, 6, 15, 2013); $iTimestamp += 24*60*60)
{ {
$sYear = date("Y", $iTimestamp); $sYear = date("Y", $iTimestamp);
$sMonth = date("Y-m", $iTimestamp); $sMonth = date("Y-m", $iTimestamp);
$sDay = date("Ymd", $iTimestamp); $sDay = date("Ymd", $iTimestamp);
for($iHour = 0; $iHour < 24; $iHour++) for($iHour = 0; $iHour < 24; $iHour++)
{ {
$sFilename = sprintf("pagecounts-".$sDay."-%02d0000", $iHour); $sFilename = sprintf("pagecounts-".$sDay."-%02d0000", $iHour);
echo $sFilename."\n"; echo $sFilename."\n";
if (!file_exists($sFilename.'.gz')) if (!file_exists($sFilename.'.gz'))
{ {
exec('wget http://dumps.wikimedia.org/other/pagecounts-raw/'.$sYear.'/'.$sMonth.'/'.$sFilename.'.gz'); exec('wget http://dumps.wikimedia.org/other/pagecounts-raw/'.$sYear.'/'.$sMonth.'/'.$sFilename.'.gz');
} }
exec('gzip -dc '.$sFilename.'.gz'.' | grep -e "^[a-z]\{2\} [^ :]\+ [0-9]\+" > hour.txt'); exec('gzip -dc '.$sFilename.'.gz'.' | grep -e "^[a-z]\{2\} [^ :]\+ [0-9]\+" > hour.txt');
$hPrevTotals = @fopen("totals.txt", "r"); $hPrevTotals = @fopen("totals.txt", "r");
$hDayTotals = @fopen("hour.txt", "r"); $hDayTotals = @fopen("hour.txt", "r");
$hNewTotals = @fopen("newtotals.txt", "w"); $hNewTotals = @fopen("newtotals.txt", "w");
$sPrevKey = $sDayKey = true; $sPrevKey = $sDayKey = true;
$sPrevLine = true; $sPrevLine = true;
$sDayLine = true; $sDayLine = true;
do do
{ {
if ($sPrevKey === $sDayKey) if ($sPrevKey === $sDayKey)
{ {
if ($sPrevLine !== true) fputs($hNewTotals, "$sPrevKey ".($iPrevValue+$iDayValue)."\n"); if ($sPrevLine !== true) fputs($hNewTotals, "$sPrevKey ".($iPrevValue+$iDayValue)."\n");
$sPrevLine = true; $sPrevLine = true;
$sDayLine = true; $sDayLine = true;
} }
else if ($sDayKey !== false && ($sPrevKey > $sDayKey || $sPrevKey === false)) else if ($sDayKey !== false && ($sPrevKey > $sDayKey || $sPrevKey === false))
{ {
fputs($hNewTotals, "$sDayKey ".($iDayValue)."\n"); fputs($hNewTotals, "$sDayKey ".($iDayValue)."\n");
$sDayLine = true; $sDayLine = true;
} }
else if ($sPrevKey !== false && ($sDayKey > $sPrevKey || $sDayKey === false)) else if ($sPrevKey !== false && ($sDayKey > $sPrevKey || $sDayKey === false))
{ {
fputs($hNewTotals, "$sPrevKey ".($iPrevValue)."\n"); fputs($hNewTotals, "$sPrevKey ".($iPrevValue)."\n");
$sPrevLine = true; $sPrevLine = true;
} }
if ($sPrevLine === true) if ($sPrevLine === true)
{ {
$sPrevLine = $hPrevTotals?fgets($hPrevTotals, 4096):false; $sPrevLine = $hPrevTotals?fgets($hPrevTotals, 4096):false;
if ($sPrevLine !== false) if ($sPrevLine !== false)
{ {
$aPrevLine = explode(' ', $sPrevLine); $aPrevLine = explode(' ', $sPrevLine);
$sPrevKey = $aPrevLine[0].' '.$aPrevLine[1]; $sPrevKey = $aPrevLine[0].' '.$aPrevLine[1];
$iPrevValue = (int)$aPrevLine[2]; $iPrevValue = (int)$aPrevLine[2];
} }
else else
{ {
$sPrevKey = false; $sPrevKey = false;
$iPrevValue = 0; $iPrevValue = 0;
} }
} }
if ($sDayLine === true) if ($sDayLine === true)
{ {
$sDayLine = $hDayTotals?fgets($hDayTotals, 4096):false; $sDayLine = $hDayTotals?fgets($hDayTotals, 4096):false;
if ($sDayLine !== false) if ($sDayLine !== false)
{ {
preg_match('#^([a-z]{2}) ([^ :]+) ([0-9]+) [0-9]+$#', $sDayLine, $aMatch); preg_match('#^([a-z]{2}) ([^ :]+) ([0-9]+) [0-9]+$#', $sDayLine, $aMatch);
$sDayKey = $aMatch[1].' '.$aMatch[2]; $sDayKey = $aMatch[1].' '.$aMatch[2];
$iDayValue = (int)$aMatch[3]; $iDayValue = (int)$aMatch[3];
} }
else else
{ {
$sDayKey = false; $sDayKey = false;
$iDayValue = 0; $iDayValue = 0;
} }
} }
} while ($sPrevLine !== false || $sDayLine !== false); } while ($sPrevLine !== false || $sDayLine !== false);
@fclose($hPrevTotals); @fclose($hPrevTotals);
@fclose($hDayTotals); @fclose($hDayTotals);
@fclose($hNewTotals); @fclose($hNewTotals);
@unlink("totals.txt"); @unlink("totals.txt");
rename("newtotals.txt", "totals.txt"); rename("newtotals.txt", "totals.txt");
} }
} }
// Notes: // Notes:
/* /*