From d45524cbfb299f5004a03c52802c64749c5ad212 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sat, 11 Jun 2016 23:07:06 +0200 Subject: [PATCH 1/9] introduce accessor function for URL parameter These functions take care of type conversion and check that the parameters contain legal values. The API now returns a Bad Request error if the format is wrong. --- lib/init-website.php | 1 + lib/lib.php | 7 ---- lib/website.php | 57 ++++++++++++++++++++++++++++++++ website/details.php | 21 ++++++------ website/hierarchy.php | 38 ++++++++-------------- website/lookup.php | 75 ++++++++++++++++++++----------------------- website/polygons.php | 30 ++++++----------- website/reverse.php | 41 +++++++++++------------ website/search.php | 24 ++++++-------- 9 files changed, 153 insertions(+), 141 deletions(-) create mode 100644 lib/website.php diff --git a/lib/init-website.php b/lib/init-website.php index fff33936..04bc518c 100644 --- a/lib/init-website.php +++ b/lib/init-website.php @@ -1,5 +1,6 @@ 0) { - $_GET['place_id'] = $oDB->getOne("select place_id from placex where osm_type = '".$_GET['osmtype']."' and osm_id = ".(int)$_GET['osmid']." order by type = 'postcode' asc"); + $sPlaceId = $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 - if (!$_GET['place_id']) + if (!$sPlaceId) { - $aPointDetails = $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 = '".$_GET['osmtype']."' and osm_id = ".(int)$_GET['osmid']." order by updated desc limit 1"); + $aPointDetails = $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 (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) { @@ -48,13 +51,9 @@ } - if (!isset($_GET['place_id'])) - { - echo "Please select a place id"; - exit; - } + if (!$sPlaceId) userError("Please select a place id"); - $iPlaceID = (int)$_GET['place_id']; + $iPlaceID = (int)$sPlaceId; if (CONST_Use_US_Tiger_Data) { @@ -139,7 +138,7 @@ $aPlaceSearchNameKeywords = false; $aPlaceSearchAddressKeywords = false; - if (isset($_GET['keywords']) && $_GET['keywords']) + if (getParamBool('keywords')) { $sSQL = "select * from search_name where place_id = $iPlaceID"; $aPlaceSearchName = $oDB->getRow($sSQL); diff --git a/website/hierarchy.php b/website/hierarchy.php index 9b9d778c..e0e960bc 100755 --- a/website/hierarchy.php +++ b/website/hierarchy.php @@ -5,28 +5,26 @@ require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php'); - - $sOutputFormat = 'html'; - if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2')) - { - $sOutputFormat = $_GET['format']; - } - ini_set('memory_limit', '200M'); $oDB =& getDB(); + $sOutputFormat = getParamSet('format', array('html', 'json'), 'html'); + $aLangPrefOrder = getPreferredLanguages(); $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]"; - if (isset($_GET['osmtype']) && isset($_GET['osmid']) && (int)$_GET['osmid'] && ($_GET['osmtype'] == 'N' || $_GET['osmtype'] == 'W' || $_GET['osmtype'] == 'R')) + $sPlaceId = getParamString('place_id'); + $sOsmType = getParamSet('osmtype', array('N', 'W', 'R')); + $iOsmId = getParamInt('osmid', -1); + if ($sOsmType && $iOsmId > 0) { - $_GET['place_id'] = $oDB->getOne("select place_id from placex where osm_type = '".$_GET['osmtype']."' and osm_id = ".(int)$_GET['osmid']." order by type = 'postcode' asc"); + $sPlaceId = $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 - if (!$_GET['place_id']) + if (!$sPlaceId) { - $aPointDetails = $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 = '".$_GET['osmtype']."' and osm_id = ".(int)$_GET['osmid']." order by updated desc limit 1"); + $aPointDetails = $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 (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) { @@ -39,13 +37,9 @@ } } - if (!isset($_GET['place_id'])) - { - echo "Please select a place id"; - exit; - } + if (!$sPlaceId) userError("Please select a place id"); - $iPlaceID = (int)$_GET['place_id']; + $iPlaceID = (int)$sPlaceId; if (CONST_Use_US_Tiger_Data) { @@ -66,11 +60,7 @@ $aPlaceAddress = array_reverse($oPlaceLookup->getAddressDetails()); - if (!sizeof($aPlaceAddress)) - { - echo "Unknown place id."; - exit; - } + if (!sizeof($aPlaceAddress)) userError("Unknown place id."); $aBreadcrums = array(); foreach($aPlaceAddress as $i => $aPlace) @@ -84,12 +74,12 @@ if ($sOutputFormat == 'html') echo ''.$aPlace['localname'].' (osm)'; } - $aDetails = array(); - $aDetails['breadcrumbs'] = $aBreadcrums; if ($sOutputFormat == 'json') { header("content-type: application/json; charset=UTF-8"); + $aDetails = array(); + $aDetails['breadcrumbs'] = $aBreadcrums; javascript_renderData($aDetails); exit; } diff --git a/website/lookup.php b/website/lookup.php index dfa09d3b..60bd60eb 100755 --- a/website/lookup.php +++ b/website/lookup.php @@ -22,11 +22,7 @@ ini_set('memory_limit', '200M'); // Format for output - $sOutputFormat = 'xml'; - if (isset($_GET['format']) && ($_GET['format'] == 'xml' || $_GET['format'] == 'json')) - { - $sOutputFormat = $_GET['format']; - } + $sOutputFormat = getParamSet('format', array('xml', 'json'), 'xml'); // Preferred language $aLangPrefOrder = getPreferredLanguages(); @@ -35,45 +31,42 @@ $aSearchResults = array(); $aCleanedQueryParts = array(); - if (isset($_GET['osm_ids'])) + + $oPlaceLookup = new PlaceLookup($oDB); + $oPlaceLookup->setLanguagePreference($aLangPrefOrder); + $oPlaceLookup->setIncludeAddressDetails(getParamBool('addressdetails', true)); + $oPlaceLookup->setIncludeExtraTags(getParamBool('extratags', false)); + $oPlaceLookup->setIncludeNameDetails(getParamBool('namedetails', false)); + + $aOsmIds = explode(',', $getParamString('osm_ids', '')); + + if (count($aOsmIds) > CONST_Places_Max_ID_count) { - $oPlaceLookup = new PlaceLookup($oDB); - $oPlaceLookup->setLanguagePreference($aLangPrefOrder); - $oPlaceLookup->setIncludeAddressDetails(getParamBool('addressdetails', true)); - $oPlaceLookup->setIncludeExtraTags(getParamBool('extratags', false)); - $oPlaceLookup->setIncludeNameDetails(getParamBool('namedetails', false)); + userError('Bulk User: Only ' . CONST_Places_Max_ID_count . " ids are allowed in one request."); + } + + foreach ($aOsmIds AS $sItem) + { + // Skip empty sItem + if (empty($sItem)) continue; - $aOsmIds = explode(',', $_GET['osm_ids']); - - if ( count($aOsmIds) > CONST_Places_Max_ID_count ) + $sType = $sItem[0]; + $iId = (int) substr($sItem, 1); + if ( $iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R') ) { - userError('Bulk User: Only ' . CONST_Places_Max_ID_count . " ids are allowed in one request."); - exit; - } - - foreach ($aOsmIds AS $sItem) - { - // Skip empty sItem - if (empty($sItem)) continue; - - $sType = $sItem[0]; - $iId = (int) substr($sItem, 1); - if ( $iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R') ) - { - $aCleanedQueryParts[] = $sType . $iId; - $oPlaceLookup->setOSMID($sType, $iId); - $oPlace = $oPlaceLookup->lookup(); - if ($oPlace){ - // we want to use the search-* output templates, so we need to fill - // $aSearchResults and slightly change the (reverse search) oPlace - // key names - $oResult = $oPlace; - unset($oResult['aAddress']); - if (isset($oPlace['aAddress'])) $oResult['address'] = $oPlace['aAddress']; - unset($oResult['langaddress']); - $oResult['name'] = $oPlace['langaddress']; - $aSearchResults[] = $oResult; - } + $aCleanedQueryParts[] = $sType . $iId; + $oPlaceLookup->setOSMID($sType, $iId); + $oPlace = $oPlaceLookup->lookup(); + if ($oPlace){ + // we want to use the search-* output templates, so we need to fill + // $aSearchResults and slightly change the (reverse search) oPlace + // key names + $oResult = $oPlace; + unset($oResult['aAddress']); + if (isset($oPlace['aAddress'])) $oResult['address'] = $oPlace['aAddress']; + unset($oResult['langaddress']); + $oResult['name'] = $oPlace['langaddress']; + $aSearchResults[] = $oResult; } } } diff --git a/website/polygons.php b/website/polygons.php index b9ce249d..92dbf70d 100755 --- a/website/polygons.php +++ b/website/polygons.php @@ -2,16 +2,14 @@ require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); - - $sOutputFormat = 'html'; ini_set('memory_limit', '200M'); $oDB =& getDB(); - if (!isset($_GET['days'])) $_GET['days'] = 1; - $bReduced = false; - if (isset($_GET['reduced'])) $bReduced = true; - $sClass = false; - if (isset($_GET['class'])) $sClass = $_GET['class']; + + $sOutputFormat = 'html'; + $iDays = getParamInt('days', 1); + $bReduced = getParamBool('reduced', false); + $sClass = getParamString('class', false); $iTotalBroken = (int) $oDB->getOne('select count(*) from import_polygon_error'); @@ -21,19 +19,11 @@ $sSQL = 'select osm_type as "type",osm_id as "id",class as "key",type as "value",name->\'name\' as "name",'; $sSQL .= 'country_code as "country",errormessage as "error message",updated'; $sSQL .= " from import_polygon_error"; - if ($_GET['days']) - { - $sSQL .= " where updated > 'now'::timestamp - '".(int)$_GET['days']." day'::interval"; - $_GET['days']++; - } - if ($bReduced) - { - $sSQL .= " and errormessage like 'Area reduced%'"; - } - if ($sClass) - { - $sSQL .= " and class = '".pg_escape_string($sClass)."'"; - } + $sSQL .= " where updated > 'now'::timestamp - '".$iDays." day'::interval"; + $iDays++; + + if ($bReduced) $sSQL .= " and errormessage like 'Area reduced%'"; + if ($sClass) $sSQL .= " and class = '".pg_escape_string($sClass)."'"; $sSQL .= " order by updated desc limit 1000"; $aPolygons = $oDB->getAll($sSQL); } diff --git a/website/reverse.php b/website/reverse.php index fd1f5c27..75eb2677 100755 --- a/website/reverse.php +++ b/website/reverse.php @@ -21,16 +21,12 @@ $bAsPoints = false; - $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson']; - $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml']; - $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg']; - $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text']; - if ( ( ($bAsGeoJSON?1:0) - + ($bAsKML?1:0) - + ($bAsSVG?1:0) - + ($bAsText?1:0) - + ($bAsPoints?1:0) - ) > CONST_PolygonOutput_MaximumTypes) + $bAsGeoJSON = getParamBool('polygon_geojson'); + $bAsKML = getParamBool('polygon_kml'); + $bAsSVG = getParamBool('polygon_svg'); + $bAsText = getParamBool('polygon_text'); + if ((($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0) + + ($bAsText?1:0) + ($bAsPoints?1:0)) > CONST_PolygonOutput_MaximumTypes) { if (CONST_PolygonOutput_MaximumTypes) { @@ -45,19 +41,14 @@ // Polygon simplification threshold (optional) - $fThreshold = 0.0; - if (isset($_GET['polygon_threshold'])) $fThreshold = (float)$_GET['polygon_threshold']; + $fThreshold = getParamFloat('polygon_threshold', 0.0); $oDB =& getDB(); ini_set('memory_limit', '200M'); // Format for output - $sOutputFormat = 'xml'; - if (isset($_GET['format']) && ( $_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2')) - { - $sOutputFormat = $_GET['format']; - } + $sOutputFormat = getParamSet('format', array('html', 'xml', 'json', 'jsonv2'), 'xml'); // Preferred language $aLangPrefOrder = getPreferredLanguages(); @@ -65,24 +56,28 @@ $hLog = logStart($oDB, 'reverse', $_SERVER['QUERY_STRING'], $aLangPrefOrder); - if (isset($_GET['osm_type']) && isset($_GET['osm_id']) && (int)$_GET['osm_id'] && ($_GET['osm_type'] == 'N' || $_GET['osm_type'] == 'W' || $_GET['osm_type'] == 'R')) + $sOsmType = getParamSet('osmtype', array('N', 'W', 'R')); + $iOsmId = getParamInt('osmid', -1); + $fLat = getParamFloat('lat'); + $fLon = getParamFloat('lon'); + if ($sOsmType && $iOsmId > 0) { - $aLookup = array('osm_type' => $_GET['osm_type'], 'osm_id' => $_GET['osm_id']); + $aLookup = array('osm_type' => $sOsmType, 'osm_id' => $iOsmId); } - else if (isset($_GET['lat']) && isset($_GET['lon']) && preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $_GET['lat']) && preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $_GET['lon'])) + else if ($fLat !== false && $fLon !==false) { $oReverseGeocode = new ReverseGeocode($oDB); $oReverseGeocode->setLanguagePreference($aLangPrefOrder); - $oReverseGeocode->setLatLon($_GET['lat'], $_GET['lon']); - $oReverseGeocode->setZoom(@$_GET['zoom']); + $oReverseGeocode->setLatLon($fLat, $fLon); + $oReverseGeocode->setZoom(getParamInt('zoom')); $aLookup = $oReverseGeocode->lookup(); if (CONST_Debug) var_dump($aLookup); } else { - $aLookup = null; + userError("Need coordinates or OSM object to lookup."); } if ($aLookup) diff --git a/website/search.php b/website/search.php index 31944974..776cfa78 100755 --- a/website/search.php +++ b/website/search.php @@ -25,24 +25,20 @@ } // Format for output - $sOutputFormat = 'html'; - if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2')) - { - $sOutputFormat = $_GET['format']; - } + $sOutputFormat = getParamSet('format', array('html', 'xml', 'json', 'jsonv2'), 'html'); // Show / use polygons if ($sOutputFormat == 'html') { - if (isset($_GET['polygon'])) $oGeocode->setIncludePolygonAsText((bool)$_GET['polygon']); + $oGeocode->setIncludePolygonAsText(getParamBool('polygon')); } else { - $bAsPoints = (boolean)isset($_GET['polygon']) && $_GET['polygon']; - $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson']; - $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml']; - $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg']; - $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text']; + $bAsPoints = getParamBool('polygon'); + $bAsGeoJSON = getParamBool('polygon_geojson'); + $bAsKML = getParamBool('polygon_kml'); + $bAsSVG = getParamBool('polygon_svg'); + $bAsText = getParamBool('polygon_text'); if ( ( ($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0) @@ -68,9 +64,7 @@ } // Polygon simplification threshold (optional) - $fThreshold = 0.0; - if (isset($_GET['polygon_threshold'])) $fThreshold = (float)$_GET['polygon_threshold']; - $oGeocode->setPolygonSimplificationThreshold($fThreshold); + $oGeocode->setPolygonSimplificationThreshold(getParamFloat('polygon_threshold', 0.0)); $oGeocode->loadParamArray($_GET); @@ -91,7 +85,7 @@ } else { - if (!(isset($_GET['q']) && $_GET['q']) && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/') + if (!getParamString('q') && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/') { $sQuery = substr(rawurldecode($_SERVER['PATH_INFO']), 1); From 76b9eb809815f0cc472bb2c8a8e6b613a4973e24 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sat, 11 Jun 2016 23:27:21 +0200 Subject: [PATCH 2/9] remove now unused bAsPoints in reverse API --- lib/template/address-json.php | 5 ----- lib/template/address-jsonv2.php | 5 ----- lib/template/address-xml.php | 7 ------- website/reverse.php | 9 ++++----- 4 files changed, 4 insertions(+), 22 deletions(-) diff --git a/lib/template/address-json.php b/lib/template/address-json.php index 6254357a..38db01c8 100644 --- a/lib/template/address-json.php +++ b/lib/template/address-json.php @@ -29,11 +29,6 @@ if (isset($aPlace['aBoundingBox'])) { $aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox']; - - if (isset($aPlace['aPolyPoints']) && $bAsPoints) - { - $aFilteredPlaces['polygonpoints'] = $aPlace['aPolyPoints']; - } } if (isset($aPlace['asgeojson'])) diff --git a/lib/template/address-jsonv2.php b/lib/template/address-jsonv2.php index 64c871c1..2cef5e31 100644 --- a/lib/template/address-jsonv2.php +++ b/lib/template/address-jsonv2.php @@ -41,11 +41,6 @@ if (isset($aPlace['aBoundingBox'])) { $aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox']; - - if (isset($aPlace['aPolyPoints']) && $bAsPoints) - { - $aFilteredPlaces['polygonpoints'] = $aPlace['aPolyPoints']; - } } if (isset($aPlace['asgeojson'])) diff --git a/lib/template/address-xml.php b/lib/template/address-xml.php index a3369d34..5e74846e 100644 --- a/lib/template/address-xml.php +++ b/lib/template/address-xml.php @@ -33,13 +33,6 @@ echo ' boundingbox="'; echo join(',', $aPlace['aBoundingBox']); echo '"'; - - if ($bAsPoints && isset($aPlace['aPolyPoints'])) - { - echo ' polygonpoints=\''; - echo json_encode($aPlace['aPolyPoints']); - echo '\''; - } } if (isset($aPlace['asgeojson'])) diff --git a/website/reverse.php b/website/reverse.php index 75eb2677..430d9e39 100755 --- a/website/reverse.php +++ b/website/reverse.php @@ -20,13 +20,12 @@ } - $bAsPoints = false; $bAsGeoJSON = getParamBool('polygon_geojson'); $bAsKML = getParamBool('polygon_kml'); $bAsSVG = getParamBool('polygon_svg'); $bAsText = getParamBool('polygon_text'); if ((($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0) - + ($bAsText?1:0) + ($bAsPoints?1:0)) > CONST_PolygonOutput_MaximumTypes) + + ($bAsText?1:0)) > CONST_PolygonOutput_MaximumTypes) { if (CONST_PolygonOutput_MaximumTypes) { @@ -70,12 +69,12 @@ $oReverseGeocode->setLanguagePreference($aLangPrefOrder); $oReverseGeocode->setLatLon($fLat, $fLon); - $oReverseGeocode->setZoom(getParamInt('zoom')); + $oReverseGeocode->setZoom(getParamInt('zoom', 18)); $aLookup = $oReverseGeocode->lookup(); if (CONST_Debug) var_dump($aLookup); } - else + else if ($sOutputFormat != 'html') { userError("Need coordinates or OSM object to lookup."); } @@ -90,7 +89,7 @@ $aPlace = $oPlaceLookup->lookupPlace($aLookup); - $oPlaceLookup->setIncludePolygonAsPoints($bAsPoints); + $oPlaceLookup->setIncludePolygonAsPoints(false); $oPlaceLookup->setIncludePolygonAsText($bAsText); $oPlaceLookup->setIncludePolygonAsGeoJSON($bAsGeoJSON); $oPlaceLookup->setIncludePolygonAsKML($bAsKML); From 6fef943e49ddd719524d1987e134d97fa89f2157 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sun, 12 Jun 2016 09:26:58 +0200 Subject: [PATCH 3/9] update links to OSM objects /browse/ is no longer necesary in the URL --- lib/template/details-error-html.php | 4 ++-- lib/template/details-html.php | 2 +- website/deletable.php | 2 +- website/hierarchy.php | 4 ++-- website/polygons.php | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/template/details-error-html.php b/lib/template/details-error-html.php index 1c6d2a0a..545dc52b 100644 --- a/lib/template/details-error-html.php +++ b/lib/template/details-error-html.php @@ -13,7 +13,7 @@ { $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':''))); if ($sOSMType) { - return ''.$sOSMType.' '.$aFeature['osm_id'].''; + return ''.$sOSMType.' '.$aFeature['osm_id'].''; } return ''; } @@ -130,4 +130,4 @@ - \ No newline at end of file + diff --git a/lib/template/details-html.php b/lib/template/details-html.php index ae36b411..7d9696b8 100644 --- a/lib/template/details-html.php +++ b/lib/template/details-html.php @@ -25,7 +25,7 @@ $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':''))); if ($sOSMType) { - return ''.$sOSMType.' '.$aFeature['osm_id'].''; + return ''.$sOSMType.' '.$aFeature['osm_id'].''; } return ''; } diff --git a/website/deletable.php b/website/deletable.php index 3283bb83..efd20ab3 100755 --- a/website/deletable.php +++ b/website/deletable.php @@ -82,7 +82,7 @@ table td { { case 'osm_id': $sOSMType = ($aRow['osm_type'] == 'N'?'node':($aRow['osm_type'] == 'W'?'way':($aRow['osm_type'] == 'R'?'relation':''))); - echo ''.$sVal.''; + echo ''.$sVal.''; break; case 'place_id': echo ''.$sVal.''; diff --git a/website/hierarchy.php b/website/hierarchy.php index e0e960bc..8c0ae1f5 100755 --- a/website/hierarchy.php +++ b/website/hierarchy.php @@ -69,7 +69,7 @@ $aBreadcrums[] = array('placeId'=>$aPlace['place_id'], 'osmType'=>$aPlace['osm_type'], 'osmId'=>$aPlace['osm_id'], 'localName'=>$aPlace['localname']); $sPlaceUrl = 'hierarchy.php?place_id='.$aPlace['place_id']; $sOSMType = ($aPlace['osm_type'] == 'N'?'node':($aPlace['osm_type'] == 'W'?'way':($aPlace['osm_type'] == 'R'?'relation':''))); - $sOSMUrl = 'http://www.openstreetmap.org/browse/'.$sOSMType.'/'.$aPlace['osm_id']; + $sOSMUrl = 'http://www.openstreetmap.org/'.$sOSMType.'/'.$aPlace['osm_id']; if ($sOutputFormat == 'html') if ($i) echo " > "; if ($sOutputFormat == 'html') echo ''.$aPlace['localname'].' (osm)'; } @@ -127,7 +127,7 @@ echo ''.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'No Name').''; echo ' ('; echo ''.($aAddressLine['isarea']=='t'?'Polygon':'Point').''; - if ($sOSMType) echo ', '.$sOSMType.' '.$aAddressLine['osm_id'].''; + if ($sOSMType) echo ', '.$sOSMType.' '.$aAddressLine['osm_id'].''; echo ', GOTO'; echo ', '.$aAddressLine['area']; echo ')'; diff --git a/website/polygons.php b/website/polygons.php index 92dbf70d..b6146d95 100755 --- a/website/polygons.php +++ b/website/polygons.php @@ -111,7 +111,7 @@ table td { break; case 'id': $sOSMType = ($aRow['type'] == 'N'?'node':($aRow['type'] == 'W'?'way':($aRow['type'] == 'R'?'relation':''))); - echo ''.$aRow['id'].''; + echo ''.$aRow['id'].''; break; default: echo "".($sVal?$sVal:' ').""; From 7a50d2f9964421e932313b15f5d7d3b05ded4c45 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sun, 12 Jun 2016 12:39:09 +0200 Subject: [PATCH 4/9] factor out link formatting function and osm type translation --- lib/output.php | 43 ++++++++++++++++++ lib/template/address-json.php | 5 +-- lib/template/address-jsonv2.php | 3 +- lib/template/address-xml.php | 3 +- lib/template/details-error-html.php | 31 ++++++------- lib/template/details-html.php | 33 ++------------ lib/template/search-batch-json.php | 2 +- lib/template/search-json.php | 3 +- lib/template/search-jsonv2.php | 2 +- lib/template/search-xml.php | 3 +- website/deletable.php | 7 +-- website/details.php | 2 +- website/hierarchy.php | 67 ++++++++++++++++------------- website/polygons.php | 9 ++-- website/reverse.php | 1 + website/search.php | 1 + 16 files changed, 113 insertions(+), 102 deletions(-) create mode 100644 lib/output.php diff --git a/lib/output.php b/lib/output.php new file mode 100644 index 00000000..722d73b1 --- /dev/null +++ b/lib/output.php @@ -0,0 +1,43 @@ +'.$sOSMType.' '.($sRefText?$sRefText:$aFeature['osm_id']).''; + } + return ''; + } + + function wikipediaLink($aFeature) + { + if ($aFeature['wikipedia']) + { + list($sLanguage, $sArticle) = explode(':',$aFeature['wikipedia']); + return ''.$aFeature['wikipedia'].''; + } + return ''; + } + + function detailsLink($aFeature, $sTitle=false) + { + if (!$aFeature['place_id']) return ''; + + return ''.($sTitle?$sTitle:$aFeature['place_id']).''; + } + diff --git a/lib/template/address-json.php b/lib/template/address-json.php index 38db01c8..bf6c700b 100644 --- a/lib/template/address-json.php +++ b/lib/template/address-json.php @@ -12,8 +12,7 @@ { 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 = ($aPlace['osm_type'] == 'N'?'node':($aPlace['osm_type'] == 'W'?'way':($aPlace['osm_type'] == 'R'?'relation': - ($aPlace['osm_type'] == 'T'?'tiger':($aPlace['osm_type'] == 'I'?'interpolation':''))))); + $sOSMType = formatOSMType($aPlace['osm_type']); if ($sOSMType) { $aFilteredPlaces['osm_type'] = $sOSMType; @@ -50,8 +49,6 @@ { $aFilteredPlaces['geokml'] = $aPlace['askml']; } - - } javascript_renderData($aFilteredPlaces); diff --git a/lib/template/address-jsonv2.php b/lib/template/address-jsonv2.php index 2cef5e31..d6214176 100644 --- a/lib/template/address-jsonv2.php +++ b/lib/template/address-jsonv2.php @@ -12,8 +12,7 @@ { if ($aPlace['place_id']) $aFilteredPlaces['place_id'] = $aPlace['place_id']; $aFilteredPlaces['licence'] = "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright"; - $sOSMType = ($aPlace['osm_type'] == 'N'?'node':($aPlace['osm_type'] == 'W'?'way':($aPlace['osm_type'] == 'R'?'relation': - ($aPlace['osm_type'] == 'T'?'tiger':($aPlace['osm_type'] == 'I'?'interpolation':''))))); + $sOSMType = formatOSMType($aPlace['osm_type']); if ($sOSMType) { $aFilteredPlaces['osm_type'] = $sOSMType; diff --git a/lib/template/address-xml.php b/lib/template/address-xml.php index 5e74846e..2bfcffbf 100644 --- a/lib/template/address-xml.php +++ b/lib/template/address-xml.php @@ -22,8 +22,7 @@ { echo "'.$sOSMType.' '.$aFeature['osm_id'].''; - } - return ''; - } - - function osm_map_url($aFeature) + function osmMapUrl($aFeature) { $sLon = $aFeature['error_x']; $sLat = $aFeature['error_y']; - if (isset($sLat)) + if (isset($sFeature['error_x']) && isset($sFeature['error_y'])) { - $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':''))); + $sBaseUrl = '//www.openstreetmap.org/'; + $sOSMType = formatOSMType($aFeature['osm_type'], false); if ($sOSMType) { - return "http://www.openstreetmap.org/?lat=".$sLat."&lon=".$sLon."&zoom=18&layers=M&".$sOSMType."=".$aFeature['osm_id']; + $sBaseUrl += $sOSMType.'/'.$aFeature['osm_id']; + } + + return 'view on osm.org'; } } return ''; @@ -45,7 +40,7 @@ return "http://localhost:8111/load_and_zoom?left=".($sLon-$fWidth)."&right=".($sLon+$fWidth)."&top=".($sLat+$fWidth)."&bottom=".($sLat-$fWidth); } - $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':''))); + $sOSMType = formatOSMType($aFeature['osm_type'], false); if ($sOSMType) { return 'http://localhost:8111/import?url=http://www.openstreetmap.org/api/0.6/'.$sOSMType.'/'.$aFeature['osm_id'].'/full'; @@ -63,7 +58,7 @@ if (isset($sLat)) { - return "http://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 ''; } @@ -87,7 +82,7 @@
- OSM: + OSM:
@@ -95,9 +90,7 @@

