]> git.openstreetmap.org Git - nominatim.git/commitdiff
introduce accessor function for URL parameter
authorSarah Hoffmann <lonvia@denofr.de>
Sat, 11 Jun 2016 21:07:06 +0000 (23:07 +0200)
committerSarah Hoffmann <lonvia@denofr.de>
Sat, 11 Jun 2016 21:07:06 +0000 (23:07 +0200)
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
lib/lib.php
lib/website.php [new file with mode: 0644]
website/details.php
website/hierarchy.php
website/lookup.php
website/polygons.php
website/reverse.php
website/search.php

index fff33936dc6d688b4ce4d54cfe62bd585221661c..04bc518ca9d3ec044dee0aa16e23ac5e064b016d 100644 (file)
@@ -1,5 +1,6 @@
 <?php
        require_once('init.php');
+       require_once('website.php');
 
        if (CONST_NoAccessControl)
        {
index 897db8e7ff58484efe7863839fd508e4c26dd612..fc3936851bbb56bd031495761e1fe6f781b703d9 100644 (file)
                exit;
        }
 
-       function getParamBool($name, $default=false)
-       {
-               if (!isset($_GET[$name])) return $default;
-
-               return (bool) $_GET[$name];
-       }
-
        function fail($sError, $sUserError = false)
        {
                if (!$sUserError) $sUserError = $sError;
diff --git a/lib/website.php b/lib/website.php
new file mode 100644 (file)
index 0000000..cf228f3
--- /dev/null
@@ -0,0 +1,57 @@
+<?php
+
+/***************************************************************************
+ *
+ * Functions for parsing URL parameters
+ *
+ */
+
+       function getParamBool($sName, $bDefault=false)
+       {
+               if (!isset($_GET[$sName])) return $bDefault;
+
+               return (bool) $_GET[$sName];
+       }
+
+       function getParamInt($sName, $bDefault=false)
+       {
+               if (!isset($_GET[$sName])) return $bDefault;
+
+               if (!preg_match('/^[+-][0-9]+$/', $_GET[$sName]))
+               {
+                       userError("Integer number expected for parameter '$sName'");
+               }
+
+               return (int) $_GET[$sName];
+       }
+
+       function getParamFloat($sName, $bDefault=false)
+       {
+               if (!isset($_GET[$sName])) return $bDefault;
+
+               if (!preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $_GET[$sName]))
+               {
+                       userError("Floating-point number expected for parameter '$sName'");
+               }
+
+               return (float) $_GET[$sName];
+       }
+
+       function getParamString($sName, $bDefault=false)
+       {
+               if (!isset($_GET[$sName])) return $bDefault;
+
+               return $_GET[$sName];
+       }
+
+       function getParamSet($sName, $aValues, $sDefault=false)
+       {
+               if (!isset($_GET[$sName])) return $sDefault;
+
+               if (!in_array($_GET[$sName], $aValues))
+               {
+                       userError("Parameter '$sName' must be one of: ".join(', ', $aValues));
+               }
+
+               return $_GET[$sName];
+       }
index 5edef6f5001938505960cf0e6dffe5d35e05d952..2891ecfca2f7cc113b9e8721ff7635d80f5abe95 100755 (executable)
        $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))
                                {
        }
 
 
-       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)
        {
 
        $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);
index 9b9d778cebd3de3f62519adab5a3aea45d956860..e0e960bc7e9e9635fdb0b77212b85bfc439d9861 100755 (executable)
@@ -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))
                                {
                }
        }
 
-       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)
        {
 
        $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)
                if ($sOutputFormat == 'html') echo '<a href="'.$sPlaceUrl.'">'.$aPlace['localname'].'</a> (<a href="'.$sOSMUrl.'">osm</a>)';
        }
 
-       $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;
        }
index dfa09d3b7ffe8a84d5fc2484b5633340b0157d1e..60bd60ebd156f2cacf1b252628d4afb9fa1765a2 100755 (executable)
        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();
 
        $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));
-               
-               $aOsmIds = explode(',', $_GET['osm_ids']);
-               
-               if ( count($aOsmIds) > CONST_Places_Max_ID_count ) 
-               {
-                       userError('Bulk User: Only ' . CONST_Places_Max_ID_count . " ids are allowed in one request.");
-                       exit;
-               }
+               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;
                
-               foreach ($aOsmIds AS $sItem) 
+               $sType = $sItem[0];
+               $iId = (int) substr($sItem, 1);
+               if ( $iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R') )
                {
-                       // 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;
                        }
                }
        }
index b9ce249d91ab161b6c835f09e3a18ff768ab835f..92dbf70daaef82f0c5e63035564b05942363ac81 100755 (executable)
@@ -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');
 
                $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);
        }
index fd1f5c27c2f7cb43683d4315dee6bc5f67da67d9..75eb26779550c31da55f6a7e17fb499383e68e1f 100755 (executable)
 
 
        $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)
                {
 
 
        // 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();
        $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)
index 31944974070007e8aca276c287c2c0a48cc9f90b..776cfa78343e7578db6657ac0f9514b41198dcd9 100755 (executable)
        }
 
        // 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);