2 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3 require_once(CONST_BasePath.'/lib/log.php');
5 ini_set('memory_limit', '200M');
9 $fLat = CONST_Default_Lat;
10 $fLon = CONST_Default_Lon;
11 $iZoom = CONST_Default_Zoom;
12 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
13 $sOutputFormat = 'html';
14 $aSearchResults = array();
15 $aExcludePlaceIDs = array();
16 $sCountryCodesSQL = false;
17 $sSuggestion = $sSuggestionURL = false;
18 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
19 $bReverseInPlan = false;
20 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iLimit > 100) $iLimit = 100;
25 $iMaxAddressRank = 30;
28 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
30 $sOutputFormat = $_GET['format'];
33 // Show / use polygons
34 $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
36 // Show address breakdown
37 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
40 $aLangPrefOrder = getPrefferedLangauges();
41 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
42 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
43 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
45 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
47 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
49 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
51 $iExcludedPlaceID = (int)$iExcludedPlaceID;
52 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
56 // Only certain ranks of feature
57 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
59 if (isset($_GET['featuretype']))
61 switch($_GET['featuretype'])
64 $iMinAddressRank = $iMaxAddressRank = 4;
67 $iMinAddressRank = $iMaxAddressRank = 8;
70 $iMinAddressRank = 14;
71 $iMaxAddressRank = 16;
75 $iMaxAddressRank = 20;
80 if (isset($_GET['countrycodes']))
82 $aCountryCodes = array();
83 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
85 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
87 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
90 $sCountryCodesSQL = join(',', $aCountryCodes);
94 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
95 if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
97 $sQuery = substr($_SERVER['PATH_INFO'], 1);
99 // reverse order of '/' seperated string
100 $aPhrases = explode('/', $sQuery);
101 $aPhrases = array_reverse($aPhrases);
102 $sQuery = join(', ',$aPhrases);
107 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
109 // Hack to make it handle "new york, ny" (and variants) correctly
110 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
111 if (isset($aLangPrefOrder['name:en']))
113 $sQuery = preg_replace('/\\bil\\b/','illinois', $sQuery);
114 $sQuery = preg_replace('/\\bal\\b/','alabama', $sQuery);
115 $sQuery = preg_replace('/\\bla\\b/','louisiana', $sQuery);
116 $sQuery = preg_replace('/\\bde louisiana\\b/','de la', $sQuery);
119 // If we have a view box create the SQL
120 // Small is the actual view box, Large is double (on each axis) that
121 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
122 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
124 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
125 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
127 if (isset($_GET['viewbox']) && $_GET['viewbox'])
129 $aCoOrdinates = explode(',',$_GET['viewbox']);
130 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
131 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
132 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
133 $aCoOrdinates[0] += $fHeight;
134 $aCoOrdinates[2] -= $fHeight;
135 $aCoOrdinates[1] += $fWidth;
136 $aCoOrdinates[3] -= $fWidth;
137 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
139 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
141 $aPoints = explode(',',$_GET['route']);
142 if (sizeof($aPoints) % 2 != 0)
144 echo "Uneven number of points";
147 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
149 foreach($aPoints as $i => $fPoint)
153 if ($i != 1) $sViewboxCentreSQL .= ",";
154 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
158 $fPrevCoord = (float)$fPoint;
161 $sViewboxCentreSQL .= ")'::geometry,4326)";
163 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
164 $sViewboxSmallSQL = $oDB->getOne($sSQL);
165 if (PEAR::isError($sViewboxSmallSQL))
167 var_dump($sViewboxSmallSQL);
170 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
172 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
173 $sViewboxLargeSQL = $oDB->getOne($sSQL);
174 if (PEAR::isError($sViewboxLargeSQL))
176 var_dump($sViewboxLargeSQL);
179 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
182 // Do we have anything that looks like a lat/lon pair?
183 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
185 $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
186 $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
187 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
189 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
191 $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
192 $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
193 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
195 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b)/', $sQuery, $aData))
197 $_GET['nearlat'] = $aData[2];
198 $_GET['nearlon'] = $aData[3];
199 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
204 // Start with a blank search
206 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
207 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
210 $sNearPointSQL = false;
211 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
213 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
214 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
215 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
216 $aSearches[0]['fRadius'] = 0.1;
219 $bSpecialTerms = false;
220 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
221 $aSpecialTerms = array();
222 foreach($aSpecialTermsRaw as $aSpecialTerm)
224 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
225 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
228 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
229 $aSpecialTerms = array();
230 foreach($aSpecialTermsRaw as $aSpecialTerm)
232 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
233 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
234 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
235 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\',\'highway\')) or country_code is not null';
236 $aSearchWords = $oDB->getAll($sSQL);
237 $aNewSearches = array();
238 foreach($aSearches as $aSearch)
240 foreach($aSearchWords as $aSearchTerm)
242 $aNewSearch = $aSearch;
243 if ($aSearchTerm['country_code'])
245 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
246 $aNewSearches[] = $aNewSearch;
247 $bSpecialTerms = true;
249 if ($aSearchTerm['class'])
251 $aNewSearch['sClass'] = $aSearchTerm['class'];
252 $aNewSearch['sType'] = $aSearchTerm['type'];
253 $aNewSearches[] = $aNewSearch;
254 $bSpecialTerms = true;
258 $aSearches = $aNewSearches;
261 // Split query into phrases
262 // Commas are used to reduce the search space by indicating where phrases split
263 $aPhrases = explode(',',$sQuery);
265 // Convert each phrase to standard form
266 // Create a list of standard words
267 // Get all 'sets' of words
268 // Generate a complete list of all
270 foreach($aPhrases as $iPhrase => $sPhrase)
272 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
273 if (PEAR::isError($aPhrase))
278 if (trim($aPhrase['string']))
280 $aPhrases[$iPhrase] = $aPhrase;
281 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
282 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
283 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
287 unset($aPhrases[$iPhrase]);
291 // reindex phrases - we make assumptions later on
292 $aPhrases = array_values($aPhrases);
294 if (sizeof($aTokens))
297 // Check which tokens we have, get the ID numbers
298 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
299 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
300 $sSQL .= ' and (class is null or class not in (\'highway\'))';
301 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
303 if (CONST_Debug) var_Dump($sSQL);
305 $aValidTokens = array();
306 if (sizeof($aTokens))
307 $aDatabaseWords = $oDB->getAll($sSQL);
309 $aDatabaseWords = array();
310 if (PEAR::IsError($aDatabaseWords))
312 var_dump($sSQL, $aDatabaseWords);
315 $aPossibleMainWordIDs = array();
316 foreach($aDatabaseWords as $aToken)
318 if (isset($aValidTokens[$aToken['word_token']]))
320 $aValidTokens[$aToken['word_token']][] = $aToken;
324 $aValidTokens[$aToken['word_token']] = array($aToken);
326 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
328 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
330 $aSuggestion = array();
331 $bSuggestion = false;
332 if (CONST_Suggestions_Enabled)
334 foreach($aPhrases as $iPhrase => $aPhrase)
336 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
338 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
339 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
340 $aRow = $aSuggestionWords[0];
341 if ($aRow && $aRow['word'])
343 $aSuggestion[] = $aRow['word'];
348 $aSuggestion[] = $aPhrase['string'];
353 $aSuggestion[] = $aPhrase['string'];
357 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
359 // Try and calculate GB postcodes we might be missing
360 foreach($aTokens as $sToken)
362 if (!isset($aValidTokens[$sToken]) && !isset($aValidTokens[' '.$sToken]) && preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
364 if (substr($aData[1],-2,1) != ' ')
366 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
367 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
369 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
370 if ($aGBPostcodeLocation)
372 $aValidTokens[$sToken] = $aGBPostcodeLocation;
378 foreach($aTokens as $sToken)
380 // Unknown single word token with a number - assume it is a house number
381 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
383 $aValidTokens[' '.$sToken] = array('class'=>'place','type'=>'house');
387 // Any words that have failed completely?
390 // Start the search process
391 $aResultPlaceIDs = array();
394 Calculate all searches using aValidTokens i.e.
396 'Wodsworth Road, Sheffield' =>
400 0 1 (wodsworth)(road)
403 Score how good the search is so they can be ordered
406 foreach($aPhrases as $iPhrase => $sPhrase)
408 $aNewPhraseSearches = array();
410 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
412 $aWordsetSearches = $aSearches;
414 // Add all words from this wordset
415 foreach($aWordset as $sToken)
417 //echo "<br><b>$sToken</b>";
418 $aNewWordsetSearches = array();
420 foreach($aWordsetSearches as $aCurrentSearch)
423 //var_dump($aCurrentSearch);
426 // If the token is valid
427 if (isset($aValidTokens[' '.$sToken]))
429 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
431 $aSearch = $aCurrentSearch;
432 $aSearch['iSearchRank']++;
433 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
435 if ($aSearch['sCountryCode'] === false)
437 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
438 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
439 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
440 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
443 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
445 if ($aSearch['fLat'] === '')
447 $aSearch['fLat'] = $aSearchTerm['lat'];
448 $aSearch['fLon'] = $aSearchTerm['lon'];
449 $aSearch['fRadius'] = $aSearchTerm['radius'];
450 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
453 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
455 if ($aSearch['sHouseNumber'] === '')
457 $aSearch['sHouseNumber'] = $sToken;
458 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
460 // Fall back to not searching for this item (better than nothing)
461 $aSearch = $aCurrentSearch;
462 $aSearch['iSearchRank'] += 1;
463 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
467 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
469 if ($aSearch['sClass'] === '')
471 $aSearch['sOperator'] = $aSearchTerm['operator'];
472 $aSearch['sClass'] = $aSearchTerm['class'];
473 $aSearch['sType'] = $aSearchTerm['type'];
474 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
475 else $aSearch['sOperator'] = 'near'; // near = in for the moment
477 // Do we have a shortcut id?
478 if ($aSearch['sOperator'] == 'name')
480 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
481 if ($iAmenityID = $oDB->getOne($sSQL))
483 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
484 $aSearch['aName'][$iAmenityID] = $iAmenityID;
485 $aSearch['sClass'] = '';
486 $aSearch['sType'] = '';
489 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
494 if (sizeof($aSearch['aName']))
496 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
498 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
502 $aSearch['iSearchRank'] += 1000; // skip;
507 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
508 // $aSearch['iNamePhrase'] = $iPhrase;
510 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
514 if (isset($aValidTokens[$sToken]))
516 // Allow searching for a word - but at extra cost
517 foreach($aValidTokens[$sToken] as $aSearchTerm)
519 //var_Dump('<hr>',$aSearch['aName']);
521 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
523 $aSearch = $aCurrentSearch;
524 $aSearch['iSearchRank'] += 1;
525 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
526 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
529 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
531 $aSearch = $aCurrentSearch;
532 $aSearch['iSearchRank'] += 2;
533 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
534 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
535 $aSearch['iNamePhrase'] = $iPhrase;
536 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
542 // Allow skipping a word - but at EXTREAM cost
543 //$aSearch = $aCurrentSearch;
544 //$aSearch['iSearchRank']+=100;
545 //$aNewWordsetSearches[] = $aSearch;
549 usort($aNewWordsetSearches, 'bySearchRank');
550 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
552 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
554 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
555 usort($aNewPhraseSearches, 'bySearchRank');
557 $aSearchHash = array();
558 foreach($aNewPhraseSearches as $iSearch => $aSearch)
560 $sHash = serialize($aSearch);
561 if (isset($aSearchHash[$sHash]))
563 unset($aNewPhraseSearches[$iSearch]);
567 $aSearchHash[$sHash] = 1;
571 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
574 // Re-group the searches by their score, junk anything over 20 as just not worth trying
575 $aGroupedSearches = array();
576 foreach($aNewPhraseSearches as $aSearch)
578 if ($aSearch['iSearchRank'] < $iMaxRank)
580 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
581 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
584 ksort($aGroupedSearches);
587 $aSearches = array();
588 foreach($aGroupedSearches as $iScore => $aNewSearches)
590 $iSearchCount += sizeof($aNewSearches);
591 $aSearches = array_merge($aSearches, $aNewSearches);
592 if ($iSearchCount > 50) break;
595 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
601 // Re-group the searches by their score, junk anything over 20 as just not worth trying
602 $aGroupedSearches = array();
603 foreach($aSearches as $aSearch)
605 if ($aSearch['iSearchRank'] < $iMaxRank)
607 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
608 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
611 ksort($aGroupedSearches);
614 if (CONST_Debug) var_Dump($aGroupedSearches);
618 $aCopyGroupedSearches = $aGroupedSearches;
619 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
621 foreach($aSearches as $iSearch => $aSearch)
623 if (sizeof($aSearch['aAddress']))
625 $iReverseItem = array_pop($aSearch['aAddress']);
626 if (isset($aPossibleMainWordIDs[$iReverseItem]))
628 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
629 $aSearch['aName'] = array($iReverseItem);
630 $aGroupedSearches[$iGroup][] = $aSearch;
632 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
633 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
639 // Filter out duplicate searches
640 $aSearchHash = array();
641 foreach($aGroupedSearches as $iGroup => $aSearches)
643 foreach($aSearches as $iSearch => $aSearch)
645 $sHash = serialize($aSearch);
646 if (isset($aSearchHash[$sHash]))
648 unset($aGroupedSearches[$iGroup][$iSearch]);
649 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
653 $aSearchHash[$sHash] = 1;
658 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
662 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
665 foreach($aSearches as $aSearch)
669 // Must have a location term
670 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
672 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
674 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
676 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
677 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
678 $sSQL .= " order by st_area(geometry) desc limit 1";
679 $aPlaceIDs = $oDB->getCol($sSQL);
684 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
685 if (!$aSearch['sClass']) continue;
686 if (CONST_Debug) var_dump('<hr>',$aSearch);
687 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
689 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
690 if ($oDB->getOne($sSQL))
692 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
693 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
694 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
695 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
696 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
697 $sSQL .= " limit $iLimit";
698 if (CONST_Debug) var_dump($sSQL);
699 $aPlaceIDs = $oDB->getCol($sSQL);
701 if (!sizeof($aPlaceIDs))
703 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
704 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
705 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
706 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
707 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
708 $sSQL .= " limit $iLimit";
709 if (CONST_Debug) var_dump($sSQL);
710 $aPlaceIDs = $oDB->getCol($sSQL);
715 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
716 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
717 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
718 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
719 $sSQL .= " limit $iLimit";
720 if (CONST_Debug) var_dump($sSQL);
721 $aPlaceIDs = $oDB->getCol($sSQL);
727 if (CONST_Debug) var_dump('<hr>',$aSearch);
728 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
729 $aPlaceIDs = array();
731 // First we need a position, either aName or fLat or both
734 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
735 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
736 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
737 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
738 if ($aSearch['fLon'] && $aSearch['fLat'])
740 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
741 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
743 if (sizeof($aExcludePlaceIDs))
745 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
747 if ($sCountryCodesSQL)
749 $aTerms[] = "country_code in ($sCountryCodesSQL)";
752 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
753 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
755 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
757 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
758 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
759 $aOrder[] = "$sImportanceSQL DESC";
763 $sSQL = "select place_id";
764 $sSQL .= " from search_name";
765 $sSQL .= " where ".join(' and ',$aTerms);
766 $sSQL .= " order by ".join(', ',$aOrder);
767 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
768 $sSQL .= " limit 50";
769 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
772 $sSQL .= " limit ".$iLimit;
774 if (CONST_Debug) var_dump($sSQL);
775 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
776 if (PEAR::IsError($aViewBoxPlaceIDs))
778 var_dump($sSQL, $aViewBoxPlaceIDs);
781 //var_dump($aViewBoxPlaceIDs);
782 // Did we have an viewbox matches?
783 $aPlaceIDs = array();
784 $bViewBoxMatch = false;
785 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
787 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
788 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
789 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
790 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
791 $aPlaceIDs[] = $aViewBoxRow['place_id'];
794 //var_Dump($aPlaceIDs);
797 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
799 $aRoadPlaceIDs = $aPlaceIDs;
800 $sPlaceIDs = join(',',$aPlaceIDs);
802 // Now they are indexed look for a house attached to a street we found
803 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
804 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
805 if (sizeof($aExcludePlaceIDs))
807 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
809 $sSQL .= " limit $iLimit";
810 if (CONST_Debug) var_dump($sSQL);
811 $aPlaceIDs = $oDB->getCol($sSQL);
813 // If not try the aux fallback table
814 if (!sizeof($aPlaceIDs))
816 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
817 if (sizeof($aExcludePlaceIDs))
819 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
821 // $sSQL .= " limit $iLimit";
822 if (CONST_Debug) var_dump($sSQL);
823 $aPlaceIDs = $oDB->getCol($sSQL);
826 if (!sizeof($aPlaceIDs))
828 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
829 if (sizeof($aExcludePlaceIDs))
831 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
833 // $sSQL .= " limit $iLimit";
834 if (CONST_Debug) var_dump($sSQL);
835 $aPlaceIDs = $oDB->getCol($sSQL);
838 // Fallback to the road
839 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
841 $aPlaceIDs = $aRoadPlaceIDs;
846 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
848 $sPlaceIDs = join(',',$aPlaceIDs);
850 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
852 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
853 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
854 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
855 $sSQL .= " order by rank_search asc limit $iLimit";
856 if (CONST_Debug) var_dump($sSQL);
857 $aPlaceIDs = $oDB->getCol($sSQL);
860 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
862 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
863 $bCacheTable = $oDB->getOne($sSQL);
865 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
867 if (CONST_Debug) var_dump($sSQL);
868 $iMaxRank = ((int)$oDB->getOne($sSQL));
870 // For state / country level searches the normal radius search doesn't work very well
872 if ($iMaxRank < 9 && $bCacheTable)
874 // Try and get a polygon to search in instead
875 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
876 if (CONST_Debug) var_dump($sSQL);
877 $sPlaceGeom = $oDB->getOne($sSQL);
887 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
888 if (CONST_Debug) var_dump($sSQL);
889 $aPlaceIDs = $oDB->getCol($sSQL);
890 $sPlaceIDs = join(',',$aPlaceIDs);
893 if ($sPlaceIDs || $sPlaceGeom)
899 // More efficient - can make the range bigger
903 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
904 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
905 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
907 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
908 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
911 $sSQL .= ",placex as f where ";
912 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
917 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
919 if (sizeof($aExcludePlaceIDs))
921 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
923 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
924 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
925 if ($iOffset) $sSQL .= " offset $iOffset";
926 $sSQL .= " limit $iLimit";
927 if (CONST_Debug) var_dump($sSQL);
928 $aPlaceIDs = $oDB->getCol($sSQL);
932 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
935 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
936 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
938 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
939 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
940 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
941 if (sizeof($aExcludePlaceIDs))
943 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
945 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
946 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
947 if ($iOffset) $sSQL .= " offset $iOffset";
948 $sSQL .= " limit $iLimit";
949 if (CONST_Debug) var_dump($sSQL);
950 $aPlaceIDs = $oDB->getCol($sSQL);
958 if (PEAR::IsError($aPlaceIDs))
960 var_dump($sSQL, $aPlaceIDs);
964 if (CONST_Debug) var_Dump($aPlaceIDs);
966 foreach($aPlaceIDs as $iPlaceID)
968 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
970 if ($iQueryLoop > 20) break;
973 if (sizeof($aResultPlaceIDs)) break;
974 if ($iGroupLoop > 4) break;
975 if ($iQueryLoop > 30) break;
978 // Did we find anything?
979 if (sizeof($aResultPlaceIDs))
981 //var_Dump($aResultPlaceIDs);exit;
982 // Get the details for display (is this a redundant extra step?)
983 $sPlaceIDs = join(',',$aResultPlaceIDs);
984 $sOrderSQL = 'CASE ';
985 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
987 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
989 $sOrderSQL .= ' ELSE 10000000 END';
990 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
991 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
992 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
993 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
994 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
995 // $sSQL .= $sOrderSQL." as porder, ";
996 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
997 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
998 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
999 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1000 if (!$bDeDupe) $sSQL .= ",place_id";
1001 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1002 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1003 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1005 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1006 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1007 $sSQL .= "null as placename,";
1008 $sSQL .= "null as ref,";
1009 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1010 // $sSQL .= $sOrderSQL." as porder, ";
1011 $sSQL .= "-0.15 as importance ";
1012 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1013 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1014 $sSQL .= "group by place_id";
1015 if (!$bDeDupe) $sSQL .= ",place_id";
1017 $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1018 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1019 $sSQL .= "null as placename,";
1020 $sSQL .= "null as ref,";
1021 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1022 // $sSQL .= $sOrderSQL." as porder, ";
1023 $sSQL .= "-0.10 as importance ";
1024 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1025 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1026 $sSQL .= "group by place_id";
1027 if (!$bDeDupe) $sSQL .= ",place_id";
1028 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1029 $sSQL .= "order by importance desc";
1030 // $sSQL .= "order by rank_search,rank_address,porder asc";
1031 if (CONST_Debug) var_dump('<hr>',$sSQL);
1032 $aSearchResults = $oDB->getAll($sSQL);
1033 //var_dump($sSQL,$aSearchResults);exit;
1035 if (PEAR::IsError($aSearchResults))
1037 var_dump($sSQL, $aSearchResults);
1041 } // end if ($sQuery)
1044 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1046 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1047 $aResultPlaceIDs = array($iPlaceID);
1049 // TODO: this needs refactoring!
1051 // Get the details for display (is this a redundant extra step?)
1052 $sPlaceIDs = join(',',$aResultPlaceIDs);
1053 $sOrderSQL = 'CASE ';
1054 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1056 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1058 $sOrderSQL .= ' ELSE 10000000 END';
1059 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1060 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1061 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1062 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1063 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1064 // $sSQL .= $sOrderSQL." as porder, ";
1065 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1066 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1067 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1068 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1069 if (!$bDeDupe) $sSQL .= ",place_id";
1070 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1071 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1072 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1074 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1075 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1076 $sSQL .= "null as placename,";
1077 $sSQL .= "null as ref,";
1078 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1079 // $sSQL .= $sOrderSQL." as porder, ";
1080 $sSQL .= "-0.15 as importance ";
1081 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1082 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1083 $sSQL .= "group by place_id";
1084 if (!$bDeDupe) $sSQL .= ",place_id";
1086 $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
1087 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1088 $sSQL .= "null as placename,";
1089 $sSQL .= "null as ref,";
1090 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1091 // $sSQL .= $sOrderSQL." as porder, ";
1092 $sSQL .= "-0.10 as importance ";
1093 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1094 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1095 $sSQL .= "group by place_id";
1096 if (!$bDeDupe) $sSQL .= ",place_id";
1097 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1098 $sSQL .= "order by importance desc";
1099 // $sSQL .= "order by rank_search,rank_address,porder asc";
1100 if (CONST_Debug) var_dump('<hr>',$sSQL);
1101 $aSearchResults = $oDB->getAll($sSQL);
1102 //var_dump($sSQL,$aSearchResults);exit;
1104 if (PEAR::IsError($aSearchResults))
1106 var_dump($sSQL, $aSearchResults);
1113 $sSearchResult = '';
1114 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1116 $sSearchResult = 'No Results Found';
1118 //var_Dump($aSearchResults);
1120 $aClassType = getClassTypesWithImportance();
1121 foreach($aSearchResults as $iResNum => $aResult)
1123 if (CONST_Search_AreaPolygons || true)
1125 // Get the bounding box and outline polygon
1126 $sSQL = "select place_id,numfeatures,area,outline,";
1127 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
1128 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
1129 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1131 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1132 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
1133 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
1134 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
1135 $aPointPolygon = $oDB->getRow($sSQL);
1136 if (PEAR::IsError($aPointPolygon))
1138 var_dump($sSQL, $aPointPolygon);
1141 if ($aPointPolygon['place_id'])
1143 // Translate geometary string to point array
1144 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1146 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1148 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1151 $iSteps = ($fRadius * 40000)^2;
1152 $fStepSize = (2*pi())/$iSteps;
1153 $aPolyPoints = array();
1154 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1156 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1158 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1159 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1160 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1161 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1164 // Output data suitable for display (points and a bounding box)
1167 $aResult['aPolyPoints'] = array();
1168 foreach($aPolyPoints as $aPoint)
1170 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1173 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1177 if (!isset($aResult['aBoundingBox']))
1180 $fDiameter = 0.0001;
1182 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1183 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1185 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1187 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1188 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1190 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1192 $fRadius = $fDiameter / 2;
1194 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1195 $fStepSize = (2*pi())/$iSteps;
1196 $aPolyPoints = array();
1197 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1199 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1201 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1202 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1203 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1204 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1206 // Output data suitable for display (points and a bounding box)
1209 $aResult['aPolyPoints'] = array();
1210 foreach($aPolyPoints as $aPoint)
1212 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1215 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1218 // Is there an icon set for this type of result?
1219 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1220 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1222 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1225 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1226 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1228 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1231 if ($bShowAddressDetails)
1233 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1234 //var_dump($aResult['address']);
1238 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1240 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1241 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1243 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1245 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1246 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1248 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1252 $aResult['importance'] = 1000000000000000;
1255 $aResult['name'] = $aResult['langaddress'];
1256 $aResult['foundorder'] = $iResNum;
1257 $aSearchResults[$iResNum] = $aResult;
1260 uasort($aSearchResults, 'byImportance');
1262 //var_dump($aSearchResults);exit;
1264 $aOSMIDDone = array();
1265 $aClassTypeNameDone = array();
1266 $aToFilter = $aSearchResults;
1267 $aSearchResults = array();
1270 foreach($aToFilter as $iResNum => $aResult)
1272 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1273 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1276 $fLat = $aResult['lat'];
1277 $fLon = $aResult['lon'];
1278 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1281 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1282 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1284 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1285 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1286 $aSearchResults[] = $aResult;
1289 // Absolute limit on number of results
1290 if (sizeof($aSearchResults) >= $iLimit) break;
1293 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1295 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1297 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1302 logEnd($oDB, $hLog, sizeof($aToFilter));
1304 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1305 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1306 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1307 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1308 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1309 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1312 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1314 $sMoreURL .= '&q='.urlencode($sQuery);
1316 if (CONST_Debug) exit;
1318 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');