- - view on osm.org - +

Edit

    diff --git a/lib/template/details-html.php b/lib/template/details-html.php index 7d9696b8..71fcc7b3 100644 --- a/lib/template/details-html.php +++ b/lib/template/details-html.php @@ -7,7 +7,6 @@ -

    ".$sTitle."

    \n"; } - function osm_link($aFeature) - { - $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':''))); - if ($sOSMType) - { - return ''.$sOSMType.' '.$aFeature['osm_id'].''; - } - return ''; - } - - function wikipedia_link($aFeature) - { - if ($aFeature['wikipedia']) - { - list($sWikipediaLanguage,$sWikipediaArticle) = explode(':',$aFeature['wikipedia']); - return ''.$aFeature['wikipedia'].''; - } - return ''; - } - - function nominatim_link($aFeature, $sTitle) - { - return ''.$sTitle.''; - } function format_distance($fDistance) { @@ -92,10 +67,10 @@ echo ''."\n"; echo ' '.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'No Name')."\n"; echo ' ' . $aAddressLine['class'].':'.$aAddressLine['type'] . "\n"; - echo ' ' . osm_link($aAddressLine) . "\n"; + echo ' ' . osmLink($aAddressLine) . "\n"; echo ' ' . (isset($aAddressLine['admin_level']) ? $aAddressLine['admin_level'] : '') . "\n"; echo ' ' . format_distance($aAddressLine['distance'])."\n"; - echo ' ' . nominatim_link($aAddressLine,'details >') . "\n"; + echo ' ' . detailsLink($aAddressLine,'details >') . "\n"; echo "\n"; } @@ -143,10 +118,10 @@ } kv('Coverage' , ($aPointDetails['isarea']=='t'?'Polygon':'Point') ); kv('Centre Point' , $aPointDetails['lat'].','.$aPointDetails['lon'] ); - kv('OSM' , osm_link($aPointDetails) ); + kv('OSM' , osmLink($aPointDetails) ); if ($aPointDetails['wikipedia']) { - kv('Wikipedia Calculated' , wikipedia_link($aPointDetails) ); + kv('Wikipedia Calculated' , wikipediaLink($aPointDetails) ); } kv('Extra Tags' , hash_to_subtable($aPointDetails['aExtraTags']) ); diff --git a/lib/template/search-batch-json.php b/lib/template/search-batch-json.php index edfe3871..60d38041 100644 --- a/lib/template/search-batch-json.php +++ b/lib/template/search-batch-json.php @@ -14,7 +14,7 @@ 'place_id'=>$aPointDetails['place_id'], ); - $sOSMType = ($aPointDetails['osm_type'] == 'N'?'node':($aPointDetails['osm_type'] == 'W'?'way':($aPointDetails['osm_type'] == 'R'?'relation':''))); + $sOSMType = formatOSMType($aPointDetails['osm_type']); if ($sOSMType) { $aPlace['osm_type'] = $sOSMType; diff --git a/lib/template/search-json.php b/lib/template/search-json.php index 5d5ebfe8..d3dc00f3 100644 --- a/lib/template/search-json.php +++ b/lib/template/search-json.php @@ -9,8 +9,7 @@ 'licence'=>"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright", ); - $sOSMType = ($aPointDetails['osm_type'] == 'N'?'node':($aPointDetails['osm_type'] == 'W'?'way':($aPointDetails['osm_type'] == 'R'? - 'relation':($aPointDetails['osm_type'] == 'T'?'tiger':($aPointDetails['osm_type'] == 'I'?'interpolation':''))))); + $sOSMType = formatOSMType($aPointDetails['osm_type']); if ($sOSMType) { $aPlace['osm_type'] = $sOSMType; diff --git a/lib/template/search-jsonv2.php b/lib/template/search-jsonv2.php index 251388b5..e907a081 100644 --- a/lib/template/search-jsonv2.php +++ b/lib/template/search-jsonv2.php @@ -7,7 +7,7 @@ 'licence'=>"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright", ); - $sOSMType = ($aPointDetails['osm_type'] == 'N'?'node':($aPointDetails['osm_type'] == 'W'?'way':($aPointDetails['osm_type'] == 'R'?'relation':($aPointDetails['osm_type'] == 'T'?'tiger':($aPointDetails['osm_type'] == 'I'?'interpolation':''))))); + $sOSMType = formatOSMType($aPointDetails['osm_type']); if ($sOSMType) { $aPlace['osm_type'] = $sOSMType; diff --git a/lib/template/search-xml.php b/lib/template/search-xml.php index 7cbcc04b..7a5c997f 100644 --- a/lib/template/search-xml.php +++ b/lib/template/search-xml.php @@ -25,8 +25,7 @@ foreach($aSearchResults as $iResNum => $aResult) { echo " "; //var_dump($aPolygons[0]); foreach($aPolygons[0] as $sCol => $sVal) @@ -81,11 +83,10 @@ table td { switch($sCol) { case 'osm_id': - $sOSMType = ($aRow['osm_type'] == 'N'?'node':($aRow['osm_type'] == 'W'?'way':($aRow['osm_type'] == 'R'?'relation':''))); - echo ''.$sVal.''; + echo ''.osmLink($aRow).''; break; case 'place_id': - echo ''.$sVal.''; + echo ''.detailsLink($aRow).''; break; default: echo "".($sVal?$sVal:' ').""; diff --git a/website/details.php b/website/details.php index 2891ecfc..b3c9591b 100755 --- a/website/details.php +++ b/website/details.php @@ -4,6 +4,7 @@ require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); + require_once(CONST_BasePath.'/lib/output.php'); $sOutputFormat = 'html'; /* @@ -173,5 +174,4 @@ $sTileAttribution = CONST_Map_Tile_Attribution; } - include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php'); diff --git a/website/hierarchy.php b/website/hierarchy.php index 8c0ae1f5..7740abbc 100755 --- a/website/hierarchy.php +++ b/website/hierarchy.php @@ -5,6 +5,7 @@ require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php'); + require_once(CONST_BasePath.'/lib/output.php'); ini_set('memory_limit', '200M'); $oDB =& getDB(); @@ -66,12 +67,17 @@ foreach($aPlaceAddress as $i => $aPlace) { if (!$aPlace['place_id']) continue; - $aBreadcrums[] = array('placeId'=>$aPlace['place_id'], 'osmType'=>$aPlace['osm_type'], 'osmId'=>$aPlace['osm_id'], 'localName'=>$aPlace['localname']); - $sPlaceUrl = 'hierarchy.php?place_id='.$aPlace['place_id']; - $sOSMType = ($aPlace['osm_type'] == 'N'?'node':($aPlace['osm_type'] == 'W'?'way':($aPlace['osm_type'] == 'R'?'relation':''))); - $sOSMUrl = 'http://www.openstreetmap.org/'.$sOSMType.'/'.$aPlace['osm_id']; - if ($sOutputFormat == 'html') if ($i) echo " > "; - if ($sOutputFormat == 'html') echo ''.$aPlace['localname'].' (osm)'; + $aBreadcrums[] = array('placeId' => $aPlace['place_id'], + 'osmType' => $aPlace['osm_type'], + 'osmId' => $aPlace['osm_id'], + 'localName' => $aPlace['localname']); + + if ($sOutputFormat == 'html') + { + $sPlaceUrl = 'hierarchy.php?place_id='.$aPlace['place_id']; + if ($i) echo " > "; + echo ''.$aPlace['localname'].' ('.osmLink($aPlace).')'; + } } @@ -114,28 +120,29 @@ if (!isset($aGroupedAddressLines[$aAddressLine['label']])) $aGroupedAddressLines[$aAddressLine['label']] = array(); $aGroupedAddressLines[$aAddressLine['label']][] = $aAddressLine; - } - foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines) - { - echo "

    $sGroupHeading

    "; - foreach($aParentOfLines as $aAddressLine) - { - $aAddressLine['localname'] = $aAddressLine['localname']?$aAddressLine['localname']:$aAddressLine['housenumber']; - $sOSMType = ($aAddressLine['osm_type'] == 'N'?'node':($aAddressLine['osm_type'] == 'W'?'way':($aAddressLine['osm_type'] == 'R'?'relation':''))); - - echo '
    '; - echo ''.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'No Name').''; - echo ' ('; - echo ''.($aAddressLine['isarea']=='t'?'Polygon':'Point').''; - if ($sOSMType) echo ', '.$sOSMType.' '.$aAddressLine['osm_id'].''; - echo ', GOTO'; - echo ', '.$aAddressLine['area']; - echo ')'; - echo '
    '; - } - } - if (sizeof($aParentOfLines) >= 500) { - echo '

    There are more child objects which are not shown.

    '; - } - echo ''; } + + foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines) + { + echo "

    $sGroupHeading

    "; + foreach($aParentOfLines as $aAddressLine) + { + $aAddressLine['localname'] = $aAddressLine['localname']?$aAddressLine['localname']:$aAddressLine['housenumber']; + $sOSMType = formatOSMType($aAddressLine['osm_type'], false); + + echo '
    '; + echo ''.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'No Name').''; + echo ' ('; + echo ''.($aAddressLine['isarea']=='t'?'Polygon':'Point').''; + if ($sOSMType) echo ', '.$sOSMType.' '.osmLink($aAddressLine).''; + echo ', GOTO'; + echo ', '.$aAddressLine['area']; + echo ')'; + echo '
    '; + } + } + if (sizeof($aParentOfLines) >= 500) { + echo '

    There are more child objects which are not shown.

    '; + } + echo ''; + } diff --git a/website/polygons.php b/website/polygons.php index b6146d95..bb350e6c 100755 --- a/website/polygons.php +++ b/website/polygons.php @@ -2,6 +2,7 @@ require_once(dirname(dirname(__FILE__)).'/settings/settings.php'); require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); + require_once(CONST_BasePath.'/lib/output.php'); ini_set('memory_limit', '200M'); $oDB =& getDB(); @@ -77,6 +78,7 @@ table td { Total number of broken polygons: $iTotalBroken

    "; + if (!$aPolygons) exit; echo ""; echo ""; //var_dump($aPolygons[0]); @@ -110,8 +112,7 @@ table td { } break; case 'id': - $sOSMType = ($aRow['type'] == 'N'?'node':($aRow['type'] == 'W'?'way':($aRow['type'] == 'R'?'relation':''))); - echo ''; + echo ''; break; default: echo ""; @@ -130,10 +131,6 @@ table td { echo ""; } echo "
    '.$aRow['id'].''.osmLink($aRow).'".($sVal?$sVal:' ')."
    "; - - - -// include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php'); ?> diff --git a/website/reverse.php b/website/reverse.php index 430d9e39..c6c7305f 100755 --- a/website/reverse.php +++ b/website/reverse.php @@ -6,6 +6,7 @@ require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php'); require_once(CONST_BasePath.'/lib/ReverseGeocode.php'); + require_once(CONST_BasePath.'/lib/output.php'); if (strpos(CONST_BulkUserIPs, ','.$_SERVER["REMOTE_ADDR"].',') !== false) { diff --git a/website/search.php b/website/search.php index 776cfa78..3c85c8f7 100755 --- a/website/search.php +++ b/website/search.php @@ -5,6 +5,7 @@ require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/Geocode.php'); + require_once(CONST_BasePath.'/lib/output.php'); ini_set('memory_limit', '200M'); From 95961d098da553a335c9c44dc6a9827b83e7fc99 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sun, 12 Jun 2016 14:34:57 +0200 Subject: [PATCH 5/9] introduce chksql function for website code and move other fail functions The default error screen now reports the full SQL even when not in debug mode as this message is often more helpful than our custom error message. --- lib/db.php | 9 ++--- lib/lib.php | 39 -------------------- lib/website.php | 83 +++++++++++++++++++++++++++++++++++++++++++ website/deletable.php | 13 +++---- website/details.php | 21 ++++------- website/hierarchy.php | 14 ++++---- website/polygons.php | 11 ++++-- website/reverse.php | 2 +- website/search.php | 2 +- 9 files changed, 116 insertions(+), 78 deletions(-) diff --git a/lib/db.php b/lib/db.php index cc84bf9b..822acc37 100644 --- a/lib/db.php +++ b/lib/db.php @@ -4,13 +4,8 @@ function &getDB($bNew = false, $bPersistent = false) { // Get the database object - $oDB = DB::connect(CONST_Database_DSN.($bNew?'?new_link=true':''), $bPersistent); - if (PEAR::IsError($oDB)) - { - var_dump(CONST_Database_DSN); - var_Dump($oDB); - fail($oDB->getMessage()); - } + $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'"); diff --git a/lib/lib.php b/lib/lib.php index fc393685..9f017fc4 100644 --- a/lib/lib.php +++ b/lib/lib.php @@ -1,44 +1,5 @@

    Internal Server Error

    "; - echo '

    Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.

    '; - echo "

    Details: ".$sError,"

    "; - echo '

    Feel free to report the bug in the OSM bug database. Please include the error message above and the URL you used.

    '; - if (CONST_Debug) - { - echo "

    Debugging Information


    "; - if ($sSQL) - { - echo "

    SQL query

    ".$sSQL.""; - } - if ($vDumpVar) - { - echo "

    Result

    "; - var_dump($vDumpVar); - echo ""; - } - } - echo "\n\n"; - exit; - } - - - function userError($sError) - { - header('HTTP/1.0 400 Bad Request'); - header('Content-type: text/html; charset=utf-8'); - echo "

    Bad Request

    "; - echo '

    Nominatim has encountered an error with your request.

    '; - echo "

    Details: ".$sError,"

    "; - echo '

    If you feel this error is incorrect feel free to report the bug in the OSM bug database. Please include the error message above and the URL you used.

    '; - echo "\n\n"; - exit; - } - function fail($sError, $sUserError = false) { if (!$sUserError) $sUserError = $sError; diff --git a/lib/website.php b/lib/website.php index cf228f38..22ec08f1 100644 --- a/lib/website.php +++ b/lib/website.php @@ -1,5 +1,88 @@ getMessage(); + + echo << + Internal Server Error + +

    Internal Server Error

    +

    Nominatim has encountered an internal error while accessing the database. + This may happen because the database is broken or because of a bug in + the software. If you think it is a bug, feel free to report + it over on + Github. Please include the URL that caused the problem and the + complete error details below.

    +

    Message: $sMsg

    +

    SQL Error: $sSqlError

    +

    Details:

    +INTERNALFAIL;
    +
    +		if (CONST_Debug)
    +		{
    +			var_dump($oSql);
    +		}
    +		else
    +		{
    +			echo "
    \n".$oSql->getUserInfo()."
    "; + } + + echo "

    "; + exit; + } + + function failInternalError($sError, $sSQL = false, $vDumpVar = false) + { + header('HTTP/1.0 500 Internal Server Error'); + header('Content-type: text/html; charset=utf-8'); + echo "

    Internal Server Error

    "; + echo '

    Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.

    '; + echo "

    Details: ".$sError,"

    "; + echo '

    Feel free to file an issue on Github. Please include the error message above and the URL you used.

    '; + if (CONST_Debug) + { + echo "

    Debugging Information


    "; + if ($sSQL) + { + echo "

    SQL query

    ".$sSQL.""; + } + if ($vDumpVar) + { + echo "

    Result

    "; + var_dump($vDumpVar); + echo ""; + } + } + echo "\n\n"; + exit; + } + + + function userError($sError) + { + header('HTTP/1.0 400 Bad Request'); + header('Content-type: text/html; charset=utf-8'); + echo "

    Bad Request

    "; + echo '

    Nominatim has encountered an error with your request.

    '; + echo "

    Details: ".$sError,"

    "; + echo '

    If you feel this error is incorrect feel file an issue on Github. Please include the error message above and the URL you used.

    '; + echo "\n\n"; + exit; + } + + /*************************************************************************** * * Functions for parsing URL parameters diff --git a/website/deletable.php b/website/deletable.php index 6521e774..95a2ec00 100755 --- a/website/deletable.php +++ b/website/deletable.php @@ -10,13 +10,14 @@ $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"; - $aPolygons = $oDB->getAll($sSQL); - if (PEAR::isError($aPolygons)) - { - failInternalError("Could not get list of deleted OSM elements.", $sSQL, $aPolygons); - } + $aPolygons = chksql($oDB->getAll($sSQL), + "Could not get list of deleted OSM elements."); -//var_dump($aPolygons); + if (CONST_DEBUG) + { + var_dump($aPolygons); + exit; + } ?> diff --git a/website/details.php b/website/details.php index b3c9591b..495db2b4 100755 --- a/website/details.php +++ b/website/details.php @@ -27,13 +27,13 @@ $iOsmId = getParamInt('osmid', -1); if ($sOsmType && $iOsmId > 0) { - $sPlaceId = $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 if (!$sPlaceId) { - $aPointDetails = $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 (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) { @@ -58,22 +58,18 @@ if (CONST_Use_US_Tiger_Data) { - $iParentPlaceID = $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 (CONST_Use_Aux_Location_data) { - $iParentPlaceID = $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; } $hLog = logStart($oDB, 'details', $_SERVER['QUERY_STRING'], $aLangPrefOrder); - // Make sure the point we are reporting on is fully indexed - //$sSQL = "UPDATE placex set indexed = true where indexed = false and place_id = $iPlaceID"; - //$oDB->query($sSQL); - // 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 .= " 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, "; @@ -83,11 +79,8 @@ $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 .= " from placex where place_id = $iPlaceID"; - $aPointDetails = $oDB->getRow($sSQL); - if (PEAR::IsError($aPointDetails)) - { - failInternalError("Could not get details of place object.", $sSQL, $aPointDetails); - } + $aPointDetails = chksql($oDB->getRow($sSQL), + "Could not get details of place object."); $aPointDetails['localname'] = $aPointDetails['localname']?$aPointDetails['localname']:$aPointDetails['housenumber']; $aClassType = getClassTypesWithImportance(); @@ -169,7 +162,7 @@ if ($sOutputFormat=='html') { - $sDataDate = $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; $sTileAttribution = CONST_Map_Tile_Attribution; } diff --git a/website/hierarchy.php b/website/hierarchy.php index 7740abbc..b14422fa 100755 --- a/website/hierarchy.php +++ b/website/hierarchy.php @@ -20,13 +20,13 @@ $iOsmId = getParamInt('osmid', -1); if ($sOsmType && $iOsmId > 0) { - $sPlaceId = $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 if (!$sPlaceId) { - $aPointDetails = $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) { + $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 (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) { $aPointDetails['error_x'] = $aMatches[1]; @@ -44,13 +44,13 @@ if (CONST_Use_US_Tiger_Data) { - $iParentPlaceID = $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 (CONST_Use_Aux_Location_data) { - $iParentPlaceID = $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; } @@ -90,14 +90,14 @@ exit; } - $aRelatedPlaceIDs = $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 .= " 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 .= " 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"; - $aParentOfLines = $oDB->getAll($sSQL); + $aParentOfLines = chksql($oDB->getAll($sSQL)); if (sizeof($aParentOfLines)) { diff --git a/website/polygons.php b/website/polygons.php index bb350e6c..b855214a 100755 --- a/website/polygons.php +++ b/website/polygons.php @@ -12,7 +12,7 @@ $bReduced = getParamBool('reduced', false); $sClass = getParamString('class', false); - $iTotalBroken = (int) $oDB->getOne('select count(*) from import_polygon_error'); + $iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error')); $aPolygons = array(); while($iTotalBroken && !sizeof($aPolygons)) @@ -26,9 +26,14 @@ if ($bReduced) $sSQL .= " and errormessage like 'Area reduced%'"; if ($sClass) $sSQL .= " and class = '".pg_escape_string($sClass)."'"; $sSQL .= " order by updated desc limit 1000"; - $aPolygons = $oDB->getAll($sSQL); + $aPolygons = chksql($oDB->getAll($sSQL)); + } + + if (CONST_Debug) + { + var_dump($aPolygons); + exit; } -//var_dump($aPolygons); ?> diff --git a/website/reverse.php b/website/reverse.php index c6c7305f..17b8a2ca 100755 --- a/website/reverse.php +++ b/website/reverse.php @@ -119,7 +119,7 @@ if ($sOutputFormat=='html') { - $sDataDate = $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; $sTileAttribution = CONST_Map_Tile_Attribution; } diff --git a/website/search.php b/website/search.php index 3c85c8f7..4baf3ef5 100755 --- a/website/search.php +++ b/website/search.php @@ -109,7 +109,7 @@ if ($sOutputFormat=='html') { - $sDataDate = $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)); From 033b9590bdf562a21a45b85e9cfaefee0db754e1 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sun, 12 Jun 2016 14:58:05 +0200 Subject: [PATCH 6/9] use chksql everywhere in lib/ Replaces manual PEAR error checks and adds the chksql wrapper where the error checks were still missing. --- lib/Geocode.php | 86 ++++++++++++++++++------------------------ lib/PlaceLookup.php | 26 +++---------- lib/ReverseGeocode.php | 46 +++++++--------------- lib/lib.php | 35 +++-------------- 4 files changed, 60 insertions(+), 133 deletions(-) diff --git a/lib/Geocode.php b/lib/Geocode.php index 0c3c5f73..aa65cb69 100644 --- a/lib/Geocode.php +++ b/lib/Geocode.php @@ -514,12 +514,8 @@ $sSQL .= " order by importance desc"; if (CONST_Debug) { echo "
    "; var_dump($sSQL); } - $aSearchResults = $this->oDB->getAll($sSQL); - - if (PEAR::IsError($aSearchResults)) - { - failInternalError("Could not get details for place.", $sSQL, $aSearchResults); - } + $aSearchResults = chksql($this->oDB->getAll($sSQL); + "Could not get details for place."); return $aSearchResults; } @@ -883,19 +879,13 @@ $sViewboxCentreSQL .= ")'::geometry,4326)"; $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")"; - $this->sViewboxSmallSQL = $this->oDB->getOne($sSQL); - if (PEAR::isError($this->sViewboxSmallSQL)) - { - failInternalError("Could not get small viewbox.", $sSQL, $this->sViewboxSmallSQL); - } + $this->sViewboxSmallSQL = chksql($this->oDB->getOne($sSQL); + "Could not get small viewbox."); $this->sViewboxSmallSQL = "'".$this->sViewboxSmallSQL."'::geometry"; $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")"; - $this->sViewboxLargeSQL = $this->oDB->getOne($sSQL); - if (PEAR::isError($this->sViewboxLargeSQL)) - { - failInternalError("Could not get large viewbox.", $sSQL, $this->sViewboxLargeSQL); - } + $this->sViewboxLargeSQL = chksql($this->oDB->getOne($sSQL), + "Could not get large viewbox."); $this->sViewboxLargeSQL = "'".$this->sViewboxLargeSQL."'::geometry"; $bBoundingBoxSearch = $this->bBoundedSearch; } @@ -961,11 +951,11 @@ foreach($aSpecialTermsRaw as $aSpecialTerm) { $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery); - $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string"); + $sToken = chksql($this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string")); $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator'; $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null'; if (CONST_Debug) var_Dump($sSQL); - $aSearchWords = $this->oDB->getAll($sSQL); + $aSearchWords = chksql($this->oDB->getAll($sSQL)); $aNewSearches = array(); foreach($aSearches as $aSearch) { @@ -1010,13 +1000,8 @@ $aTokens = array(); foreach($aPhrases as $iPhrase => $sPhrase) { - $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string"); - if (PEAR::isError($aPhrase)) - { - userError("Illegal query string (not an UTF-8 string): ".$sPhrase); - if (CONST_Debug) var_dump($aPhrase); - exit; - } + $aPhrase = chksql($this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string"), + "Cannot nomralize query string (is it an UTF-8 string?)"); if (trim($aPhrase['string'])) { $aPhrases[$iPhrase] = $aPhrase; @@ -1043,11 +1028,14 @@ if (CONST_Debug) var_Dump($sSQL); $aValidTokens = array(); - if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL); - else $aDatabaseWords = array(); - if (PEAR::IsError($aDatabaseWords)) + if (sizeof($aTokens)) { - failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords); + $aDatabaseWords = chksql($this->oDB->getAll($sSQL), + "Could not get word tokens."); + } + else + { + $aDatabaseWords = array(); } $aPossibleMainWordIDs = array(); $aWordFrequencyScores = array(); @@ -1264,7 +1252,7 @@ $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)"; $sSQL .= " order by st_area(geometry) desc limit 1"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); } else { @@ -1276,7 +1264,7 @@ if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue; if (!$aSearch['sClass']) continue; $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'"; - if ($this->oDB->getOne($sSQL)) + if (chksql($this->oDB->getOne($sSQL))) { $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct"; if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)"; @@ -1289,7 +1277,7 @@ if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc"; $sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); // If excluded place IDs are given, it is fair to assume that // there have been results in the small box, so no further @@ -1304,7 +1292,7 @@ if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc"; $sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); } } else @@ -1315,7 +1303,7 @@ if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc"; $sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); } } } @@ -1426,10 +1414,8 @@ $sSQL .= " limit ".$this->iLimit; if (CONST_Debug) { var_dump($sSQL); } - $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL); - if (PEAR::IsError($aViewBoxPlaceIDs)) - { - failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs); + $aViewBoxPlaceIDs = chksql($this->oDB->getAll($sSQL)); + "Could not get places for search terms."); } //var_dump($aViewBoxPlaceIDs); // Did we have an viewbox matches? @@ -1464,7 +1450,7 @@ } $sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); // if nothing found, search in the interpolation line table if(!sizeof($aPlaceIDs)) @@ -1486,7 +1472,7 @@ //$sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); //get place IDs - $aPlaceIDs = $this->oDB->getCol($sSQL, 0); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0)); } // If nothing found try the aux fallback table @@ -1499,7 +1485,7 @@ } //$sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); } //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger) @@ -1521,7 +1507,7 @@ //$sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); //get place IDs - $aPlaceIDs = $this->oDB->getCol($sSQL, 0); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0)); } // Fallback to the road (if no housenumber was found) @@ -1548,18 +1534,18 @@ if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)"; $sSQL .= " order by rank_search asc limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aClassPlaceIDs = $this->oDB->getCol($sSQL); + $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL)); } if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in { $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'"; - $bCacheTable = $this->oDB->getOne($sSQL); + $bCacheTable = chksql($this->oDB->getOne($sSQL)); $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)"; if (CONST_Debug) var_dump($sSQL); - $this->iMaxRank = ((int)$this->oDB->getOne($sSQL)); + $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL))); // For state / country level searches the normal radius search doesn't work very well $sPlaceGeom = false; @@ -1568,7 +1554,7 @@ // Try and get a polygon to search in instead $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1"; if (CONST_Debug) var_dump($sSQL); - $sPlaceGeom = $this->oDB->getOne($sSQL); + $sPlaceGeom = chksql($this->oDB->getOne($sSQL)); } if ($sPlaceGeom) @@ -1580,7 +1566,7 @@ $this->iMaxRank += 5; $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank"; if (CONST_Debug) var_dump($sSQL); - $aPlaceIDs = $this->oDB->getCol($sSQL); + $aPlaceIDs = chksql($this->oDB->getCol($sSQL)); $sPlaceIDs = join(',',$aPlaceIDs); } @@ -1619,7 +1605,7 @@ if ($this->iOffset) $sSQL .= " offset $this->iOffset"; $sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL)); + $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL))); } else { @@ -1641,7 +1627,7 @@ if ($this->iOffset) $sSQL .= " offset $this->iOffset"; $sSQL .= " limit $this->iLimit"; if (CONST_Debug) var_dump($sSQL); - $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL)); + $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL))); } } } @@ -1685,7 +1671,7 @@ $sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',',array_keys($aResultPlaceIDs)).")"; $sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)"; if (CONST_Debug) var_dump($sSQL); - $aFilteredPlaceIDs = $this->oDB->getCol($sSQL); + $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL)); $tempIDs = array(); foreach($aFilteredPlaceIDs as $placeID) { diff --git a/lib/PlaceLookup.php b/lib/PlaceLookup.php index be60ff07..831f6ef6 100644 --- a/lib/PlaceLookup.php +++ b/lib/PlaceLookup.php @@ -100,7 +100,7 @@ function setOSMID($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"; - $this->iPlaceID = $this->oDB->getOne($sSQL); + $this->iPlaceID = chksql($this->oDB->getOne($sSQL)); } function lookupPlace($details) @@ -175,13 +175,7 @@ $sSQL .= " from placex where place_id = ".(int)$this->iPlaceID; } - $aPlace = $this->oDB->getRow($sSQL); - - - if (PEAR::IsError($aPlace)) - { - failInternalError("Could not lookup place.", $sSQL, $aPlace); - } + $aPlace = chksql($this->oDB->getRow($sSQL), "Could not lookup place"); if (!$aPlace['place_id']) return null; @@ -248,13 +242,7 @@ if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'"; $sSQL .= " order by rank_address desc,isaddress desc"; - $aAddressLines = $this->oDB->getAll($sSQL); - if (PEAR::IsError($aAddressLines)) - { - var_dump($aAddressLines); - exit; - } - return $aAddressLines; + return chksql($this->oDB->getAll($sSQL)); } function getAddressNames($housenumber = -1) @@ -332,12 +320,8 @@ $sSQL .= $sFrom; } - $aPointPolygon = $this->oDB->getRow($sSQL); - if (PEAR::IsError($aPointPolygon)) - { - echo var_dump($aPointPolygon); - failInternalError("Could not get outline.", $sSQL, $aPointPolygon); - } + $aPointPolygon = chksql($this->oDB->getRow($sSQL), + "Could not get outline"); if ($aPointPolygon['place_id']) { diff --git a/lib/ReverseGeocode.php b/lib/ReverseGeocode.php index 05093af3..4eeb5cc4 100644 --- a/lib/ReverseGeocode.php +++ b/lib/ReverseGeocode.php @@ -148,11 +148,8 @@ $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))'; $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1'; if (CONST_Debug) var_dump($sSQL); - $aPlace = $this->oDB->getRow($sSQL); - if (PEAR::IsError($aPlace)) - { - failInternalError("Could not determine closest place.", $sSQL, $aPlace); - } + $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'); @@ -172,17 +169,14 @@ $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL); var_dump($sSQL); - $aAllHouses = $this->oDB->getAll($sSQL); + $aAllHouses = chksql($this->oDB->getAll($sSQL)); foreach($aAllHouses as $i) { echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "
    \n"; } } - $aPlaceLine = $this->oDB->getRow($sSQL); - if (PEAR::IsError($aPlaceLine)) - { - failInternalError("Could not determine closest housenumber on an osm interpolation line.", $sSQL, $aPlaceLine); - } + $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); @@ -192,20 +186,14 @@ // 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 = $this->oDB->getRow($sSQL); - if (PEAR::IsError($aDistancePlacex)) - { - failInternalError("Could not determine distance between searched point and placex house.", $sSQL, $aDistancePlacex); - } + $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 = $this->oDB->getRow($sSQL); - if (PEAR::IsError($aDistanceInterpolation)) - { - failInternalError("Could not determine distance between searched point and interpolated house.", $sSQL, $aDistanceInterpolation); - } + $aDistanceInterpolation = chksql($this->oDB->getRow($sSQL), + "Could not determine distance between searched point and interpolated house."); $fDistanceInterpolation = $aDistanceInterpolation['distance']; if ($fDistanceInterpolation < $fDistancePlacex) { @@ -244,18 +232,15 @@ $sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL); var_dump($sSQL); - $aAllHouses = $this->oDB->getAll($sSQL); + $aAllHouses = chksql($this->oDB->getAll($sSQL)); foreach($aAllHouses as $i) { echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "
    \n"; } } - $aPlaceTiger = $this->oDB->getRow($sSQL); - if (PEAR::IsError($aPlaceTiger)) - { - failInternalError("Could not determine closest Tiger place.", $sSQL, $aPlaceTiger); - } + $aPlaceTiger = chksql($this->oDB->getRow($sSQL), + "Could not determine closest Tiger place."); if ($aPlaceTiger) { if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger); @@ -279,11 +264,8 @@ $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 = $this->oDB->getOne($sSQL); - if (PEAR::IsError($iPlaceID)) - { - failInternalError("Could not get parent for place.", $sSQL, $iPlaceID); - } + $iPlaceID = chksql($this->oDB->getOne($sSQL), + "Could not get parent for place."); if (!$iPlaceID) { $iPlaceID = $aPlace['place_id']; diff --git a/lib/lib.php b/lib/lib.php index 9f017fc4..ec5b9b1f 100644 --- a/lib/lib.php +++ b/lib/lib.php @@ -177,12 +177,7 @@ { // Try an exact match on the gb_postcode table $sSQL = 'select \'AA\', ST_X(ST_Centroid(geometry)) as lon,ST_Y(ST_Centroid(geometry)) as lat from gb_postcode where postcode = \''.$sPostcode.'\''; - $aNearPostcodes = $oDB->getAll($sSQL); - if (PEAR::IsError($aNearPostcodes)) - { - var_dump($sSQL, $aNearPostcodes); - exit; - } + $aNearPostcodes = chksql($oDB->getAll($sSQL)); if (sizeof($aNearPostcodes)) { @@ -655,12 +650,7 @@ if (!$bRaw) $sSQL .= " WHERE isaddress OR type = 'country_code'"; $sSQL .= " order by rank_address desc,isaddress desc"; - $aAddressLines = $oDB->getAll($sSQL); - if (PEAR::IsError($aAddressLines)) - { - var_dump($aAddressLines); - exit; - } + $aAddressLines = chksql($oDB->getAll($sSQL)); if ($bRaw) return $aAddressLines; //echo "
    ";
     		//var_dump($aAddressLines);
    @@ -758,12 +748,7 @@
     			$sSQL .= ' OR ST_DWithin('.$sPointSQL.', ST_Centroid(geometry), '.$fSearchDiam.'))';
     			$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
     			//var_dump($sSQL);
    -			$aPlace = $oDB->getRow($sSQL);
    -			if (PEAR::IsError($aPlace))
    -			{
    -				var_Dump($sSQL, $aPlace);
    -				exit;
    -			}
    +			$aPlace = chksql($oDB->getRow($sSQL));
     			$iPlaceID = $aPlace['place_id'];
     		}
     
    @@ -771,22 +756,12 @@
     		if ($iPlaceID)
     		{
     			$sSQL = "select address_place_id from place_addressline where cached_rank_address <= $iMaxRank and place_id = $iPlaceID order by cached_rank_address desc,isaddress desc,distance desc limit 1";
    -			$iPlaceID = $oDB->getOne($sSQL);
    -			if (PEAR::IsError($iPlaceID))
    -			{
    -				var_Dump($sSQL, $iPlaceID);
    -				exit;
    -			}
    +			$iPlaceID = chksql($oDB->getOne($sSQL));
     
     			if ($iPlaceID && $aPlace['place_id'] && $iMaxRank < 28)
     			{
     				$sSQL = "select address_place_id from place_addressline where cached_rank_address <= $iMaxRank and place_id = ".$aPlace['place_id']." order by cached_rank_address desc,isaddress desc,distance desc";
    -				$iPlaceID = $oDB->getOne($sSQL);
    -				if (PEAR::IsError($iPlaceID))
    -				{
    -					var_Dump($sSQL, $iPlaceID);
    -					exit;
    -				}
    +				$iPlaceID = chksql($oDB->getOne($sSQL));
     			}
     			if (!$iPlaceID)
     			{
    
    From 348a3082c926bc6f8d9a2b5ba9341a9bae338ab6 Mon Sep 17 00:00:00 2001
    From: Sarah Hoffmann 
    Date: Sun, 12 Jun 2016 22:33:37 +0200
    Subject: [PATCH 7/9] fix syntax errors and update tests
    
    Some of the tests with bad parameters now return a HTTP 400.
    ---
     lib/Geocode.php                           | 12 +++---------
     lib/template/details-error-html.php       |  6 +-----
     lib/website.php                           |  2 +-
     tests/features/api/reverse_simple.feature | 12 ++++++------
     tests/features/api/search_params.feature  | 10 ++++++++--
     tests/features/api/search_simple.feature  |  2 +-
     website/lookup.php                        |  3 ++-
     website/reverse.php                       |  4 ++--
     8 files changed, 24 insertions(+), 27 deletions(-)
    
    diff --git a/lib/Geocode.php b/lib/Geocode.php
    index aa65cb69..876a40b5 100644
    --- a/lib/Geocode.php
    +++ b/lib/Geocode.php
    @@ -514,7 +514,7 @@
     
     			$sSQL .= " order by importance desc";
     			if (CONST_Debug) { echo "
    "; var_dump($sSQL); } - $aSearchResults = chksql($this->oDB->getAll($sSQL); + $aSearchResults = chksql($this->oDB->getAll($sSQL), "Could not get details for place."); return $aSearchResults; @@ -879,7 +879,7 @@ $sViewboxCentreSQL .= ")'::geometry,4326)"; $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")"; - $this->sViewboxSmallSQL = chksql($this->oDB->getOne($sSQL); + $this->sViewboxSmallSQL = chksql($this->oDB->getOne($sSQL), "Could not get small viewbox."); $this->sViewboxSmallSQL = "'".$this->sViewboxSmallSQL."'::geometry"; @@ -1414,9 +1414,8 @@ $sSQL .= " limit ".$this->iLimit; if (CONST_Debug) { var_dump($sSQL); } - $aViewBoxPlaceIDs = chksql($this->oDB->getAll($sSQL)); + $aViewBoxPlaceIDs = chksql($this->oDB->getAll($sSQL), "Could not get places for search terms."); - } //var_dump($aViewBoxPlaceIDs); // Did we have an viewbox matches? $aPlaceIDs = array(); @@ -1638,11 +1637,6 @@ } - if (PEAR::IsError($aPlaceIDs)) - { - failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs); - } - if (CONST_Debug) { echo "
    Place IDs: "; var_Dump($aPlaceIDs); } foreach($aPlaceIDs as $iPlaceID) diff --git a/lib/template/details-error-html.php b/lib/template/details-error-html.php index f93cca4d..bc00f84d 100644 --- a/lib/template/details-error-html.php +++ b/lib/template/details-error-html.php @@ -11,9 +11,6 @@ function osmMapUrl($aFeature) { - $sLon = $aFeature['error_x']; - $sLat = $aFeature['error_y']; - if (isset($sFeature['error_x']) && isset($sFeature['error_y'])) { $sBaseUrl = '//www.openstreetmap.org/'; @@ -23,8 +20,7 @@ $sBaseUrl += $sOSMType.'/'.$aFeature['osm_id']; } - return 'view on osm.org'; - } + return 'view on osm.org'; } return ''; } diff --git a/lib/website.php b/lib/website.php index 22ec08f1..23cec940 100644 --- a/lib/website.php +++ b/lib/website.php @@ -100,7 +100,7 @@ INTERNALFAIL; { if (!isset($_GET[$sName])) return $bDefault; - if (!preg_match('/^[+-][0-9]+$/', $_GET[$sName])) + if (!preg_match('/^[+-]?[0-9]+$/', $_GET[$sName])) { userError("Integer number expected for parameter '$sName'"); } diff --git a/tests/features/api/reverse_simple.feature b/tests/features/api/reverse_simple.feature index 5d79fd4b..6100f54c 100644 --- a/tests/features/api/reverse_simple.feature +++ b/tests/features/api/reverse_simple.feature @@ -99,35 +99,35 @@ Feature: Simple Reverse Tests | lat | 51.51 When sending an API call reverse - Then exactly 0 results are returned + Then a HTTP 400 is returned Scenario: Missing lat parameter Given the request parameters | lon | -79.39114 When sending an API call reverse - Then exactly 0 results are returned + Then a HTTP 400 is returned Scenario: Missing osm_id parameter Given the request parameters | osm_type | N When sending an API call reverse - Then exactly 0 results are returned + Then a HTTP 400 is returned Scenario: Missing osm_type parameter Given the request parameters | osm_id | 3498564 When sending an API call reverse - Then exactly 0 results are returned + Then a HTTP 400 is returned Scenario Outline: Bad format for lat or lon Given the request parameters | lat | lon | | | | When sending an API call reverse - Then exactly 0 results are returned + Then a HTTP 400 is returned Examples: | lat | lon @@ -137,4 +137,4 @@ Feature: Simple Reverse Tests | 48.966.0 | 8.4482 | 48.966 | 8.448.2 | Nan | 8.448 - | 48.966 | Nan \ No newline at end of file + | 48.966 | Nan diff --git a/tests/features/api/search_params.feature b/tests/features/api/search_params.feature index 150d6bdc..0b21d558 100644 --- a/tests/features/api/search_params.feature +++ b/tests/features/api/search_params.feature @@ -187,7 +187,6 @@ Feature: Search queries | 0.0 | 0.5 | 999 - | nan Scenario Outline: Search with polygon threshold (xml) Given the request parameters @@ -203,7 +202,14 @@ Feature: Search queries | 0.0 | 0.5 | 999 - | nan + + Scenario Outline: Search with invalid polygon threshold (xml) + Given the request parameters + | polygon_geojson | polygon_threshold + | 1 | + When sending xml search query "switzerland" + Then a HTTP 400 is returned + Scenario Outline: Search with extratags Given the request parameters diff --git a/tests/features/api/search_simple.feature b/tests/features/api/search_simple.feature index 2cb27b7c..0020cc2e 100644 --- a/tests/features/api/search_simple.feature +++ b/tests/features/api/search_simple.feature @@ -61,7 +61,7 @@ Feature: Simple Tests | format | fd$# When sending search query "Berlin" - Then the result is valid html + Then a HTTP 400 is returned Scenario Outline: Simple Searches When sending search query "" diff --git a/website/lookup.php b/website/lookup.php index 60bd60eb..9d0cea4c 100755 --- a/website/lookup.php +++ b/website/lookup.php @@ -5,6 +5,7 @@ require_once(CONST_BasePath.'/lib/init-website.php'); require_once(CONST_BasePath.'/lib/log.php'); require_once(CONST_BasePath.'/lib/PlaceLookup.php'); + require_once(CONST_BasePath.'/lib/output.php'); if (strpos(CONST_BulkUserIPs, ','.$_SERVER["REMOTE_ADDR"].',') !== false) { @@ -38,7 +39,7 @@ $oPlaceLookup->setIncludeExtraTags(getParamBool('extratags', false)); $oPlaceLookup->setIncludeNameDetails(getParamBool('namedetails', false)); - $aOsmIds = explode(',', $getParamString('osm_ids', '')); + $aOsmIds = explode(',', getParamString('osm_ids', '')); if (count($aOsmIds) > CONST_Places_Max_ID_count) { diff --git a/website/reverse.php b/website/reverse.php index 17b8a2ca..7f5eca78 100755 --- a/website/reverse.php +++ b/website/reverse.php @@ -56,8 +56,8 @@ $hLog = logStart($oDB, 'reverse', $_SERVER['QUERY_STRING'], $aLangPrefOrder); - $sOsmType = getParamSet('osmtype', array('N', 'W', 'R')); - $iOsmId = getParamInt('osmid', -1); + $sOsmType = getParamSet('osm_type', array('N', 'W', 'R')); + $iOsmId = getParamInt('osm_id', -1); $fLat = getParamFloat('lat'); $fLon = getParamFloat('lon'); if ($sOsmType && $iOsmId > 0) From e842d8793c1c416a75bbae39c004184f1ed66289 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sun, 12 Jun 2016 23:22:14 +0200 Subject: [PATCH 8/9] allow parameters to be empty Consider empty parameters as unset and use the default. Simplifies use in forms. --- lib/website.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/website.php b/lib/website.php index 23cec940..cb714959 100644 --- a/lib/website.php +++ b/lib/website.php @@ -91,14 +91,14 @@ INTERNALFAIL; function getParamBool($sName, $bDefault=false) { - if (!isset($_GET[$sName])) return $bDefault; + if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $bDefault; return (bool) $_GET[$sName]; } function getParamInt($sName, $bDefault=false) { - if (!isset($_GET[$sName])) return $bDefault; + if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $bDefault; if (!preg_match('/^[+-]?[0-9]+$/', $_GET[$sName])) { @@ -110,7 +110,7 @@ INTERNALFAIL; function getParamFloat($sName, $bDefault=false) { - if (!isset($_GET[$sName])) return $bDefault; + if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $bDefault; if (!preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $_GET[$sName])) { @@ -122,14 +122,14 @@ INTERNALFAIL; function getParamString($sName, $bDefault=false) { - if (!isset($_GET[$sName])) return $bDefault; + if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $bDefault; return $_GET[$sName]; } function getParamSet($sName, $aValues, $sDefault=false) { - if (!isset($_GET[$sName])) return $sDefault; + if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $sDefault; if (!in_array($_GET[$sName], $aValues)) { From 10c5d7f6f6f6ea321fea870e1ec984fa5e4af135 Mon Sep 17 00:00:00 2001 From: Sarah Hoffmann Date: Sun, 12 Jun 2016 23:25:47 +0200 Subject: [PATCH 9/9] fix more syntax errors in error functions --- lib/website.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/website.php b/lib/website.php index cb714959..a6afb698 100644 --- a/lib/website.php +++ b/lib/website.php @@ -39,7 +39,7 @@ INTERNALFAIL; echo "
    \n".$oSql->getUserInfo()."
    "; } - echo "

    "; + echo "

    "; exit; } @@ -76,7 +76,7 @@ INTERNALFAIL; header('Content-type: text/html; charset=utf-8'); echo "

    Bad Request

    "; echo '

    Nominatim has encountered an error with your request.

    '; - echo "

    Details: ".$sError,"

    "; + echo "

    Details: ".$sError."

    "; echo '

    If you feel this error is incorrect feel file an issue on Github. Please include the error message above and the URL you used.

    '; echo "\n\n"; exit;