Merge pull request #524 from mtmail/PSR2-function-declarations

fix function declaration errors according to PSR2 coding style guide
This commit is contained in:
Sarah Hoffmann
2016-09-11 12:07:35 +02:00
committed by GitHub
28 changed files with 340 additions and 245 deletions

View File

@@ -207,12 +207,12 @@ class Geocode
function loadParamArray($oParams) function loadParamArray($oParams)
{ {
$this->bIncludeAddressDetails = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails
$this->bIncludeAddressDetails); = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
$this->bIncludeExtraTags = $oParams->getBool('extratags', $this->bIncludeExtraTags
$this->bIncludeExtraTags); = $oParams->getBool('extratags', $this->bIncludeExtraTags);
$this->bIncludeNameDetails = $oParams->getBool('namedetails', $this->bIncludeNameDetails
$this->bIncludeNameDetails); = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
$this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch); $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
$this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe); $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
@@ -279,13 +279,15 @@ class Geocode
// Search query // Search query
$sQuery = $oParams->getString('q'); $sQuery = $oParams->getString('q');
if (!$sQuery) { if (!$sQuery) {
$this->setStructuredQuery($oParams->getString('amenity'), $this->setStructuredQuery(
$oParams->getString('street'), $oParams->getString('amenity'),
$oParams->getString('city'), $oParams->getString('street'),
$oParams->getString('county'), $oParams->getString('city'),
$oParams->getString('state'), $oParams->getString('county'),
$oParams->getString('country'), $oParams->getString('state'),
$oParams->getString('postalcode')); $oParams->getString('country'),
$oParams->getString('postalcode')
);
$this->setReverseInPlan(false); $this->setReverseInPlan(false);
} else { } else {
$this->setQuery($sQuery); $this->setQuery($sQuery);
@@ -322,7 +324,7 @@ class Geocode
$this->loadStructuredAddressElement($sCity, 'city', 14, 24, false); $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
$this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false); $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
$this->loadStructuredAddressElement($sState, 'state', 8, 8, false); $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
$this->loadStructuredAddressElement($sPostalCode, 'postalcode' , 5, 11, array(5, 11)); $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
$this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false); $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
if (sizeof($this->aStructuredQuery) > 0) { if (sizeof($this->aStructuredQuery) > 0) {
@@ -359,7 +361,7 @@ class Geocode
//$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1 //$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))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
// Get the details for display (is this a redundant extra step?) // Get the details for display (is this a redundant extra step?)
$sPlaceIDs = join(',', array_keys($aPlaceIDs)); $sPlaceIDs = join(',', array_keys($aPlaceIDs));
@@ -381,7 +383,7 @@ class Geocode
$sSQL .= "from placex where place_id in ($sPlaceIDs) "; $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
$sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank "; $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'"; 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 ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
$sSQL .= ") "; $sSQL .= ") ";
if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList "; if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
$sSQL .= "and linked_place_id is null "; $sSQL .= "and linked_place_id is null ";
@@ -476,8 +478,10 @@ class Geocode
if (CONST_Debug) { if (CONST_Debug) {
echo "<hr>"; var_dump($sSQL); echo "<hr>"; var_dump($sSQL);
} }
$aSearchResults = chksql($this->oDB->getAll($sSQL), $aSearchResults = chksql(
"Could not get details for place."); $this->oDB->getAll($sSQL),
"Could not get details for place."
);
return $aSearchResults; return $aSearchResults;
} }
@@ -624,8 +628,8 @@ class Geocode
if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch; if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) { foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
if (empty($aSearchTermToken['country_code']) if (empty($aSearchTermToken['country_code'])
&& empty($aSearchTermToken['lat']) && empty($aSearchTermToken['lat'])
&& empty($aSearchTermToken['class']) && empty($aSearchTermToken['class'])
) { ) {
$aSearch = $aCurrentSearch; $aSearch = $aCurrentSearch;
$aSearch['iSearchRank'] += 1; $aSearch['iSearchRank'] += 1;
@@ -738,7 +742,7 @@ class Geocode
{ {
if (!$this->sQuery && !$this->aStructuredQuery) return false; if (!$this->sQuery && !$this->aStructuredQuery) return false;
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
$sCountryCodesSQL = false; $sCountryCodesSQL = false;
if ($this->aCountryCodes) { if ($this->aCountryCodes) {
$sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes)); $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
@@ -748,20 +752,24 @@ class Geocode
// Conflicts between US state abreviations and various words for 'the' in different languages // 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*il\s*(,|$)/', '\1illinois\2', $sQuery);
$sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery); $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
$sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery); $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
} }
$bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL; $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
if ($this->sViewboxCentreSQL) { if ($this->sViewboxCentreSQL) {
// For complex viewboxes (routes) precompute the bounding geometry // For complex viewboxes (routes) precompute the bounding geometry
$sGeom = chksql($this->oDB->getOne("select ".$this->sViewboxSmallSQL), $sGeom = chksql(
"Could not get small viewbox"); $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
"Could not get small viewbox"
);
$this->sViewboxSmallSQL = "'".$sGeom."'::geometry"; $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
$sGeom = chksql($this->oDB->getOne("select ".$this->sViewboxLargeSQL), $sGeom = chksql(
"Could not get large viewbox"); $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
"Could not get large viewbox"
);
$this->sViewboxLargeSQL = "'".$sGeom."'::geometry"; $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
} }
@@ -853,7 +861,7 @@ class Geocode
$aPhrases = $this->aStructuredQuery; $aPhrases = $this->aStructuredQuery;
$bStructuredPhrases = true; $bStructuredPhrases = true;
} else { } else {
$aPhrases = explode(',',$sQuery); $aPhrases = explode(',', $sQuery);
$bStructuredPhrases = false; $bStructuredPhrases = false;
} }
@@ -863,11 +871,13 @@ class Geocode
// Generate a complete list of all // Generate a complete list of all
$aTokens = array(); $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"), $aPhrase = chksql(
"Cannot nomralize query string (is it an UTF-8 string?)"); $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] = $aPhrase;
$aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']); $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
$aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0); $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
$aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets'])); $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
} else { } else {
@@ -882,14 +892,16 @@ class Geocode
if (sizeof($aTokens)) { if (sizeof($aTokens)) {
// Check which tokens we have, get the ID numbers // 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 = '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)).')'; $sSQL .= ' from word where word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
if (CONST_Debug) var_Dump($sSQL); if (CONST_Debug) var_Dump($sSQL);
$aValidTokens = array(); $aValidTokens = array();
if (sizeof($aTokens)) { if (sizeof($aTokens)) {
$aDatabaseWords = chksql($this->oDB->getAll($sSQL), $aDatabaseWords = chksql(
"Could not get word tokens."); $this->oDB->getAll($sSQL),
"Could not get word tokens."
);
} else { } else {
$aDatabaseWords = array(); $aDatabaseWords = array();
} }
@@ -917,15 +929,15 @@ class Geocode
foreach ($aTokens as $sToken) { foreach ($aTokens as $sToken) {
// Source of gb postcodes is now definitive - always use // 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 (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 (substr($aData[1], -2, 1) != ' ') {
$aData[0] = substr($aData[0],0,strlen($aData[1])-1).' '.substr($aData[0],strlen($aData[1])-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); $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
} }
$aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB); $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
if ($aGBPostcodeLocation) { if ($aGBPostcodeLocation) {
$aValidTokens[$sToken] = $aGBPostcodeLocation; $aValidTokens[$sToken] = $aGBPostcodeLocation;
} }
} else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) { } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
// US ZIP+4 codes - if there is no token, // US ZIP+4 codes - if there is no token,
// merge in the 5-digit ZIP code // merge in the 5-digit ZIP code
if (isset($aValidTokens[$aData[1]])) { if (isset($aValidTokens[$aData[1]])) {
@@ -944,7 +956,7 @@ class Geocode
foreach ($aTokens as $sToken) { foreach ($aTokens as $sToken) {
// Unknown single word token with a number - assume it is a house number // 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')); $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
} }
} }
@@ -1077,7 +1089,7 @@ class Geocode
$sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)"; $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)"; 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).")"; $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
} }
if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc"; if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
$sSQL .= " limit $this->iLimit"; $sSQL .= " limit $this->iLimit";
@@ -1108,7 +1120,7 @@ class Geocode
$aPlaceIDs = chksql($this->oDB->getCol($sSQL)); $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
} }
} }
} else if ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) { } elseif ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
// If a coordinate is given, the search must either // If a coordinate is given, the search must either
// be for a name or a special search. Ignore everythin else. // be for a name or a special search. Ignore everythin else.
$aPlaceIDs = array(); $aPlaceIDs = array();
@@ -1132,19 +1144,19 @@ class Geocode
// TODO: filter out the pointless search terms (2 letter name tokens and less) // TODO: filter out the pointless search terms (2 letter name tokens and less)
// they might be right - but they are just too darned expensive to run // 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['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['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 // For infrequent name terms disable index usage for address
if (CONST_Search_NameOnlySearchFrequencyThreshold && if (CONST_Search_NameOnlySearchFrequencyThreshold
sizeof($aSearch['aName']) == 1 && && 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']),",")."]"; $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
} else { } else {
$aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]"; $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
if (sizeof($aSearch['aAddressNonSearch'])) { if (sizeof($aSearch['aAddressNonSearch'])) {
$aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]"; $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
} }
} }
} }
@@ -1164,7 +1176,7 @@ class Geocode
$aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC"; $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).")"; $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
} }
if ($sCountryCodesSQL) { if ($sCountryCodesSQL) {
$aTerms[] = "country_code in ($sCountryCodesSQL)"; $aTerms[] = "country_code in ($sCountryCodesSQL)";
@@ -1183,7 +1195,7 @@ class Geocode
$aOrder[] = "$sImportanceSQL DESC"; $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'; $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
$aOrder[] = 'exactmatch DESC'; $aOrder[] = 'exactmatch DESC';
} else { } else {
$sExactMatchSQL = '0::int as exactmatch'; $sExactMatchSQL = '0::int as exactmatch';
@@ -1193,8 +1205,8 @@ class Geocode
$sSQL = "select place_id, "; $sSQL = "select place_id, ";
$sSQL .= $sExactMatchSQL; $sSQL .= $sExactMatchSQL;
$sSQL .= " from search_name"; $sSQL .= " from search_name";
$sSQL .= " where ".join(' and ',$aTerms); $sSQL .= " where ".join(' and ', $aTerms);
$sSQL .= " order by ".join(', ',$aOrder); $sSQL .= " order by ".join(', ', $aOrder);
if ($aSearch['sHouseNumber'] || $aSearch['sClass']) { if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
$sSQL .= " limit 20"; $sSQL .= " limit 20";
} elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) { } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
@@ -1204,8 +1216,10 @@ class Geocode
} }
if (CONST_Debug) var_dump($sSQL); if (CONST_Debug) var_dump($sSQL);
$aViewBoxPlaceIDs = chksql($this->oDB->getAll($sSQL), $aViewBoxPlaceIDs = chksql(
"Could not get places for search terms."); $this->oDB->getAll($sSQL),
"Could not get places for search terms."
);
//var_dump($aViewBoxPlaceIDs); //var_dump($aViewBoxPlaceIDs);
// Did we have an viewbox matches? // Did we have an viewbox matches?
$aPlaceIDs = array(); $aPlaceIDs = array();
@@ -1226,13 +1240,13 @@ class Geocode
if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) { if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
$searchedHousenumber = intval($aSearch['sHouseNumber']); $searchedHousenumber = intval($aSearch['sHouseNumber']);
$aRoadPlaceIDs = $aPlaceIDs; $aRoadPlaceIDs = $aPlaceIDs;
$sPlaceIDs = join(',',$aPlaceIDs); $sPlaceIDs = join(',', $aPlaceIDs);
// Now they are indexed, look for a house attached to a street we found // Now they are indexed, look for a house attached to a street we found
$sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M'; $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
$sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'"; $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 .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
} }
$sSQL .= " limit $this->iLimit"; $sSQL .= " limit $this->iLimit";
if (CONST_Debug) var_dump($sSQL); if (CONST_Debug) var_dump($sSQL);
@@ -1263,7 +1277,7 @@ class Geocode
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'])."'"; $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 .= " and parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
} }
//$sSQL .= " limit $this->iLimit"; //$sSQL .= " limit $this->iLimit";
if (CONST_Debug) var_dump($sSQL); if (CONST_Debug) var_dump($sSQL);
@@ -1339,7 +1353,7 @@ class Geocode
$sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank"; $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
if (CONST_Debug) var_dump($sSQL); if (CONST_Debug) var_dump($sSQL);
$aPlaceIDs = chksql($this->oDB->getCol($sSQL)); $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
$sPlaceIDs = join(',',$aPlaceIDs); $sPlaceIDs = join(',', $aPlaceIDs);
} }
if ($sPlaceIDs || $sPlaceGeom) { if ($sPlaceIDs || $sPlaceGeom) {
@@ -1350,8 +1364,8 @@ class Geocode
$sOrderBySQL = ''; $sOrderBySQL = '';
if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)"; if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)"; elseif ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)"; elseif ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
$sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l"; $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 ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
@@ -1364,7 +1378,7 @@ class Geocode
$sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) "; $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
} }
if (sizeof($this->aExcludePlaceIDs)) { if (sizeof($this->aExcludePlaceIDs)) {
$sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")"; $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
} }
if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)"; if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc"; if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
@@ -1383,7 +1397,7 @@ class Geocode
$sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) "; $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']."' "; $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).")"; $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
} }
if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)"; if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc"; if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
@@ -1413,16 +1427,16 @@ class Geocode
// Need to verify passes rank limits before dropping out of the loop (yuk!) // Need to verify passes rank limits before dropping out of the loop (yuk!)
// reduces the number of place ids, like a filter // reduces the number of place ids, like a filter
// rank_address is 30 for interpolated housenumbers // rank_address is 30 for interpolated housenumbers
$sSQL = "select place_id from placex where place_id in (".join(',',array_keys($aResultPlaceIDs)).") "; $sSQL = "select place_id from placex where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
$sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank "; $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'"; 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 ($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 .= ") 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 "; $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")"; if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
} }
$sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',',array_keys($aResultPlaceIDs)).")"; $sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
$sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)"; $sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
if (CONST_Debug) var_dump($sSQL); if (CONST_Debug) var_dump($sSQL);
$aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL)); $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
@@ -1448,9 +1462,11 @@ class Geocode
$oReverse = new ReverseGeocode($this->oDB); $oReverse = new ReverseGeocode($this->oDB);
$oReverse->setZoom(18); $oReverse->setZoom(18);
$aLookup = $oReverse->lookup((float)$this->aNearPoint[0], $aLookup = $oReverse->lookup(
(float)$this->aNearPoint[1], (float)$this->aNearPoint[0],
false); (float)$this->aNearPoint[1],
false
);
if (CONST_Debug) var_dump("Reverse search", $aLookup); if (CONST_Debug) var_dump("Reverse search", $aLookup);
@@ -1473,7 +1489,7 @@ class Geocode
} }
$aClassType = getClassTypesWithImportance(); $aClassType = getClassTypesWithImportance();
$aRecheckWords = preg_split('/\b[\s,\\-]*/u',$sQuery); $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 (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
} }
@@ -1507,17 +1523,17 @@ class Geocode
// Is there an icon set for this type of result? // Is there an icon set for this type of result?
if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 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'; $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']) 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']; $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
} elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
&& $aClassType[$aResult['class'].':'.$aResult['type']]['label'] && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
) { ) {
$aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label']; $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
} }
@@ -1547,7 +1563,7 @@ class Geocode
} }
// Adjust importance for the number of exact string matches in the result // Adjust importance for the number of exact string matches in the result
$aResult['importance'] = max(0.001,$aResult['importance']); $aResult['importance'] = max(0.001, $aResult['importance']);
$iCountWords = 0; $iCountWords = 0;
$sAddress = $aResult['langaddress']; $sAddress = $aResult['langaddress'];
foreach ($aRecheckWords as $i => $sWord) { foreach ($aRecheckWords as $i => $sWord) {
@@ -1566,7 +1582,7 @@ class Geocode
// - number of exact matches from the query // - 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']]; $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
} else if (isset($this->exactMatchCache[$aResult['parent_place_id']])) { } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
$aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']]; $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
} }
// - importance of the class/type // - importance of the class/type
@@ -1597,7 +1613,7 @@ class Geocode
$bFirst = false; $bFirst = false;
} }
if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']]) 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; $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
$aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true; $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;

