]> git.openstreetmap.org Git - nominatim.git/commitdiff
Merge pull request #469 from lonvia/refactor-php
authorSarah Hoffmann <lonvia@denofr.de>
Mon, 13 Jun 2016 18:13:38 +0000 (20:13 +0200)
committerGitHub <noreply@github.com>
Mon, 13 Jun 2016 18:13:38 +0000 (20:13 +0200)
Some refactoring of website php

27 files changed:
lib/Geocode.php
lib/PlaceLookup.php
lib/ReverseGeocode.php
lib/db.php
lib/init-website.php
lib/lib.php
lib/output.php [new file with mode: 0644]
lib/template/address-json.php
lib/template/address-jsonv2.php
lib/template/address-xml.php
lib/template/details-error-html.php
lib/template/details-html.php
lib/template/search-batch-json.php
lib/template/search-json.php
lib/template/search-jsonv2.php
lib/template/search-xml.php
lib/website.php [new file with mode: 0644]
tests/features/api/reverse_simple.feature
tests/features/api/search_params.feature
tests/features/api/search_simple.feature
website/deletable.php
website/details.php
website/hierarchy.php
website/lookup.php
website/polygons.php
website/reverse.php
website/search.php

index 0c3c5f735c6bdbf43df1cabc49db8eaceb128d88..876a40b585692e9017f9cba2762d87ec97287575 100644 (file)
 
                        $sSQL .= " order by importance desc";
                        if (CONST_Debug) { echo "<hr>"; 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;
                }
                                $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;
                        }
                                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)
                                        {
                                $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;
                                        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();
                                                                                $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
                                                                {
                                                                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)";
                                                                        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
                                                                                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
                                                                        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));
                                                                }
                                                        }
                                                }
                                                                        $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?
                                                                $aPlaceIDs = array();
                                                                }
                                                                $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))
                                                                        //$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
                                                                        }
                                                                        //$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)
                                                                        //$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)
                                                                        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;
                                                                                // 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)
                                                                                $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);
                                                                        }
 
                                                                                        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
                                                                                {
                                                                                        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)));
                                                                                }
                                                                        }
                                                                }
 
                                                }
 
