function setFeatureType($sFeatureType)
{
- switch($sFeatureType)
- {
+ switch ($sFeatureType) {
case 'country':
$this->setRankRange(4, 4);
break;
$this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
$sSep = '';
- foreach($this->aRoutePoints as $aPoint)
- {
+ foreach ($this->aRoutePoints as $aPoint) {
$fPoint = (float)$aPoint;
$this->sViewboxCentreSQL .= $sSep.$fPoint;
$sSep = ($sSep == ' ') ? ',' : ' ';
// List of excluded Place IDs - used for more acurate pageing
$sExcluded = $oParams->getStringList('exclude_place_ids');
- if ($sExcluded)
- {
- foreach($sExcluded as $iExcludedPlaceID)
- {
+ if ($sExcluded) {
+ foreach ($sExcluded as $iExcludedPlaceID) {
$iExcludedPlaceID = (int)$iExcludedPlaceID;
if ($iExcludedPlaceID)
$aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
// Country code list
$sCountries = $oParams->getStringList('countrycodes');
- if ($sCountries)
- {
- foreach($sCountries as $sCountryCode)
- {
- if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
- {
+ if ($sCountries) {
+ foreach ($sCountries as $sCountryCode) {
+ if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
$aCountries[] = strtolower($sCountryCode);
}
}
}
$aViewbox = $oParams->getStringList('viewboxlbrt');
- if ($aViewbox)
- {
+ if ($aViewbox) {
$this->setViewbox($aViewbox);
- }
- else
- {
+ } else {
$aViewbox = $oParams->getStringList('viewbox');
- if ($aViewbox)
- {
+ if ($aViewbox) {
$this->setViewBox(array($aViewbox[0], $aViewbox[3],
$aViewbox[2], $aViewbox[1]));
- }
- else
- {
+ } else {
$aRoute = $oParams->getStringList('route');
$fRouteWidth = $oParams->getFloat('routewidth');
- if ($aRoute && $fRouteWidth)
- {
+ if ($aRoute && $fRouteWidth) {
$this->setRoute($aRoute, $fRouteWidth);
}
}
{
// Search query
$sQuery = $oParams->getString('q');
- if (!$sQuery)
- {
+ if (!$sQuery) {
$this->setStructuredQuery($oParams->getString('amenity'),
$oParams->getString('street'),
$oParams->getString('city'),
$oParams->getString('country'),
$oParams->getString('postalcode'));
$this->setReverseInPlan(false);
- }
- else
- {
+ } else {
$this->setQuery($sQuery);
}
}
$sValue = trim($sValue);
if (!$sValue) return false;
$this->aStructuredQuery[$sKey] = $sValue;
- if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30)
- {
+ if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
$this->iMinAddressRank = $iNewMinAddressRank;
$this->iMaxAddressRank = $iNewMaxAddressRank;
}
$this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11));
$this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
- if (sizeof($this->aStructuredQuery) > 0)
- {
+ if (sizeof($this->aStructuredQuery) > 0) {
$this->sQuery = join(', ', $this->aStructuredQuery);
- if ($this->iMaxAddressRank < 30)
- {
+ if ($this->iMaxAddressRank < 30) {
$sAllowedTypesSQLList = '(\'place\',\'boundary\')';
}
}
$aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
- foreach($aOrderToFallback as $sType)
- {
- if (isset($aParams[$sType]))
- {
+ foreach ($aOrderToFallback as $sType) {
+ if (isset($aParams[$sType])) {
unset($aParams[$sType]);
$this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
return true;
function getDetails($aPlaceIDs)
{
//$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
- if (sizeof($aPlaceIDs) == 0) return array();
+ if (sizeof($aPlaceIDs) == 0) return array();
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
if ($this->bIncludeNameDetails) $sSQL .= ",name";
$sSQL .= ",extratags->'place' ";
- if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
- {
+ if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
//only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
// with start- and endnumber, the common osm housenumbers are usually saved as points
$sHousenumbers = "";
$i = 0;
$length = count($aPlaceIDs);
- foreach($aPlaceIDs as $placeID => $housenumber)
- {
+ foreach ($aPlaceIDs as $placeID => $housenumber) {
$i++;
$sHousenumbers .= "(".$placeID.", ".$housenumber.")";
- if($i<$length)
- $sHousenumbers .= ", ";
+ if ($i<$length) $sHousenumbers .= ", ";
}
- if (CONST_Use_US_Tiger_Data)
- {
+ if (CONST_Use_US_Tiger_Data) {
//Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
$sSQL .= " union";
$sSQL .= " select 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 30 as rank_search, 30 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code";
$sSQL .= " group by place_id, housenumber_for_place, calculated_country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
if (!$this->bDeDupe) $sSQL .= ", place_id ";
- if (CONST_Use_Aux_Location_data)
- {
+ if (CONST_Use_Aux_Location_data) {
$sSQL .= " union ";
$sSQL .= "select 'L' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 0 as rank_search, 0 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code, ";
$sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress, ";
}
$sSQL .= " order by importance desc";
- if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
+ if (CONST_Debug) {
+ echo "<hr>"; var_dump($sSQL);
+ }
$aSearchResults = chksql($this->oDB->getAll($sSQL),
"Could not get details for place.");
Score how good the search is so they can be ordered
*/
- foreach($aPhrases as $iPhrase => $sPhrase)
- {
+ foreach ($aPhrases as $iPhrase => $sPhrase) {
$aNewPhraseSearches = array();
if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
else $sPhraseType = '';
- foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
- {
+ foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
// Too many permutations - too expensive
if ($iWordSet > 120) break;
$aWordsetSearches = $aSearches;
// Add all words from this wordset
- foreach($aWordset as $iToken => $sToken)
- {
+ foreach ($aWordset as $iToken => $sToken) {
//echo "<br><b>$sToken</b>";
$aNewWordsetSearches = array();
- foreach($aWordsetSearches as $aCurrentSearch)
- {
+ foreach ($aWordsetSearches as $aCurrentSearch) {
//echo "<i>";
//var_dump($aCurrentSearch);
//echo "</i>";
// If the token is valid
- if (isset($aValidTokens[' '.$sToken]))
- {
- foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
- {
+ if (isset($aValidTokens[' '.$sToken])) {
+ foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
$aSearch = $aCurrentSearch;
$aSearch['iSearchRank']++;
- if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
- {
- if ($aSearch['sCountryCode'] === false)
- {
+ if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
+ if ($aSearch['sCountryCode'] === false) {
$aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
// Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
- if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)))
- {
+ if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
$aSearch['iSearchRank'] += 5;
}
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
- }
- elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
- {
- if ($aSearch['fLat'] === '')
- {
+ } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
+ if ($aSearch['fLat'] === '') {
$aSearch['fLat'] = $aSearchTerm['lat'];
$aSearch['fLon'] = $aSearchTerm['lon'];
$aSearch['fRadius'] = $aSearchTerm['radius'];
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
- }
- elseif ($sPhraseType == 'postalcode')
- {
+ } elseif ($sPhraseType == 'postalcode') {
// We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
- if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
- {
+ if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
// If we already have a name try putting the postcode first
- if (sizeof($aSearch['aName']))
- {
+ if (sizeof($aSearch['aName'])) {
$aNewSearch = $aSearch;
$aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
$aNewSearch['aName'] = array();
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
}
- if (sizeof($aSearch['aName']))
- {
- if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
- {
+ if (sizeof($aSearch['aName'])) {
+ if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
$aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
- }
- else
- {
+ } else {
$aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
$aSearch['iSearchRank'] += 1000; // skip;
}
- }
- else
- {
+ } else {
$aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
//$aSearch['iNamePhrase'] = $iPhrase;
}
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
-
- }
- elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
- {
- if ($aSearch['sHouseNumber'] === '')
- {
+ } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
+ if ($aSearch['sHouseNumber'] === '') {
$aSearch['sHouseNumber'] = $sToken;
// sanity check: if the housenumber is not mainly made
// up of numbers, add a penalty
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
*/
}
- }
- elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
- {
- if ($aSearch['sClass'] === '')
- {
+ } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
+ if ($aSearch['sClass'] === '') {
$aSearch['sOperator'] = $aSearchTerm['operator'];
$aSearch['sClass'] = $aSearchTerm['class'];
$aSearch['sType'] = $aSearchTerm['type'];
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
- }
- elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
- {
- if (sizeof($aSearch['aName']))
- {
- if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false))
- {
+ } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
+ if (sizeof($aSearch['aName'])) {
+ if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
$aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
- }
- else
- {
+ } else {
$aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
$aSearch['iSearchRank'] += 1000; // skip;
}
- }
- else
- {
+ } else {
$aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
//$aSearch['iNamePhrase'] = $iPhrase;
}
// Look for partial matches.
// Note that there is no point in adding country terms here
// because country are omitted in the address.
- if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country')
- {
+ if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
// Allow searching for a word - but at extra cost
- foreach($aValidTokens[$sToken] as $aSearchTerm)
- {
- if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
- {
- if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false)
- {
+ foreach ($aValidTokens[$sToken] as $aSearchTerm) {
+ if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
+ if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
$aSearch = $aCurrentSearch;
$aSearch['iSearchRank'] += 1;
- if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
- {
+ if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
$aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
- }
- elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
- {
+ } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
$aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
$aSearch['iSearchRank'] += 1;
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
- foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
- {
+ foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
if (empty($aSearchTermToken['country_code'])
&& empty($aSearchTermToken['lat'])
- && empty($aSearchTermToken['class']))
- {
+ && empty($aSearchTermToken['class'])
+ ) {
$aSearch = $aCurrentSearch;
$aSearch['iSearchRank'] += 1;
$aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
}
- }
- else
- {
+ } else {
$aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
}
- if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
- {
+ if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
$aSearch = $aCurrentSearch;
$aSearch['iSearchRank'] += 1;
if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
- if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
+ if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
$aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
- else
+ } else {
$aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
+ }
$aSearch['iNamePhrase'] = $iPhrase;
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
}
}
}
- }
- else
- {
+ } else {
// Allow skipping a word - but at EXTREAM cost
//$aSearch = $aCurrentSearch;
//$aSearch['iSearchRank']+=100;
usort($aNewPhraseSearches, 'bySearchRank');
$aSearchHash = array();
- foreach($aNewPhraseSearches as $iSearch => $aSearch)
- {
+ foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
$sHash = serialize($aSearch);
if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
else $aSearchHash[$sHash] = 1;
// Re-group the searches by their score, junk anything over 20 as just not worth trying
$aGroupedSearches = array();
- foreach($aNewPhraseSearches as $aSearch)
- {
- if ($aSearch['iSearchRank'] < $this->iMaxRank)
- {
+ foreach ($aNewPhraseSearches as $aSearch) {
+ if ($aSearch['iSearchRank'] < $this->iMaxRank) {
if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
$aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
}
$iSearchCount = 0;
$aSearches = array();
- foreach($aGroupedSearches as $iScore => $aNewSearches)
- {
+ foreach ($aGroupedSearches as $iScore => $aNewSearches) {
$iSearchCount += sizeof($aNewSearches);
$aSearches = array_merge($aSearches, $aNewSearches);
if ($iSearchCount > 50) break;
}
//if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
-
}
return $aGroupedSearches;
-
}
/* Perform the actual query lookup.
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
$sCountryCodesSQL = false;
- if ($this->aCountryCodes)
- {
+ if ($this->aCountryCodes) {
$sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
}
$sQuery = $this->sQuery;
// Conflicts between US state abreviations and various words for 'the' in different languages
- if (isset($this->aLangPrefOrder['name:en']))
- {
+ if (isset($this->aLangPrefOrder['name:en'])) {
$sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/','\1illinois\2', $sQuery);
$sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery);
$sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery);
}
$bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
- if ($this->sViewboxCentreSQL)
- {
+ if ($this->sViewboxCentreSQL) {
// For complex viewboxes (routes) precompute the bounding geometry
$sGeom = chksql($this->oDB->getOne("select ".$this->sViewboxSmallSQL),
"Could not get small viewbox");
}
// Do we have anything that looks like a lat/lon pair?
- if ( $aLooksLike = looksLikeLatLonPair($sQuery) )
- {
+ if ($aLooksLike = looksLikeLatLonPair($sQuery)) {
$this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
$sQuery = $aLooksLike['query'];
}
$aSearchResults = array();
- if ($sQuery || $this->aStructuredQuery)
- {
+ if ($sQuery || $this->aStructuredQuery) {
// Start with a blank search
$aSearches = array(
array('iSearchRank' => 0,
// Do we have a radius search?
$sNearPointSQL = false;
- if ($this->aNearPoint)
- {
+ if ($this->aNearPoint) {
$sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
$aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
$aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
$bSpecialTerms = false;
preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
$aSpecialTerms = array();
- foreach($aSpecialTermsRaw as $aSpecialTerm)
- {
+ foreach ($aSpecialTermsRaw as $aSpecialTerm) {
$sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
$aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
}
preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
$aSpecialTerms = array();
- if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity'])
- {
+ if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
$aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
unset($this->aStructuredQuery['amenity']);
}
- foreach($aSpecialTermsRaw as $aSpecialTerm)
- {
+
+ foreach ($aSpecialTermsRaw as $aSpecialTerm) {
$sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
$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';
if (CONST_Debug) var_Dump($sSQL);
$aSearchWords = chksql($this->oDB->getAll($sSQL));
$aNewSearches = array();
- foreach($aSearches as $aSearch)
- {
- foreach($aSearchWords as $aSearchTerm)
- {
+ foreach ($aSearches as $aSearch) {
+ foreach ($aSearchWords as $aSearchTerm) {
$aNewSearch = $aSearch;
- if ($aSearchTerm['country_code'])
- {
+ if ($aSearchTerm['country_code']) {
$aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
$aNewSearches[] = $aNewSearch;
$bSpecialTerms = true;
}
- if ($aSearchTerm['class'])
- {
+ if ($aSearchTerm['class']) {
$aNewSearch['sClass'] = $aSearchTerm['class'];
$aNewSearch['sType'] = $aSearchTerm['type'];
$aNewSearches[] = $aNewSearch;
// Split query into phrases
// Commas are used to reduce the search space by indicating where phrases split
- if ($this->aStructuredQuery)
- {
+ if ($this->aStructuredQuery) {
$aPhrases = $this->aStructuredQuery;
$bStructuredPhrases = true;
- }
- else
- {
+ } else {
$aPhrases = explode(',',$sQuery);
$bStructuredPhrases = false;
}
// Get all 'sets' of words
// Generate a complete list of all
$aTokens = array();
- foreach($aPhrases as $iPhrase => $sPhrase)
- {
+ foreach ($aPhrases as $iPhrase => $sPhrase) {
$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']))
- {
+ if (trim($aPhrase['string'])) {
$aPhrases[$iPhrase] = $aPhrase;
$aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
$aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
$aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
- }
- else
- {
+ } else {
unset($aPhrases[$iPhrase]);
}
}
$aPhraseTypes = array_keys($aPhrases);
$aPhrases = array_values($aPhrases);
- if (sizeof($aTokens))
- {
+ if (sizeof($aTokens)) {
// Check which tokens we have, get the ID numbers
$sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
$sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
if (CONST_Debug) var_Dump($sSQL);
$aValidTokens = array();
- if (sizeof($aTokens))
- {
+ if (sizeof($aTokens)) {
$aDatabaseWords = chksql($this->oDB->getAll($sSQL),
"Could not get word tokens.");
- }
- else
- {
+ } else {
$aDatabaseWords = array();
}
$aPossibleMainWordIDs = array();
$aWordFrequencyScores = array();
- foreach($aDatabaseWords as $aToken)
- {
+ foreach ($aDatabaseWords as $aToken) {
// Very special case - require 2 letter country param to match the country code found
if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
- && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code'])
- {
+ && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
+ ) {
continue;
}
- if (isset($aValidTokens[$aToken['word_token']]))
- {
+ if (isset($aValidTokens[$aToken['word_token']])) {
$aValidTokens[$aToken['word_token']][] = $aToken;
- }
- else
- {
+ } else {
$aValidTokens[$aToken['word_token']] = array($aToken);
}
if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
// Try and calculate GB postcodes we might be missing
- foreach($aTokens as $sToken)
- {
+ foreach ($aTokens as $sToken) {
// Source of gb postcodes is now definitive - always use
- if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
- {
- if (substr($aData[1],-2,1) != ' ')
- {
+ if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
+ if (substr($aData[1],-2,1) != ' ') {
$aData[0] = substr($aData[0],0,strlen($aData[1])-1).' '.substr($aData[0],strlen($aData[1])-1);
$aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
}
$aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
- if ($aGBPostcodeLocation)
- {
+ if ($aGBPostcodeLocation) {
$aValidTokens[$sToken] = $aGBPostcodeLocation;
}
- }
- // US ZIP+4 codes - if there is no token,
- // merge in the 5-digit ZIP code
- else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
- {
- if (isset($aValidTokens[$aData[1]]))
- {
- foreach($aValidTokens[$aData[1]] as $aToken)
- {
- if (!$aToken['class'])
- {
- if (isset($aValidTokens[$sToken]))
- {
+ } else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
+ // US ZIP+4 codes - if there is no token,
+ // merge in the 5-digit ZIP code
+ if (isset($aValidTokens[$aData[1]])) {
+ foreach ($aValidTokens[$aData[1]] as $aToken) {
+ if (!$aToken['class']) {
+ if (isset($aValidTokens[$sToken])) {
$aValidTokens[$sToken][] = $aToken;
- }
- else
- {
+ } else {
$aValidTokens[$sToken] = array($aToken);
}
}
}
}
- foreach($aTokens as $sToken)
- {
+ foreach ($aTokens as $sToken) {
// Unknown single word token with a number - assume it is a house number
- if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
- {
+ if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken)) {
$aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
}
}
$aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
- if ($this->bReverseInPlan)
- {
+ if ($this->bReverseInPlan) {
// Reverse phrase array and also reverse the order of the wordsets in
// the first and final phrase. Don't bother about phrases in the middle
// because order in the address doesn't matter.
$aPhrases = array_reverse($aPhrases);
$aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
- if (sizeof($aPhrases) > 1)
- {
+ if (sizeof($aPhrases) > 1) {
$aFinalPhrase = end($aPhrases);
$aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
}
$aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
- foreach($aGroupedSearches as $aSearches)
- {
- foreach($aSearches as $aSearch)
- {
- if ($aSearch['iSearchRank'] < $this->iMaxRank)
- {
+ foreach ($aGroupedSearches as $aSearches) {
+ foreach ($aSearches as $aSearch) {
+ if ($aSearch['iSearchRank'] < $this->iMaxRank) {
if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
$aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
}
-
}
}
$aGroupedSearches = $aReverseGroupedSearches;
ksort($aGroupedSearches);
}
- }
- else
- {
+ } else {
// Re-group the searches by their score, junk anything over 20 as just not worth trying
$aGroupedSearches = array();
- foreach($aSearches as $aSearch)
- {
- if ($aSearch['iSearchRank'] < $this->iMaxRank)
- {
+ foreach ($aSearches as $aSearch) {
+ if ($aSearch['iSearchRank'] < $this->iMaxRank) {
if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
$aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
}
}
if (CONST_Debug) var_Dump($aGroupedSearches);
-
- if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0)
- {
+ if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
$aCopyGroupedSearches = $aGroupedSearches;
- foreach($aCopyGroupedSearches as $iGroup => $aSearches)
- {
- foreach($aSearches as $iSearch => $aSearch)
- {
+ foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
+ foreach ($aSearches as $iSearch => $aSearch) {
$aReductionsList = array($aSearch['aAddress']);
$iSearchRank = $aSearch['iSearchRank'];
- while(sizeof($aReductionsList) > 0)
- {
+ while (sizeof($aReductionsList) > 0) {
$iSearchRank += 5;
if ($iSearchRank > iMaxRank) break 3;
$aNewReductionsList = array();
- foreach($aReductionsList as $aReductionsWordList)
- {
- for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
- {
+ foreach ($aReductionsList as $aReductionsWordList) {
+ for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
$aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
$aReverseSearch = $aSearch;
$aSearch['aAddress'] = $aReductionsWordListResult;
$aSearch['iSearchRank'] = $iSearchRank;
$aGroupedSearches[$iSearchRank][] = $aReverseSearch;
- if (sizeof($aReductionsWordListResult) > 0)
- {
+ if (sizeof($aReductionsWordListResult) > 0) {
$aNewReductionsList[] = $aReductionsWordListResult;
}
}
// Filter out duplicate searches
$aSearchHash = array();
- foreach($aGroupedSearches as $iGroup => $aSearches)
- {
- foreach($aSearches as $iSearch => $aSearch)
- {
+ foreach ($aGroupedSearches as $iGroup => $aSearches) {
+ foreach ($aSearches as $iSearch => $aSearch) {
$sHash = serialize($aSearch);
- if (isset($aSearchHash[$sHash]))
- {
+ if (isset($aSearchHash[$sHash])) {
unset($aGroupedSearches[$iGroup][$iSearch]);
if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
- }
- else
- {
+ } else {
$aSearchHash[$sHash] = 1;
}
}
$iGroupLoop = 0;
$iQueryLoop = 0;
- foreach($aGroupedSearches as $iGroupedRank => $aSearches)
- {
+ foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
$iGroupLoop++;
- foreach($aSearches as $aSearch)
- {
+ foreach ($aSearches as $aSearch) {
$iQueryLoop++;
$searchedHousenumber = -1;
- if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
+ if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
// No location term?
- if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
- {
- if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
- {
+ if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon']) {
+ if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
// Just looking for a country by code - look it up
- if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
- {
+ if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
$sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
if ($bBoundingBoxSearch)
$sSQL .= " order by st_area(geometry) desc limit 1";
if (CONST_Debug) var_dump($sSQL);
$aPlaceIDs = chksql($this->oDB->getCol($sSQL));
- }
- else
- {
+ } else {
$aPlaceIDs = array();
}
- }
- else
- {
+ } 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 (chksql($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)";
$sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
}
if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
// there have been results in the small box, so no further
// expansion in that case.
// Also don't expand if bounded results were requested.
- if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch)
- {
+ if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
$sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
$sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
if (CONST_Debug) var_dump($sSQL);
$aPlaceIDs = chksql($this->oDB->getCol($sSQL));
}
- }
- else
- {
+ } else {
$sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
$sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
$aPlaceIDs = chksql($this->oDB->getCol($sSQL));
}
}
- }
- // If a coordinate is given, the search must either
- // be for a name or a special search. Ignore everythin else.
- else if ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass'])
- {
+ } else if ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
+ // If a coordinate is given, the search must either
+ // be for a name or a special search. Ignore everythin else.
$aPlaceIDs = array();
- }
- else
- {
+ } else {
$aPlaceIDs = array();
// First we need a position, either aName or fLat or both
$aTerms = array();
$aOrder = array();
- if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress']))
- {
+ if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
$sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
$aOrder[] = "";
$aOrder[0] = " (exists(select place_id from placex where parent_place_id = search_name.place_id";
// they might be right - but they are just too darned expensive to run
if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
- if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
- {
+ if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
// For infrequent name terms disable index usage for address
if (CONST_Search_NameOnlySearchFrequencyThreshold &&
sizeof($aSearch['aName']) == 1 &&
- $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
- {
+ $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
+ ) {
$aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
- }
- else
- {
+ } else {
$aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
- if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
+ if (sizeof($aSearch['aAddressNonSearch'])) {
+ $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
+ }
}
}
if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
- if ($aSearch['sHouseNumber'])
- {
+ if ($aSearch['sHouseNumber']) {
$aTerms[] = "address_rank between 16 and 27";
- }
- else
- {
- if ($this->iMinAddressRank > 0)
- {
+ } else {
+ if ($this->iMinAddressRank > 0) {
$aTerms[] = "address_rank >= ".$this->iMinAddressRank;
}
- if ($this->iMaxAddressRank < 30)
- {
+ if ($this->iMaxAddressRank < 30) {
$aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
}
}
- if ($aSearch['fLon'] && $aSearch['fLat'])
- {
+ if ($aSearch['fLon'] && $aSearch['fLat']) {
$aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
$aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
}
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
}
- if ($sCountryCodesSQL)
- {
+ if ($sCountryCodesSQL) {
$aTerms[] = "country_code in ($sCountryCodesSQL)";
}
if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
- if ($aSearch['sHouseNumber'])
- {
+ if ($aSearch['sHouseNumber']) {
$sImportanceSQL = '- abs(26 - address_rank) + 3';
- }
- else
- {
+ } else {
$sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
}
if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
$aOrder[] = "$sImportanceSQL DESC";
- if (sizeof($aSearch['aFullNameAddress']))
- {
+ if (sizeof($aSearch['aFullNameAddress'])) {
$sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
$aOrder[] = 'exactmatch DESC';
} else {
$sExactMatchSQL = '0::int as exactmatch';
}
- if (sizeof($aTerms))
- {
+ if (sizeof($aTerms)) {
$sSQL = "select place_id, ";
$sSQL .= $sExactMatchSQL;
$sSQL .= " from search_name";
$sSQL .= " where ".join(' and ',$aTerms);
$sSQL .= " order by ".join(', ',$aOrder);
- if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
+ if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
$sSQL .= " limit 20";
- elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
+ } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
$sSQL .= " limit 1";
- else
+ } else {
$sSQL .= " limit ".$this->iLimit;
+ }
- if (CONST_Debug) { var_dump($sSQL); }
+ if (CONST_Debug) var_dump($sSQL);
$aViewBoxPlaceIDs = chksql($this->oDB->getAll($sSQL),
"Could not get places for search terms.");
//var_dump($aViewBoxPlaceIDs);
// Did we have an viewbox matches?
$aPlaceIDs = array();
$bViewBoxMatch = false;
- foreach($aViewBoxPlaceIDs as $aViewBoxRow)
- {
+ foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
//if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
//if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
//if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
//exit;
//now search for housenumber, if housenumber provided
- if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
- {
+ if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
$searchedHousenumber = intval($aSearch['sHouseNumber']);
$aRoadPlaceIDs = $aPlaceIDs;
$sPlaceIDs = join(',',$aPlaceIDs);
// Now they are indexed, look for a house attached to a street we found
$sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
$sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
}
$sSQL .= " limit $this->iLimit";
$aPlaceIDs = chksql($this->oDB->getCol($sSQL));
// if nothing found, search in the interpolation line table
- if(!sizeof($aPlaceIDs))
- {
+ if (!sizeof($aPlaceIDs)) {
// do we need to use transliteration and the regex for housenumbers???
//new query for lines, not housenumbers anymore
- if($searchedHousenumber%2 == 0){
+ if ($searchedHousenumber%2 == 0) {
//if housenumber is even, look for housenumber in streets with interpolationtype even or all
$sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
- }else{
+ } else {
//look for housenumber in streets with interpolationtype odd or all
$sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
}
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
}
//$sSQL .= " limit $this->iLimit";
}
// If nothing found try the aux fallback table
- if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs))
- {
+ if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
$sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and parent_place_id not in (".join(',',$this->aExcludePlaceIDs).")";
}
//$sSQL .= " limit $this->iLimit";
}
//if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
- if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs))
- {
+ if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
//new query for lines, not housenumbers anymore
- if($searchedHousenumber%2 == 0){
+ if ($searchedHousenumber%2 == 0) {
//if housenumber is even, look for housenumber in streets with interpolationtype even or all
$sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
- }else{
+ } else {
//look for housenumber in streets with interpolationtype odd or all
$sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
}
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
}
//$sSQL .= " limit $this->iLimit";
}
// Fallback to the road (if no housenumber was found)
- if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
- {
+ if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
$aPlaceIDs = $aRoadPlaceIDs;
//set to -1, if no housenumbers were found
$searchedHousenumber = -1;
}
- if ($aSearch['sClass'] && sizeof($aPlaceIDs))
- {
+ if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
$sPlaceIDs = join(',', $aPlaceIDs);
$aClassPlaceIDs = array();
- if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
- {
+ if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
// If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
$sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
$sSQL .= " and linked_place_id is null";
$aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
}
- if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
- {
+ if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
$sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
$bCacheTable = chksql($this->oDB->getOne($sSQL));
// For state / country level searches the normal radius search doesn't work very well
$sPlaceGeom = false;
- if ($this->iMaxRank < 9 && $bCacheTable)
- {
+ if ($this->iMaxRank < 9 && $bCacheTable) {
// 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 = chksql($this->oDB->getOne($sSQL));
}
- if ($sPlaceGeom)
- {
+ if ($sPlaceGeom) {
$sPlaceIDs = false;
- }
- else
- {
+ } else {
$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);
$sPlaceIDs = join(',',$aPlaceIDs);
}
- if ($sPlaceIDs || $sPlaceGeom)
- {
-
+ if ($sPlaceIDs || $sPlaceGeom) {
$fRange = 0.01;
- if ($bCacheTable)
- {
+ if ($bCacheTable) {
// More efficient - can make the range bigger
$fRange = 0.05;
$sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
- if ($sPlaceIDs)
- {
+ if ($sPlaceIDs) {
$sSQL .= ",placex as f where ";
$sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
}
- if ($sPlaceGeom)
- {
+ if ($sPlaceGeom) {
$sSQL .= " where ";
$sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
}
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
}
if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
$sSQL .= " limit $this->iLimit";
if (CONST_Debug) var_dump($sSQL);
$aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
- }
- else
- {
+ } else {
if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
$sOrderBySQL = '';
$sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
$sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
$sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
- if (sizeof($this->aExcludePlaceIDs))
- {
+ if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
}
if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
}
}
}
-
$aPlaceIDs = $aClassPlaceIDs;
-
}
-
}
- if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
+ if (CONST_Debug) {
+ echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs);
+ }
- foreach($aPlaceIDs as $iPlaceID)
- {
+ foreach ($aPlaceIDs as $iPlaceID) {
// array for placeID => -1 | Tiger housenumber
$aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
}
if ($iQueryLoop > 20) break;
}
- if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
- {
+ if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
// Need to verify passes rank limits before dropping out of the loop (yuk!)
// reduces the number of place ids, like a filter
// rank_address is 30 for interpolated housenumbers
$sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
- if (CONST_Use_US_Tiger_Data)
- {
+ if (CONST_Use_US_Tiger_Data) {
$sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',array_keys($aResultPlaceIDs)).") ";
$sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
if (CONST_Debug) var_dump($sSQL);
$aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
$tempIDs = array();
- foreach($aFilteredPlaceIDs as $placeID)
- {
+ foreach ($aFilteredPlaceIDs as $placeID) {
$tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
}
$aResultPlaceIDs = $tempIDs;
}
// Did we find anything?
- if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
- {
+ if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
$aSearchResults = $this->getDetails($aResultPlaceIDs);
}
-
- }
- else
- {
+ } else {
// Just interpret as a reverse geocode
$oReverse = new ReverseGeocode($this->oDB);
$oReverse->setZoom(18);
if (CONST_Debug) var_dump("Reverse search", $aLookup);
- if ($aLookup['place_id'])
+ if ($aLookup['place_id']) {
$aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
- else
+ } else {
$aSearchResults = array();
+ }
}
// No results? Done
- if (!sizeof($aSearchResults))
- {
- if ($this->bFallback)
- {
- if ($this->fallbackStructuredQuery())
- {
+ if (!sizeof($aSearchResults)) {
+ if ($this->bFallback) {
+ if ($this->fallbackStructuredQuery()) {
return $this->lookup();
}
}
$aClassType = getClassTypesWithImportance();
$aRecheckWords = preg_split('/\b[\s,\\-]*/u',$sQuery);
- foreach($aRecheckWords as $i => $sWord)
- {
+ foreach ($aRecheckWords as $i => $sWord) {
if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
}
- if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
+ if (CONST_Debug) {
+ echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords);
+ }
$oPlaceLookup = new PlaceLookup($this->oDB);
$oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
$oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
$oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
- foreach($aSearchResults as $iResNum => $aResult)
- {
+ foreach ($aSearchResults as $iResNum => $aResult) {
// Default
$fDiameter = getResultDiameter($aResult);
$aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
- if ($aOutlineResult)
- {
+ if ($aOutlineResult) {
$aResult = array_merge($aResult, $aOutlineResult);
}
- if ($aResult['extra_place'] == 'city')
- {
+ if ($aResult['extra_place'] == 'city') {
$aResult['class'] = 'place';
$aResult['type'] = 'city';
$aResult['rank_search'] = 16;
// Is there an icon set for this type of result?
if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
- && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
- {
+ && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
+ ) {
$aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
}
if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
- && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
- {
+ && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
+ ) {
$aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
- }
- elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
- && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
- {
+ } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
+ && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
+ ) {
$aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
}
// if tag '&addressdetails=1' is set in query
- if ($this->bIncludeAddressDetails)
- {
+ if ($this->bIncludeAddressDetails) {
// getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
$aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
- if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
- {
+ if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
$aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
}
}
- if ($this->bIncludeExtraTags)
- {
- if ($aResult['extra'])
- {
+
+ if ($this->bIncludeExtraTags) {
+ if ($aResult['extra']) {
$aResult['sExtraTags'] = json_decode($aResult['extra']);
- }
- else
- {
+ } else {
$aResult['sExtraTags'] = (object) array();
}
}
- if ($this->bIncludeNameDetails)
- {
- if ($aResult['names'])
- {
+ if ($this->bIncludeNameDetails) {
+ if ($aResult['names']) {
$aResult['sNameDetails'] = json_decode($aResult['names']);
- }
- else
- {
+ } else {
$aResult['sNameDetails'] = (object) array();
}
}
$aResult['importance'] = max(0.001,$aResult['importance']);
$iCountWords = 0;
$sAddress = $aResult['langaddress'];
- foreach($aRecheckWords as $i => $sWord)
- {
- if (stripos($sAddress, $sWord)!==false)
- {
+ foreach ($aRecheckWords as $i => $sWord) {
+ if (stripos($sAddress, $sWord)!==false) {
$iCountWords++;
if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
}
// - approximate importance of address parts
$aResult['foundorder'] = -$aResult['addressimportance']/10;
// - number of exact matches from the query
- if (isset($this->exactMatchCache[$aResult['place_id']]))
+ if (isset($this->exactMatchCache[$aResult['place_id']])) {
$aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
- else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
+ } else if (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
$aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
+ }
// - importance of the class/type
if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
- && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
- {
+ && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
+ ) {
$aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
- }
- else
- {
+ } else {
$aResult['foundorder'] += 0.01;
}
- if (CONST_Debug) { var_dump($aResult); }
+ if (CONST_Debug) var_dump($aResult);
$aSearchResults[$iResNum] = $aResult;
}
uasort($aSearchResults, 'byImportance');
$aSearchResults = array();
$bFirst = true;
- foreach($aToFilter as $iResNum => $aResult)
- {
+ foreach ($aToFilter as $iResNum => $aResult) {
$this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
- if ($bFirst)
- {
+ if ($bFirst) {
$fLat = $aResult['lat'];
$fLon = $aResult['lon'];
if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
$bFirst = false;
}
if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
- && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
- {
+ && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
+ ) {
$aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
$aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
$aSearchResults[] = $aResult;
function getBool($sName, $bDefault=false)
{
- if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
- {
+ if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault;
}
function getInt($sName, $bDefault=false)
{
- if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
- {
+ if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault;
}
- if (!preg_match('/^[+-]?[0-9]+$/', $this->aParams[$sName]))
- {
+ if (!preg_match('/^[+-]?[0-9]+$/', $this->aParams[$sName])) {
userError("Integer number expected for parameter '$sName'");
}
function getFloat($sName, $bDefault=false)
{
- if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
- {
+ if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault;
}
- if (!preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $this->aParams[$sName]))
- {
+ if (!preg_match('/^[+-]?[0-9]*\.?[0-9]+$/', $this->aParams[$sName])) {
userError("Floating-point number expected for parameter '$sName'");
}
function getString($sName, $bDefault=false)
{
- if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
- {
+ if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault;
}
function getSet($sName, $aValues, $sDefault=false)
{
- if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0)
- {
+ if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $sDefault;
}
- if (!in_array($this->aParams[$sName], $aValues))
- {
+ if (!in_array($this->aParams[$sName], $aValues)) {
userError("Parameter '$sName' must be one of: ".join(', ', $aValues));
}
{
$sValue = $this->getString($sName);
- if ($sValue)
- {
+ if ($sValue) {
return explode(',', $sValue);
}
function getPreferredLanguages($sFallback=NULL)
{
- if ($sFallback === NULL && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
- {
+ if ($sFallback === NULL && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
$sFallback = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
}
$aLanguages = array();
$sLangString = $this->getString('accept-language', $sFallback);
- if ($sLangString)
- {
- if (preg_match_all('/(([a-z]{1,8})(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $sLangString, $aLanguagesParse, PREG_SET_ORDER))
- {
- foreach($aLanguagesParse as $iLang => $aLanguage)
- {
+ if ($sLangString) {
+ if (preg_match_all('/(([a-z]{1,8})(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $sLangString, $aLanguagesParse, PREG_SET_ORDER)) {
+ foreach ($aLanguagesParse as $iLang => $aLanguage) {
$aLanguages[$aLanguage[1]] = isset($aLanguage[5])?(float)$aLanguage[5]:1 - ($iLang/100);
if (!isset($aLanguages[$aLanguage[2]])) $aLanguages[$aLanguage[2]] = $aLanguages[$aLanguage[1]]/10;
}
arsort($aLanguages);
}
}
- if (!sizeof($aLanguages) && CONST_Default_Language)
- {
+ if (!sizeof($aLanguages) && CONST_Default_Language) {
$aLanguages[CONST_Default_Language] = 1;
}
- foreach($aLanguages as $sLanguage => $fLanguagePref)
- {
+ foreach ($aLanguages as $sLanguage => $fLanguagePref) {
$aLangPrefOrder['short_name:'.$sLanguage] = 'short_name:'.$sLanguage;
$aLangPrefOrder['name:'.$sLanguage] = 'name:'.$sLanguage;
}
$aLangPrefOrder['short_name'] = 'short_name';
$aLangPrefOrder['name'] = 'name';
$aLangPrefOrder['brand'] = 'brand';
- foreach($aLanguages as $sLanguage => $fLanguagePref)
- {
+ foreach ($aLanguages as $sLanguage => $fLanguagePref) {
$aLangPrefOrder['official_name:'.$sLanguage] = 'official_name:'.$sLanguage;
}
$aLangPrefOrder['official_name'] = 'official_name';
$bIsTiger = CONST_Use_US_Tiger_Data && $sType == 'tiger';
$bIsInterpolation = $sType == 'interpolation';
- if ($bIsTiger)
- {
+ if ($bIsTiger) {
$sSQL = "select place_id,partition, 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, housenumber, null as street, null as isin, postcode,";
$sSQL .= " 'us' as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
$sSQL .= " coalesce(null,0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, 'us' as calculated_country_code, ";
$sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
$sSQL .= " END as housenumber";
$sSQL .= " from location_property_tiger where place_id = ".$iPlaceID.") as blub1) as blub2";
- }
- else if ($bIsInterpolation)
- {
+ } else if ($bIsInterpolation) {
$sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,";
$sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
$sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, ";
// testcase: interpolationtype=odd, startnumber=1000, endnumber=1006, fInterpolFraction=1 => housenumber=1007 => error in st_lineinterpolatepoint
// but this will never happen, because if the searched point is that close to the endnumber, the endnumber house will be directly taken from placex (in ReverseGeocode.php line 220)
// and not interpolated
- }
- else
- {
+ } else {
$sSQL = "select placex.place_id, partition, osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode, country_code, parent_place_id, linked_place_id, rank_address, rank_search, ";
$sSQL .= " coalesce(importance,0.75-(rank_search::float/40)) as importance, indexed_status, indexed_date, wikipedia, calculated_country_code, ";
$sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
if (!$aPlace['place_id']) return null;
- if ($this->bAddressDetails)
- {
+ if ($this->bAddressDetails) {
// to get addressdetails for tiger data, the housenumber is needed
$iHousenumber = ($bIsTiger || $bIsInterpolation) ? $aPlace['housenumber'] : -1;
$aPlace['aAddress'] = $this->getAddressNames($aPlace['place_id'],
$iHousenumber);
}
- if ($this->bExtraTags)
- {
- if ($aPlace['extra'])
- {
+ if ($this->bExtraTags) {
+ if ($aPlace['extra']) {
$aPlace['sExtraTags'] = json_decode($aPlace['extra']);
- }
- else
- {
+ } else {
$aPlace['sExtraTags'] = (object) array();
}
}
- if ($this->bNameDetails)
- {
- if ($aPlace['names'])
- {
+ if ($this->bNameDetails) {
+ if ($aPlace['names']) {
$aPlace['sNameDetails'] = json_decode($aPlace['names']);
- }
- else
- {
+ } else {
$aPlace['sNameDetails'] = (object) array();
}
}
$aClassType = getClassTypes();
$sAddressType = '';
$sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
- if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
- {
+ if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel'])) {
$sAddressType = $aClassType[$aClassType]['simplelabel'];
- }
- else
- {
+ } else {
$sClassType = $aPlace['class'].':'.$aPlace['type'];
if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
$sAddressType = $aClassType[$sClassType]['simplelabel'];
$aAddress = array();
$aFallback = array();
$aClassType = getClassTypes();
- foreach($aAddressLines as $aLine)
- {
+ foreach ($aAddressLines as $aLine) {
$bFallback = false;
$aTypeLabel = false;
- if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
- elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
- elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
- {
+ if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
+ $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
+ } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
+ $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
+ } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
$aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
$bFallback = true;
- }
- else
- {
+ } else {
$aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
$bFallback = true;
}
- if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
- {
+ if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
$sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
$sTypeLabel = str_replace(' ','_',$sTypeLabel);
- if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
- {
+ if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
$aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
}
$aFallback[$sTypeLabel] = $bFallback;
$aOutlineResult = array();
if (!$iPlaceID) return $aOutlineResult;
- if (CONST_Search_AreaPolygons)
- {
+ if (CONST_Search_AreaPolygons) {
// Get the bounding box and outline polygon
$sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
$sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
$sFrom = " from placex where place_id = ".$iPlaceID;
- if ($this->fPolygonSimplificationThreshold > 0)
- {
+ if ($this->fPolygonSimplificationThreshold > 0) {
$sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
- }
- else
- {
+ } else {
$sSQL .= $sFrom;
}
$aPointPolygon = chksql($this->oDB->getRow($sSQL),
"Could not get outline");
- if ($aPointPolygon['place_id'])
- {
- if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
- {
+ if ($aPointPolygon['place_id']) {
+ if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
$aOutlineResult['lat'] = $aPointPolygon['centrelat'];
$aOutlineResult['lon'] = $aPointPolygon['centrelon'];
}
if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
- if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
- {
+ if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
$aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
$aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
}
- if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
- {
+
+ if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
$aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
$aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
}
} // CONST_Search_AreaPolygons
// as a fallback we generate a bounding box without knowing the size of the geometry
- if ( (!isset($aOutlineResult['aBoundingBox'])) && isset($fLon) )
- {
-
- if ($this->bIncludePolygonAsPoints)
- {
+ if ((!isset($aOutlineResult['aBoundingBox'])) && isset($fLon)) {
+ //
+ if ($this->bIncludePolygonAsPoints) {
$sGeometryText = 'POINT('.$fLon.','.$fLat.')';
$aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
}
$bIsInUnitedStates = false;
$bPlaceIsTiger = false;
$bPlaceIsLine = false;
- while(!$iPlaceID && $fSearchDiam < $fMaxAreaDistance)
- {
+ while (!$iPlaceID && $fSearchDiam < $fMaxAreaDistance) {
$fSearchDiam = $fSearchDiam * 2;
// If we have to expand the search area by a large amount then we need a larger feature
$bIsInUnitedStates = ($aPlace['calculated_country_code'] == 'us');
}
// if a street or house was found, look in interpolation lines table
- if ($bDoInterpolation && $this->iMaxRank >= 28 && $aPlace && $aPlace['rank_search'] >= 26)
- {
+ if ($bDoInterpolation && $this->iMaxRank >= 28 && $aPlace && $aPlace['rank_search'] >= 26) {
// if a house was found, search the interpolation line that is at least as close as the house
$sSQL = 'SELECT place_id, parent_place_id, 30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
$sSQL .= ' FROM location_property_osmline';
$sSQL .= ' and indexed_status = 0 ';
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
- if (CONST_Debug)
- {
+ if (CONST_Debug) {
$sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
var_dump($sSQL);
$aAllHouses = chksql($this->oDB->getAll($sSQL));
- foreach($aAllHouses as $i)
- {
+ foreach ($aAllHouses as $i) {
echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
}
}
$aPlaceLine = chksql($this->oDB->getRow($sSQL),
"Could not determine closest housenumber on an osm interpolation line.");
- if ($aPlaceLine)
- {
+ if ($aPlaceLine) {
if (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine);
- if ($aPlace['rank_search'] == 30)
- {
+ if ($aPlace['rank_search'] == 30) {
// if a house was already found in placex, we have to find out,
// if the placex house or the interpolated house are closer to the searched point
// distance between point and placex house
$aDistanceInterpolation = chksql($this->oDB->getRow($sSQL),
"Could not determine distance between searched point and interpolated house.");
$fDistanceInterpolation = $aDistanceInterpolation['distance'];
- if ($fDistanceInterpolation < $fDistancePlacex)
- {
+ if ($fDistanceInterpolation < $fDistancePlacex) {
// interpolation is closer to point than placex house
$bPlaceIsLine = true;
$aPlace = $aPlaceLine;
$iMaxRank = 30;
}
// else: nothing to do, take placex house from above
- }
- else
- {
+ } else {
$bPlaceIsLine = true;
$aPlace = $aPlaceLine;
$iPlaceID = $aPlaceLine['place_id'];
}
// Only street found? If it's in the US we can check TIGER data for nearest housenumber
- if (CONST_Use_US_Tiger_Data && $bDoInterpolation && $bIsInUnitedStates && $this->iMaxRank >= 28 && $iPlaceID && ($aPlace['rank_search'] == 26 || $aPlace['rank_search'] == 27 ))
- {
+ if (CONST_Use_US_Tiger_Data && $bDoInterpolation && $bIsInUnitedStates && $this->iMaxRank >= 28 && $iPlaceID && ($aPlace['rank_search'] == 26 || $aPlace['rank_search'] == 27 )) {
$fSearchDiam = 0.001;
$sSQL = 'SELECT place_id,parent_place_id,30 as rank_search, ST_line_locate_point(linegeo,'.$sPointSQL.') as fraction';
//if (CONST_Debug) { $sSQL .= ', housenumber, ST_distance('.$sPointSQL.', centroid) as distance, st_y(centroid) as lat, st_x(centroid) as lon'; }
$sSQL .= ' AND ST_DWithin('.$sPointSQL.', linegeo, '.$fSearchDiam.')'; //no centroid anymore in Tiger data, now we have lines
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', linegeo) ASC limit 1';
- if (CONST_Debug)
- {
+ if (CONST_Debug) {
$sSQL = preg_replace('/limit 1/', 'limit 100', $sSQL);
var_dump($sSQL);
$aAllHouses = chksql($this->oDB->getAll($sSQL));
- foreach($aAllHouses as $i)
- {
+ foreach ($aAllHouses as $i) {
echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
}
}
$aPlaceTiger = chksql($this->oDB->getRow($sSQL),
"Could not determine closest Tiger place.");
- if ($aPlaceTiger)
- {
+ if ($aPlaceTiger) {
if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
$bPlaceIsTiger = true;
$aPlace = $aPlaceTiger;
}
// The point we found might be too small - use the address to find what it is a child of
- if ($iPlaceID && $iMaxRank < 28)
- {
- if (($aPlace['rank_search'] > 28 || $bPlaceIsTiger || $bPlaceIsLine) && $iParentPlaceID)
- {
+ if ($iPlaceID && $iMaxRank < 28) {
+ if (($aPlace['rank_search'] > 28 || $bPlaceIsTiger || $bPlaceIsLine) && $iParentPlaceID) {
$iPlaceID = $iParentPlaceID;
}
$sSQL = 'select address_place_id';
$sSQL .= ' LIMIT 1';
$iPlaceID = chksql($this->oDB->getOne($sSQL),
"Could not get parent for place.");
- if (!$iPlaceID)
- {
+ if (!$iPlaceID) {
$iPlaceID = $aPlace['place_id'];
}
}
$aQuick = array();
$aCounts = array();
- foreach($aSpec as $aLine)
- {
- if (is_array($aLine))
- {
+ foreach ($aSpec as $aLine) {
+ if (is_array($aLine)) {
if ($aLine[0]) $aQuick['--'.$aLine[0]] = $aLine;
if ($aLine[1]) $aQuick['-'.$aLine[1]] = $aLine;
$aCounts[$aLine[0]] = 0;
$aResult = array();
$bUnknown = false;
$iSize = sizeof($aArg);
- for ($i = 1; $i < $iSize; $i++)
- {
- if (isset($aQuick[$aArg[$i]]))
- {
+ for ($i = 1; $i < $iSize; $i++) {
+ if (isset($aQuick[$aArg[$i]])) {
$aLine = $aQuick[$aArg[$i]];
$aCounts[$aLine[0]]++;
$xVal = null;
- if ($aLine[4] == $aLine[5])
- {
- if ($aLine[4])
- {
+ if ($aLine[4] == $aLine[5]) {
+ if ($aLine[4]) {
$xVal = array();
- for($n = $aLine[4]; $i < $iSize && $n; $n--)
- {
+ for ($n = $aLine[4]; $i < $iSize && $n; $n--) {
$i++;
if ($i >= $iSize || $aArg[$i][0] == '-') showUsage($aSpec, $bExitOnError, 'Parameter of \''.$aLine[0].'\' is missing');
- switch ($aLine[6])
- {
- case 'realpath':
- $xVal[] = realpath($aArg[$i]);
- break;
- case 'realdir':
- $sPath = realpath(dirname($aArg[$i]));
- if ($sPath)
- $xVal[] = $sPath . '/' . basename($aArg[$i]);
- else
- $xVal[] = $sPath;
- break;
- case 'bool':
- $xVal[] = (bool)$aArg[$i];
- break;
- case 'int':
- $xVal[] = (int)$aArg[$i];
- break;
- case 'float':
- $xVal[] = (float)$aArg[$i];
- break;
- default:
- $xVal[] = $aArg[$i];
- break;
+ switch ($aLine[6]) {
+ case 'realpath':
+ $xVal[] = realpath($aArg[$i]);
+ break;
+ case 'realdir':
+ $sPath = realpath(dirname($aArg[$i]));
+ if ($sPath) {
+ $xVal[] = $sPath . '/' . basename($aArg[$i]);
+ } else {
+ $xVal[] = $sPath;
+ }
+ break;
+ case 'bool':
+ $xVal[] = (bool)$aArg[$i];
+ break;
+ case 'int':
+ $xVal[] = (int)$aArg[$i];
+ break;
+ case 'float':
+ $xVal[] = (float)$aArg[$i];
+ break;
+ default:
+ $xVal[] = $aArg[$i];
+ break;
}
}
if ($aLine[4] == 1) $xVal = $xVal[0];
- }
- else
- {
+ } else {
$xVal = true;
}
- }
- else
- {
+ } else {
fail('Variable numbers of params not yet supported');
}
- if ($aLine[3] > 1)
- {
+ if ($aLine[3] > 1) {
if (!array_key_exists($aLine[0], $aResult)) $aResult[$aLine[0]] = array();
$aResult[$aLine[0]][] = $xVal;
- }
- else
- {
+ } else {
$aResult[$aLine[0]] = $xVal;
}
- }
- else
- {
+ } else {
$bUnknown = $aArg[$i];
}
}
if (array_key_exists('help', $aResult)) showUsage($aSpec);
if ($bUnknown && $bExitOnUnknown) showUsage($aSpec, $bExitOnError, 'Unknown option \''.$bUnknown.'\'');
- foreach($aSpec as $aLine)
- {
- if (is_array($aLine))
- {
+ foreach ($aSpec as $aLine) {
+ if (is_array($aLine)) {
if ($aCounts[$aLine[0]] < $aLine[2]) showUsage($aSpec, $bExitOnError, 'Option \''.$aLine[0].'\' is missing');
if ($aCounts[$aLine[0]] > $aLine[3]) showUsage($aSpec, $bExitOnError, 'Option \''.$aLine[0].'\' is pressent too many times');
- switch ($aLine[6])
- {
- case 'bool':
- if (!array_key_exists($aLine[0], $aResult))
- $aResult[$aLine[0]] = false;
- break;
+ switch ($aLine[6]) {
+ case 'bool':
+ if (!array_key_exists($aLine[0], $aResult))
+ $aResult[$aLine[0]] = false;
+ break;
}
}
}
function showUsage($aSpec, $bExit = false, $sError = false)
{
- if ($sError)
- {
+ if ($sError) {
echo basename($_SERVER['argv'][0]).': '.$sError."\n";
echo 'Try `'.basename($_SERVER['argv'][0]).' --help` for more information.'."\n";
exit;
}
echo "Usage: ".basename($_SERVER['argv'][0])."\n";
$bFirst = true;
- foreach($aSpec as $aLine)
- {
- if (is_array($aLine))
- {
- if ($bFirst)
- {
+ foreach ($aSpec as $aLine) {
+ if (is_array($aLine)) {
+ if ($bFirst) {
$bFirst = false;
echo "\n";
}
if ($aLine[0]) $aNames[] = '--'.$aLine[0];
$sName = join(', ',$aNames);
echo ' '.$sName.str_repeat(' ',30-strlen($sName)).$aLine[7]."\n";
- }
- else
- {
+ } else {
echo $aLine."\n";
}
}
function chksql($oSql, $sMsg = false)
{
- if (PEAR::isError($oSql))
- {
+ if (PEAR::isError($oSql)) {
fail($sMsg || $oSql->getMessage(), $oSql->userinfo);
}
if (CONST_HTTP_Proxy) {
$proxy = 'tcp://' . CONST_HTTP_Proxy_Host . ':' . CONST_HTTP_Proxy_Port;
$aHeaders = array();
- if(CONST_HTTP_Proxy_Login != null && CONST_HTTP_Proxy_Login != '' && CONST_HTTP_Proxy_Password != null && CONST_HTTP_Proxy_Password != '') {
+ if (CONST_HTTP_Proxy_Login != null && CONST_HTTP_Proxy_Login != '' && CONST_HTTP_Proxy_Password != null && CONST_HTTP_Proxy_Password != '') {
$auth = base64_encode(CONST_HTTP_Proxy_Login . ':' . CONST_HTTP_Proxy_Password);
$aHeaders = array("Proxy-Authorization: Basic $auth");
}
<p><b>Details:</b> <pre>
INTERNALFAIL;
- if (CONST_Debug)
- {
+ if (CONST_Debug) {
var_dump($oSql);
- }
- else
- {
+ } else {
echo "<pre>\n".$oSql->getUserInfo()."</pre>";
}
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)
- {
+ if (CONST_Debug) {
echo "<hr><h2>Debugging Information</h2><br>";
- if ($sSQL)
- {
+ if ($sSQL) {
echo "<h3>SQL query</h3><code>".$sSQL."</code>";
}
- if ($vDumpVar)
- {
+ if ($vDumpVar) {
echo "<h3>Result</h3> <code>";
var_dump($vDumpVar);
echo "</code>";
* HTTP Reply header setup
*/
-if (CONST_NoAccessControl)
-{
+if (CONST_NoAccessControl) {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: OPTIONS,GET");
- if (!empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
- {
+ if (!empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header("Access-Control-Allow-Headers: ".$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
}
}
require_once(CONST_BasePath.'/lib/lib.php');
require_once(CONST_BasePath.'/lib/db.php');
-if (get_magic_quotes_gpc())
-{
+if (get_magic_quotes_gpc()) {
echo "Please disable magic quotes in your php.ini configuration\n";
exit;
}
$aResult = array(array(join(' ',$aWords)));
$sFirstToken = '';
if ($iDepth < 8) {
- while(sizeof($aWords) > 1)
- {
+ while (sizeof($aWords) > 1) {
$sWord = array_shift($aWords);
$sFirstToken .= ($sFirstToken?' ':'').$sWord;
$aRest = getWordSets($aWords, $iDepth+1);
- foreach($aRest as $aSet)
- {
+ foreach ($aRest as $aSet) {
$aResult[] = array_merge(array($sFirstToken),$aSet);
}
}
{
$aResult = array(array(join(' ',$aWords)));
$sFirstToken = '';
- if ($iDepth < 8)
- {
- while(sizeof($aWords) > 1)
- {
+ if ($iDepth < 8) {
+ while (sizeof($aWords) > 1) {
$sWord = array_pop($aWords);
$sFirstToken = $sWord.($sFirstToken?' ':'').$sFirstToken;
$aRest = getInverseWordSets($aWords, $iDepth+1);
- foreach($aRest as $aSet)
- {
+ foreach ($aRest as $aSet) {
$aResult[] = array_merge(array($sFirstToken),$aSet);
}
}
function getTokensFromSets($aSets)
{
$aTokens = array();
- foreach($aSets as $aSet)
- {
- foreach($aSet as $sWord)
- {
+ foreach ($aSets as $aSet) {
+ foreach ($aSet as $sWord) {
$aTokens[' '.$sWord] = ' '.$sWord;
$aTokens[$sWord] = $sWord;
}
$sSQL = 'select \'AA\', ST_X(ST_Centroid(geometry)) as lon,ST_Y(ST_Centroid(geometry)) as lat from gb_postcode where postcode = \''.$sPostcode.'\'';
$aNearPostcodes = chksql($oDB->getAll($sSQL));
- if (sizeof($aNearPostcodes))
- {
+ if (sizeof($aNearPostcodes)) {
$aPostcodes = array();
- foreach($aNearPostcodes as $aPostcode)
- {
+ foreach ($aNearPostcodes as $aPostcode) {
$aPostcodes[] = array('lat' => $aPostcode['lat'], 'lon' => $aPostcode['lon'], 'radius' => 0.005);
}
{
$aOrders = getClassTypes();
$i = 1;
- foreach($aOrders as $sID => $a)
- {
+ foreach ($aOrders as $sID => $a) {
$aOrders[$sID]['importance'] = $i++;
}
return $aOrders;
$fDiameter = 0.0001;
if (isset($aResult['class'])
- && isset($aResult['type'])
- && isset($aResult['admin_level'])
- && isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
- && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
- {
+ && isset($aResult['type'])
+ && isset($aResult['admin_level'])
+ && isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
+ && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']
+ ) {
$fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
- }
- elseif (isset($aResult['class'])
- && isset($aResult['type'])
- && isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
- && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
- {
+ } elseif (isset($aResult['class'])
+ && isset($aResult['type'])
+ && isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
+ && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']
+ ) {
$fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
}
$iOptions |= JSON_UNESCAPED_UNICODE;
$jsonout = json_encode($xVal, $iOptions);
- if( ! isset($_GET['json_callback']))
- {
+ if (! isset($_GET['json_callback'])) {
header("Content-Type: application/json; charset=UTF-8");
echo $jsonout;
- } else
- {
- if (preg_match('/^[$_\p{L}][$_\p{L}\p{Nd}.[\]]*$/u',$_GET['json_callback']))
- {
+ } else {
+ if (preg_match('/^[$_\p{L}][$_\p{L}\p{Nd}.[\]]*$/u',$_GET['json_callback'])) {
header("Content-Type: application/javascript; charset=UTF-8");
echo $_GET['json_callback'].'('.$jsonout.')';
- }
- else
- {
+ } else {
header('HTTP/1.0 400 Bad Request');
}
}
function _debugDumpGroupedSearches($aData, $aTokens)
{
$aWordsIDs = array();
- if ($aTokens)
- {
- foreach($aTokens as $sToken => $aWords)
- {
- if ($aWords)
- {
- foreach($aWords as $aToken)
- {
+ if ($aTokens) {
+ foreach ($aTokens as $sToken => $aWords) {
+ if ($aWords) {
+ foreach ($aWords as $aToken) {
$aWordsIDs[$aToken['word_id']] = $sToken.'('.$aToken['word_id'].')';
}
}
}
echo "<table border=\"1\">";
echo "<tr><th>rank</th><th>Name Tokens</th><th>Name Not</th><th>Address Tokens</th><th>Address Not</th><th>country</th><th>operator</th><th>class</th><th>type</th><th>house#</th><th>Lat</th><th>Lon</th><th>Radius</th></tr>";
- foreach($aData as $iRank => $aRankedSet)
- {
- foreach($aRankedSet as $aRow)
- {
+ foreach ($aData as $iRank => $aRankedSet) {
+ foreach ($aRankedSet as $aRow) {
echo "<tr>";
echo "<td>$iRank</td>";
echo "<td>";
$sSep = '';
- foreach($aRow['aName'] as $iWordID)
- {
+ foreach ($aRow['aName'] as $iWordID) {
echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
$sSep = ', ';
}
echo "<td>";
$sSep = '';
- foreach($aRow['aNameNonSearch'] as $iWordID)
- {
+ foreach ($aRow['aNameNonSearch'] as $iWordID) {
echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
$sSep = ', ';
}
echo "<td>";
$sSep = '';
- foreach($aRow['aAddress'] as $iWordID)
- {
+ foreach ($aRow['aAddress'] as $iWordID) {
echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
$sSep = ', ';
}
echo "<td>";
$sSep = '';
- foreach($aRow['aAddressNonSearch'] as $iWordID)
- {
+ foreach ($aRow['aAddressNonSearch'] as $iWordID) {
echo $sSep.'#'.$aWordsIDs[$iWordID].'#';
$sSep = ', ';
}
$aAddress = array();
$aFallback = array();
$aClassType = getClassTypes();
- foreach($aAddressLines as $aLine)
- {
+ foreach ($aAddressLines as $aLine) {
$bFallback = false;
$aTypeLabel = false;
- if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
- elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
- elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
- {
+ if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) {
+ $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
+ } elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) {
+ $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
+ } elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))])) {
$aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
$bFallback = true;
- }
- else
- {
+ } else {
$aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
$bFallback = true;
}
- if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
- {
+ if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
$sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
$sTypeLabel = str_replace(' ','_',$sTypeLabel);
- if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
- {
+ if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
$aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
}
$aFallback[$sTypeLabel] = $bFallback;
$fQueryLat = null;
$fQueryLon = null;
- // degrees decimal minutes
- // N 40 26.767, W 79 58.933
- // N 40°26.767′, W 79°58.933′
- // 1 2 3 4 5 6
- if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[° ]+([0-9.]+)?[′\']*[, ]+([EW])[ ]+([0-9]+)[° ]+([0-9]+[0-9.]*)[′\']*?\\b/', $sQuery, $aData))
- {
+ if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[° ]+([0-9.]+)?[′\']*[, ]+([EW])[ ]+([0-9]+)[° ]+([0-9]+[0-9.]*)[′\']*?\\b/', $sQuery, $aData)) {
+ // 1 2 3 4 5 6
+ // degrees decimal minutes
+ // N 40 26.767, W 79 58.933
+ // N 40°26.767′, W 79°58.933′
$sFound = $aData[0];
$fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
$fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
- }
- // degrees decimal minutes
- // 40 26.767 N, 79 58.933 W
- // 40° 26.767′ N 79° 58.933′ W
- // 1 2 3 4 5 6
- elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+[0-9.]*)?[′\']*[ ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+[0-9.]*)?[′\' ]+([EW])\\b/', $sQuery, $aData))
- {
+ } elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+[0-9.]*)?[′\']*[ ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+[0-9.]*)?[′\' ]+([EW])\\b/', $sQuery, $aData)) {
+ // 1 2 3 4 5 6
+ // degrees decimal minutes
+ // 40 26.767 N, 79 58.933 W
+ // 40° 26.767′ N 79° 58.933′ W
$sFound = $aData[0];
$fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
$fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
- }
- // degrees decimal seconds
- // N 40 26 46 W 79 58 56
- // N 40° 26′ 46″, W 79° 58′ 56″
- // 1 2 3 4 5 6 7 8
- elseif (preg_match('/\\b([NS])[ ]([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″"]*[, ]+([EW])[ ]([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″"]*\\b/', $sQuery, $aData))
- {
+ } elseif (preg_match('/\\b([NS])[ ]([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″"]*[, ]+([EW])[ ]([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″"]*\\b/', $sQuery, $aData)) {
+ // 1 2 3 4 5 6 7 8
+ // degrees decimal seconds
+ // N 40 26 46 W 79 58 56
+ // N 40° 26′ 46″, W 79° 58′ 56″
$sFound = $aData[0];
$fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60 + $aData[4]/3600);
$fQueryLon = ($aData[5]=='E'?1:-1) * ($aData[6] + $aData[7]/60 + $aData[8]/3600);
- }
- // degrees decimal seconds
- // 40 26 46 N 79 58 56 W
- // 40° 26′ 46″ N, 79° 58′ 56″ W
- // 1 2 3 4 5 6 7 8
- elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″" ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″" ]+([EW])\\b/', $sQuery, $aData))
- {
+ } elseif (preg_match('/\\b([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″" ]+([NS])[, ]+([0-9]+)[° ]+([0-9]+)[′\' ]+([0-9]+)[″" ]+([EW])\\b/', $sQuery, $aData)) {
+ // 1 2 3 4 5 6 7 8
+ // degrees decimal seconds
+ // 40 26 46 N 79 58 56 W
+ // 40° 26′ 46″ N, 79° 58′ 56″ W
$sFound = $aData[0];
$fQueryLat = ($aData[4]=='N'?1:-1) * ($aData[1] + $aData[2]/60 + $aData[3]/3600);
$fQueryLon = ($aData[8]=='E'?1:-1) * ($aData[5] + $aData[6]/60 + $aData[7]/3600);
- }
- // degrees decimal
- // N 40.446° W 79.982°
- // 1 2 3 4
- elseif (preg_match('/\\b([NS])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*[, ]+([EW])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*\\b/', $sQuery, $aData))
- {
+ } elseif (preg_match('/\\b([NS])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*[, ]+([EW])[ ]([0-9]+[0-9]*\\.[0-9]+)[°]*\\b/', $sQuery, $aData)) {
+ // 1 2 3 4
+ // degrees decimal
+ // N 40.446° W 79.982°
$sFound = $aData[0];
$fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2]);
$fQueryLon = ($aData[3]=='E'?1:-1) * ($aData[4]);
- }
- // degrees decimal
- // 40.446° N 79.982° W
- // 1 2 3 4
- elseif (preg_match('/\\b([0-9]+[0-9]*\\.[0-9]+)[° ]+([NS])[, ]+([0-9]+[0-9]*\\.[0-9]+)[° ]+([EW])\\b/', $sQuery, $aData))
- {
+ } elseif (preg_match('/\\b([0-9]+[0-9]*\\.[0-9]+)[° ]+([NS])[, ]+([0-9]+[0-9]*\\.[0-9]+)[° ]+([EW])\\b/', $sQuery, $aData)) {
+ // 1 2 3 4
+ // degrees decimal
+ // 40.446° N 79.982° W
$sFound = $aData[0];
$fQueryLat = ($aData[2]=='N'?1:-1) * ($aData[1]);
$fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[3]);
- }
- // degrees decimal
- // 12.34, 56.78
- // [12.456,-78.90]
- // 1 2 3 4
- elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData))
- {
+ } elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData)) {
+ // 1 2 3 4
+ // degrees decimal
+ // 12.34, 56.78
+ // [12.456,-78.90]
$sFound = $aData[0];
$fQueryLat = $aData[2];
$fQueryLon = $aData[3];
function geometryText2Points($geometry_as_text, $fRadius)
{
$aPolyPoints = NULL;
- if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
- {
+ if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch)) {
+ //
preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
- }
- elseif (preg_match('#LINESTRING\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
- {
+ //
+ } elseif (preg_match('#LINESTRING\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch)) {
+ //
preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
- }
- elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
- {
+ //
+ } elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch)) {
+ //
preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
- }
- elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#', $geometry_as_text, $aMatch))
- {
+ //
+ } elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#', $geometry_as_text, $aMatch)) {
+ //
$aPolyPoints = createPointsAroundCenter($aMatch[1], $aMatch[2], $fRadius);
+ //
}
- if (isset($aPolyPoints))
- {
+ if (isset($aPolyPoints)) {
$aResultPoints = array();
- foreach($aPolyPoints as $aPoint)
- {
+ foreach ($aPolyPoints as $aPoint) {
$aResultPoints[] = array($aPoint[1], $aPoint[2]);
}
return $aResultPoints;
function createPointsAroundCenter($fLon, $fLat, $fRadius)
{
- $iSteps = max(8, min(100, ($fRadius * 40000)^2));
- $fStepSize = (2*pi())/$iSteps;
- $aPolyPoints = array();
- for($f = 0; $f < 2*pi(); $f += $fStepSize)
- {
- $aPolyPoints[] = array('', $fLon+($fRadius*sin($f)), $fLat+($fRadius*cos($f)) );
- }
- return $aPolyPoints;
+ $iSteps = max(8, min(100, ($fRadius * 40000)^2));
+ $fStepSize = (2*pi())/$iSteps;
+ $aPolyPoints = array();
+ for ($f = 0; $f < 2*pi(); $f += $fStepSize) {
+ $aPolyPoints[] = array('', $fLon+($fRadius*sin($f)), $fLat+($fRadius*cos($f)) );
+ }
+ return $aPolyPoints;
}
$sOutputFormat = '';
if (isset($_GET['format'])) $sOutputFormat = $_GET['format'];
- if ($sType == 'reverse')
- {
+ if ($sType == 'reverse') {
$sOutQuery = (isset($_GET['lat'])?$_GET['lat']:'').'/';
if (isset($_GET['lon'])) $sOutQuery .= $_GET['lon'];
if (isset($_GET['zoom'])) $sOutQuery .= '/'.$_GET['zoom'];
- }
- else
+ } else {
$sOutQuery = $sQuery;
+ }
$hLog = array(
date('Y-m-d H:i:s',$aStartTime[0]).'.'.$aStartTime[1],
$fStartTime
);
- if (CONST_Log_DB)
- {
+ if (CONST_Log_DB) {
if (isset($_GET['email']))
$sUserAgent = $_GET['email'];
elseif (isset($_SERVER['HTTP_REFERER']))
$sUserAgent = $_SERVER['HTTP_REFERER'];
elseif (isset($_SERVER['HTTP_USER_AGENT']))
$sUserAgent = $_SERVER['HTTP_USER_AGENT'];
- else
- $sUserAgent = '';
+ else $sUserAgent = '';
$sSQL = 'insert into new_query_log (type,starttime,query,ipaddress,useragent,language,format,searchterm)';
$sSQL .= ' values ('.getDBQuoted($sType).','.getDBQuoted($hLog[0]).','.getDBQuoted($hLog[2]);
$sSQL .= ','.getDBQuoted($hLog[1]).','.getDBQuoted($sUserAgent).','.getDBQuoted(join(',',$aLanguageList)).','.getDBQuoted($sOutputFormat).','.getDBQuoted($hLog[3]).')';
{
$fEndTime = microtime(true);
- if (CONST_Log_DB)
- {
+ if (CONST_Log_DB) {
$aEndTime = explode('.', $fEndTime);
if (!$aEndTime[1]) $aEndTime[1] = '0';
$sEndTime = date('Y-m-d H:i:s',$aEndTime[0]).'.'.$aEndTime[1];
$oDB->query($sSQL);
}
- if (CONST_Log_File)
- {
+ if (CONST_Log_File) {
$aOutdata = sprintf("[%s] %.4f %d %s \"%s\"\n",
$hLog[0], $fEndTime-$hLog[5], $iNumResults,
$hLog[4], $hLog[2]);
function osmLink($aFeature, $sRefText=false)
{
$sOSMType = formatOSMType($aFeature['osm_type'], false);
- if ($sOSMType)
- {
+ if ($sOSMType) {
return '<a href="//www.openstreetmap.org/'.$sOSMType.'/'.$aFeature['osm_id'].'">'.$sOSMType.' '.($sRefText?$sRefText:$aFeature['osm_id']).'</a>';
}
return '';
function wikipediaLink($aFeature)
{
- if ($aFeature['wikipedia'])
- {
+ if ($aFeature['wikipedia']) {
list($sLanguage, $sArticle) = explode(':',$aFeature['wikipedia']);
return '<a href="https://'.$sLanguage.'.wikipedia.org/wiki/'.urlencode($sArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>';
}
--- /dev/null
+<?xml version="1.0"?>
+<ruleset name="Nominatim Standard">
+
+ <description>Nominatim coding standard</description>
+
+ <!-- based on another standard, you can find it here -->
+ <!-- /usr/share/php/PHP/CodeSniffer/Standards/PSR2/ruleset.xml -->
+ <!-- https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/PSR2/ruleset.xml -->
+ <rule ref="PSR2"/>
+
+
+
+
+ <!-- currently 300 warnings, we set a limit later -->
+ <rule ref="Generic.Files.LineLength">
+ <properties>
+ <property name="lineLimit" value="9999"/>
+ <property name="absoluteLineLimit" value="0"/>
+ </properties>
+ </rule>
+
+
+
+ <!-- **************************************************************
+ DOCUMENTATION
+ ************************************************************** -->
+
+ <rule ref="PEAR.Commenting.FileComment.Missing">
+ <severity>0</severity>
+ </rule>
+ <rule ref="PEAR.Commenting.ClassComment.Missing">
+ <severity>0</severity>
+ </rule>
+ <rule ref="PEAR.Commenting.FunctionComment.Missing">
+ <severity>0</severity>
+ </rule>
+
+
+
+
+ <!-- **************************************************************
+ COMMENTS
+ ************************************************************** -->
+
+ <!-- We allow comments after statements -->
+ <rule ref="Squiz.Commenting.PostStatementComment.Found">
+ <severity>0</severity>
+ </rule>
+ <!-- ... even without space e.g. //some words -->
+ <rule ref="Squiz.Commenting.InlineComment.NoSpaceBefore">
+ <severity>0</severity>
+ </rule>
+
+ <!-- Comments don't have to start uppercase -->
+ <rule ref="Squiz.Commenting.InlineComment.NotCapital">
+ <severity>0</severity>
+ </rule>
+ <!-- Comments don't have to end with one of .!? -->
+ <rule ref="Squiz.Commenting.InlineComment.InvalidEndChar">
+ <severity>0</severity>
+ </rule>
+
+ <!-- we don't need '} // functionname()' at end of large blocks -->
+ <rule ref="Squiz.Commenting.ClosingDeclarationComment.Missing">
+ <severity>0</severity>
+ </rule>
+ <!-- .. same for conditions -->
+ <rule ref="Squiz.Commenting.LongConditionClosingComment.Missing">
+ <severity>0</severity>
+ </rule>
+
+
+
+
+
+ <!-- **************************************************************
+ INDENTATION, SPACING
+ ************************************************************** -->
+
+ <!-- We use tabs -->
+ <rule ref="Generic.WhiteSpace.DisallowTabIndent.TabsUsed">
+ <severity>0</severity>
+ </rule>
+
+ <!-- We don't need 2 blank lines after function -->
+ <rule ref="Squiz.WhiteSpace.FunctionSpacing.After">
+ <severity>0</severity>
+ </rule>
+
+ <!-- Aligned looks nicer, but causes too many warnings currently -->
+ <rule ref="Generic.Formatting.MultipleStatementAlignment.NotSame">
+ <severity>0</severity>
+ </rule>
+
+ <!-- Aligned looks nicer, but causes too many warnings currently -->
+ <rule ref="Squiz.Arrays.ArrayDeclaration.DoubleArrowNotAligned">
+ <severity>0</severity>
+ </rule>
+
+
+
+
+
+
+
+ <!-- **************************************************************
+ VARIABLES
+ ************************************************************** -->
+
+ <!-- CONST_this_var is fine, we don't need ConstThisVar -->
+ <rule ref="Generic.NamingConventions.UpperCaseConstantName.ConstantNotUpperCase">
+ <severity>0</severity>
+ </rule>
+
+ <!-- simply disagree with "Each line in an array declaration must end in a comma" -->
+ <rule ref="Squiz.Arrays.ArrayDeclaration.NoCommaAfterLast">
+ <severity>0</severity>
+ </rule>
+ <rule ref="Squiz.Arrays.ArrayDeclaration.NoComma">
+ <severity>0</severity>
+ </rule>
+
+ <!-- We allow "$abc = array($aPoint[1], $aPoint[2])" -->
+ <rule ref="Squiz.Arrays.ArrayDeclaration.SingleLineNotAllowed">
+ <severity>0</severity>
+ </rule>
+
+
+
+
+ <!-- **************************************************************
+ CONTROL STRUCTURES
+ ************************************************************** -->
+
+ <!-- we allow "if (a) echo 'b'" without brackets -->
+ <rule ref="Generic.ControlStructures.InlineControlStructure.NotAllowed">
+ <severity>0</severity>
+ </rule>
+ <rule ref="Generic.ControlStructures.InlineControlStructure.Discouraged">
+ <severity>0</severity>
+ </rule>
+ <rule ref="Squiz.PHP.DisallowInlineIf.Found">
+ <severity>0</severity>
+ </rule>
+
+ <!-- We allow "if (a)". No need for "if (a === TRUE)" -->
+ <rule ref="Squiz.Operators.ComparisonOperatorUsage.ImplicitTrue">
+ <severity>0</severity>
+ </rule>
+ <!-- ... same for "if (!a)" -->
+ <rule ref="Squiz.Operators.ComparisonOperatorUsage.NotAllowed">
+ <severity>0</severity>
+ </rule>
+
+ <!-- We allow
+ if (a)
+ {
+ -->
+ <rule ref="PEAR.ControlStructures.MultiLineCondition.NewlineBeforeOpenBrace">
+ <severity>0</severity>
+ </rule>
+ <!-- ... same -->
+ <rule ref="Squiz.WhiteSpace.ControlStructureSpacing.NoLineAfterClose">
+ <severity>0</severity>
+ </rule>
+ <!-- ... same for foreach/while etc -->
+ <rule ref="PEAR.ControlStructures.ControlSignature">
+ <severity>0</severity>
+ </rule>
+ <!-- ... same -->
+ <rule ref="Squiz.WhiteSpace.FunctionClosingBraceSpace.SpacingBeforeClose">
+ <severity>0</severity>
+ </rule>
+
+
+</ruleset>
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
$m = getBucketMemcache();
- if (!$m)
-{
+if (!$m) {
echo "ERROR: Bucket memcache is not configured\n";
exit;
}
-if ($aResult['list'])
-{
+if ($aResult['list']) {
$iCurrentSleeping = $m->get('sleepCounter');
echo "\n Sleeping blocks count: $iCurrentSleeping\n";
echo "\n";
printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", "Key", "Total Blocks", "Current", "Still Blocked", "Last Block Time", "Sleeping");
printf(" %'--40s-|-%'-12s-|-%'-7s-|-%'-13s-|-%'-31s-|-%'-8s\n", "", "", "", "", "", "");
- foreach($aBlocks as $sKey => $aDetails)
- {
+ foreach ($aBlocks as $sKey => $aDetails) {
printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", $sKey, $aDetails['totalBlocks'],
(int)$aDetails['currentBucketSize'], $aDetails['currentlyBlocked']?'Y':'N',
date("r", $aDetails['lastBlockTimestamp']), $aDetails['isSleeping']?'Y':'N');
echo "\n";
}
-if ($aResult['delete'])
-{
+if ($aResult['delete']) {
$m->set('sleepCounter', 0);
clearBucketBlocks();
}
-if ($aResult['flush'])
-{
+if ($aResult['flush']) {
$m->flush();
}
include(CONST_InstallPath.'/settings/phrase_settings.php');
-if (true)
-{
+if (true) {
$sURL = 'http://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Country_Codes';
$sWikiPageXML = file_get_contents($sURL);
- if (preg_match_all('#\\| ([a-z]{2}) \\|\\| [^|]+\\|\\| ([a-z,]+)#', $sWikiPageXML, $aMatches, PREG_SET_ORDER))
- {
- foreach($aMatches as $aMatch)
- {
+ if (preg_match_all('#\\| ([a-z]{2}) \\|\\| [^|]+\\|\\| ([a-z,]+)#', $sWikiPageXML, $aMatches, PREG_SET_ORDER)) {
+ foreach ($aMatches as $aMatch) {
$aLanguages = explode(',', $aMatch[2]);
- foreach($aLanguages as $i => $s)
- {
+ foreach ($aLanguages as $i => $s) {
$aLanguages[$i] = '"'.pg_escape_string($s).'"';
}
echo "UPDATE country_name set country_default_language_codes = '{".join(',',$aLanguages)."}' where country_code = '".pg_escape_string($aMatch[1])."';\n";
}
*/
-if ($aCMDResult['create-tables'])
-{
+if ($aCMDResult['create-tables']) {
$sSQL = <<<'EOD'
CREATE TABLE wikipedia_article (
language text NOT NULL,
$aTemplateStack = array();
$aState = array('body');
- foreach($aPageText as $i => $sPart)
- {
- switch($sPart)
- {
+ foreach ($aPageText as $i => $sPart) {
+ switch ($sPart) {
case '{{':
array_unshift($aTemplateStack, array('', array()));
array_unshift($aState, 'template');
break;
case '}}':
- if ($aState[0] == 'template' || $aState[0] == 'templateparam')
- {
+ if ($aState[0] == 'template' || $aState[0] == 'templateparam') {
$aTemplate = array_shift($aTemplateStack);
array_shift($aState);
$aTemplates[] = $aTemplate;
-
}
break;
case '[[':
array_unshift($aState, 'link');
break;
case ']]':
- if ($aState[0] == 'link' || $aState[0] == 'linksynonim')
- {
+ if ($aState[0] == 'link' || $aState[0] == 'linksynonim') {
if (!$sLinkSyn) $sLinkSyn = $sLinkPage;
if (substr($sLinkPage, 0, 6) == 'Image:') $sLinkSyn = substr($sLinkPage, 6);
$aLinks[] = array($sLinkPage, $sLinkSyn);
array_shift($aState);
- switch($aState[0])
- {
+ switch ($aState[0]) {
case 'template':
$aTemplateStack[0][0] .= trim($sPart);
break;
}
break;
case '|':
- if ($aState[0] == 'template' || $aState[0] == 'templateparam')
- {
+ if ($aState[0] == 'template' || $aState[0] == 'templateparam') {
// Create a new template paramater
$aState[0] = 'templateparam';
array_unshift($aTemplateStack[0][1], '');
if ($aState[0] == 'link') $aState[0] = 'linksynonim';
break;
default:
- switch($aState[0])
- {
+ switch ($aState[0]) {
case 'template':
$aTemplateStack[0][0] .= trim($sPart);
break;
function _templatesToProperties($aTemplates)
{
$aPageProperties = array();
- foreach($aTemplates as $iTemplate => $aTemplate)
- {
+ foreach ($aTemplates as $iTemplate => $aTemplate) {
$aParams = array();
- foreach(array_reverse($aTemplate[1]) as $iParam => $sParam)
- {
- if (($iPos = strpos($sParam, '=')) === FALSE)
- {
+ foreach (array_reverse($aTemplate[1]) as $iParam => $sParam) {
+ if (($iPos = strpos($sParam, '=')) === FALSE) {
$aParams[] = trim($sParam);
- }
- else
- {
+ } else {
$aParams[trim(substr($sParam, 0, $iPos))] = trim(substr($sParam, $iPos+1));
}
}
$aTemplates[$iTemplate][1] = $aParams;
if (!isset($aPageProperties['sOfficialName']) && isset($aParams['official_name']) && $aParams['official_name']) $aPageProperties['sOfficialName'] = $aParams['official_name'];
- if (!isset($aPageProperties['iPopulation']) && isset($aParams['population']) && $aParams['population'] && preg_match('#^[0-9.,]+#', $aParams['population']))
- {
+ if (!isset($aPageProperties['iPopulation']) && isset($aParams['population']) && $aParams['population'] && preg_match('#^[0-9.,]+#', $aParams['population'])) {
$aPageProperties['iPopulation'] = (int)str_replace(array(',','.'), '', $aParams['population']);
}
- if (!isset($aPageProperties['iPopulation']) && isset($aParams['population_total']) && $aParams['population_total'] && preg_match('#^[0-9.,]+#', $aParams['population_total']))
- {
+ if (!isset($aPageProperties['iPopulation']) && isset($aParams['population_total']) && $aParams['population_total'] && preg_match('#^[0-9.,]+#', $aParams['population_total'])) {
$aPageProperties['iPopulation'] = (int)str_replace(array(',','.'), '', $aParams['population_total']);
}
- if (!isset($aPageProperties['iPopulation']) && isset($aParams['population_urban']) && $aParams['population_urban'] && preg_match('#^[0-9.,]+#', $aParams['population_urban']))
- {
+ if (!isset($aPageProperties['iPopulation']) && isset($aParams['population_urban']) && $aParams['population_urban'] && preg_match('#^[0-9.,]+#', $aParams['population_urban'])) {
$aPageProperties['iPopulation'] = (int)str_replace(array(',','.'), '', $aParams['population_urban']);
}
- if (!isset($aPageProperties['iPopulation']) && isset($aParams['population_estimate']) && $aParams['population_estimate'] && preg_match('#^[0-9.,]+#', $aParams['population_estimate']))
- {
+ if (!isset($aPageProperties['iPopulation']) && isset($aParams['population_estimate']) && $aParams['population_estimate'] && preg_match('#^[0-9.,]+#', $aParams['population_estimate'])) {
$aPageProperties['iPopulation'] = (int)str_replace(array(',','.'), '', $aParams['population_estimate']);
}
- if (!isset($aPageProperties['sWebsite']) && isset($aParams['website']) && $aParams['website'])
- {
- if (preg_match('#^\\[?([^ \\]]+)[^\\]]*\\]?$#', $aParams['website'], $aMatch))
- {
+ if (!isset($aPageProperties['sWebsite']) && isset($aParams['website']) && $aParams['website']) {
+ if (preg_match('#^\\[?([^ \\]]+)[^\\]]*\\]?$#', $aParams['website'], $aMatch)) {
$aPageProperties['sWebsite'] = $aMatch[1];
- if (strpos($aPageProperties['sWebsite'],':/'.'/') === FALSE)
- {
+ if (strpos($aPageProperties['sWebsite'],':/'.'/') === FALSE) {
$aPageProperties['sWebsite'] = 'http:/'.'/'.$aPageProperties['sWebsite'];
}
}
}
- if (!isset($aPageProperties['sTopLevelDomain']) && isset($aParams['cctld']) && $aParams['cctld'])
- {
+ if (!isset($aPageProperties['sTopLevelDomain']) && isset($aParams['cctld']) && $aParams['cctld']) {
$aPageProperties['sTopLevelDomain'] = str_replace(array('[',']','.'),'', $aParams['cctld']);
}
- if (!isset($aPageProperties['sInfoboxType']) && strtolower(substr($aTemplate[0],0,7)) == 'infobox')
- {
+ if (!isset($aPageProperties['sInfoboxType']) && strtolower(substr($aTemplate[0],0,7)) == 'infobox') {
$aPageProperties['sInfoboxType'] = trim(substr($aTemplate[0],8));
// $aPageProperties['aInfoboxParams'] = $aParams;
}
// Assume the first template with lots of params is the type (fallback for infobox)
- if (!isset($aPageProperties['sPossibleInfoboxType']) && sizeof($aParams) > 10)
- {
+ if (!isset($aPageProperties['sPossibleInfoboxType']) && sizeof($aParams) > 10) {
$aPageProperties['sPossibleInfoboxType'] = trim($aTemplate[0]);
// $aPageProperties['aInfoboxParams'] = $aParams;
}
// do we have a lat/lon
- if (!isset($aPageProperties['fLat']))
- {
- if (isset($aParams['latd']) && isset($aParams['longd']))
- {
+ if (!isset($aPageProperties['fLat'])) {
+ if (isset($aParams['latd']) && isset($aParams['longd'])) {
$aPageProperties['fLat'] = degreesAndMinutesToDecimal($aParams['latd'], @$aParams['latm'], @$aParams['lats'], @$aParams['latNS']);
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aParams['longd'], @$aParams['longm'], @$aParams['longs'], @$aParams['longEW']);
}
- if (isset($aParams['lat_degrees']) && isset($aParams['lat_degrees']))
- {
+ if (isset($aParams['lat_degrees']) && isset($aParams['lat_degrees'])) {
$aPageProperties['fLat'] = degreesAndMinutesToDecimal($aParams['lat_degrees'], @$aParams['lat_minutes'], @$aParams['lat_seconds'], @$aParams['lat_direction']);
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aParams['long_degrees'], @$aParams['long_minutes'], @$aParams['long_seconds'], @$aParams['long_direction']);
}
- if (isset($aParams['latitude']) && isset($aParams['longitude']))
- {
- if (preg_match('#[0-9.]+#', $aParams['latitude']) && preg_match('#[0-9.]+#', $aParams['longitude']))
- {
+ if (isset($aParams['latitude']) && isset($aParams['longitude'])) {
+ if (preg_match('#[0-9.]+#', $aParams['latitude']) && preg_match('#[0-9.]+#', $aParams['longitude'])) {
$aPageProperties['fLat'] = (float)$aParams['latitude'];
$aPageProperties['fLon'] = (float)$aParams['longitude'];
}
}
- if (strtolower($aTemplate[0]) == 'coord')
- {
- if (isset($aParams[3]) && (strtoupper($aParams[3]) == 'N' || strtoupper($aParams[3]) == 'S'))
- {
+ if (strtolower($aTemplate[0]) == 'coord') {
+ if (isset($aParams[3]) && (strtoupper($aParams[3]) == 'N' || strtoupper($aParams[3]) == 'S')) {
$aPageProperties['fLat'] = degreesAndMinutesToDecimal($aParams[0], $aParams[1], $aParams[2], $aParams[3]);
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aParams[4], $aParams[5], $aParams[6], $aParams[7]);
- }
- elseif (isset($aParams[0]) && isset($aParams[1]) && isset($aParams[2]) && (strtoupper($aParams[2]) == 'N' || strtoupper($aParams[2]) == 'S'))
- {
+ } elseif (isset($aParams[0]) && isset($aParams[1]) && isset($aParams[2]) && (strtoupper($aParams[2]) == 'N' || strtoupper($aParams[2]) == 'S')) {
$aPageProperties['fLat'] = degreesAndMinutesToDecimal($aParams[0], $aParams[1], 0, $aParams[2]);
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aParams[3], $aParams[4], 0, $aParams[5]);
- }
- else if (isset($aParams[0]) && isset($aParams[1]) && (strtoupper($aParams[1]) == 'N' || strtoupper($aParams[1]) == 'S'))
- {
+ } else if (isset($aParams[0]) && isset($aParams[1]) && (strtoupper($aParams[1]) == 'N' || strtoupper($aParams[1]) == 'S')) {
$aPageProperties['fLat'] = (strtoupper($aParams[1]) == 'N'?1:-1) * (float)$aParams[0];
$aPageProperties['fLon'] = (strtoupper($aParams[3]) == 'E'?1:-1) * (float)$aParams[2];
- }
- else if (isset($aParams[0]) && is_numeric($aParams[0]) && isset($aParams[1]) && is_numeric($aParams[1]))
- {
+ } else if (isset($aParams[0]) && is_numeric($aParams[0]) && isset($aParams[1]) && is_numeric($aParams[1])) {
$aPageProperties['fLat'] = (float)$aParams[0];
$aPageProperties['fLon'] = (float)$aParams[1];
}
}
- if (isset($aParams['Latitude']) && isset($aParams['Longitude']))
- {
+ if (isset($aParams['Latitude']) && isset($aParams['Longitude'])) {
$aParams['Latitude'] = str_replace(' ',' ',$aParams['Latitude']);
$aParams['Longitude'] = str_replace(' ',' ',$aParams['Longitude']);
- if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([NS]) to ([0-9]+)°( ([0-9]+)′)? ([NS])#', $aParams['Latitude'], $aMatch))
- {
+ if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([NS]) to ([0-9]+)°( ([0-9]+)′)? ([NS])#', $aParams['Latitude'], $aMatch)) {
$aPageProperties['fLat'] =
(degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4])
+degreesAndMinutesToDecimal($aMatch[5], $aMatch[7], 0, $aMatch[8])) / 2;
- }
- else if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([NS])#', $aParams['Latitude'], $aMatch))
- {
+ } else if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([NS])#', $aParams['Latitude'], $aMatch)) {
$aPageProperties['fLat'] = degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]);
}
- if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([EW]) to ([0-9]+)°( ([0-9]+)′)? ([EW])#', $aParams['Longitude'], $aMatch))
- {
+ if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([EW]) to ([0-9]+)°( ([0-9]+)′)? ([EW])#', $aParams['Longitude'], $aMatch)) {
$aPageProperties['fLon'] =
(degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4])
+degreesAndMinutesToDecimal($aMatch[5], $aMatch[7], 0, $aMatch[8])) / 2;
- }
- else if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([EW])#', $aParams['Longitude'], $aMatch))
- {
+ } else if (preg_match('#^([0-9]+)°( ([0-9]+)′)? ([EW])#', $aParams['Longitude'], $aMatch)) {
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]);
}
}
}
}
- if (isset($aPageProperties['sPossibleInfoboxType']))
- {
+ if (isset($aPageProperties['sPossibleInfoboxType'])) {
if (!isset($aPageProperties['sInfoboxType'])) $aPageProperties['sInfoboxType'] = '#'.$aPageProperties['sPossibleInfoboxType'];
unset($aPageProperties['sPossibleInfoboxType']);
}
return $aPageProperties;
}
-if (isset($aCMDResult['parse-wikipedia']))
-{
+if (isset($aCMDResult['parse-wikipedia'])) {
$oDB =& getDB();
$aArticleNames = $oDB->getCol('select page_title from content where page_namespace = 0 and page_id %10 = '.$aCMDResult['parse-wikipedia'].' and (page_content ilike \'%{{Coord%\' or (page_content ilike \'%lat%\' and page_content ilike \'%lon%\'))');
// $aArticleNames = $oDB->getCol($sSQL = 'select page_title from content where page_namespace = 0 and (page_content ilike \'%{{Coord%\' or (page_content ilike \'%lat%\' and page_content ilike \'%lon%\')) and page_title in (\'Virginia\')');
- foreach($aArticleNames as $sArticleName)
- {
+ foreach ($aArticleNames as $sArticleName) {
$sPageText = $oDB->getOne('select page_content from content where page_namespace = 0 and page_title = \''.pg_escape_string($sArticleName).'\'');
$aP = _templatesToProperties(_parseWikipediaContent($sPageText));
- if (isset($aP['sInfoboxType']))
- {
+ if (isset($aP['sInfoboxType'])) {
$aP['sInfoboxType'] = preg_replace('#\\s+#',' ',$aP['sInfoboxType']);
$sSQL = 'update wikipedia_article set ';
$sSQL .= 'infobox_type = \''.pg_escape_string($aP['sInfoboxType']).'\'';
$sSQL .= ' where language = \'en\' and title = \''.pg_escape_string($sArticleName).'\';';
$oDB->query($sSQL);
}
- if (isset($aP['iPopulation']))
- {
+ if (isset($aP['iPopulation'])) {
$sSQL = 'update wikipedia_article set ';
$sSQL .= 'population = \''.pg_escape_string($aP['iPopulation']).'\'';
$sSQL .= ' where language = \'en\' and title = \''.pg_escape_string($sArticleName).'\';';
$oDB->query($sSQL);
}
- if (isset($aP['sWebsite']))
- {
+ if (isset($aP['sWebsite'])) {
$sSQL = 'update wikipedia_article set ';
$sSQL .= 'website = \''.pg_escape_string($aP['sWebsite']).'\'';
$sSQL .= ' where language = \'en\' and title = \''.pg_escape_string($sArticleName).'\';';
$oDB->query($sSQL);
}
- if (isset($aP['fLat']) && ($aP['fLat']!='-0' || $aP['fLon']!='-0'))
- {
+ if (isset($aP['fLat']) && ($aP['fLat']!='-0' || $aP['fLon']!='-0')) {
if (!isset($aP['sInfoboxType'])) $aP['sInfoboxType'] = '';
echo $sArticleName.'|'.$aP['sInfoboxType'].'|'.$aP['fLat'].'|'.$aP['fLon'] ."\n";
$sSQL = 'update wikipedia_article set ';
function nominatimXMLStart($hParser, $sName, $aAttr)
{
global $aNominatRecords;
- switch($sName)
- {
+ switch ($sName) {
case 'PLACE':
$aNominatRecords[] = $aAttr;
break;
}
-if (isset($aCMDResult['link']))
-{
+if (isset($aCMDResult['link'])) {
$oDB =& getDB();
$aWikiArticles = $oDB->getAll("select * from wikipedia_article where language = 'en' and lat is not null and osm_type is null and totalcount < 31 order by importance desc limit 200000");
// If you point this script at production OSM you will be blocked
$sNominatimBaseURL = 'http://SEVERNAME/search.php';
- foreach($aWikiArticles as $aRecord)
- {
+ foreach ($aWikiArticles as $aRecord) {
$aRecord['name'] = str_replace('_',' ',$aRecord['title']);
$sURL = $sNominatimBaseURL.'?format=xml&accept-language=en';
echo "\n-- ".$aRecord['name'].", ".$aRecord['infobox_type']."\n";
$fMaxDist = 0.0000001;
$bUnknown = false;
- switch(strtolower($aRecord['infobox_type']))
- {
+ switch (strtolower($aRecord['infobox_type'])) {
case 'former country':
continue 2;
case 'sea':
xml_parse($hXMLParser, $sXML, true);
xml_parser_free($hXMLParser);
- if (!isset($aNominatRecords[0]))
- {
+ if (!isset($aNominatRecords[0])) {
$aNameParts = preg_split('#[(,]#',$aRecord['name']);
- if (sizeof($aNameParts) > 1)
- {
+ if (sizeof($aNameParts) > 1) {
$sNameURL = $sURL.'&q='.urlencode(trim($aNameParts[0]));
var_Dump($sNameURL);
$sXML = file_get_contents($sNameURL);
}
// assume first is best/right
- for($i = 0; $i < sizeof($aNominatRecords); $i++)
- {
+ for ($i = 0; $i < sizeof($aNominatRecords); $i++) {
$fDiff = ($aRecord['lat']-$aNominatRecords[$i]['LAT']) * ($aRecord['lat']-$aNominatRecords[$i]['LAT']);
$fDiff += ($aRecord['lon']-$aNominatRecords[$i]['LON']) * ($aRecord['lon']-$aNominatRecords[$i]['LON']);
$fDiff = sqrt($fDiff);
else $fMaxDist = 0.001;
}
echo "-- FOUND \"".substr($aNominatRecords[$i]['DISPLAY_NAME'],0,50)."\", ".$aNominatRecords[$i]['CLASS'].", ".$aNominatRecords[$i]['TYPE'].", ".$aNominatRecords[$i]['PLACE_RANK'].", ".$aNominatRecords[$i]['OSM_TYPE']." (dist:$fDiff, max:$fMaxDist)\n";
- if ($fDiff > $fMaxDist)
- {
+ if ($fDiff > $fMaxDist) {
echo "-- Diff too big $fDiff (max: $fMaxDist)".$aRecord['lat'].','.$aNominatRecords[$i]['LAT'].' & '.$aRecord['lon'].','.$aNominatRecords[$i]['LON']." \n";
- }
- else
- {
+ } else {
$sSQL = "update wikipedia_article set osm_type=";
- switch($aNominatRecords[$i]['OSM_TYPE'])
- {
+ switch ($aNominatRecords[$i]['OSM_TYPE']) {
case 'relation': $sSQL .= "'R'"; break;
case 'way': $sSQL .= "'W'"; break;
case 'node': $sSQL .= "'N'"; break;
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
-if (isset($aCMDResult['parse-tiger']))
-{
+if (isset($aCMDResult['parse-tiger'])) {
if (!file_exists(CONST_Tiger_Data_Path)) mkdir(CONST_Tiger_Data_Path);
$sTempDir = tempnam('/tmp', 'tiger');
unlink($sTempDir);
mkdir($sTempDir);
- foreach(glob($aCMDResult['parse-tiger'].'/tl_20??_?????_edges.zip', 0) as $sImportFile)
- {
+ foreach (glob($aCMDResult['parse-tiger'].'/tl_20??_?????_edges.zip', 0) as $sImportFile) {
set_time_limit(30);
preg_match('#([0-9]{5})_(.*)#',basename($sImportFile), $aMatch);
$sCountyID = $aMatch[1];
$sUnzipCmd = "unzip -d $sTempDir $sImportFile";
exec($sUnzipCmd);
$sShapeFile = $sTempDir.'/'.basename($sImportFile, '.zip').'.shp';
- if (!file_exists($sShapeFile))
- {
+ if (!file_exists($sShapeFile)) {
echo "Failed unzip ($sImportFile)\n";
- }
- else
- {
+ } else {
$sParseCmd = CONST_BasePath.'/utils/tigerAddressImport.py '.$sShapeFile;
exec($sParseCmd);
$sOsmFile = $sTempDir.'/'.basename($sImportFile, '.zip').'.osm1.osm';
- if (!file_exists($sOsmFile))
- {
+ if (!file_exists($sOsmFile)) {
echo "Failed parse ($sImportFile)\n";
- }
- else
- {
+ } else {
copy($sOsmFile, CONST_Tiger_Data_Path.'/'.$sCountyID.'.sql');
}
}
// Cleanup
- foreach(glob($sTempDir.'/*') as $sTmpFile)
- {
+ foreach (glob($sTempDir.'/*') as $sTmpFile) {
unlink($sTmpFile);
}
-
}
}
$oDB =& getDB();
$oParams = new ParameterParser($aCMDResult);
-if ($oParams->getBool('search'))
-{
+if ($oParams->getBool('search')) {
if (isset($aCMDResult['nodedupe'])) $aCMDResult['dedupe'] = 'false';
$oGeocode = new Geocode($oDB);
$aSearchResults = $oGeocode->lookup();
- if (version_compare(phpversion(), "5.4.0", '<'))
+ if (version_compare(phpversion(), "5.4.0", '<')) {
echo json_encode($aSearchResults);
- else
+ } else {
echo json_encode($aSearchResults, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n";
-}
-else
-{
+ }
+} else {
showUsage($aCMDOptions, true);
}
$aToDo = array(251, 293, 328, 399.1, 455.1, 479, 496, 499, 574, 609, 702, 790, 846, 865, 878, 894, 902, 961, 980);
$hFile = @fopen($sFile, "r");
-if (!$hFile)
-{
+if (!$hFile) {
echo "Unable to open file: $sFile\n";
exit;
}
$i = 0;
-while (($sLine = fgets($hFile, 10000)) !== false)
-{
+while (($sLine = fgets($hFile, 10000)) !== false) {
$i++;
if (!in_array($i, $aToDo)) continue;
- if (preg_match('#"GET (.*) HTTP/1.[01]"#', $sLine, $aResult))
- {
+ if (preg_match('#"GET (.*) HTTP/1.[01]"#', $sLine, $aResult)) {
$sURL1 = $sHost1.$aResult[1];
$sURL2 = $sHost2.$aResult[1];
$sRes1 = '';
$k = 0;
- while(!$sRes1 && $k < 10)
- {
+ while (!$sRes1 && $k < 10) {
$sRes1 = file_get_contents($sURL1);
$k++;
if (!$sRes1) sleep(10);
$sRes2 = str_replace($sHost2, '', $sRes2);
$sRes2 = str_replace($sHost2Escaped, '', $sRes2);
- if ($sRes1 != $sRes2)
- {
+ if ($sRes1 != $sRes2) {
echo "$i:\n";
var_dump($sURL1, $sURL2);
$sRes = $sURL1.":\n";
- for ($j = 0; $j < strlen($sRes1); $j+=40)
- {
+ for ($j = 0; $j < strlen($sRes1); $j+=40) {
$sRes .= substr($sRes1, $j, 40)."\n";
}
file_put_contents('log/'.$i.'.1', $sRes);
$sRes = $sURL2.":\n";
- for ($j = 0; $j < strlen($sRes2); $j+=40)
- {
+ for ($j = 0; $j < strlen($sRes2); $j+=40) {
$sRes .= substr($sRes2, $j, 40)."\n";
}
file_put_contents('log/'.$i.'.2', $sRes);
}
echo ".\n";
- }
- else
- {
+ } else {
var_dump($sLine);
}
}
$bDidSomething = false;
// Check if osm-file is set and points to a valid file if --all or --import-data is given
-if ($aCMDResult['import-data'] || $aCMDResult['all'])
-{
- if (!isset($aCMDResult['osm-file']))
- {
+if ($aCMDResult['import-data'] || $aCMDResult['all']) {
+ if (!isset($aCMDResult['osm-file'])) {
fail('missing --osm-file for data import');
}
- if (!file_exists($aCMDResult['osm-file']))
- {
+ if (!file_exists($aCMDResult['osm-file'])) {
fail('the path supplied to --osm-file does not exist');
}
- if (!is_readable($aCMDResult['osm-file']))
- {
+ if (!is_readable($aCMDResult['osm-file'])) {
fail('osm-file "'.$aCMDResult['osm-file'].'" not readable');
}
}
// This is a pretty hard core default - the number of processors in the box - 1
$iInstances = isset($aCMDResult['threads'])?$aCMDResult['threads']:(getProcessorCount()-1);
-if ($iInstances < 1)
-{
+if ($iInstances < 1) {
$iInstances = 1;
echo "WARNING: resetting threads to $iInstances\n";
}
-if ($iInstances > getProcessorCount())
-{
+if ($iInstances > getProcessorCount()) {
$iInstances = getProcessorCount();
echo "WARNING: resetting threads to $iInstances\n";
}
// Assume we can steal all the cache memory in the box (unless told otherwise)
-if (isset($aCMDResult['osm2pgsql-cache']))
-{
+if (isset($aCMDResult['osm2pgsql-cache'])) {
$iCacheMemory = $aCMDResult['osm2pgsql-cache'];
-}
-else
-{
+} else {
$iCacheMemory = getCacheMemoryMB();
}
$aDSNInfo = DB::parseDSN(CONST_Database_DSN);
if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
-if ($aCMDResult['create-db'] || $aCMDResult['all'])
-{
+if ($aCMDResult['create-db'] || $aCMDResult['all']) {
echo "Create DB\n";
$bDidSomething = true;
$oDB = DB::connect(CONST_Database_DSN, false);
- if (!PEAR::isError($oDB))
- {
+ if (!PEAR::isError($oDB)) {
fail('database already exists ('.CONST_Database_DSN.')');
}
passthruCheckReturn('createdb -E UTF-8 -p '.$aDSNInfo['port'].' '.$aDSNInfo['database']);
}
-if ($aCMDResult['setup-db'] || $aCMDResult['all'])
-{
+if ($aCMDResult['setup-db'] || $aCMDResult['all']) {
echo "Setup DB\n";
$bDidSomething = true;
// TODO: path detection, detection memory, etc.
$fPostgresVersion = getPostgresVersion($oDB);
echo 'Postgres version found: '.$fPostgresVersion."\n";
- if ($fPostgresVersion < 9.1)
- {
+ if ($fPostgresVersion < 9.1) {
fail("Minimum supported version of Postgresql is 9.1.");
}
// versions add a dummy function that returns nothing.
$iNumFunc = chksql($oDB->getOne("select count(*) from pg_proc where proname = 'hstore_to_json'"));
- if ($iNumFunc == 0)
- {
+ if ($iNumFunc == 0) {
pgsqlRunScript("create function hstore_to_json(dummy hstore) returns text AS 'select null::text' language sql immutable");
echo "WARNING: Postgresql is too old. extratags and namedetails API not available.";
}
$fPostgisVersion = getPostgisVersion($oDB);
echo 'Postgis version found: '.$fPostgisVersion."\n";
- if ($fPostgisVersion < 2.1)
- {
+ if ($fPostgisVersion < 2.1) {
// Function was renamed in 2.1 and throws an annoying deprecation warning
pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
}
pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql');
pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
- if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz'))
- {
+ if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz')) {
pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
- }
- else
- {
+ } else {
echo "WARNING: external UK postcode table not found.\n";
}
- if (CONST_Use_Extra_US_Postcodes)
- {
+ if (CONST_Use_Extra_US_Postcodes) {
pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
}
- if ($aCMDResult['no-partitions'])
- {
+ if ($aCMDResult['no-partitions']) {
pgsqlRunScript('update country_name set partition = 0');
}
pgsqlRunScript('create type wikipedia_article_match as ()');
}
-if ($aCMDResult['import-data'] || $aCMDResult['all'])
-{
+if ($aCMDResult['import-data'] || $aCMDResult['all']) {
echo "Import\n";
$bDidSomething = true;
$osm2pgsql = CONST_Osm2pgsql_Binary;
- if (!file_exists($osm2pgsql))
- {
+ if (!file_exists($osm2pgsql)) {
echo "Please download and build osm2pgsql.\nIf it is already installed, check the path in your local settings (settings/local.php) file.\n";
fail("osm2pgsql not found in '$osm2pgsql'");
}
- if (!is_null(CONST_Osm2pgsql_Flatnode_File))
- {
+ if (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
$osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
}
if (CONST_Tablespace_Osm2pgsql_Data)
passthruCheckReturn($osm2pgsql);
$oDB =& getDB();
- if (!chksql($oDB->getRow('select * from place limit 1')))
- {
+ if (!chksql($oDB->getRow('select * from place limit 1'))) {
fail('No Data');
}
}
-if ($aCMDResult['create-functions'] || $aCMDResult['all'])
-{
+if ($aCMDResult['create-functions'] || $aCMDResult['all']) {
echo "Functions\n";
$bDidSomething = true;
if (!file_exists(CONST_InstallPath.'/module/nominatim.so')) fail("nominatim module not built");
create_sql_functions($aCMDResult);
}
-if ($aCMDResult['create-tables'] || $aCMDResult['all'])
-{
+if ($aCMDResult['create-tables'] || $aCMDResult['all']) {
$bDidSomething = true;
echo "Tables\n";
create_sql_functions($aCMDResult);
}
-if ($aCMDResult['create-partition-tables'] || $aCMDResult['all'])
-{
+if ($aCMDResult['create-partition-tables'] || $aCMDResult['all']) {
echo "Partition Tables\n";
$bDidSomething = true;
}
-if ($aCMDResult['create-partition-functions'] || $aCMDResult['all'])
-{
+if ($aCMDResult['create-partition-functions'] || $aCMDResult['all']) {
echo "Partition Functions\n";
$bDidSomething = true;
pgsqlRunPartitionScript($sTemplate);
}
-if ($aCMDResult['import-wikipedia-articles'] || $aCMDResult['all'])
-{
+if ($aCMDResult['import-wikipedia-articles'] || $aCMDResult['all']) {
$bDidSomething = true;
$sWikiArticlesFile = CONST_BasePath.'/data/wikipedia_article.sql.bin';
$sWikiRedirectsFile = CONST_BasePath.'/data/wikipedia_redirect.sql.bin';
- if (file_exists($sWikiArticlesFile))
- {
+ if (file_exists($sWikiArticlesFile)) {
echo "Importing wikipedia articles...";
pgsqlRunDropAndRestore($sWikiArticlesFile);
echo "...done\n";
- }
- else
- {
+ } else {
echo "WARNING: wikipedia article dump file not found - places will have default importance\n";
}
- if (file_exists($sWikiRedirectsFile))
- {
+ if (file_exists($sWikiRedirectsFile)) {
echo "Importing wikipedia redirects...";
pgsqlRunDropAndRestore($sWikiRedirectsFile);
echo "...done\n";
- }
- else
- {
+ } else {
echo "WARNING: wikipedia redirect dump file not found - some place importance values may be missing\n";
}
}
-if ($aCMDResult['load-data'] || $aCMDResult['all'])
-{
+if ($aCMDResult['load-data'] || $aCMDResult['all']) {
echo "Drop old Data\n";
$bDidSomething = true;
$sSQL = 'select distinct partition from country_name';
$aPartitions = chksql($oDB->getCol($sSQL));
if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
- foreach($aPartitions as $sPartition)
- {
+ foreach ($aPartitions as $sPartition) {
if (!pg_query($oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($oDB->connection));
echo '.';
}
echo ".\n";
// pre-create the word list
- if (!$aCMDResult['disable-token-precalc'])
- {
+ if (!$aCMDResult['disable-token-precalc']) {
echo "Loading word list\n";
pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
}
echo "Load Data\n";
$aDBInstances = array();
$iLoadThreads = max(1, $iInstances - 1);
- for($i = 0; $i < $iLoadThreads; $i++)
- {
+ for ($i = 0; $i < $iLoadThreads; $i++) {
$aDBInstances[$i] =& getDB(true);
$sSQL = 'insert into placex (osm_type, osm_id, class, type, name, admin_level, ';
$sSQL .= 'housenumber, street, addr_place, isin, postcode, country_code, extratags, ';
if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
$bAnyBusy = true;
- while($bAnyBusy)
- {
+ while ($bAnyBusy) {
$bAnyBusy = false;
- for($i = 0; $i <= $iLoadThreads; $i++)
- {
+ for ($i = 0; $i <= $iLoadThreads; $i++) {
if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
}
sleep(1);
pgsqlRunScript('ANALYSE');
}
-if ($aCMDResult['import-tiger-data'])
-{
+if ($aCMDResult['import-tiger-data']) {
$bDidSomething = true;
$sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
pgsqlRunScript($sTemplate, false);
$aDBInstances = array();
- for($i = 0; $i < $iInstances; $i++)
- {
+ for ($i = 0; $i < $iInstances; $i++) {
$aDBInstances[$i] =& getDB(true);
}
- foreach(glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile)
- {
+ foreach (glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile) {
echo $sFile.': ';
$hFile = fopen($sFile, "r");
$sSQL = fgets($hFile, 100000);
$iLines = 0;
- while(true)
- {
- for($i = 0; $i < $iInstances; $i++)
- {
- if (!pg_connection_busy($aDBInstances[$i]->connection))
- {
- while(pg_get_result($aDBInstances[$i]->connection));
+ while (true) {
+ for ($i = 0; $i < $iInstances; $i++) {
+ if (!pg_connection_busy($aDBInstances[$i]->connection)) {
+ while (pg_get_result($aDBInstances[$i]->connection));
$sSQL = fgets($hFile, 100000);
if (!$sSQL) break 2;
if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
$iLines++;
- if ($iLines == 1000)
- {
+ if ($iLines == 1000) {
echo ".";
$iLines = 0;
}
fclose($hFile);
$bAnyBusy = true;
- while($bAnyBusy)
- {
+ while ($bAnyBusy) {
$bAnyBusy = false;
- for($i = 0; $i < $iInstances; $i++)
- {
+ for ($i = 0; $i < $iInstances; $i++) {
if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
}
usleep(10);
pgsqlRunScript($sTemplate, false);
}
-if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all'])
-{
+if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all']) {
$bDidSomething = true;
$oDB =& getDB();
if (!pg_query($oDB->connection, 'DELETE from placex where osm_type=\'P\'')) fail(pg_last_error($oDB->connection));
$sSQL .= "from placex where postcode is not null group by calculated_country_code,postcode) as x";
if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
- if (CONST_Use_Extra_US_Postcodes)
- {
+ if (CONST_Use_Extra_US_Postcodes) {
$sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,calculated_country_code,geometry) ";
$sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,'us',";
$sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from us_postcode";
}
}
-if ($aCMDResult['osmosis-init'] || ($aCMDResult['all'] && !$aCMDResult['drop'])) // no use doing osmosis-init when dropping update tables
-{
+if ($aCMDResult['osmosis-init'] || ($aCMDResult['all'] && !$aCMDResult['drop'])) { // no use doing osmosis-init when dropping update tables
$bDidSomething = true;
$oDB =& getDB();
- if (!file_exists(CONST_Osmosis_Binary))
- {
+ if (!file_exists(CONST_Osmosis_Binary)) {
echo "Please download osmosis.\nIf it is already installed, check the path in your local settings (settings/local.php) file.\n";
- if (!$aCMDResult['all'])
- {
+ if (!$aCMDResult['all']) {
fail("osmosis not found in '".CONST_Osmosis_Binary."'");
}
- }
- else
- {
- if (file_exists(CONST_InstallPath.'/settings/configuration.txt'))
- {
+ } else {
+ if (file_exists(CONST_InstallPath.'/settings/configuration.txt')) {
echo "settings/configuration.txt already exists\n";
- }
- else
- {
+ } else {
passthru(CONST_Osmosis_Binary.' --read-replication-interval-init '.CONST_InstallPath.'/settings');
// update osmosis configuration.txt with our settings
passthru("sed -i 's!baseUrl=.*!baseUrl=".CONST_Replication_Url."!' ".CONST_InstallPath.'/settings/configuration.txt');
// download.geofabrik.de: <a href="000/">000/</a></td><td align="right">26-Feb-2013 11:53 </td>
// planet.openstreetmap.org: <a href="273/">273/</a> 2013-03-11 07:41 -
preg_match_all('#<a href="[0-9]{3}/">([0-9]{3}/)</a>\s*([-0-9a-zA-Z]+ [0-9]{2}:[0-9]{2})#', $sRep, $aRepMatches, PREG_SET_ORDER);
- if ($aRepMatches)
- {
+ if ($aRepMatches) {
$aPrevRepMatch = false;
- foreach($aRepMatches as $aRepMatch)
- {
+ foreach ($aRepMatches as $aRepMatch) {
if (strtotime($aRepMatch[2]) < $iLastNodeTimestamp) break;
$aPrevRepMatch = $aRepMatch;
}
$sRep = file_get_contents($sRepURL."?C=M;O=D;F=1");
preg_match_all('#<a href="[0-9]{3}/">([0-9]{3}/)</a>\s*([-0-9a-zA-Z]+ [0-9]{2}:[0-9]{2})#', $sRep, $aRepMatches, PREG_SET_ORDER);
$aPrevRepMatch = false;
- foreach($aRepMatches as $aRepMatch)
- {
+ foreach ($aRepMatches as $aRepMatch) {
if (strtotime($aRepMatch[2]) < $iLastNodeTimestamp) break;
$aPrevRepMatch = $aRepMatch;
}
$sRep = file_get_contents($sRepURL."?C=M;O=D;F=1");
preg_match_all('#<a href="[0-9]{3}.state.txt">([0-9]{3}).state.txt</a>\s*([-0-9a-zA-Z]+ [0-9]{2}:[0-9]{2})#', $sRep, $aRepMatches, PREG_SET_ORDER);
$aPrevRepMatch = false;
- foreach($aRepMatches as $aRepMatch)
- {
+ foreach ($aRepMatches as $aRepMatch) {
if (strtotime($aRepMatch[2]) < $iLastNodeTimestamp) break;
$aPrevRepMatch = $aRepMatch;
}
pg_query($oDB->connection, 'TRUNCATE import_status');
$sSQL = "INSERT INTO import_status VALUES('".$aRepMatch[2]."')";
pg_query($oDB->connection, $sSQL);
- }
- else
- {
- if (!$aCMDResult['all'])
- {
+ } else {
+ if (!$aCMDResult['all']) {
fail("Cannot read state file directory.");
}
}
}
}
-if ($aCMDResult['index'] || $aCMDResult['all'])
-{
+if ($aCMDResult['index'] || $aCMDResult['all']) {
$bDidSomething = true;
$sOutputFile = '';
$sBaseCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$iInstances.$sOutputFile;
passthruCheckReturn($sBaseCmd.' -r 26');
}
-if ($aCMDResult['create-search-indices'] || $aCMDResult['all'])
-{
+if ($aCMDResult['create-search-indices'] || $aCMDResult['all']) {
echo "Search indices\n";
$bDidSomething = true;
pgsqlRunScript($sTemplate);
}
-if ($aCMDResult['drop'])
-{
+if ($aCMDResult['drop']) {
// The implementation is potentially a bit dangerous because it uses
// a positive selection of tables to keep, and deletes everything else.
// Including any tables that the unsuspecting user might have manually
$aDropTables = array();
$aHaveTables = chksql($oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'"));
- foreach($aHaveTables as $sTable)
- {
+ foreach ($aHaveTables as $sTable) {
$bFound = false;
- foreach ($aKeepTables as $sKeep)
- {
- if (fnmatch($sKeep, $sTable))
- {
+ foreach ($aKeepTables as $sKeep) {
+ if (fnmatch($sKeep, $sTable)) {
$bFound = true;
break;
}
if (!$bFound) array_push($aDropTables, $sTable);
}
- foreach ($aDropTables as $sDrop)
- {
+ foreach ($aDropTables as $sDrop) {
if ($aCMDResult['verbose']) echo "dropping table $sDrop\n";
@pg_query($oDB->connection, "DROP TABLE $sDrop CASCADE");
// ignore warnings/errors as they might be caused by a table having
// been deleted already by CASCADE
}
- if (!is_null(CONST_Osm2pgsql_Flatnode_File))
- {
+ if (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
if ($aCMDResult['verbose']) echo "deleting ".CONST_Osm2pgsql_Flatnode_File."\n";
unlink(CONST_Osm2pgsql_Flatnode_File);
}
}
-if (!$bDidSomething)
-{
+if (!$bDidSomething) {
showUsage($aCMDOptions, true);
-}
-else
-{
+} else {
echo "Setup finished.\n";
}
$sCMD = 'psql -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'];
$ahGzipPipes = null;
- if (preg_match('/\\.gz$/', $sFilename))
- {
+ if (preg_match('/\\.gz$/', $sFilename)) {
$aDescriptors = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
if (!is_resource($hGzipProcess)) fail('unable to start zcat');
$aReadPipe = $ahGzipPipes[1];
fclose($ahGzipPipes[0]);
- }
- else
- {
+ } else {
$sCMD .= ' -f '.$sFilename;
$aReadPipe = array('pipe', 'r');
}
// TODO: error checking
- while(!feof($ahPipes[1]))
- {
+ while (!feof($ahPipes[1])) {
echo fread($ahPipes[1], 4096);
}
fclose($ahPipes[1]);
$iReturn = proc_close($hProcess);
- if ($iReturn > 0)
- {
+ if ($iReturn > 0) {
fail("pgsql returned with error code ($iReturn)");
}
- if ($ahGzipPipes)
- {
+ if ($ahGzipPipes) {
fclose($ahGzipPipes[1]);
proc_close($hGzipProcess);
}
$hProcess = @proc_open($sCMD, $aDescriptors, $ahPipes);
if (!is_resource($hProcess)) fail('unable to start pgsql');
- while(strlen($sScript))
- {
+ while (strlen($sScript)) {
$written = fwrite($ahPipes[0], $sScript);
if ($written <= 0) break;
$sScript = substr($sScript, $written);
}
fclose($ahPipes[0]);
$iReturn = proc_close($hProcess);
- if ($bfatal && $iReturn > 0)
- {
+ if ($bfatal && $iReturn > 0) {
fail("pgsql returned with error code ($iReturn)");
}
}
if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
- foreach($aMatches as $aMatch)
- {
+ foreach ($aMatches as $aMatch) {
$sResult = '';
- foreach($aPartitions as $sPartitionName)
- {
+ foreach ($aPartitions as $sPartitionName) {
$sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
}
$sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
fclose($ahPipes[0]);
// TODO: error checking
- while(!feof($ahPipes[1]))
- {
+ while (!feof($ahPipes[1])) {
echo fread($ahPipes[1], 4096);
}
fclose($ahPipes[1]);
fclose($ahPipes[0]);
// TODO: error checking
- while(!feof($ahPipes[1]))
- {
+ while (!feof($ahPipes[1])) {
echo fread($ahPipes[1], 4096);
}
fclose($ahPipes[1]);
function replace_tablespace($sTemplate, $sTablespace, $sSql)
{
- if ($sTablespace)
+ if ($sTablespace) {
$sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"',
$sSql);
- else
+ } else {
$sSql = str_replace($sTemplate, '', $sSql);
+ }
return $sSql;
}
{
$sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
$sTemplate = str_replace('{modulepath}', CONST_InstallPath.'/module', $sTemplate);
- if ($aCMDResult['enable-diff-updates'])
- {
+ if ($aCMDResult['enable-diff-updates']) {
$sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
}
- if ($aCMDResult['enable-debug-statements'])
- {
+ if ($aCMDResult['enable-debug-statements']) {
$sTemplate = str_replace('--DEBUG:', '', $sTemplate);
}
- if (CONST_Limit_Reindexing)
- {
+ if (CONST_Limit_Reindexing) {
$sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
}
- if (!CONST_Use_US_Tiger_Data)
- {
+ if (!CONST_Use_US_Tiger_Data) {
$sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
}
- if (!CONST_Use_Aux_Location_data)
- {
+ if (!CONST_Use_Aux_Location_data) {
$sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
}
pgsqlRunScript($sTemplate);
ini_set('memory_limit', '800M');
ini_set('display_errors', 'stderr');
- $aCMDOptions = array(
- "Import and export special phrases",
- array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
- array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
- array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
- array('countries', '', 0, 1, 0, 0, 'bool', 'Create import script for country codes and names'),
- array('wiki-import', '', 0, 1, 0, 0, 'bool', 'Create import script for search phrases '),
- );
- getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
+$aCMDOptions = array(
+ "Import and export special phrases",
+ array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
+ array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
+ array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
+ array('countries', '', 0, 1, 0, 0, 'bool', 'Create import script for country codes and names'),
+ array('wiki-import', '', 0, 1, 0, 0, 'bool', 'Create import script for search phrases '),
+);
+getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
- include(CONST_InstallPath.'/settings/phrase_settings.php');
+include(CONST_InstallPath.'/settings/phrase_settings.php');
if ($aCMDResult['countries']) {
echo "select count(*) from (select getorcreate_country(make_standard_name(country_code), country_code) from country_name where country_code is not null) as x;\n";
echo "select count(*) from (select getorcreate_country(make_standard_name(get_name_by_language(country_name.name,ARRAY['name'])), country_code) from country_name where get_name_by_language(country_name.name, ARRAY['name']) is not null) as x;\n";
- foreach($aLanguageIn as $sLanguage)
- {
+ foreach ($aLanguageIn as $sLanguage) {
echo "select count(*) from (select getorcreate_country(make_standard_name(get_name_by_language(country_name.name,ARRAY['name:".$sLanguage."'])), country_code) from country_name where get_name_by_language(country_name.name, ARRAY['name:".$sLanguage."']) is not null) as x;\n";
}
}
-if ($aCMDResult['wiki-import'])
-{
+if ($aCMDResult['wiki-import']) {
$aPairs = array();
- foreach($aLanguageIn as $sLanguage)
- {
+ foreach ($aLanguageIn as $sLanguage) {
$sURL = 'http://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/'.strtoupper($sLanguage);
$sWikiPageXML = file_get_contents($sURL);
- if (preg_match_all('#\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([\\-YN])#', $sWikiPageXML, $aMatches, PREG_SET_ORDER))
- {
- foreach($aMatches as $aMatch)
- {
+ if (preg_match_all('#\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([^|]+) \\|\\| ([\\-YN])#', $sWikiPageXML, $aMatches, PREG_SET_ORDER)) {
+ foreach ($aMatches as $aMatch) {
$sLabel = trim($aMatch[1]);
$sClass = trim($aMatch[2]);
$sType = trim($aMatch[3]);
}
$aPairs[$sClass.'|'.$sType] = array($sClass, $sType);
- switch(trim($aMatch[4]))
- {
- case 'near':
- echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'near');\n";
- break;
- case 'in':
- echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'in');\n";
- break;
- default:
- echo "select getorcreate_amenity(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType');\n";
- break;
+ switch (trim($aMatch[4])) {
+ case 'near':
+ echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'near');\n";
+ break;
+ case 'in':
+ echo "select getorcreate_amenityoperator(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType', 'in');\n";
+ break;
+ default:
+ echo "select getorcreate_amenity(make_standard_name('".pg_escape_string($sLabel)."'), '$sClass', '$sType');\n";
+ break;
}
}
}
echo "create index idx_placex_classtype on placex (class, type);";
- foreach($aPairs as $aPair)
- {
+ foreach ($aPairs as $aPair) {
echo "create table place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1]);
if (CONST_Tablespace_Aux_Data)
echo " tablespace ".CONST_Tablespace_Aux_Data;
echo ";\n";
echo "GRANT SELECT ON place_classtype_".pg_escape_string($aPair[0])."_".pg_escape_string($aPair[1]).' TO "'.CONST_Database_Web_User."\";\n";
-
}
echo "drop index idx_placex_classtype;";
// cache memory to be used by osm2pgsql, should not be more than the available memory
$iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
-if ($iCacheMemory + 500 > getTotalMemoryMB())
-{
+if ($iCacheMemory + 500 > getTotalMemoryMB()) {
$iCacheMemory = getCacheMemoryMB();
echo "WARNING: resetting cache memory to $iCacheMemory\n";
}
$sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas --number-processes 1 -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
-if (!is_null(CONST_Osm2pgsql_Flatnode_File))
-{
+if (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
$sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
}
-if (isset($aResult['import-diff']))
-{
+if (isset($aResult['import-diff'])) {
// import diff directly (e.g. from osmosis --rri)
$sNextFile = $aResult['import-diff'];
- if (!file_exists($sNextFile))
- {
+ if (!file_exists($sNextFile)) {
fail("Cannot open $sNextFile\n");
}
echo $sCMD."\n";
exec($sCMD, $sJunk, $iErrorLevel);
- if ($iErrorLevel)
- {
+ if ($iErrorLevel) {
fail("Error from osm2pgsql, $iErrorLevel\n");
}
$sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
$bHaveDiff = false;
-if (isset($aResult['import-file']) && $aResult['import-file'])
-{
+if (isset($aResult['import-file']) && $aResult['import-file']) {
$bHaveDiff = true;
$sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
echo $sCMD."\n";
exec($sCMD, $sJunk, $iErrorLevel);
- if ($iErrorLevel)
- {
+ if ($iErrorLevel) {
fail("Error converting osm to osc, osmosis returned: $iErrorLevel\n");
}
}
$bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
$sContentURL = '';
-if (isset($aResult['import-node']) && $aResult['import-node'])
-{
- if ($bUseOSMApi)
- {
+if (isset($aResult['import-node']) && $aResult['import-node']) {
+ if ($bUseOSMApi) {
$sContentURL = 'http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
- }
- else
- {
+ } else {
$sContentURL = 'http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
}
}
-if (isset($aResult['import-way']) && $aResult['import-way'])
-{
- if ($bUseOSMApi)
- {
+
+if (isset($aResult['import-way']) && $aResult['import-way']) {
+ if ($bUseOSMApi) {
$sContentURL = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
- }
- else
- {
+ } else {
$sContentURL = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
}
}
-if (isset($aResult['import-relation']) && $aResult['import-relation'])
-{
- if ($bUseOSMApi)
- {
+
+if (isset($aResult['import-relation']) && $aResult['import-relation']) {
+ if ($bUseOSMApi) {
$sContentURLsModifyXMLstr = 'http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
- }
- else
- {
+ } else {
$sContentURL = 'http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;';
}
}
-if ($sContentURL)
-{
+
+if ($sContentURL) {
$sModifyXMLstr = file_get_contents($sContentURL);
$bHaveDiff = true;
$sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
echo $sCMD."\n";
$hProc = proc_open($sCMD, $aSpec, $aPipes);
- if (!is_resource($hProc))
- {
+ if (!is_resource($hProc)) {
fail("Error converting osm to osc, osmosis failed\n");
}
fwrite($aPipes[0], $sModifyXMLstr);
$sErrors = stream_get_contents($aPipes[2]);
if ($aResult['verbose']) echo $sErrors;
fclose($aPipes[2]);
- if ($iError = proc_close($hProc))
- {
+ if ($iError = proc_close($hProc)) {
echo $sOut;
echo $sErrors;
fail("Error converting osm to osc, osmosis returned: $iError\n");
}
}
-if ($bHaveDiff)
-{
+if ($bHaveDiff) {
// import generated change file
$sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile;
echo $sCMD."\n";
exec($sCMD, $sJunk, $iErrorLevel);
- if ($iErrorLevel)
- {
+ if ($iErrorLevel) {
fail("osm2pgsql exited with error level $iErrorLevel\n");
}
}
-if ($aResult['deduplicate'])
-{
-
- if (getPostgresVersion() < 9.3)
- {
+if ($aResult['deduplicate']) {
+ //
+ if (getPostgresVersion() < 9.3) {
fail("ERROR: deduplicate is only currently supported in postgresql 9.3");
}
$sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' ' and class is null and type is null and country_code is null group by word_token having count(*) > 1 order by word_token";
$aDuplicateTokens = chksql($oDB->getAll($sSQL));
- foreach($aDuplicateTokens as $aToken)
- {
+ foreach ($aDuplicateTokens as $aToken) {
if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
echo "Deduping ".$aToken['word_token']."\n";
$sSQL = "select word_id,(select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num from word where word_token = '".$aToken['word_token']."' and class is null and type is null and country_code is null order by num desc";
$aKeep = array_shift($aTokenSet);
$iKeepID = $aKeep['word_id'];
- foreach($aTokenSet as $aRemove)
- {
+ foreach ($aTokenSet as $aRemove) {
$sSQL = "update search_name set";
$sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID."),";
$sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
chksql($oDB->query($sSQL));
- foreach ($aPartitions as $sPartition)
- {
+ foreach ($aPartitions as $sPartition) {
$sSQL = "update search_name_".$sPartition." set";
$sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID.")";
$sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
}
}
-if ($aResult['index'])
-{
+if ($aResult['index']) {
passthru(CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']);
}
-if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
-{
-
+if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
+ //
if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
fail("Error: Update interval too low for download.geofabrik.de. Please check install documentation (http://wiki.openstreetmap.org/wiki/Nominatim/Installation#Updates)\n");
}
$sCMDImport = $sOsm2pgsqlCmd.' '.$sImportFile;
$sCMDIndex = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'];
- while(true)
- {
+ while (true) {
$fStartTime = time();
$iFileSize = 1001;
- if (!file_exists($sImportFile))
- {
+ if (!file_exists($sImportFile)) {
// First check if there are new updates published (except for minutelies - there's always new diffs to process)
- if ( CONST_Replication_Update_Interval > 60 )
- {
-
+ if (CONST_Replication_Update_Interval > 60) {
unset($aReplicationLag);
exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel);
- while ($iErrorLevel > 0 || $aReplicationLag[0] < 1)
- {
- if ($iErrorLevel)
- {
+ while ($iErrorLevel > 0 || $aReplicationLag[0] < 1) {
+ if ($iErrorLevel) {
echo "Error: $iErrorLevel. ";
echo "Re-trying: ".$sCMDCheckReplicationLag." in ".CONST_Replication_Recheck_Interval." secs\n";
- }
- else
- {
+ } else {
echo ".";
}
sleep(CONST_Replication_Recheck_Interval);
$fCMDStartTime = time();
echo $sCMDDownload."\n";
exec($sCMDDownload, $sJunk, $iErrorLevel);
- while ($iErrorLevel > 0)
- {
+ while ($iErrorLevel > 0) {
echo "Error: $iErrorLevel\n";
sleep(60);
echo 'Re-trying: '.$sCMDDownload."\n";
$fCMDStartTime = time();
echo $sCMDImport."\n";
exec($sCMDImport, $sJunk, $iErrorLevel);
- if ($iErrorLevel)
- {
+ if ($iErrorLevel) {
echo "Error: $iErrorLevel\n";
exit($iErrorLevel);
}
$sThisIndexCmd = $sCMDIndex;
$fCMDStartTime = time();
- if (!$aResult['no-index'])
- {
+ if (!$aResult['no-index']) {
echo "$sThisIndexCmd\n";
exec($sThisIndexCmd, $sJunk, $iErrorLevel);
- if ($iErrorLevel)
- {
+ if ($iErrorLevel) {
echo "Error: $iErrorLevel\n";
exit($iErrorLevel);
}
echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n";
if (!$aResult['import-osmosis-all']) exit(0);
- if ( CONST_Replication_Update_Interval > 60 )
- {
+ if (CONST_Replication_Update_Interval > 60) {
$iSleep = max(0,(strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time()));
- }
- else
- {
+ } else {
$iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
}
echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
$bVerbose = $aResult['verbose'];
if (!$aResult['search-only']) {
-
$oReverseGeocode = new ReverseGeocode($oDB);
$oReverseGeocode->setZoom(20);
$oPlaceLookup = new PlaceLookup($oDB);
echo "Warm reverse: ";
if ($bVerbose) echo "\n";
- for($i = 0; $i < 1000; $i++) {
+ for ($i = 0; $i < 1000; $i++) {
$fLat = rand(-9000, 9000) / 100;
$fLon = rand(-18000, 18000) / 100;
if ($bVerbose) echo "$fLat, $fLon = ";
$aLookup = $oReverseGeocode->lookup($fLat, $fLon);
- if ($aLookup && $aLookup['place_id'])
- {
+ if ($aLookup && $aLookup['place_id']) {
$aDetails = $oPlaceLookup->lookup((int)$aLookup['place_id'],
$aLookup['type'], $aLookup['fraction']);
if ($bVerbose) echo $aDetails['langaddress']."\n";
+ } else {
+ echo ".";
}
- else echo ".";
}
echo "\n";
}
if (!$aResult['reverse-only']) {
-
$oGeocode =& new Geocode($oDB);
echo "Warm search: ";
if ($bVerbose) echo "\n";
$sSQL = 'select word from word where word is not null order by search_name_count desc limit 1000';
- foreach($oDB->getCol($sSQL) as $sWord) {
+ foreach ($oDB->getCol($sSQL) as $sWord) {
if ($bVerbose) echo "$sWord = ";
$oGeocode->setLanguagePreference(array('en'));
$oGeocode->setQuery($sWord);
$aPolygons = chksql($oDB->getAll($sSQL),
"Could not get list of deleted OSM elements.");
- if (CONST_DEBUG)
- {
+ if (CONST_DEBUG) {
var_dump($aPolygons);
exit;
}
if (!$aPolygons) exit;
echo "<tr>";
//var_dump($aPolygons[0]);
- foreach($aPolygons[0] as $sCol => $sVal)
- {
+ foreach ($aPolygons[0] as $sCol => $sVal) {
echo "<th>".$sCol."</th>";
}
echo "</tr>";
- foreach($aPolygons as $aRow)
- {
+ foreach ($aPolygons as $aRow) {
echo "<tr>";
- foreach($aRow as $sCol => $sVal)
- {
- switch($sCol)
- {
+ foreach ($aRow as $sCol => $sVal) {
+ switch ($sCol) {
case 'osm_id':
echo '<td>'.osmLink($aRow).'</td>';
break;
$oDB =& getDB();
-if ($sOsmType && $iOsmId > 0)
-{
+if ($sOsmType && $iOsmId > 0) {
$sPlaceId = chksql($oDB->getOne("select place_id from placex where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by type = 'postcode' asc"));
// Be nice about our error messages for broken geometry
- if (!$sPlaceId)
- {
+ if (!$sPlaceId) {
$aPointDetails = chksql($oDB->getRow("select osm_type, osm_id, errormessage, class, type, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ST_AsText(prevgeometry) as prevgeom, ST_AsText(newgeometry) as newgeom from import_polygon_error where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by updated desc limit 1"));
if (!PEAR::isError($aPointDetails) && $aPointDetails) {
- if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches))
- {
+ if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) {
$aPointDetails['error_x'] = $aMatches[1];
$aPointDetails['error_y'] = $aMatches[2];
- }
- else
- {
+ } else {
$aPointDetails['error_x'] = 0;
$aPointDetails['error_y'] = 0;
}
$iPlaceID = (int)$sPlaceId;
-if (CONST_Use_US_Tiger_Data)
-{
+if (CONST_Use_US_Tiger_Data) {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_tiger where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
}
-if (CONST_Use_Aux_Location_data)
-{
+if (CONST_Use_Aux_Location_data) {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_aux where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
}
// Get all alternative names (languages, etc)
$sSQL = "select (each(name)).key,(each(name)).value from placex where place_id = $iPlaceID order by (each(name)).key";
$aPointDetails['aNames'] = $oDB->getAssoc($sSQL);
-if (PEAR::isError($aPointDetails['aNames'])) // possible timeout
-{
+if (PEAR::isError($aPointDetails['aNames'])) { // possible timeout
$aPointDetails['aNames'] = [];
}
// Extra tags
$sSQL = "select (each(extratags)).key,(each(extratags)).value from placex where place_id = $iPlaceID order by (each(extratags)).key";
$aPointDetails['aExtraTags'] = $oDB->getAssoc($sSQL);
-if (PEAR::isError($aPointDetails['aExtraTags'])) // possible timeout
-{
+if (PEAR::isError($aPointDetails['aExtraTags'])) { // possible timeout
$aPointDetails['aExtraTags'] = [];
}
$sSQL .= " where linked_place_id = $iPlaceID";
$sSQL .= " order by rank_address asc,rank_search asc,get_name_by_language(name,$sLanguagePrefArraySQL),housenumber";
$aLinkedLines = $oDB->getAll($sSQL);
-if (PEAR::isError($aLinkedLines)) // possible timeout
-{
+if (PEAR::isError($aLinkedLines)) { // possible timeout
$aLinkedLines = [];
}
$sSQL .= " (select centroid as placegeometry from placex where place_id = $iPlaceID) as x";
$sSQL .= " order by rank_address asc,rank_search asc,localname,housenumber";
$aParentOfLines = $oDB->getAll($sSQL);
-if (PEAR::isError($aParentOfLines)) // possible timeout
-{
+if (PEAR::isError($aParentOfLines)) { // possible timeout
$aParentOfLines = [];
}
$aPlaceSearchNameKeywords = false;
$aPlaceSearchAddressKeywords = false;
-if ($oParams->getBool('keywords'))
-{
+if ($oParams->getBool('keywords')) {
$sSQL = "select * from search_name where place_id = $iPlaceID";
$aPlaceSearchName = $oDB->getRow($sSQL);
- if (PEAR::isError($aPlaceSearchName)) // possible timeout
- {
+ if (PEAR::isError($aPlaceSearchName)) { // possible timeout
$aPlaceSearchName = [];
}
$sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['name_vector'],1,-1).")";
$aPlaceSearchNameKeywords = $oDB->getAll($sSQL);
- if (PEAR::isError($aPlaceSearchNameKeywords)) // possible timeout
- {
+ if (PEAR::isError($aPlaceSearchNameKeywords)) { // possible timeout
$aPlaceSearchNameKeywords = [];
}
$sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['nameaddress_vector'],1,-1).")";
$aPlaceSearchAddressKeywords = $oDB->getAll($sSQL);
- if (PEAR::isError($aPlaceSearchAddressKeywords)) // possible timeout
- {
+ if (PEAR::isError($aPlaceSearchAddressKeywords)) { // possible timeout
$aPlaceSearchAddressKeywords = [];
}
-
}
logEnd($oDB, $hLog, 1);
-if ($sOutputFormat=='html')
-{
+if ($sOutputFormat=='html') {
$sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1"));
$sTileURL = CONST_Map_Tile_URL;
$sTileAttribution = CONST_Map_Tile_Attribution;
$oDB =& getDB();
-if ($sOsmType && $iOsmId > 0)
-{
+if ($sOsmType && $iOsmId > 0) {
$sPlaceId = chksql($oDB->getOne("select place_id from placex where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by type = 'postcode' asc"));
// Be nice about our error messages for broken geometry
- if (!$sPlaceId)
- {
+ if (!$sPlaceId) {
$aPointDetails = chksql($oDB->getRow("select osm_type, osm_id, errormessage, class, type, get_name_by_language(name,$sLanguagePrefArraySQL) as localname, ST_AsText(prevgeometry) as prevgeom, ST_AsText(newgeometry) as newgeom from import_polygon_error where osm_type = '".$sOsmType."' and osm_id = ".$iOsmId." order by updated desc limit 1"));
if ($aPointDetails) {
- if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches))
- {
+ if (preg_match('/\[(-?\d+\.\d+) (-?\d+\.\d+)\]/', $aPointDetails['errormessage'], $aMatches)) {
$aPointDetails['error_x'] = $aMatches[1];
$aPointDetails['error_y'] = $aMatches[2];
}
$iPlaceID = (int)$sPlaceId;
-if (CONST_Use_US_Tiger_Data)
-{
+if (CONST_Use_US_Tiger_Data) {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_tiger where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
}
-if (CONST_Use_Aux_Location_data)
-{
+if (CONST_Use_Aux_Location_data) {
$iParentPlaceID = chksql($oDB->getOne('select parent_place_id from location_property_aux where place_id = '.$iPlaceID));
if ($iParentPlaceID) $iPlaceID = $iParentPlaceID;
}
if (!sizeof($aPlaceAddress)) userError("Unknown place id.");
$aBreadcrums = array();
-foreach($aPlaceAddress as $i => $aPlace)
-{
+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']);
- if ($sOutputFormat == 'html')
- {
+ if ($sOutputFormat == 'html') {
$sPlaceUrl = 'hierarchy.php?place_id='.$aPlace['place_id'];
if ($i) echo " > ";
echo '<a href="'.$sPlaceUrl.'">'.$aPlace['localname'].'</a> ('.osmLink($aPlace).')';
}
-if ($sOutputFormat == 'json')
-{
+if ($sOutputFormat == 'json') {
header("content-type: application/json; charset=UTF-8");
$aDetails = array();
$aDetails['breadcrumbs'] = $aBreadcrums;
$sSQL .= " order by rank_address asc,rank_search asc,localname,class, type,housenumber";
$aParentOfLines = chksql($oDB->getAll($sSQL));
-if (sizeof($aParentOfLines))
-{
+if (sizeof($aParentOfLines)) {
echo '<h2>Parent Of:</h2>';
$aClassType = getClassTypesWithImportance();
$aGroupedAddressLines = array();
- foreach($aParentOfLines as $aAddressLine)
- {
+ foreach ($aParentOfLines as $aAddressLine) {
if (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'])
- && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'])
- {
+ && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']
+ ) {
$aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'];
- }
- elseif (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'])
- && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'])
- {
+ } elseif (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'])
+ && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']
+ ) {
$aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'];
- }
- else $aAddressLine['label'] = ucwords($aAddressLine['type']);
+ } else $aAddressLine['label'] = ucwords($aAddressLine['type']);
if (!isset($aGroupedAddressLines[$aAddressLine['label']])) $aGroupedAddressLines[$aAddressLine['label']] = array();
$aGroupedAddressLines[$aAddressLine['label']][] = $aAddressLine;
}
- foreach($aGroupedAddressLines as $sGroupHeading => $aParentOfLines)
- {
+ foreach ($aGroupedAddressLines as $sGroupHeading => $aParentOfLines) {
echo "<h3>$sGroupHeading</h3>";
- foreach($aParentOfLines as $aAddressLine)
- {
+ foreach ($aParentOfLines as $aAddressLine) {
$aAddressLine['localname'] = $aAddressLine['localname']?$aAddressLine['localname']:$aAddressLine['housenumber'];
$sOSMType = formatOSMType($aAddressLine['osm_type'], false);
$aOsmIds = explode(',', $oParams->getString('osm_ids', ''));
-if (count($aOsmIds) > CONST_Places_Max_ID_count)
-{
+if (count($aOsmIds) > CONST_Places_Max_ID_count) {
userError('Bulk User: Only ' . CONST_Places_Max_ID_count . " ids are allowed in one request.");
}
-foreach ($aOsmIds AS $sItem)
-{
+foreach ($aOsmIds AS $sItem) {
// Skip empty sItem
if (empty($sItem)) continue;
$sType = $sItem[0];
$iId = (int) substr($sItem, 1);
- if ( $iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R') )
- {
+ if ($iId > 0 && ($sType == 'N' || $sType == 'W' || $sType == 'R')) {
$aCleanedQueryParts[] = $sType . $iId;
$oPlace = $oPlaceLookup->lookupOSMID($sType, $iId);
- if ($oPlace){
+ 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
$iTotalBroken = (int) chksql($oDB->getOne('select count(*) from import_polygon_error'));
$aPolygons = array();
- while($iTotalBroken && !sizeof($aPolygons))
- {
+ while ($iTotalBroken && !sizeof($aPolygons)) {
$sSQL = 'select osm_type as "type",osm_id as "id",class as "key",type as "value",name->\'name\' as "name",';
$sSQL .= 'country_code as "country",errormessage as "error message",updated';
$sSQL .= " from import_polygon_error";
$aPolygons = chksql($oDB->getAll($sSQL));
}
- if (CONST_Debug)
- {
+ if (CONST_Debug) {
var_dump($aPolygons);
exit;
}
echo "<table>";
echo "<tr>";
//var_dump($aPolygons[0]);
- foreach($aPolygons[0] as $sCol => $sVal)
- {
+ foreach ($aPolygons[0] as $sCol => $sVal) {
echo "<th>".$sCol."</th>";
}
echo "<th> </th>";
echo "<th> </th>";
echo "</tr>";
$aSeen = array();
- foreach($aPolygons as $aRow)
- {
+ foreach ($aPolygons as $aRow) {
if (isset($aSeen[$aRow['type'].$aRow['id']])) continue;
$aSeen[$aRow['type'].$aRow['id']] = 1;
echo "<tr>";
- foreach($aRow as $sCol => $sVal)
- {
- switch($sCol)
- {
+ foreach ($aRow as $sCol => $sVal) {
+ switch ($sCol) {
case 'error message':
- if (preg_match('/Self-intersection\\[([0-9.\\-]+) ([0-9.\\-]+)\\]/',$sVal,$aMatch))
- {
+ if (preg_match('/Self-intersection\\[([0-9.\\-]+) ([0-9.\\-]+)\\]/',$sVal,$aMatch)) {
$aRow['lat'] = $aMatch[2];
$aRow['lon'] = $aMatch[1];
echo "<td><a href=\"http://www.openstreetmap.org/?lat=".$aMatch[2]."&lon=".$aMatch[1]."&zoom=18&layers=M&".$sOSMType."=".$aRow['id']."\">".($sVal?$sVal:' ')."</a></td>";
- }
- else
- {
+ } else {
echo "<td>".($sVal?$sVal:' ')."</td>";
}
break;
}
}
echo "<td><a href=\"http://localhost:8111/import?url=http://www.openstreetmap.org/api/0.6/".$sOSMType.'/'.$aRow['id']."/full\" target=\"josm\">josm</a></td>";
- if (isset($aRow['lat']))
- {
+ if (isset($aRow['lat'])) {
echo "<td><a href=\"http://open.mapquestapi.com/dataedit/index_flash.html?lat=".$aRow['lat']."&lon=".$aRow['lon']."&zoom=18\" target=\"potlatch2\">P2</a></td>";
- }
- else
- {
+ } else {
echo "<td> </td>";
}
echo "</tr>";
$bAsSVG = $oParams->getBool('polygon_svg');
$bAsText = $oParams->getBool('polygon_text');
if ((($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0)
- + ($bAsText?1:0)) > CONST_PolygonOutput_MaximumTypes)
-{
- if (CONST_PolygonOutput_MaximumTypes)
- {
+ + ($bAsText?1:0)) > CONST_PolygonOutput_MaximumTypes
+) {
+ if (CONST_PolygonOutput_MaximumTypes) {
userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
- }
- else
- {
+ } else {
userError("Polygon output is disabled");
}
}
$iOsmId = $oParams->getInt('osm_id', -1);
$fLat = $oParams->getFloat('lat');
$fLon = $oParams->getFloat('lon');
-if ($sOsmType && $iOsmId > 0)
-{
+if ($sOsmType && $iOsmId > 0) {
$aPlace = $oPlaceLookup->lookupOSMID($sOsmType, $iOsmId);
-}
-else if ($fLat !== false && $fLon !== false)
-{
+} else if ($fLat !== false && $fLon !== false) {
$oReverseGeocode = new ReverseGeocode($oDB);
$oReverseGeocode->setZoom($oParams->getInt('zoom', 18));
$aPlace = $oPlaceLookup->lookup((int)$aLookup['place_id'],
$aLookup['type'], $aLookup['fraction']);
-}
-else if ($sOutputFormat != 'html')
-{
+} else if ($sOutputFormat != 'html') {
userError("Need coordinates or OSM object to lookup.");
}
-if ($aPlace)
-{
+if ($aPlace) {
$oPlaceLookup->setIncludePolygonAsPoints(false);
$oPlaceLookup->setIncludePolygonAsText($bAsText);
$oPlaceLookup->setIncludePolygonAsGeoJSON($bAsGeoJSON);
$aPlace['lon'], $aPlace['lat'],
$fRadius);
- if ($aOutlineResult)
- {
+ if ($aOutlineResult) {
$aPlace = array_merge($aPlace, $aOutlineResult);
}
}
-if (CONST_Debug)
-{
+if (CONST_Debug) {
var_dump($aPlace);
exit;
}
-if ($sOutputFormat=='html')
-{
+if ($sOutputFormat=='html') {
$sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1"));
$sTileURL = CONST_Map_Tile_URL;
$sTileAttribution = CONST_Map_Tile_Attribution;
|| isset($aLangPrefOrder['name:de'])
|| isset($aLangPrefOrder['name:ru'])
|| isset($aLangPrefOrder['name:ja'])
- || isset($aLangPrefOrder['name:pl']))
-{
+ || isset($aLangPrefOrder['name:pl'])
+) {
$oGeocode->setReverseInPlan(true);
}
$sOutputFormat = $oParams->getSet('format', array('html', 'xml', 'json', 'jsonv2'), 'html');
// Show / use polygons
-if ($sOutputFormat == 'html')
-{
+if ($sOutputFormat == 'html') {
$oGeocode->setIncludePolygonAsText($oParams->getBool('polygon'));
$bAsText = false;
-}
-else
-{
+} else {
$bAsPoints = $oParams->getBool('polygon');
$bAsGeoJSON = $oParams->getBool('polygon_geojson');
$bAsKML = $oParams->getBool('polygon_kml');
$bAsSVG = $oParams->getBool('polygon_svg');
$bAsText = $oParams->getBool('polygon_text');
- if ( ( ($bAsGeoJSON?1:0)
+ if (( ($bAsGeoJSON?1:0)
+ ($bAsKML?1:0)
+ ($bAsSVG?1:0)
+ ($bAsText?1:0)
+ ($bAsPoints?1:0)
- ) > CONST_PolygonOutput_MaximumTypes)
- {
- if (CONST_PolygonOutput_MaximumTypes)
- {
+ ) > CONST_PolygonOutput_MaximumTypes
+ ) {
+ if (CONST_PolygonOutput_MaximumTypes) {
userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
- }
- else
- {
+ } else {
userError("Polygon output is disabled");
}
exit;
$oGeocode->loadParamArray($oParams);
-if (CONST_Search_BatchMode && isset($_GET['batch']))
-{
+if (CONST_Search_BatchMode && isset($_GET['batch'])) {
$aBatch = json_decode($_GET['batch'], true);
$aBatchResults = array();
- foreach($aBatch as $aBatchParams)
- {
+ foreach ($aBatch as $aBatchParams) {
$oBatchGeocode = clone $oGeocode;
$oBatchParams = new ParameterParser($aBatchParams);
$oBatchGeocode->loadParamArray($oBatchParams);
$oGeocode->setQueryFromParams($oParams);
if (!$oGeocode->getQueryString()
- && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
-{
+ && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/') {
$sQuery = substr(rawurldecode($_SERVER['PATH_INFO']), 1);
// reverse order of '/' separated string
$aSearchResults = $oGeocode->lookup();
if ($aSearchResults === false) $aSearchResults = array();
-if ($sOutputFormat=='html')
-{
+if ($sOutputFormat=='html') {
$sDataDate = chksql($oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1"));
}
logEnd($oDB, $hLog, sizeof($aSearchResults));
}
$oDB =& DB::connect(CONST_Database_DSN, false);
-if (!$oDB || PEAR::isError($oDB))
-{
+if (!$oDB || PEAR::isError($oDB)) {
statusError("No database");
}
$sStandardWord = $oDB->getOne("select make_standard_name('a')");
-if (PEAR::isError($sStandardWord))
-{
+if (PEAR::isError($sStandardWord)) {
statusError("Module failed");
}
-if ($sStandardWord != 'a')
-{
+if ($sStandardWord != 'a') {
statusError("Module call failed");
}
$iWordID = $oDB->getOne("select word_id,word_token, word, class, type, country_code, operator, search_name_count from word where word_token in (' a')");
-if (PEAR::isError($iWordID))
-{
+if (PEAR::isError($iWordID)) {
statusError("Query failed");
}
-if (!$iWordID)
-{
+if (!$iWordID) {
statusError("No value");
}