View File

@@ -4,12 +4,12 @@ class ParameterParser
{ {
private $aParams; private $aParams;
function __construct($aParams=NULL) function __construct($aParams = NULL)
{ {
$this->aParams = ($aParams === NULL) ? $_GET : $aParams; $this->aParams = ($aParams === NULL) ? $_GET : $aParams;
} }
function getBool($sName, $bDefault=false) function getBool($sName, $bDefault = false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) { if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault; return $bDefault;
@@ -18,7 +18,7 @@ class ParameterParser
return (bool) $this->aParams[$sName]; return (bool) $this->aParams[$sName];
} }
function getInt($sName, $bDefault=false) function getInt($sName, $bDefault = false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) { if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault; return $bDefault;
@@ -31,7 +31,7 @@ class ParameterParser
return (int) $this->aParams[$sName]; return (int) $this->aParams[$sName];
} }
function getFloat($sName, $bDefault=false) function getFloat($sName, $bDefault = false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) { if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault; return $bDefault;
@@ -44,7 +44,7 @@ class ParameterParser
return (float) $this->aParams[$sName]; return (float) $this->aParams[$sName];
} }
function getString($sName, $bDefault=false) function getString($sName, $bDefault = false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) { if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $bDefault; return $bDefault;
@@ -53,7 +53,7 @@ class ParameterParser
return $this->aParams[$sName]; return $this->aParams[$sName];
} }
function getSet($sName, $aValues, $sDefault=false) function getSet($sName, $aValues, $sDefault = false)
{ {
if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) { if (!isset($this->aParams[$sName]) || strlen($this->aParams[$sName]) == 0) {
return $sDefault; return $sDefault;
@@ -66,7 +66,7 @@ class ParameterParser
return $this->aParams[$sName]; return $this->aParams[$sName];
} }
function getStringList($sName, $aDefault=false) function getStringList($sName, $aDefault = false)
{ {
$sValue = $this->getString($sName); $sValue = $this->getString($sName);
@@ -77,7 +77,7 @@ class ParameterParser
return $aDefault; return $aDefault;
} }
function getPreferredLanguages($sFallback=NULL) function getPreferredLanguages($sFallback = NULL)
{ {
if ($sFallback === NULL && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) { if ($sFallback === NULL && isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
$sFallback = $_SERVER["HTTP_ACCEPT_LANGUAGE"]; $sFallback = $_SERVER["HTTP_ACCEPT_LANGUAGE"];

View File

@@ -96,7 +96,7 @@ class PlaceLookup
{ {
if (!$iPlaceID) return null; if (!$iPlaceID) return null;
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
$bIsTiger = CONST_Use_US_Tiger_Data && $sType == 'tiger'; $bIsTiger = CONST_Use_US_Tiger_Data && $sType == 'tiger';
$bIsInterpolation = $sType == 'interpolation'; $bIsInterpolation = $sType == 'interpolation';
@@ -116,7 +116,7 @@ class PlaceLookup
$sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int"; $sSQL .= " WHEN interpolationtype='all' THEN (".$fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
$sSQL .= " END as housenumber"; $sSQL .= " END as housenumber";
$sSQL .= " from location_property_tiger where place_id = ".$iPlaceID.") as blub1) as blub2"; $sSQL .= " from location_property_tiger where place_id = ".$iPlaceID.") as blub1) as blub2";
} else if ($bIsInterpolation) { } elseif ($bIsInterpolation) {
$sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,"; $sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,";
$sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,"; $sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
$sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, "; $sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, ";
@@ -155,8 +155,7 @@ class PlaceLookup
if ($this->bAddressDetails) { if ($this->bAddressDetails) {
// to get addressdetails for tiger data, the housenumber is needed // to get addressdetails for tiger data, the housenumber is needed
$iHousenumber = ($bIsTiger || $bIsInterpolation) ? $aPlace['housenumber'] : -1; $iHousenumber = ($bIsTiger || $bIsInterpolation) ? $aPlace['housenumber'] : -1;
$aPlace['aAddress'] = $this->getAddressNames($aPlace['place_id'], $aPlace['aAddress'] = $this->getAddressNames($aPlace['place_id'], $iHousenumber);
$iHousenumber);
} }
if ($this->bExtraTags) { if ($this->bExtraTags) {
@@ -194,7 +193,7 @@ class PlaceLookup
function getAddressDetails($iPlaceID, $bAll = false, $housenumber = -1) function getAddressDetails($iPlaceID, $bAll = false, $housenumber = -1)
{ {
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
$sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$iPlaceID.",".$housenumber.")"; $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$iPlaceID.",".$housenumber.")";
if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'"; if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'";
@@ -226,7 +225,7 @@ class PlaceLookup
} }
if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) { if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
$sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']); $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
$sTypeLabel = str_replace(' ','_',$sTypeLabel); $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') { if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
$aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber']; $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
} }
@@ -247,7 +246,7 @@ class PlaceLookup
// astext // astext
// lat // lat
// lon // lon
function getOutlines($iPlaceID, $fLon=null, $fLat=null, $fRadius=null) function getOutlines($iPlaceID, $fLon = null, $fLat = null, $fRadius = null)
{ {
$aOutlineResult = array(); $aOutlineResult = array();
@@ -270,8 +269,7 @@ class PlaceLookup
$sSQL .= $sFrom; $sSQL .= $sFrom;
} }
$aPointPolygon = chksql($this->oDB->getRow($sSQL), $aPointPolygon = chksql($this->oDB->getRow($sSQL), "Could not get outline");
"Could not get outline");
if ($aPointPolygon['place_id']) { if ($aPointPolygon['place_id']) {
if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) { if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {

View File

@@ -78,8 +78,10 @@ class ReverseGeocode
$sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))'; $sSQL .= ' OR ST_DWithin('.$sPointSQL.', centroid, '.$fSearchDiam.'))';
$sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1'; $sSQL .= ' ORDER BY ST_distance('.$sPointSQL.', geometry) ASC limit 1';
if (CONST_Debug) var_dump($sSQL); if (CONST_Debug) var_dump($sSQL);
$aPlace = chksql($this->oDB->getRow($sSQL), $aPlace = chksql(
"Could not determine closest place."); $this->oDB->getRow($sSQL),
"Could not determine closest place."
);
$iPlaceID = $aPlace['place_id']; $iPlaceID = $aPlace['place_id'];
$iParentPlaceID = $aPlace['parent_place_id']; $iParentPlaceID = $aPlace['parent_place_id'];
$bIsInUnitedStates = ($aPlace['calculated_country_code'] == 'us'); $bIsInUnitedStates = ($aPlace['calculated_country_code'] == 'us');
@@ -102,8 +104,10 @@ class ReverseGeocode
echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n"; echo $i['housenumber'] . ' | ' . $i['distance'] * 1000 . ' | ' . $i['lat'] . ' | ' . $i['lon']. ' | '. "<br>\n";
} }
} }
$aPlaceLine = chksql($this->oDB->getRow($sSQL), $aPlaceLine = chksql(
"Could not determine closest housenumber on an osm interpolation line."); $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 (CONST_Debug) var_dump('found housenumber in interpolation lines table', $aPlaceLine);
if ($aPlace['rank_search'] == 30) { if ($aPlace['rank_search'] == 30) {
@@ -111,14 +115,18 @@ class ReverseGeocode
// if the placex house or the interpolated house are closer to the searched point // if the placex house or the interpolated house are closer to the searched point
// distance between point and placex house // distance between point and placex house
$sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID; $sSQL = 'SELECT ST_distance('.$sPointSQL.', house.geometry) as distance FROM placex as house WHERE house.place_id='.$iPlaceID;
$aDistancePlacex = chksql($this->oDB->getRow($sSQL), $aDistancePlacex = chksql(
"Could not determine distance between searched point and placex house."); $this->oDB->getRow($sSQL),
"Could not determine distance between searched point and placex house."
);
$fDistancePlacex = $aDistancePlacex['distance']; $fDistancePlacex = $aDistancePlacex['distance'];
// distance between point and interpolated house (fraction on interpolation line) // distance between point and interpolated house (fraction on interpolation line)
$sSQL = 'SELECT ST_distance('.$sPointSQL.', ST_LineInterpolatePoint(linegeo, '.$aPlaceLine['fraction'].')) as distance'; $sSQL = 'SELECT ST_distance('.$sPointSQL.', ST_LineInterpolatePoint(linegeo, '.$aPlaceLine['fraction'].')) as distance';
$sSQL .= ' FROM location_property_osmline WHERE place_id = '.$aPlaceLine['place_id']; $sSQL .= ' FROM location_property_osmline WHERE place_id = '.$aPlaceLine['place_id'];
$aDistanceInterpolation = chksql($this->oDB->getRow($sSQL), $aDistanceInterpolation = chksql(
"Could not determine distance between searched point and interpolated house."); $this->oDB->getRow($sSQL),
"Could not determine distance between searched point and interpolated house."
);
$fDistanceInterpolation = $aDistanceInterpolation['distance']; $fDistanceInterpolation = $aDistanceInterpolation['distance'];
if ($fDistanceInterpolation < $fDistancePlacex) { if ($fDistanceInterpolation < $fDistancePlacex) {
// interpolation is closer to point than placex house // interpolation is closer to point than placex house
@@ -160,8 +168,10 @@ class ReverseGeocode
} }
} }
$aPlaceTiger = chksql($this->oDB->getRow($sSQL), $aPlaceTiger = chksql(
"Could not determine closest Tiger place."); $this->oDB->getRow($sSQL),
"Could not determine closest Tiger place."
);
if ($aPlaceTiger) { if ($aPlaceTiger) {
if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger); if (CONST_Debug) var_dump('found Tiger housenumber', $aPlaceTiger);
$bPlaceIsTiger = true; $bPlaceIsTiger = true;
@@ -183,8 +193,7 @@ class ReverseGeocode
$sSQL .= " WHERE place_id = $iPlaceID"; $sSQL .= " WHERE place_id = $iPlaceID";
$sSQL .= " ORDER BY abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc"; $sSQL .= " ORDER BY abs(cached_rank_address - $iMaxRank) asc,cached_rank_address desc,isaddress desc,distance desc";
$sSQL .= ' LIMIT 1'; $sSQL .= ' LIMIT 1';
$iPlaceID = chksql($this->oDB->getOne($sSQL), $iPlaceID = chksql($this->oDB->getOne($sSQL), "Could not get parent for place.");
"Could not get parent for place.");
if (!$iPlaceID) { if (!$iPlaceID) {
$iPlaceID = $aPlace['place_id']; $iPlaceID = $aPlace['place_id'];
} }

View File

@@ -109,8 +109,8 @@ function showUsage($aSpec, $bExit = false, $sError = false)
$aNames = array(); $aNames = array();
if ($aLine[1]) $aNames[] = '-'.$aLine[1]; if ($aLine[1]) $aNames[] = '-'.$aLine[1];
if ($aLine[0]) $aNames[] = '--'.$aLine[0]; if ($aLine[0]) $aNames[] = '--'.$aLine[0];
$sName = join(', ',$aNames); $sName = join(', ', $aNames);
echo ' '.$sName.str_repeat(' ',30-strlen($sName)).$aLine[7]."\n"; echo ' '.$sName.str_repeat(' ', 30-strlen($sName)).$aLine[7]."\n";
} else { } else {
echo $aLine."\n"; echo $aLine."\n";
} }

View File

@@ -5,8 +5,10 @@ require_once('DB.php');
function &getDB($bNew = false, $bPersistent = false) function &getDB($bNew = false, $bPersistent = false)
{ {
// Get the database object // Get the database object
$oDB = chksql(DB::connect(CONST_Database_DSN.($bNew?'?new_link=true':''), $bPersistent), $oDB = chksql(
"Failed to establish database connection"); DB::connect(CONST_Database_DSN.($bNew?'?new_link=true':''), $bPersistent),
"Failed to establish database connection"
);
$oDB->setFetchMode(DB_FETCHMODE_ASSOC); $oDB->setFetchMode(DB_FETCHMODE_ASSOC);
$oDB->query("SET DateStyle TO 'sql,european'"); $oDB->query("SET DateStyle TO 'sql,european'");
$oDB->query("SET client_encoding TO 'utf-8'"); $oDB->query("SET client_encoding TO 'utf-8'");

View File

@@ -52,7 +52,7 @@ function byImportance($a, $b)
function getWordSets($aWords, $iDepth) function getWordSets($aWords, $iDepth)
{ {
$aResult = array(array(join(' ',$aWords))); $aResult = array(array(join(' ', $aWords)));
$sFirstToken = ''; $sFirstToken = '';
if ($iDepth < 8) { if ($iDepth < 8) {
while (sizeof($aWords) > 1) { while (sizeof($aWords) > 1) {
@@ -60,7 +60,7 @@ function getWordSets($aWords, $iDepth)
$sFirstToken .= ($sFirstToken?' ':'').$sWord; $sFirstToken .= ($sFirstToken?' ':'').$sWord;
$aRest = getWordSets($aWords, $iDepth+1); $aRest = getWordSets($aWords, $iDepth+1);
foreach ($aRest as $aSet) { foreach ($aRest as $aSet) {
$aResult[] = array_merge(array($sFirstToken),$aSet); $aResult[] = array_merge(array($sFirstToken), $aSet);
} }
} }
} }
@@ -69,7 +69,7 @@ function getWordSets($aWords, $iDepth)
function getInverseWordSets($aWords, $iDepth) function getInverseWordSets($aWords, $iDepth)
{ {
$aResult = array(array(join(' ',$aWords))); $aResult = array(array(join(' ', $aWords)));
$sFirstToken = ''; $sFirstToken = '';
if ($iDepth < 8) { if ($iDepth < 8) {
while (sizeof($aWords) > 1) { while (sizeof($aWords) > 1) {
@@ -77,7 +77,7 @@ function getInverseWordSets($aWords, $iDepth)
$sFirstToken = $sWord.($sFirstToken?' ':'').$sFirstToken; $sFirstToken = $sWord.($sFirstToken?' ':'').$sFirstToken;
$aRest = getInverseWordSets($aWords, $iDepth+1); $aRest = getInverseWordSets($aWords, $iDepth+1);
foreach ($aRest as $aSet) { foreach ($aRest as $aSet) {
$aResult[] = array_merge(array($sFirstToken),$aSet); $aResult[] = array_merge(array($sFirstToken), $aSet);
} }
} }
} }
@@ -453,9 +453,9 @@ function getResultDiameter($aResult)
) { ) {
$fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']; $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
} elseif (isset($aResult['class']) } elseif (isset($aResult['class'])
&& isset($aResult['type']) && isset($aResult['type'])
&& isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) && isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
&& $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'] && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']
) { ) {
$fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']; $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
} }
@@ -474,7 +474,7 @@ function javascript_renderData($xVal, $iOptions = 0)
header("Content-Type: application/json; charset=UTF-8"); header("Content-Type: application/json; charset=UTF-8");
echo $jsonout; echo $jsonout;
} else { } else {
if (preg_match('/^[$_\p{L}][$_\p{L}\p{Nd}.[\]]*$/u',$_GET['json_callback'])) { if (preg_match('/^[$_\p{L}][$_\p{L}\p{Nd}.[\]]*$/u', $_GET['json_callback'])) {
header("Content-Type: application/javascript; charset=UTF-8"); header("Content-Type: application/javascript; charset=UTF-8");
echo $_GET['json_callback'].'('.$jsonout.')'; echo $_GET['json_callback'].'('.$jsonout.')';
} else { } else {
@@ -583,7 +583,7 @@ function getAddressDetails(&$oDB, $sLanguagePrefArraySQL, $iPlaceID, $sCountryCo
} }
if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) { if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber']))) {
$sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']); $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
$sTypeLabel = str_replace(' ','_',$sTypeLabel); $sTypeLabel = str_replace(' ', '_', $sTypeLabel);
if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') { if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place') {
$aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber']; $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
} }
@@ -600,7 +600,7 @@ function addQuotes($s)
} }
// returns boolean // returns boolean
function validLatLon($fLat,$fLon) function validLatLon($fLat, $fLon)
{ {
return ($fLat <= 90.1 && $fLat >= -90.1 && $fLon <= 180.1 && $fLon >= -180.1); return ($fLat <= 90.1 && $fLat >= -90.1 && $fLon <= 180.1 && $fLon >= -180.1);
} }

View File

@@ -18,7 +18,7 @@ function logStart(&$oDB, $sType = '', $sQuery = '', $aLanguageList = array())
} }
$hLog = array( $hLog = array(
date('Y-m-d H:i:s',$aStartTime[0]).'.'.$aStartTime[1], date('Y-m-d H:i:s', $aStartTime[0]).'.'.$aStartTime[1],
$_SERVER["REMOTE_ADDR"], $_SERVER["REMOTE_ADDR"],
$_SERVER['QUERY_STRING'], $_SERVER['QUERY_STRING'],
$sOutQuery, $sOutQuery,
@@ -36,7 +36,7 @@ function logStart(&$oDB, $sType = '', $sQuery = '', $aLanguageList = array())
else $sUserAgent = ''; else $sUserAgent = '';
$sSQL = 'insert into new_query_log (type,starttime,query,ipaddress,useragent,language,format,searchterm)'; $sSQL = 'insert into new_query_log (type,starttime,query,ipaddress,useragent,language,format,searchterm)';
$sSQL .= ' values ('.getDBQuoted($sType).','.getDBQuoted($hLog[0]).','.getDBQuoted($hLog[2]); $sSQL .= ' values ('.getDBQuoted($sType).','.getDBQuoted($hLog[0]).','.getDBQuoted($hLog[2]);
$sSQL .= ','.getDBQuoted($hLog[1]).','.getDBQuoted($sUserAgent).','.getDBQuoted(join(',',$aLanguageList)).','.getDBQuoted($sOutputFormat).','.getDBQuoted($hLog[3]).')'; $sSQL .= ','.getDBQuoted($hLog[1]).','.getDBQuoted($sUserAgent).','.getDBQuoted(join(',', $aLanguageList)).','.getDBQuoted($sOutputFormat).','.getDBQuoted($hLog[3]).')';
$oDB->query($sSQL); $oDB->query($sSQL);
} }
@@ -50,7 +50,7 @@ function logEnd(&$oDB, $hLog, $iNumResults)
if (CONST_Log_DB) { if (CONST_Log_DB) {
$aEndTime = explode('.', $fEndTime); $aEndTime = explode('.', $fEndTime);
if (!$aEndTime[1]) $aEndTime[1] = '0'; if (!$aEndTime[1]) $aEndTime[1] = '0';
$sEndTime = date('Y-m-d H:i:s',$aEndTime[0]).'.'.$aEndTime[1]; $sEndTime = date('Y-m-d H:i:s', $aEndTime[0]).'.'.$aEndTime[1];
$sSQL = 'update new_query_log set endtime = '.getDBQuoted($sEndTime).', results = '.$iNumResults; $sSQL = 'update new_query_log set endtime = '.getDBQuoted($sEndTime).', results = '.$iNumResults;
$sSQL .= ' where starttime = '.getDBQuoted($hLog[0]); $sSQL .= ' where starttime = '.getDBQuoted($hLog[0]);
@@ -60,9 +60,14 @@ function logEnd(&$oDB, $hLog, $iNumResults)
} }
if (CONST_Log_File) { if (CONST_Log_File) {
$aOutdata = sprintf("[%s] %.4f %d %s \"%s\"\n", $aOutdata = sprintf(
$hLog[0], $fEndTime-$hLog[5], $iNumResults, "[%s] %.4f %d %s \"%s\"\n",
$hLog[4], $hLog[2]); $hLog[0],
$fEndTime-$hLog[5],
$iNumResults,
$hLog[4],
$hLog[2]
);
file_put_contents(CONST_Log_File, $aOutdata, FILE_APPEND | LOCK_EX); file_put_contents(CONST_Log_File, $aOutdata, FILE_APPEND | LOCK_EX);
} }

View File

@@ -1,6 +1,6 @@
<?php <?php
function formatOSMType($sType, $bIncludeExternal=true) function formatOSMType($sType, $bIncludeExternal = true)
{ {
if ($sType == 'N') return 'node'; if ($sType == 'N') return 'node';
if ($sType == 'W') return 'way'; if ($sType == 'W') return 'way';
@@ -14,7 +14,7 @@ function formatOSMType($sType, $bIncludeExternal=true)
return ''; return '';
} }
function osmLink($aFeature, $sRefText=false) function osmLink($aFeature, $sRefText = false)
{ {
$sOSMType = formatOSMType($aFeature['osm_type'], false); $sOSMType = formatOSMType($aFeature['osm_type'], false);
if ($sOSMType) { if ($sOSMType) {
@@ -26,13 +26,13 @@ function osmLink($aFeature, $sRefText=false)
function wikipediaLink($aFeature) function wikipediaLink($aFeature)
{ {
if ($aFeature['wikipedia']) { if ($aFeature['wikipedia']) {
list($sLanguage, $sArticle) = explode(':',$aFeature['wikipedia']); list($sLanguage, $sArticle) = explode(':', $aFeature['wikipedia']);
return '<a href="https://'.$sLanguage.'.wikipedia.org/wiki/'.urlencode($sArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>'; return '<a href="https://'.$sLanguage.'.wikipedia.org/wiki/'.urlencode($sArticle).'" target="_blank">'.$aFeature['wikipedia'].'</a>';
} }
return ''; return '';
} }
function detailsLink($aFeature, $sTitle=false) function detailsLink($aFeature, $sTitle = false)
{ {
if (!$aFeature['place_id']) return ''; if (!$aFeature['place_id']) return '';

View File

@@ -77,11 +77,6 @@
INDENTATION, SPACING INDENTATION, SPACING
************************************************************** --> ************************************************************** -->
<!-- We use tabs -->
<rule ref="Generic.WhiteSpace.DisallowTabIndent.TabsUsed">
<severity>0</severity>
</rule>
<!-- We don't need 2 blank lines after function --> <!-- We don't need 2 blank lines after function -->
<rule ref="Squiz.WhiteSpace.FunctionSpacing.After"> <rule ref="Squiz.WhiteSpace.FunctionSpacing.After">
<severity>0</severity> <severity>0</severity>

View File

@@ -32,9 +32,15 @@ if ($aResult['list']) {
printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", "Key", "Total Blocks", "Current", "Still Blocked", "Last Block Time", "Sleeping"); printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", "Key", "Total Blocks", "Current", "Still Blocked", "Last Block Time", "Sleeping");
printf(" %'--40s-|-%'-12s-|-%'-7s-|-%'-13s-|-%'-31s-|-%'-8s\n", "", "", "", "", "", ""); printf(" %'--40s-|-%'-12s-|-%'-7s-|-%'-13s-|-%'-31s-|-%'-8s\n", "", "", "", "", "", "");
foreach ($aBlocks as $sKey => $aDetails) { foreach ($aBlocks as $sKey => $aDetails) {
printf(" %-40s | %12s | %7s | %13s | %31s | %8s\n", $sKey, $aDetails['totalBlocks'], printf(
(int)$aDetails['currentBucketSize'], $aDetails['currentlyBlocked']?'Y':'N', " %-40s | %12s | %7s | %13s | %31s | %8s\n",
date("r", $aDetails['lastBlockTimestamp']), $aDetails['isSleeping']?'Y':'N'); $sKey,
$aDetails['totalBlocks'],
(int)$aDetails['currentBucketSize'],
$aDetails['currentlyBlocked']?'Y':'N',
date("r", $aDetails['lastBlockTimestamp']),
$aDetails['isSleeping']?'Y':'N'
);
} }
echo "\n"; echo "\n";
} }

View File

@@ -27,7 +27,7 @@ if (true) {
foreach ($aLanguages as $i => $s) { foreach ($aLanguages as $i => $s) {
$aLanguages[$i] = '"'.pg_escape_string($s).'"'; $aLanguages[$i] = '"'.pg_escape_string($s).'"';
} }
echo "UPDATE country_name set country_default_language_codes = '{".join(',',$aLanguages)."}' where country_code = '".pg_escape_string($aMatch[1])."';\n"; echo "UPDATE country_name set country_default_language_codes = '{".join(',', $aLanguages)."}' where country_code = '".pg_escape_string($aMatch[1])."';\n";
} }
} }
} }

View File

@@ -90,7 +90,7 @@ EOD;
$oDB->query($sSQL); $oDB->query($sSQL);
} }
function degreesAndMinutesToDecimal($iDegrees, $iMinutes=0, $fSeconds=0, $sNSEW='N') function degreesAndMinutesToDecimal($iDegrees, $iMinutes = 0, $fSeconds = 0, $sNSEW = 'N')
{ {
$sNSEW = strtoupper($sNSEW); $sNSEW = strtoupper($sNSEW);
return ($sNSEW == 'S' || $sNSEW == 'W'?-1:1) * ((float)$iDegrees + (float)$iMinutes/60 + (float)$fSeconds/3600); return ($sNSEW == 'S' || $sNSEW == 'W'?-1:1) * ((float)$iDegrees + (float)$iMinutes/60 + (float)$fSeconds/3600);
@@ -224,17 +224,17 @@ function _templatesToProperties($aTemplates)
if (!isset($aPageProperties['sWebsite']) && isset($aParams['website']) && $aParams['website']) { if (!isset($aPageProperties['sWebsite']) && isset($aParams['website']) && $aParams['website']) {
if (preg_match('#^\\[?([^ \\]]+)[^\\]]*\\]?$#', $aParams['website'], $aMatch)) { if (preg_match('#^\\[?([^ \\]]+)[^\\]]*\\]?$#', $aParams['website'], $aMatch)) {
$aPageProperties['sWebsite'] = $aMatch[1]; $aPageProperties['sWebsite'] = $aMatch[1];
if (strpos($aPageProperties['sWebsite'],':/'.'/') === FALSE) { if (strpos($aPageProperties['sWebsite'], ':/'.'/') === FALSE) {
$aPageProperties['sWebsite'] = 'http:/'.'/'.$aPageProperties['sWebsite']; $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']); $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['sInfoboxType'] = trim(substr($aTemplate[0], 8));
// $aPageProperties['aInfoboxParams'] = $aParams; // $aPageProperties['aInfoboxParams'] = $aParams;
} }
@@ -267,22 +267,22 @@ function _templatesToProperties($aTemplates)
} 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['fLat'] = degreesAndMinutesToDecimal($aParams[0], $aParams[1], 0, $aParams[2]);
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aParams[3], $aParams[4], 0, $aParams[5]); $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')) { } elseif (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['fLat'] = (strtoupper($aParams[1]) == 'N'?1:-1) * (float)$aParams[0];
$aPageProperties['fLon'] = (strtoupper($aParams[3]) == 'E'?1:-1) * (float)$aParams[2]; $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])) { } elseif (isset($aParams[0]) && is_numeric($aParams[0]) && isset($aParams[1]) && is_numeric($aParams[1])) {
$aPageProperties['fLat'] = (float)$aParams[0]; $aPageProperties['fLat'] = (float)$aParams[0];
$aPageProperties['fLon'] = (float)$aParams[1]; $aPageProperties['fLon'] = (float)$aParams[1];
} }
} }
if (isset($aParams['Latitude']) && isset($aParams['Longitude'])) { if (isset($aParams['Latitude']) && isset($aParams['Longitude'])) {
$aParams['Latitude'] = str_replace('&nbsp;',' ',$aParams['Latitude']); $aParams['Latitude'] = str_replace('&nbsp;', ' ', $aParams['Latitude']);
$aParams['Longitude'] = str_replace('&nbsp;',' ',$aParams['Longitude']); $aParams['Longitude'] = str_replace('&nbsp;', ' ', $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'] = $aPageProperties['fLat'] =
(degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]) (degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4])
+degreesAndMinutesToDecimal($aMatch[5], $aMatch[7], 0, $aMatch[8])) / 2; +degreesAndMinutesToDecimal($aMatch[5], $aMatch[7], 0, $aMatch[8])) / 2;
} else if (preg_match('#^([0-9]+)°(([0-9]+))? ([NS])#', $aParams['Latitude'], $aMatch)) { } elseif (preg_match('#^([0-9]+)°(([0-9]+))? ([NS])#', $aParams['Latitude'], $aMatch)) {
$aPageProperties['fLat'] = degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]); $aPageProperties['fLat'] = degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]);
} }
@@ -290,7 +290,7 @@ function _templatesToProperties($aTemplates)
$aPageProperties['fLon'] = $aPageProperties['fLon'] =
(degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]) (degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4])
+degreesAndMinutesToDecimal($aMatch[5], $aMatch[7], 0, $aMatch[8])) / 2; +degreesAndMinutesToDecimal($aMatch[5], $aMatch[7], 0, $aMatch[8])) / 2;
} else if (preg_match('#^([0-9]+)°(([0-9]+))? ([EW])#', $aParams['Longitude'], $aMatch)) { } elseif (preg_match('#^([0-9]+)°(([0-9]+))? ([EW])#', $aParams['Longitude'], $aMatch)) {
$aPageProperties['fLon'] = degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]); $aPageProperties['fLon'] = degreesAndMinutesToDecimal($aMatch[1], $aMatch[3], 0, $aMatch[4]);
} }
} }
@@ -312,7 +312,7 @@ if (isset($aCMDResult['parse-wikipedia'])) {
$aP = _templatesToProperties(_parseWikipediaContent($sPageText)); $aP = _templatesToProperties(_parseWikipediaContent($sPageText));
if (isset($aP['sInfoboxType'])) { if (isset($aP['sInfoboxType'])) {
$aP['sInfoboxType'] = preg_replace('#\\s+#',' ',$aP['sInfoboxType']); $aP['sInfoboxType'] = preg_replace('#\\s+#', ' ', $aP['sInfoboxType']);
$sSQL = 'update wikipedia_article set '; $sSQL = 'update wikipedia_article set ';
$sSQL .= 'infobox_type = \''.pg_escape_string($aP['sInfoboxType']).'\''; $sSQL .= 'infobox_type = \''.pg_escape_string($aP['sInfoboxType']).'\'';
$sSQL .= ' where language = \'en\' and title = \''.pg_escape_string($sArticleName).'\';'; $sSQL .= ' where language = \'en\' and title = \''.pg_escape_string($sArticleName).'\';';
@@ -365,7 +365,7 @@ if (isset($aCMDResult['link'])) {
$sNominatimBaseURL = 'http://SEVERNAME/search.php'; $sNominatimBaseURL = 'http://SEVERNAME/search.php';
foreach ($aWikiArticles as $aRecord) { foreach ($aWikiArticles as $aRecord) {
$aRecord['name'] = str_replace('_',' ',$aRecord['title']); $aRecord['name'] = str_replace('_', ' ', $aRecord['title']);
$sURL = $sNominatimBaseURL.'?format=xml&accept-language=en'; $sURL = $sNominatimBaseURL.'?format=xml&accept-language=en';
@@ -388,7 +388,7 @@ if (isset($aCMDResult['link'])) {
$sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist); $sURL .= "&viewbox=".($aRecord['lon']-$fMaxDist).",".($aRecord['lat']+$fMaxDist).",".($aRecord['lon']+$fMaxDist).",".($aRecord['lat']-$fMaxDist);
break; break;
case 'prefecture japan': case 'prefecture japan':
$aRecord['name'] = trim(str_replace(' Prefecture',' ', $aRecord['name'])); $aRecord['name'] = trim(str_replace(' Prefecture', ' ', $aRecord['name']));
case 'state': case 'state':
case '#us state': case '#us state':
case 'county': case 'county':
@@ -482,7 +482,7 @@ if (isset($aCMDResult['link'])) {
xml_parser_free($hXMLParser); xml_parser_free($hXMLParser);
if (!isset($aNominatRecords[0])) { if (!isset($aNominatRecords[0])) {
$aNameParts = preg_split('#[(,]#',$aRecord['name']); $aNameParts = preg_split('#[(,]#', $aRecord['name']);
if (sizeof($aNameParts) > 1) { if (sizeof($aNameParts) > 1) {
$sNameURL = $sURL.'&q='.urlencode(trim($aNameParts[0])); $sNameURL = $sURL.'&q='.urlencode(trim($aNameParts[0]));
var_Dump($sNameURL); var_Dump($sNameURL);
@@ -514,7 +514,7 @@ if (isset($aCMDResult['link'])) {
elseif ($iRank <= 26) $fMaxDist = 0.001; elseif ($iRank <= 26) $fMaxDist = 0.001;
else $fMaxDist = 0.001; 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"; 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"; echo "-- Diff too big $fDiff (max: $fMaxDist)".$aRecord['lat'].','.$aNominatRecords[$i]['LAT'].' & '.$aRecord['lon'].','.$aNominatRecords[$i]['LON']." \n";
} else { } else {

View File

@@ -26,7 +26,7 @@ if (isset($aCMDResult['parse-tiger'])) {
foreach (glob($aCMDResult['parse-tiger'].'/tl_20??_?????_edges.zip', 0) as $sImportFile) { foreach (glob($aCMDResult['parse-tiger'].'/tl_20??_?????_edges.zip', 0) as $sImportFile) {
set_time_limit(30); set_time_limit(30);
preg_match('#([0-9]{5})_(.*)#',basename($sImportFile), $aMatch); preg_match('#([0-9]{5})_(.*)#', basename($sImportFile), $aMatch);
$sCountyID = $aMatch[1]; $sCountyID = $aMatch[1];
echo "Processing ".$sCountyID."...\n"; echo "Processing ".$sCountyID."...\n";
$sUnzipCmd = "unzip -d $sTempDir $sImportFile"; $sUnzipCmd = "unzip -d $sTempDir $sImportFile";

View File

@@ -197,18 +197,36 @@ if ($aCMDResult['create-tables'] || $aCMDResult['all']) {
echo "Tables\n"; echo "Tables\n";
$sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql'); $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
$sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate); $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
$sTemplate = replace_tablespace('{ts:address-data}', $sTemplate = replace_tablespace(
CONST_Tablespace_Address_Data, $sTemplate); '{ts:address-data}',
$sTemplate = replace_tablespace('{ts:address-index}', CONST_Tablespace_Address_Data,
CONST_Tablespace_Address_Index, $sTemplate); $sTemplate
$sTemplate = replace_tablespace('{ts:search-data}', );
CONST_Tablespace_Search_Data, $sTemplate); $sTemplate = replace_tablespace(
$sTemplate = replace_tablespace('{ts:search-index}', '{ts:address-index}',
CONST_Tablespace_Search_Index, $sTemplate); CONST_Tablespace_Address_Index,
$sTemplate = replace_tablespace('{ts:aux-data}', $sTemplate
CONST_Tablespace_Aux_Data, $sTemplate); );
$sTemplate = replace_tablespace('{ts:aux-index}', $sTemplate = replace_tablespace(
CONST_Tablespace_Aux_Index, $sTemplate); '{ts:search-data}',
CONST_Tablespace_Search_Data,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:search-index}',
CONST_Tablespace_Search_Index,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-data}',
CONST_Tablespace_Aux_Data,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-index}',
CONST_Tablespace_Aux_Index,
$sTemplate
);
pgsqlRunScript($sTemplate, false); pgsqlRunScript($sTemplate, false);
// re-run the functions // re-run the functions
@@ -221,18 +239,36 @@ if ($aCMDResult['create-partition-tables'] || $aCMDResult['all']) {
$bDidSomething = true; $bDidSomething = true;
$sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql'); $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
$sTemplate = replace_tablespace('{ts:address-data}', $sTemplate = replace_tablespace(
CONST_Tablespace_Address_Data, $sTemplate); '{ts:address-data}',
$sTemplate = replace_tablespace('{ts:address-index}', CONST_Tablespace_Address_Data,
CONST_Tablespace_Address_Index, $sTemplate); $sTemplate
$sTemplate = replace_tablespace('{ts:search-data}', );
CONST_Tablespace_Search_Data, $sTemplate); $sTemplate = replace_tablespace(
$sTemplate = replace_tablespace('{ts:search-index}', '{ts:address-index}',
CONST_Tablespace_Search_Index, $sTemplate); CONST_Tablespace_Address_Index,
$sTemplate = replace_tablespace('{ts:aux-data}', $sTemplate
CONST_Tablespace_Aux_Data, $sTemplate); );
$sTemplate = replace_tablespace('{ts:aux-index}', $sTemplate = replace_tablespace(
CONST_Tablespace_Aux_Index, $sTemplate); '{ts:search-data}',
CONST_Tablespace_Search_Data,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:search-index}',
CONST_Tablespace_Search_Index,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-data}',
CONST_Tablespace_Aux_Data,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-index}',
CONST_Tablespace_Aux_Index,
$sTemplate
);
pgsqlRunPartitionScript($sTemplate); pgsqlRunPartitionScript($sTemplate);
} }
@@ -351,10 +387,16 @@ if ($aCMDResult['import-tiger-data']) {
$sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql'); $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
$sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate); $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
$sTemplate = replace_tablespace('{ts:aux-data}', $sTemplate = replace_tablespace(
CONST_Tablespace_Aux_Data, $sTemplate); '{ts:aux-data}',
$sTemplate = replace_tablespace('{ts:aux-index}', CONST_Tablespace_Aux_Data,
CONST_Tablespace_Aux_Index, $sTemplate); $sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-index}',
CONST_Tablespace_Aux_Index,
$sTemplate
);
pgsqlRunScript($sTemplate, false); pgsqlRunScript($sTemplate, false);
$aDBInstances = array(); $aDBInstances = array();
@@ -401,10 +443,16 @@ if ($aCMDResult['import-tiger-data']) {
echo "Creating indexes\n"; echo "Creating indexes\n";
$sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql'); $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
$sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate); $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
$sTemplate = replace_tablespace('{ts:aux-data}', $sTemplate = replace_tablespace(
CONST_Tablespace_Aux_Data, $sTemplate); '{ts:aux-data}',
$sTemplate = replace_tablespace('{ts:aux-index}', CONST_Tablespace_Aux_Data,
CONST_Tablespace_Aux_Index, $sTemplate); $sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-index}',
CONST_Tablespace_Aux_Index,
$sTemplate
);
pgsqlRunScript($sTemplate, false); pgsqlRunScript($sTemplate, false);
} }
@@ -522,12 +570,21 @@ if ($aCMDResult['create-search-indices'] || $aCMDResult['all']) {
$bDidSomething = true; $bDidSomething = true;
$sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql'); $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
$sTemplate = replace_tablespace('{ts:address-index}', $sTemplate = replace_tablespace(
CONST_Tablespace_Address_Index, $sTemplate); '{ts:address-index}',
$sTemplate = replace_tablespace('{ts:search-index}', CONST_Tablespace_Address_Index,
CONST_Tablespace_Search_Index, $sTemplate); $sTemplate
$sTemplate = replace_tablespace('{ts:aux-index}', );
CONST_Tablespace_Aux_Index, $sTemplate); $sTemplate = replace_tablespace(
'{ts:search-index}',
CONST_Tablespace_Search_Index,
$sTemplate
);
$sTemplate = replace_tablespace(
'{ts:aux-index}',
CONST_Tablespace_Aux_Index,
$sTemplate
);
pgsqlRunScript($sTemplate); pgsqlRunScript($sTemplate);
} }
@@ -759,8 +816,7 @@ function passthruCheckReturn($cmd)
function replace_tablespace($sTemplate, $sTablespace, $sSql) function replace_tablespace($sTemplate, $sTablespace, $sSql)
{ {
if ($sTablespace) { if ($sTablespace) {
$sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"', $sSql);
$sSql);
} else { } else {
$sSql = str_replace($sTemplate, '', $sSql); $sSql = str_replace($sTemplate, '', $sSql);
} }

View File

@@ -46,8 +46,9 @@ if ($aCMDResult['wiki-import']) {
# quotes into the wiki # quotes into the wiki
$sType = preg_replace('/&quot;/', '', $sType); $sType = preg_replace('/&quot;/', '', $sType);
# sanity check, in case somebody added garbage in the wiki # sanity check, in case somebody added garbage in the wiki
if (preg_match('/^\\w+$/', $sClass) < 1 || if (preg_match('/^\\w+$/', $sClass) < 1
preg_match('/^\\w+$/', $sType) < 1) { || preg_match('/^\\w+$/', $sType) < 1
) {
trigger_error("Bad class/type for language $sLanguage: $sClass=$sType"); trigger_error("Bad class/type for language $sLanguage: $sClass=$sType");
exit; exit;
} }

View File

@@ -264,10 +264,10 @@ if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
} }
$iFileSize = filesize($sImportFile); $iFileSize = filesize($sImportFile);
$sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory); $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')"; $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s', $fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')";
var_Dump($sSQL); var_Dump($sSQL);
$oDB->query($sSQL); $oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed osmosis step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n"; echo date('Y-m-d H:i:s')." Completed osmosis step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
} }
$iFileSize = filesize($sImportFile); $iFileSize = filesize($sImportFile);
@@ -281,10 +281,10 @@ if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
echo "Error: $iErrorLevel\n"; echo "Error: $iErrorLevel\n";
exit($iErrorLevel); exit($iErrorLevel);
} }
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')"; $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s', $fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')";
var_Dump($sSQL); var_Dump($sSQL);
$oDB->query($sSQL); $oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed osm2pgsql step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n"; echo date('Y-m-d H:i:s')." Completed osm2pgsql step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
// Archive for debug? // Archive for debug?
unlink($sImportFile); unlink($sImportFile);
@@ -304,22 +304,22 @@ if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
} }
} }
$sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')"; $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s', $fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')";
var_Dump($sSQL); var_Dump($sSQL);
$oDB->query($sSQL); $oDB->query($sSQL);
echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n"; echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
$sSQL = "update import_status set lastimportdate = '$sBatchEnd'"; $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
$oDB->query($sSQL); $oDB->query($sSQL);
$fDuration = time() - $fStartTime; $fDuration = time() - $fStartTime;
echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n"; 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 (!$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())); $iSleep = max(0, (strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time()));
} else { } else {
$iSleep = max(0,CONST_Replication_Update_Interval-$fDuration); $iSleep = max(0, CONST_Replication_Update_Interval-$fDuration);
} }
echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n"; echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
sleep($iSleep); sleep($iSleep);
@@ -330,5 +330,5 @@ function getosmosistimestamp($sOsmosisConfigDirectory)
{ {
$sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt'); $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
preg_match('#timestamp=(.+)#', $sStateFile, $aResult); preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
return str_replace('\:',':',$aResult[1]); return str_replace('\:', ':', $aResult[1]);
} }