-                                               if (PEAR::IsError($aPlaceIDs))
-                                               {
-                                                       failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
-                                               }
-
                                                if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
 
                                                foreach($aPlaceIDs as $iPlaceID)
                                                $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)
                                                {
index be60ff0782ba02221ae60ed369455b895a4c6bc8..831f6ef6ca4d4e838696843f9db89c709c6cfefb 100644 (file)
                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)
                                $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;
 
                        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)
                                        $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'])
                                {
index 05093af388cfaf36ddd192290f3d96409d8af7d3..4eeb5cc4851e4d647614597a03660cd64de09966 100644 (file)
                                $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');
                                        $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']. ' | '. "<br>\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);
                                                // 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)
                                                {
                                        $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']. ' | '. "<br>\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);
                                $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'];
index cc84bf9bdaf71df7261aa393721e25c567771336..822acc37d4997f64bca66bc7ea506dcb3ab0f9e3 100644 (file)
@@ -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'");
index fff33936dc6d688b4ce4d54cfe62bd585221661c..04bc518ca9d3ec044dee0aa16e23ac5e064b016d 100644 (file)
@@ -1,5 +1,6 @@
 <?php
        require_once('init.php');
+       require_once('website.php');
 
        if (CONST_NoAccessControl)
        {
index 897db8e7ff58484efe7863839fd508e4c26dd612..ec5b9b1f4330f3a68cce22ef2959767045ddeaaa 100644 (file)
@@ -1,51 +1,5 @@
 <?php
 
-       function failInternalError($sError, $sSQL = false, $vDumpVar = false)
-       {
-               header('HTTP/1.0 500 Internal Server Error');
-               header('Content-type: text/html; charset=utf-8');
-               echo "<html><body><h1>Internal Server Error</h1>";
-               echo '<p>Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.</p>';
-               echo "<p><b>Details:</b> ".$sError,"</p>";
-               echo '<p>Feel free to report the bug in the <a href="http://trac.openstreetmap.org">OSM bug database</a>. Please include the error message above and the URL you used.</p>';
-               if (CONST_Debug)
-               {
-                       echo "<hr><h2>Debugging Information</h2><br>";
-                       if ($sSQL)
-                       {
-                               echo "<h3>SQL query</h3><code>".$sSQL."</code>";
-                       }
-                       if ($vDumpVar)
-                       {
-                               echo "<h3>Result</h3> <code>";
-                               var_dump($vDumpVar);
-                               echo "</code>";
-                       }
-               }
-               echo "\n</body></html>\n";
-               exit;
-       }
-
-
-       function userError($sError)
-       {
-               header('HTTP/1.0 400 Bad Request');
-               header('Content-type: text/html; charset=utf-8');
-               echo "<html><body><h1>Bad Request</h1>";
-               echo '<p>Nominatim has encountered an error with your request.</p>';
-               echo "<p><b>Details:</b> ".$sError,"</p>";
-               echo '<p>If you feel this error is incorrect feel free to report the bug in the <a href="http://trac.openstreetmap.org">OSM bug database</a>. Please include the error message above and the URL you used.</p>';
-               echo "\n</body></html>\n";
-               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;
        {
                // 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))
                {
                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 "<pre>";
                //var_dump($aAddressLines);
                        $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'];
                }
 
                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)
                        {
diff --git a/lib/output.php b/lib/output.php
new file mode 100644 (file)
index 0000000..722d73b
--- /dev/null
@@ -0,0 +1,43 @@
+<?php
+
+       function formatOSMType($sType, $bIncludeExternal=true)
+       {
+               if ($sType == 'N') return 'node';
+               if ($sType == 'W') return 'way';
+               if ($sType == 'R') return 'relation';
+
+               if (!$bIncludeExternal) return '';
+
+               if ($sType == 'T') return 'tiger';
+               if ($sType == 'I') return 'way';
+
+               return '';
+       }
+
+       function osmLink($aFeature, $sRefText=false)
+       {
+               $sOSMType = formatOSMType($aFeature['osm_type'], false);
+               if ($sOSMType)
+               {
+                       return '<a href="//www.openstreetmap.org/'.$sOSMType.'/'.$aFeature['osm_id'].'">'.$sOSMType.' '.($sRefText?$sRefText:$aFeature['osm_id']).'</a>';
+               }
+               return '';
+       }
+
+       function wikipediaLink($aFeature)
+       {
+               if ($aFeature['wikipedia'])
+               {
+                       list($sLanguage, $sArticle) = explode(':',$aFeature['wikipedia']);
+                       return '<a href="https://'.$sLanguage.'.wikipedia.org/wiki/'.urlencode($sArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>';
+               }
+               return '';
+       }
+
+       function detailsLink($aFeature, $sTitle=false)
+       {
+               if (!$aFeature['place_id']) return '';
+
+               return '<a href="details.php?place_id='.$aFeature['place_id'].'">'.($sTitle?$sTitle:$aFeature['place_id']).'</a>';
+       }
+
index 6254357a711b3727498a722b06c61640d04ca308..bf6c700bf580acaec788671cbf734a8167613db0 100644 (file)
@@ -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;
                if (isset($aPlace['aBoundingBox']))
                {
                        $aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox'];
-
-                       if (isset($aPlace['aPolyPoints']) && $bAsPoints)
-                       {
-                               $aFilteredPlaces['polygonpoints'] = $aPlace['aPolyPoints'];
-                       }
                }
 
                if (isset($aPlace['asgeojson']))
@@ -55,8 +49,6 @@
                {
                        $aFilteredPlaces['geokml'] = $aPlace['askml'];
                }
-
-
        }
 
        javascript_renderData($aFilteredPlaces);
index 64c871c10c9d748c057a4df35f30d1bdad0e12bb..d62141769b89cc33ecc26e19fb6e03d585f95b74 100644 (file)
@@ -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;
                if (isset($aPlace['aBoundingBox']))
                {
                        $aFilteredPlaces['boundingbox'] = $aPlace['aBoundingBox'];
-
-                       if (isset($aPlace['aPolyPoints']) && $bAsPoints)
-                       {
-                               $aFilteredPlaces['polygonpoints'] = $aPlace['aPolyPoints'];
-                       }
                }
 
                if (isset($aPlace['asgeojson']))
index a3369d34890e3b0a95c3cd897e5bce34155b581d..2bfcffbf5ac0b3a3d8bb6b0e646e3139b5b90697 100644 (file)
@@ -22,8 +22,7 @@
        {
                echo "<result";
                if ($aPlace['place_id']) echo ' place_id="'.$aPlace['place_id'].'"';
-               $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) echo ' osm_type="'.$sOSMType.'"'.' osm_id="'.$aPlace['osm_id'].'"';
                if ($aPlace['ref']) echo ' ref="'.htmlspecialchars($aPlace['ref']).'"';
                if (isset($aPlace['lat'])) echo ' lat="'.htmlspecialchars($aPlace['lat']).'"';
                        echo ' boundingbox="';
                        echo join(',', $aPlace['aBoundingBox']);
                        echo '"';
-
-                       if ($bAsPoints && isset($aPlace['aPolyPoints']))
-                       {
-                               echo ' polygonpoints=\'';
-                               echo json_encode($aPlace['aPolyPoints']);
-                               echo '\'';
-                       }
                }
 
                if (isset($aPlace['asgeojson']))
index 1c6d2a0a4db705f89bcf856d6ced3453f0019f05..bc00f84d6e97d88639722850bfd68ce5e561fa17 100644 (file)
@@ -9,27 +9,18 @@
 
 <?php
 
-       function osm_link($aFeature)
+       function osmMapUrl($aFeature)
        {
-               $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':'')));
-               if ($sOSMType) {
-                       return '<a href="http://www.openstreetmap.org/browse/'.$sOSMType.'/'.$aFeature['osm_id'].'">'.$sOSMType.' '.$aFeature['osm_id'].'</a>';
-               }
-               return '';
-       }
-
-       function osm_map_url($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 '<a href="'.$sBaseUrl.'?mlat='.$aFeature['error_y'].'&mlon='.$aFeature['error_x'].'">view on osm.org</a>';
                }
                return '';
        }
@@ -45,7 +36,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 +54,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 +78,7 @@
                                        </div>
 
                                        <div>
-                                               OSM: <span class="label"><?php echo osm_link($aPointDetails); ?><span>
+                                               OSM: <span class="label"><?php echo osmLink($aPointDetails); ?><span>
                                        </div>
 
 
@@ -95,9 +86,7 @@
                                        <p>
                                                <?php echo $aPointDetails['errormessage']?$aPointDetails['errormessage']:'unknown'; ?>
                                        </p>
-                                       <?php if (osm_map_url($aPointDetails)) { ?>
-                                               <a href="<?php echo osm_map_url($aPointDetails); ?>">view on osm.org</a>
-                                       <?php } ?>
+                                       <?php echo osmMapUrl($aPointDetails); ?>
 
                                        <h4>Edit</h4>
                                        <ul>
 
        <?php include(CONST_BasePath.'/lib/template/includes/html-footer.php'); ?>
        </body>
-</html>
\ No newline at end of file
+</html>
index ae36b411b5ae69e6ed10f96d6b0e684bd3b24249..71fcc7b3e0a0aa67c61151ce496e2c5dd02bba10 100644 (file)
@@ -7,7 +7,6 @@
 </head>
 
 
-
 <?php
 
        function headline($sTitle)
                echo "<tr class='all-columns'><td colspan='6'><h3>".$sTitle."</h3></td></tr>\n";
        }
 
-       function osm_link($aFeature)
-       {
-               $sOSMType = ($aFeature['osm_type'] == 'N'?'node':($aFeature['osm_type'] == 'W'?'way':($aFeature['osm_type'] == 'R'?'relation':'')));
-               if ($sOSMType)
-               {
-                       return '<a href="http://www.openstreetmap.org/browse/'.$sOSMType.'/'.$aFeature['osm_id'].'">'.$sOSMType.' '.$aFeature['osm_id'].'</a>';
-               }
-               return '';
-       }
-
-       function wikipedia_link($aFeature)
-       {
-               if ($aFeature['wikipedia'])
-               {
-                       list($sWikipediaLanguage,$sWikipediaArticle) = explode(':',$aFeature['wikipedia']);
-                       return '<a href="https://'.$sWikipediaLanguage.'.wikipedia.org/wiki/'.urlencode($sWikipediaArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>';
-               }
-               return '';
-       }
-
-       function nominatim_link($aFeature, $sTitle)
-       {
-               return '<a href="details.php?place_id='.$aFeature['place_id'].'">'.$sTitle.'</a>';
-       }
 
        function format_distance($fDistance)
        {
                echo '<tr class="' . ($bNotUsed?'notused':'') . '">'."\n";
                echo '  <td class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>')."</td>\n";
                echo '  <td>' . $aAddressLine['class'].':'.$aAddressLine['type'] . "</td>\n";
-               echo '  <td>' . osm_link($aAddressLine) . "</td>\n";
+               echo '  <td>' . osmLink($aAddressLine) . "</td>\n";
                echo '  <td>' . (isset($aAddressLine['admin_level']) ? $aAddressLine['admin_level'] : '') . "</td>\n";
                echo '  <td>' . format_distance($aAddressLine['distance'])."</td>\n";
-               echo '  <td>' . nominatim_link($aAddressLine,'details &gt;') . "</td>\n";
+               echo '  <td>' . detailsLink($aAddressLine,'details &gt;') . "</td>\n";
                echo "</tr>\n";
        }
 
                                        }
                                        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']) );
index edfe3871403684842fa822afcb2f4722a09db5b7..60d380418d6f74e86f665173d16a112fe3600b2b 100644 (file)
@@ -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;
index 5d5ebfe81f9782706c4cb9ed24a74920c9baf15e..d3dc00f3b505b497eb90f404d770f9ce2e2d0f56 100644 (file)
@@ -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;
index 251388b51a4157e6a7bd54871936eb79880d028f..e907a081f206750ac1a7e37de321c796c9de9af8 100644 (file)
@@ -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;
index 7cbcc04bf605623e3485b03f9d15910e7f649259..7a5c997fddd1b35b222871b7cd160fdca161c0e3 100644 (file)
@@ -25,8 +25,7 @@
        foreach($aSearchResults as $iResNum => $aResult)
        {
                echo "<place place_id='".$aResult['place_id']."'";
-               $sOSMType = ($aResult['osm_type'] == 'N'?'node':($aResult['osm_type'] == 'W'?'way':($aResult['osm_type'] == 'R'?'relation':
-               ($aResult['osm_type'] == 'T'?'tiger':($aResult['osm_type'] == 'I'?'interpolation':'')))));
+               $sOSMType = formatOSMType($aResult['osm_type']);
                if ($sOSMType)
                {
                        echo " osm_type='$sOSMType'";
diff --git a/lib/website.php b/lib/website.php
new file mode 100644 (file)
index 0000000..a6afb69
--- /dev/null
@@ -0,0 +1,140 @@
+<?php
+
+/***************************************************************************
+ *
+ * Error handling functions
+ *
+ */
+       function chksql($oSql, $sMsg = "Database request failed")
+       {
+               if (!PEAR::isError($oSql)) return $oSql;
+
+               header('HTTP/1.0 500 Internal Server Error');
+               header('Content-type: text/html; charset=utf-8');
+
+               $sSqlError = $oSql->getMessage();
+
+               echo <<<INTERNALFAIL
+       <html>
+         <head><title>Internal Server Error</title></head>
+         <body>
+               <h1>Internal Server Error</h1>
+               <p>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 <a href="https://github.com/twain47/Nominatim/issues">
+                  Github</a>. Please include the URL that caused the problem and the
+                  complete error details below.</p>
+               <p><b>Message:</b> $sMsg</p>
+               <p><b>SQL Error:</b> $sSqlError</p>
+               <p><b>Details:</b> <pre>
+INTERNALFAIL;
+
+               if (CONST_Debug)
+               {
+                       var_dump($oSql);
+               }
+               else
+               {
+                       echo "<pre>\n".$oSql->getUserInfo()."</pre>";
+               }
+
+               echo "</pre></p></body></html>";
+               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 "<html><body><h1>Internal Server Error</h1>";
+               echo '<p>Nominatim has encountered an internal error while processing your request. This is most likely because of a bug in the software.</p>';
+               echo "<p><b>Details:</b> ".$sError,"</p>";
+               echo '<p>Feel free to file an issue on <a href="https://github.com/twain47/Nominatim/issues">Github</a>. Please include the error message above and the URL you used.</p>';
+               if (CONST_Debug)
+               {
+                       echo "<hr><h2>Debugging Information</h2><br>";
+                       if ($sSQL)
+                       {
+                               echo "<h3>SQL query</h3><code>".$sSQL."</code>";
+                       }
+                       if ($vDumpVar)
+                       {
+                               echo "<h3>Result</h3> <code>";
+                               var_dump($vDumpVar);
+                               echo "</code>";
+                       }
+               }
+               echo "\n</body></html>\n";
+               exit;
+       }
+
+
+       function userError($sError)
+       {
+               header('HTTP/1.0 400 Bad Request');
+               header('Content-type: text/html; charset=utf-8');
+               echo "<html><body><h1>Bad Request</h1>";
+               echo '<p>Nominatim has encountered an error with your request.</p>';
+               echo "<p><b>Details:</b> ".$sError."</p>";
+               echo '<p>If you feel this error is incorrect feel file an issue on <a href="https://github.com/twain47/Nominatim/issues">Github</a>. Please include the error message above and the URL you used.</p>';
+               echo "\n</body></html>\n";
+               exit;
+       }
+
+
+/***************************************************************************
+ *
+ * Functions for parsing URL parameters
+ *
+ */
+
+       function getParamBool($sName, $bDefault=false)
+       {
+               if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $bDefault;
+
+               return (bool) $_GET[$sName];
+       }
+
+       function getParamInt($sName, $bDefault=false)
+       {
+               if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) 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]) || strlen($_GET[$sName]) == 0) 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]) || strlen($_GET[$sName]) == 0) return $bDefault;
+
+               return $_GET[$sName];
+       }
+
+       function getParamSet($sName, $aValues, $sDefault=false)
+       {
+               if (!isset($_GET[$sName]) || strlen($_GET[$sName]) == 0) return $sDefault;
+
+               if (!in_array($_GET[$sName], $aValues))
+               {
+                       userError("Parameter '$sName' must be one of: ".join(', ', $aValues));
+               }
+
+               return $_GET[$sName];
+       }
index 5d79fd4b8af1e22bb61343fe2d7af3d5ba620171..6100f54c623df10155e320cafccb771f4cf84729 100644 (file)
@@ -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   |
           | <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