View File

@@ -39,8 +39,11 @@ if (!$aResult['search-only']) {
if ($bVerbose) echo "$fLat, $fLon = "; if ($bVerbose) echo "$fLat, $fLon = ";
$aLookup = $oReverseGeocode->lookup($fLat, $fLon); $aLookup = $oReverseGeocode->lookup($fLat, $fLon);
if ($aLookup && $aLookup['place_id']) { if ($aLookup && $aLookup['place_id']) {
$aDetails = $oPlaceLookup->lookup((int)$aLookup['place_id'], $aDetails = $oPlaceLookup->lookup(
$aLookup['type'], $aLookup['fraction']); (int)$aLookup['place_id'],
$aLookup['type'],
$aLookup['fraction']
);
if ($bVerbose) echo $aDetails['langaddress']."\n"; if ($bVerbose) echo $aDetails['langaddress']."\n";
} else { } else {
echo "."; echo ".";

View File

@@ -31,6 +31,7 @@
python-numpy php-phpunit-PHPUnit python-numpy php-phpunit-PHPUnit
pip install --user --upgrade pip setuptools lettuce==0.2.18 six==1.9 \ pip install --user --upgrade pip setuptools lettuce==0.2.18 six==1.9 \
haversine Shapely pytidylib haversine Shapely pytidylib
sudo pear install PHP_CodeSniffer
# #
# System Configuration # System Configuration

View File

@@ -27,6 +27,7 @@ sudo apt-get install -y -qq python-Levenshtein python-shapely \
python-numpy phpunit python-numpy phpunit
sudo -H pip install --quiet 'setuptools>=23.0.0' lettuce==0.2.18 'six>=1.9' haversine sudo -H pip install --quiet 'setuptools>=23.0.0' lettuce==0.2.18 'six>=1.9' haversine
sudo pear install PHP_CodeSniffer
sudo service postgresql restart sudo service postgresql restart
sudo -u postgres createuser -S www-data sudo -u postgres createuser -S www-data

View File

@@ -38,6 +38,7 @@ export DEBIAN_FRONTEND=noninteractive #DOCS:
python-numpy phpunit python-numpy phpunit
pip install --user lettuce==0.2.18 six==1.7 haversine pip install --user lettuce==0.2.18 six==1.7 haversine
sudo pear install PHP_CodeSniffer
# #
# System Configuration # System Configuration

View File

@@ -10,8 +10,7 @@
$oDB =& getDB(); $oDB =& getDB();
$sSQL = "select placex.place_id, calculated_country_code as country_code, name->'name' as name, i.* from placex, import_polygon_delete i where placex.osm_id = i.osm_id and placex.osm_type = i.osm_type and placex.class = i.class and placex.type = i.type"; $sSQL = "select placex.place_id, calculated_country_code as country_code, name->'name' as name, i.* from placex, import_polygon_delete i where placex.osm_id = i.osm_id and placex.osm_type = i.osm_type and placex.class = i.class and placex.type = i.type";
$aPolygons = chksql($oDB->getAll($sSQL), $aPolygons = chksql($oDB->getAll($sSQL), "Could not get list of deleted OSM elements.");
"Could not get list of deleted OSM elements.");
if (CONST_DEBUG) { if (CONST_DEBUG) {
var_dump($aPolygons); var_dump($aPolygons);

View File

@@ -11,7 +11,7 @@ $oParams = new ParameterParser();
$sOutputFormat = 'html'; $sOutputFormat = 'html';
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $aLangPrefOrder))."]";
$sPlaceId = $oParams->getString('place_id'); $sPlaceId = $oParams->getString('place_id');
$sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R')); $sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R'));
@@ -66,8 +66,7 @@ $sSQL .= " ST_y(centroid) as lat, ST_x(centroid) as lon,";
$sSQL .= " case when importance = 0 OR importance IS NULL then 0.75-(rank_search::float/40) else importance end as calculated_importance, "; $sSQL .= " case when importance = 0 OR importance IS NULL then 0.75-(rank_search::float/40) else importance end as calculated_importance, ";
$sSQL .= " ST_AsText(CASE WHEN ST_NPoints(geometry) > 5000 THEN ST_SimplifyPreserveTopology(geometry, 0.0001) ELSE geometry END) as outlinestring"; $sSQL .= " ST_AsText(CASE WHEN ST_NPoints(geometry) > 5000 THEN ST_SimplifyPreserveTopology(geometry, 0.0001) ELSE geometry END) as outlinestring";
$sSQL .= " from placex where place_id = $iPlaceID"; $sSQL .= " from placex where place_id = $iPlaceID";
$aPointDetails = chksql($oDB->getRow($sSQL), $aPointDetails = chksql($oDB->getRow($sSQL), "Could not get details of place object.");
"Could not get details of place object.");
$aPointDetails['localname'] = $aPointDetails['localname']?$aPointDetails['localname']:$aPointDetails['housenumber']; $aPointDetails['localname'] = $aPointDetails['localname']?$aPointDetails['localname']:$aPointDetails['housenumber'];
$aClassType = getClassTypesWithImportance(); $aClassType = getClassTypesWithImportance();
@@ -122,14 +121,14 @@ if ($oParams->getBool('keywords')) {
$aPlaceSearchName = []; $aPlaceSearchName = [];
} }
$sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['name_vector'],1,-1).")"; $sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['name_vector'], 1, -1).")";
$aPlaceSearchNameKeywords = $oDB->getAll($sSQL); $aPlaceSearchNameKeywords = $oDB->getAll($sSQL);
if (PEAR::isError($aPlaceSearchNameKeywords)) { // possible timeout if (PEAR::isError($aPlaceSearchNameKeywords)) { // possible timeout
$aPlaceSearchNameKeywords = []; $aPlaceSearchNameKeywords = [];
} }
$sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['nameaddress_vector'],1,-1).")"; $sSQL = "select * from word where word_id in (".substr($aPlaceSearchName['nameaddress_vector'], 1, -1).")";
$aPlaceSearchAddressKeywords = $oDB->getAll($sSQL); $aPlaceSearchAddressKeywords = $oDB->getAll($sSQL);
if (PEAR::isError($aPlaceSearchAddressKeywords)) { // possible timeout if (PEAR::isError($aPlaceSearchAddressKeywords)) { // possible timeout
$aPlaceSearchAddressKeywords = []; $aPlaceSearchAddressKeywords = [];

View File

@@ -12,7 +12,7 @@ $oParams = new ParameterParser();
$sOutputFormat = $oParams->getSet('format', array('html', 'json'), 'html'); $sOutputFormat = $oParams->getSet('format', array('html', 'json'), 'html');
$aLangPrefOrder = $oParams->getPreferredLanguages(); $aLangPrefOrder = $oParams->getPreferredLanguages();
$sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]"; $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $aLangPrefOrder))."]";
$sPlaceId = $oParams->getString('place_id'); $sPlaceId = $oParams->getString('place_id');
$sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R')); $sOsmType = $oParams->getSet('osmtype', array('N', 'W', 'R'));
@@ -90,7 +90,7 @@ $aRelatedPlaceIDs = chksql($oDB->getCol($sSQL = "select place_id from placex whe
$sSQL = "select obj.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, st_area(geometry) as area, "; $sSQL = "select obj.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') as isarea, st_area(geometry) as area, ";
$sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength "; $sSQL .= " get_name_by_language(name,$sLanguagePrefArraySQL) as localname, length(name::text) as namelength ";
$sSQL .= " from (select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, geometry, name from placex "; $sSQL .= " from (select placex.place_id, osm_type, osm_id, class, type, housenumber, admin_level, rank_address, rank_search, geometry, name from placex ";
$sSQL .= " where parent_place_id in (".join(',',$aRelatedPlaceIDs).") and name is not null order by rank_address asc,rank_search asc limit 500) as obj"; $sSQL .= " where parent_place_id in (".join(',', $aRelatedPlaceIDs).") and name is not null order by rank_address asc,rank_search asc limit 500) as obj";
$sSQL .= " order by rank_address asc,rank_search asc,localname,class, type,housenumber"; $sSQL .= " order by rank_address asc,rank_search asc,localname,class, type,housenumber";
$aParentOfLines = chksql($oDB->getAll($sSQL)); $aParentOfLines = chksql($oDB->getAll($sSQL));
@@ -100,11 +100,11 @@ if (sizeof($aParentOfLines)) {
$aGroupedAddressLines = array(); $aGroupedAddressLines = array();
foreach ($aParentOfLines as $aAddressLine) { foreach ($aParentOfLines as $aAddressLine) {
if (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']) if (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'])
&& $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'] && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']
) { ) {
$aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label']; $aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type'].':'.$aAddressLine['admin_level']]['label'];
} elseif (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']) } elseif (isset($aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'])
&& $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'] && $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']
) { ) {
$aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label']; $aAddressLine['label'] = $aClassType[$aAddressLine['class'].':'.$aAddressLine['type']]['label'];
} else $aAddressLine['label'] = ucwords($aAddressLine['type']); } else $aAddressLine['label'] = ucwords($aAddressLine['type']);