index 150d6bdcf45479d1255eeca63afc262347de31e3..0b21d5584e6c164b13542a3fa9fe81f95c72aa0c 100644 (file)
@@ -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               | <th>
+        When sending xml search query "switzerland"
+        Then a HTTP 400 is returned
+
 
     Scenario Outline: Search with extratags
         Given the request parameters
index 2cb27b7cf61be0c3237f23220d804bf876374d18..0020cc2e4e9afb91ab4485c88d0e9c4d6bc4be8b 100644 (file)
@@ -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 "<query>"
index 3283bb8300b3e6fbbc2c57d5b4b3fbd03ea84df0..95a2ec00b8d214c565033600c6d6be184c5593f5 100755 (executable)
@@ -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');
 
        $sOutputFormat = 'html';
        ini_set('memory_limit', '200M');
        $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))
+       $aPolygons = chksql($oDB->getAll($sSQL),
+                           "Could not get list of deleted OSM elements.");
+
+       if (CONST_DEBUG)
        {
-               failInternalError("Could not get list of deleted OSM elements.", $sSQL, $aPolygons);
+               var_dump($aPolygons);
+               exit;
        }
-
-//var_dump($aPolygons);
 ?>
 <!DOCTYPE html>
 <html>
@@ -66,6 +68,7 @@ table td {
 
 <table>
 <?php
+       if (!$aPolygons) exit;
        echo "<tr>";
 //var_dump($aPolygons[0]);
        foreach($aPolygons[0] as $sCol => $sVal)
@@ -81,11 +84,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 '<td><a href="http://www.openstreetmap.org/browse/'.$sOSMType.'/'.$sVal.'" target="_new">'.$sVal.'</a></td>';
+                                       echo '<td>'.osmLink($aRow).'</td>';
                                        break;
                                case 'place_id':
-                                       echo '<td><a href="'.CONST_Website_BaseURL.'details?place_id='.$sVal.'">'.$sVal.'</a></td>';
+                                       echo '<td>'.detailsLink($aRow).'</td>';
                                        break;
                                default:
                                        echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
index 5edef6f5001938505960cf0e6dffe5d35e05d952..495db2b40e668277fd18ceb92bfbc10cba5c923f 100755 (executable)
@@ -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';
        /*
        $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 = 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 (!$_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 = 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))
                                {
        }
 
 
-       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)
        {
-               $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, ";
        $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();
 
        $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);
 
        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;
        }
 
-       
        include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php');
index 9b9d778cebd3de3f62519adab5a3aea45d956860..b14422fa6a80e7ff8a409ecbc8a8dca940b2c4c4 100755 (executable)
@@ -5,29 +5,28 @@
        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'];
-       }
-
+       require_once(CONST_BasePath.'/lib/output.php');
        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 = 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 (!$_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");
-                       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];
                }
        }
 
-       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)
        {
-               $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;
        }
 
 
        $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 (!$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/browse/'.$sOSMType.'/'.$aPlace['osm_id'];
-               if ($sOutputFormat == 'html') if ($i) echo " > ";
-               if ($sOutputFormat == 'html') echo '<a href="'.$sPlaceUrl.'">'.$aPlace['localname'].'</a> (<a href="'.$sOSMUrl.'">osm</a>)';
+               $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 " &gt; ";
+                       echo '<a href="'.$sPlaceUrl.'">'.$aPlace['localname'].'</a> ('.osmLink($aPlace).')';
+               }
        }
 
-       $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;
        }
 
-       $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))
        {
 
                        if (!isset($aGroupedAddressLines[$aAddressLine['label']])) $aGroupedAddressLines[$aAddressLine['label']] = array();
                                $aGroupedAddressLines[$aAddressLine['label']][] = $aAddressLine;
-                       }
-                       foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines)
+               }
+
+               foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines)
+               {
+                       echo "<h3>$sGroupHeading</h3>";
+                       foreach($aParentOfLines as $aAddressLine)
                        {
-                               echo "<h3>$sGroupHeading</h3>";
-                               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 '<div class="line">';
-                                       echo '<span class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>').'</span>';
-                                       echo ' (';
-                                       echo '<span class="area">'.($aAddressLine['isarea']=='t'?'Polygon':'Point').'</span>';
-                                       if ($sOSMType) echo ', <span class="osm"><span class="label"></span>'.$sOSMType.' <a href="http://www.openstreetmap.org/browse/'.$sOSMType.'/'.$aAddressLine['osm_id'].'">'.$aAddressLine['osm_id'].'</a></span>';
-                                       echo ', <a href="hierarchy.php?place_id='.$aAddressLine['place_id'].'">GOTO</a>';
-                                       echo ', '.$aAddressLine['area'];
-                                       echo ')';
-                                       echo '</div>';
-                               }
-                       }
-                       if (sizeof($aParentOfLines) >= 500) {
-                               echo '<p>There are more child objects which are not shown.</p>';
+                               $aAddressLine['localname'] = $aAddressLine['localname']?$aAddressLine['localname']:$aAddressLine['housenumber'];
+                               $sOSMType = formatOSMType($aAddressLine['osm_type'], false);
+
+                               echo '<div class="line">';
+                               echo '<span class="name">'.(trim($aAddressLine['localname'])?$aAddressLine['localname']:'<span class="noname">No Name</span>').'</span>';
+                               echo ' (';
+                               echo '<span class="area">'.($aAddressLine['isarea']=='t'?'Polygon':'Point').'</span>';
+                               if ($sOSMType) echo ', <span class="osm"><span class="label"></span>'.$sOSMType.' '.osmLink($aAddressLine).'</span>';
+                               echo ', <a href="hierarchy.php?place_id='.$aAddressLine['place_id'].'">GOTO</a>';
+                               echo ', '.$aAddressLine['area'];
+                               echo ')';
+                               echo '</div>';
                        }
-                       echo '</div>';
                }
+               if (sizeof($aParentOfLines) >= 500) {
+                       echo '<p>There are more child objects which are not shown.</p>';
+               }
+               echo '</div>';
+       }
index dfa09d3b7ffe8a84d5fc2484b5633340b0157d1e..9d0cea4cc3602d4dd22b840c53cb79b2f621821a 100755 (executable)
@@ -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)
        {
        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..b855214a89a6ece1e65e762ef40f67e0a0ef28e8 100755 (executable)
@@ -2,18 +2,17 @@
        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';
+       require_once(CONST_BasePath.'/lib/output.php');
        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'];
 
-       $iTotalBroken = (int) $oDB->getOne('select count(*) from import_polygon_error');
+       $sOutputFormat = 'html';
+       $iDays = getParamInt('days', 1);
+       $bReduced = getParamBool('reduced', false);
+       $sClass = getParamString('class', false);
+
+       $iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error'));
 
        $aPolygons = array();
        while($iTotalBroken && !sizeof($aPolygons))
                $sSQL = 'select osm_type as "type",osm_id as "id",class as "key",type as "value",name->\'name\' as "name",';
                $sSQL .= 'country_code as "country",errormessage as "error message",updated';
                $sSQL .= " from import_polygon_error";
-               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);
+               $aPolygons = chksql($oDB->getAll($sSQL));
+       }
+
+       if (CONST_Debug)
+       {
+               var_dump($aPolygons);
+               exit;
        }
-//var_dump($aPolygons);
 ?>
 <!DOCTYPE html>
 <html>
@@ -87,6 +83,7 @@ table td {
 <?php
 
        echo "<p>Total number of broken polygons: $iTotalBroken</p>";
+       if (!$aPolygons) exit;
        echo "<table>";
        echo "<tr>";
 //var_dump($aPolygons[0]);
@@ -120,8 +117,7 @@ table td {
                                }
                                break;
                        case 'id':
-                               $sOSMType = ($aRow['type'] == 'N'?'node':($aRow['type'] == 'W'?'way':($aRow['type'] == 'R'?'relation':'')));
-                               echo '<td><a href="http://www.openstreetmap.org/browse/'.$sOSMType.'/'.$aRow['id'].'" target="_new">'.$aRow['id'].'</a></td>';
+                               echo '<td>'.osmLink($aRow).'</td>';
                                break;
                        default:
                                echo "<td>".($sVal?$sVal:'&nbsp;')."</td>";
@@ -140,10 +136,6 @@ table td {
                echo "</tr>";
        }
        echo "</table>";
-
-
-
-//     include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php');
 ?>
 </body>
 </html>
index fd1f5c27c2f7cb43683d4315dee6bc5f67da67d9..7f5eca78e5cea47237dbcbf5279761f0f38403ad 100755 (executable)
@@ -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)
        {
        }
 
 
-       $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)) > 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('osm_type', array('N', 'W', 'R'));
+       $iOsmId = getParamInt('osm_id', -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', 18));
 
                $aLookup = $oReverseGeocode->lookup();
                if (CONST_Debug) var_dump($aLookup);
        }
-       else
+       else if ($sOutputFormat != 'html')
        {
-               $aLookup = null;
+               userError("Need coordinates or OSM object to lookup.");
        }
 
        if ($aLookup)
@@ -95,7 +90,7 @@
 
                $aPlace = $oPlaceLookup->lookupPlace($aLookup);
 
-               $oPlaceLookup->setIncludePolygonAsPoints($bAsPoints);
+               $oPlaceLookup->setIncludePolygonAsPoints(false);
                $oPlaceLookup->setIncludePolygonAsText($bAsText);
                $oPlaceLookup->setIncludePolygonAsGeoJSON($bAsGeoJSON);
                $oPlaceLookup->setIncludePolygonAsKML($bAsKML);
 
        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;
        }
index 31944974070007e8aca276c287c2c0a48cc9f90b..4baf3ef5572b9b9fc288b7e7485aa3778eb1f30c 100755 (executable)
@@ -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');
 
        }
 
        // 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 +65,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 +86,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);
 
 
        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));