View File

@@ -62,7 +62,7 @@ foreach ($aOsmIds AS $sItem) {
if (CONST_Debug) exit; if (CONST_Debug) exit;
$sXmlRootTag = 'lookupresults'; $sXmlRootTag = 'lookupresults';
$sQuery = join(',',$aCleanedQueryParts); $sQuery = join(',', $aCleanedQueryParts);
// we initialize these to avoid warnings in our logfile // we initialize these to avoid warnings in our logfile
$sViewBox = ''; $sViewBox = '';
$bShowPolygons = ''; $bShowPolygons = '';

View File

@@ -101,7 +101,7 @@ table td {
foreach ($aRow as $sCol => $sVal) { foreach ($aRow as $sCol => $sVal) {
switch ($sCol) { switch ($sCol) {
case 'error message': case 'error message':
if (preg_match('/Self-intersection\\[([0-9.\\-]+) ([0-9.\\-]+)\\]/',$sVal,$aMatch)) { if (preg_match('/Self-intersection\\[([0-9.\\-]+) ([0-9.\\-]+)\\]/', $sVal, $aMatch)) {
$aRow['lat'] = $aMatch[2]; $aRow['lat'] = $aMatch[2];
$aRow['lon'] = $aMatch[1]; $aRow['lon'] = $aMatch[1];
echo "<td><a href=\"http://www.openstreetmap.org/?lat=".$aMatch[2]."&lon=".$aMatch[1]."&zoom=18&layers=M&".$sOSMType."=".$aRow['id']."\">".($sVal?$sVal:'&nbsp;')."</a></td>"; echo "<td><a href=\"http://www.openstreetmap.org/?lat=".$aMatch[2]."&lon=".$aMatch[1]."&zoom=18&layers=M&".$sOSMType."=".$aRow['id']."\">".($sVal?$sVal:'&nbsp;')."</a></td>";

View File

@@ -15,9 +15,9 @@ $bAsGeoJSON = $oParams->getBool('polygon_geojson');
$bAsKML = $oParams->getBool('polygon_kml'); $bAsKML = $oParams->getBool('polygon_kml');
$bAsSVG = $oParams->getBool('polygon_svg'); $bAsSVG = $oParams->getBool('polygon_svg');
$bAsText = $oParams->getBool('polygon_text'); $bAsText = $oParams->getBool('polygon_text');
if ((($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0)
+ ($bAsText?1:0)) > CONST_PolygonOutput_MaximumTypes $iWantedTypes = ($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0) + ($bAsText?1:0);
) { if ($iWantedTypes > CONST_PolygonOutput_MaximumTypes) {
if (CONST_PolygonOutput_MaximumTypes) { if (CONST_PolygonOutput_MaximumTypes) {
userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option"); userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
} else { } else {
@@ -51,16 +51,19 @@ $fLat = $oParams->getFloat('lat');
$fLon = $oParams->getFloat('lon'); $fLon = $oParams->getFloat('lon');
if ($sOsmType && $iOsmId > 0) { if ($sOsmType && $iOsmId > 0) {
$aPlace = $oPlaceLookup->lookupOSMID($sOsmType, $iOsmId); $aPlace = $oPlaceLookup->lookupOSMID($sOsmType, $iOsmId);
} else if ($fLat !== false && $fLon !== false) { } elseif ($fLat !== false && $fLon !== false) {
$oReverseGeocode = new ReverseGeocode($oDB); $oReverseGeocode = new ReverseGeocode($oDB);
$oReverseGeocode->setZoom($oParams->getInt('zoom', 18)); $oReverseGeocode->setZoom($oParams->getInt('zoom', 18));
$aLookup = $oReverseGeocode->lookup($fLat, $fLon); $aLookup = $oReverseGeocode->lookup($fLat, $fLon);
if (CONST_Debug) var_dump($aLookup); if (CONST_Debug) var_dump($aLookup);
$aPlace = $oPlaceLookup->lookup((int)$aLookup['place_id'], $aPlace = $oPlaceLookup->lookup(
$aLookup['type'], $aLookup['fraction']); (int)$aLookup['place_id'],
} else if ($sOutputFormat != 'html') { $aLookup['type'],
$aLookup['fraction']
);
} elseif ($sOutputFormat != 'html') {
userError("Need coordinates or OSM object to lookup."); userError("Need coordinates or OSM object to lookup.");
} }
@@ -73,9 +76,12 @@ if ($aPlace) {
$oPlaceLookup->setPolygonSimplificationThreshold($fThreshold); $oPlaceLookup->setPolygonSimplificationThreshold($fThreshold);
$fRadius = $fDiameter = getResultDiameter($aPlace); $fRadius = $fDiameter = getResultDiameter($aPlace);
$aOutlineResult = $oPlaceLookup->getOutlines($aPlace['place_id'], $aOutlineResult = $oPlaceLookup->getOutlines(
$aPlace['lon'], $aPlace['lat'], $aPlace['place_id'],
$fRadius); $aPlace['lon'],
$aPlace['lat'],
$fRadius
);
if ($aOutlineResult) { if ($aOutlineResult) {
$aPlace = array_merge($aPlace, $aOutlineResult); $aPlace = array_merge($aPlace, $aOutlineResult);

View File

@@ -38,13 +38,8 @@ if ($sOutputFormat == 'html') {
$bAsKML = $oParams->getBool('polygon_kml'); $bAsKML = $oParams->getBool('polygon_kml');
$bAsSVG = $oParams->getBool('polygon_svg'); $bAsSVG = $oParams->getBool('polygon_svg');
$bAsText = $oParams->getBool('polygon_text'); $bAsText = $oParams->getBool('polygon_text');
if (( ($bAsGeoJSON?1:0) $iWantedTypes = ($bAsGeoJSON?1:0) + ($bAsKML?1:0) + ($bAsSVG?1:0) + ($bAsText?1:0) + ($bAsPoints?1:0);
+ ($bAsKML?1:0) if ($iWantedTypes > CONST_PolygonOutput_MaximumTypes) {
+ ($bAsSVG?1:0)
+ ($bAsText?1:0)
+ ($bAsPoints?1:0)
) > CONST_PolygonOutput_MaximumTypes
) {
if (CONST_PolygonOutput_MaximumTypes) { if (CONST_PolygonOutput_MaximumTypes) {
userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option"); userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
} else { } else {
@@ -82,13 +77,15 @@ if (CONST_Search_BatchMode && isset($_GET['batch'])) {
$oGeocode->setQueryFromParams($oParams); $oGeocode->setQueryFromParams($oParams);
if (!$oGeocode->getQueryString() if (!$oGeocode->getQueryString()
&& isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/') { && isset($_SERVER['PATH_INFO'])
&& $_SERVER['PATH_INFO'][0] == '/'
) {
$sQuery = substr(rawurldecode($_SERVER['PATH_INFO']), 1); $sQuery = substr(rawurldecode($_SERVER['PATH_INFO']), 1);
// reverse order of '/' separated string // reverse order of '/' separated string
$aPhrases = explode('/', $sQuery); $aPhrases = explode('/', $sQuery);
$aPhrases = array_reverse($aPhrases); $aPhrases = array_reverse($aPhrases);
$sQuery = join(', ',$aPhrases); $sQuery = join(', ', $aPhrases);
$oGeocode->setQuery($sQuery); $oGeocode->setQuery($sQuery);
} }
@@ -107,7 +104,7 @@ $sViewBox = $oGeocode->getViewBoxString();
$bShowPolygons = (isset($_GET['polygon']) && $_GET['polygon']); $bShowPolygons = (isset($_GET['polygon']) && $_GET['polygon']);
$aExcludePlaceIDs = $oGeocode->getExcludedPlaceIDs(); $aExcludePlaceIDs = $oGeocode->getExcludedPlaceIDs();
$sMoreURL = CONST_Website_BaseURL.'search.php?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs); $sMoreURL = CONST_Website_BaseURL.'search.php?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',', $aExcludePlaceIDs);
if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"]; if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
if ($bShowPolygons) $sMoreURL .= '&polygon=1'; if ($bShowPolygons) $sMoreURL .= '&polygon=1';
if ($oGeocode->getIncludeAddressDetails()) $sMoreURL .= '&addressdetails=1'; if ($oGeocode->getIncludeAddressDetails()) $sMoreURL .= '&addressdetails=1';