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 $sSuggestion = $sSuggestionURL = false;
17 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
18 $bReverseInPlan = false;
19 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 if ($iLimit > 100) $iLimit = 100;
24 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
26 $sOutputFormat = $_GET['format'];
29 // Show / use polygons
30 $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
32 // Show address breakdown
33 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
36 $aLangPrefOrder = getPrefferedLangauges();
37 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
38 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
40 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
42 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
44 $iExcludedPlaceID = (int)$iExcludedPlaceID;
45 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
50 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
51 if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
53 $sQuery = substr($_SERVER['PATH_INFO'], 1);
55 // reverse order of '/' seperated string
56 $aPhrases = explode('/', $sQuery);
57 $aPhrases = array_reverse($aPhrases);
58 $sQuery = join(', ',$aPhrases);
63 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
65 // If we have a view box create the SQL
66 // Small is the actual view box, Large is double (on each axis) that
67 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
68 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
70 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
71 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
73 if (isset($_GET['viewbox']) && $_GET['viewbox'])
75 $aCoOrdinates = explode(',',$_GET['viewbox']);
76 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
77 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
78 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
79 $aCoOrdinates[0] += $fHeight;
80 $aCoOrdinates[2] -= $fHeight;
81 $aCoOrdinates[1] += $fWidth;
82 $aCoOrdinates[3] -= $fWidth;
83 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
85 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
87 $aPoints = explode(',',$_GET['route']);
88 if (sizeof($aPoints) % 2 != 0)
90 echo "Uneven number of points";
93 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
95 foreach($aPoints as $i => $fPoint)
99 if ($i != 1) $sViewboxCentreSQL .= ",";
100 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
104 $fPrevCoord = (float)$fPoint;
107 $sViewboxCentreSQL .= ")'::geometry,4326)";
109 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
110 $sViewboxSmallSQL = $oDB->getOne($sSQL);
111 if (PEAR::isError($sViewboxSmallSQL))
113 var_dump($sViewboxSmallSQL);
116 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
118 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
119 $sViewboxLargeSQL = $oDB->getOne($sSQL);
120 if (PEAR::isError($sViewboxLargeSQL))
122 var_dump($sViewboxLargeSQL);
125 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
128 // Do we have anything that looks like a lat/lon pair?
129 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
131 $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
132 $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
133 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
135 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
137 $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
138 $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
139 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
141 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b])/', $sQuery, $aData))
143 $_GET['nearlat'] = $aData[2];
144 $_GET['nearlon'] = $aData[3];
145 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
151 // Start with a blank search
153 array('iSearchRank' => 0, 'iNamePhrase' => 0, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
154 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
157 $sNearPointSQL = false;
158 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
160 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
161 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
162 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
163 $aSearches[0]['fRadius'] = 0.1;
166 $bSpecialTerms = false;
167 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
168 $aSpecialTerms = array();
169 foreach($aSpecialTermsRaw as $aSpecialTerm)
171 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
172 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
175 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
176 $aSpecialTerms = array();
177 foreach($aSpecialTermsRaw as $aSpecialTerm)
179 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
180 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
181 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
182 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class != \'place\') or country_code is not null';
183 $aSearchWords = $oDB->getAll($sSQL);
184 $aNewSearches = array();
185 foreach($aSearches as $aSearch)
187 foreach($aSearchWords as $aSearchTerm)
189 $aNewSearch = $aSearch;
190 if ($aSearchTerm['country_code'])
192 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
193 $aNewSearches[] = $aNewSearch;
194 $bSpecialTerms = true;
196 if ($aSearchTerm['class'])
198 $aNewSearch['sClass'] = $aSearchTerm['class'];
199 $aNewSearch['sType'] = $aSearchTerm['type'];
200 $aNewSearches[] = $aNewSearch;
201 $bSpecialTerms = true;
205 $aSearches = $aNewSearches;
208 // Split query into phrases
209 // Commas are used to reduce the search space by indicating where phrases split
210 $aPhrases = explode(',',$sQuery);
212 // Convert each phrase to standard form
213 // Create a list of standard words
214 // Get all 'sets' of words
215 // Generate a complete list of all
217 foreach($aPhrases as $iPhrase => $sPhrase)
219 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
220 if (PEAR::isError($aPhrase))
225 if (trim($aPhrase['string']))
227 $aPhrases[$iPhrase] = $aPhrase;
228 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
229 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
230 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
234 unset($aPhrases[$iPhrase]);
238 // reindex phrases - we make assumptions later on
239 $aPhrases = array_values($aPhrases);
241 if (sizeof($aTokens))
244 // Check which tokens we have, get the ID numbers
245 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
246 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
247 // $sSQL .= ' group by word_token, word, class, type, location,country_code';
249 if (CONST_Debug) var_Dump($sSQL);
251 $aValidTokens = array();
252 if (sizeof($aTokens))
253 $aDatabaseWords = $oDB->getAll($sSQL);
255 $aDatabaseWords = array();
256 if (PEAR::IsError($aDatabaseWords))
258 var_dump($sSQL, $aDatabaseWords);
261 foreach($aDatabaseWords as $aToken)
263 if (isset($aValidTokens[$aToken['word_token']]))
265 $aValidTokens[$aToken['word_token']][] = $aToken;
269 $aValidTokens[$aToken['word_token']] = array($aToken);
272 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
274 $aSuggestion = array();
275 $bSuggestion = false;
276 if (CONST_Suggestions_Enabled)
278 foreach($aPhrases as $iPhrase => $aPhrase)
280 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
282 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
283 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
284 $aRow = $aSuggestionWords[0];
285 if ($aRow && $aRow['word'])
287 $aSuggestion[] = $aRow['word'];
292 $aSuggestion[] = $aPhrase['string'];
297 $aSuggestion[] = $aPhrase['string'];
301 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
303 // Try and calculate GB postcodes we might be missing
304 foreach($aTokens as $sToken)
306 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))
308 if (substr($aData[1],-2,1) != ' ')
310 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
311 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
313 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
314 if ($aGBPostcodeLocation)
316 $aValidTokens[$sToken] = $aGBPostcodeLocation;
321 // Any words that have failed completely?
324 // Start the search process
325 $aResultPlaceIDs = array();
328 Calculate all searches using aValidTokens i.e.
330 'Wodsworth Road, Sheffield' =>
334 0 1 (wodsworth)(road)
337 Score how good the search is so they can be ordered
340 foreach($aPhrases as $iPhrase => $sPhrase)
342 $aNewPhraseSearches = array();
344 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
346 $aWordsetSearches = $aSearches;
348 // Add all words from this wordset
349 foreach($aWordset as $sToken)
351 $aNewWordsetSearches = array();
353 foreach($aWordsetSearches as $aCurrentSearch)
355 // If the token is valid
356 if (isset($aValidTokens[' '.$sToken]))
358 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
360 $aSearch = $aCurrentSearch;
361 $aSearch['iSearchRank']++;
362 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
364 if ($aSearch['sCountryCode'] === false)
366 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
367 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
368 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
369 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
372 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
374 if ($aSearch['fLat'] === '')
376 $aSearch['fLat'] = $aSearchTerm['lat'];
377 $aSearch['fLon'] = $aSearchTerm['lon'];
378 $aSearch['fRadius'] = $aSearchTerm['radius'];
379 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
382 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
384 if ($aSearch['sHouseNumber'] === '')
386 $aSearch['sHouseNumber'] = $sToken;
387 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
389 // Fall back to not searching for this item (better than nothing)
390 $aSearch = $aCurrentSearch;
391 $aSearch['iSearchRank'] += 2;
392 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
395 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
397 if ($aSearch['sClass'] === '')
399 $aSearch['sOperator'] = $aSearchTerm['operator'];
400 $aSearch['sClass'] = $aSearchTerm['class'];
401 $aSearch['sType'] = $aSearchTerm['type'];
402 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
403 else $aSearch['sOperator'] = 'near'; // near = in for the moment
405 // Do we have a shortcut id?
406 if ($aSearch['sOperator'] == 'name')
408 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
409 if ($iAmenityID = $oDB->getOne($sSQL))
411 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
412 $aSearch['aName'][$iAmenityID] = $iAmenityID;
413 $aSearch['sClass'] = '';
414 $aSearch['sType'] = '';
417 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
422 if (sizeof($aSearch['aName']))
424 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
428 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
429 $aSearch['iNamePhrase'] = $iPhrase;
431 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
435 if (isset($aValidTokens[$sToken]))
437 // Allow searching for a word - but at extra cost
438 foreach($aValidTokens[$sToken] as $aSearchTerm)
440 $aSearch = $aCurrentSearch;
441 $aSearch['iSearchRank']+=5;
442 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
443 if (!sizeof($aSearch['aName']) || $aSearch['iNamePhrase'] == $iPhrase)
445 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
446 $aSearch['iNamePhrase'] = $iPhrase;
448 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
453 // Allow skipping a word - but at EXTREAM cost
454 //$aSearch = $aCurrentSearch;
455 //$aSearch['iSearchRank']+=100;
456 //$aNewWordsetSearches[] = $aSearch;
460 usort($aNewWordsetSearches, 'bySearchRank');
461 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
463 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
465 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
466 usort($aNewPhraseSearches, 'bySearchRank');
467 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
470 // Re-group the searches by their score, junk anything over 20 as just not worth trying
471 $aGroupedSearches = array();
472 foreach($aNewPhraseSearches as $aSearch)
474 if ($aSearch['iSearchRank'] < $iMaxRank)
476 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
477 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
480 ksort($aGroupedSearches);
483 $aSearches = array();
484 foreach($aGroupedSearches as $iScore => $aNewSearches)
486 $iSearchCount += sizeof($aNewSearches);
487 $aSearches = array_merge($aSearches, $aNewSearches);
488 if ($iSearchCount > 50) break;
494 // Re-group the searches by their score, junk anything over 20 as just not worth trying
495 $aGroupedSearches = array();
496 foreach($aSearches as $aSearch)
498 if ($aSearch['iSearchRank'] < $iMaxRank)
500 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
501 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
504 ksort($aGroupedSearches);
507 if (CONST_Debug) var_Dump($aGroupedSearches);
511 foreach($aGroupedSearches as $iGroup => $aSearches)
513 foreach($aSearches as $iSearch => $aSearch)
515 if (sizeof($aSearch['aAddress']))
517 $aReverseSearch = $aSearch;
518 $iReverseItem = array_pop($aSearch['aAddress']);
519 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
520 $aGroupedSearches[$iGroup][] = $aReverseSearch;
526 //var_Dump($aGroupedSearches); exit;
528 // Filter out duplicate searches
529 $aSearchHash = array();
530 foreach($aGroupedSearches as $iGroup => $aSearches)
532 foreach($aSearches as $iSearch => $aSearch)
534 $sHash = serialize($aSearch);
535 if (isset($aSearchHash[$sHash]))
537 unset($aGroupedSearches[$iGroup][$iSearch]);
538 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
542 $aSearchHash[$sHash] = 1;
547 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
551 foreach($aGroupedSearches as $iGroup => $aSearches)
553 foreach($aSearches as $iSearch => $aSearch)
555 if (sizeof($aSearch['aAddress']))
557 $aReverseSearch = $aSearch;
558 $iReverseItem = array_pop($aSearch['aAddress']);
559 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
560 $aGroupedSearches[$iGroup][] = $aReverseSearch;
566 // Filter out duplicate searches
567 $aSearchHash = array();
568 foreach($aGroupedSearches as $iGroup => $aSearches)
570 foreach($aSearches as $iSearch => $aSearch)
572 $sHash = serialize($aSearch);
573 if (isset($aSearchHash[$sHash]))
575 unset($aGroupedSearches[$iGroup][$iSearch]);
576 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
580 $aSearchHash[$sHash] = 1;
585 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
589 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
592 foreach($aSearches as $aSearch)
595 // Must have a location term
596 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress'] && !$aSearch['fLon']))
598 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
599 if (!$aSearch['sClass']) continue;
600 if (CONST_Debug) var_dump('<hr>',$aSearch);
601 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
603 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
604 if ($oDB->getOne($sSQL))
606 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
607 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
608 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
609 $sSQL .= " limit $iLimit";
610 if (CONST_Debug) var_dump($sSQL);
611 $aPlaceIDs = $oDB->getCol($sSQL);
613 if (!sizeof($aPlaceIDs))
615 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
616 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
617 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
618 $sSQL .= " limit $iLimit";
619 if (CONST_Debug) var_dump($sSQL);
620 $aPlaceIDs = $oDB->getCol($sSQL);
625 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
626 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
627 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
628 $sSQL .= " limit $iLimit";
629 if (CONST_Debug) var_dump($sSQL);
630 $aPlaceIDs = $oDB->getCol($sSQL);
635 if ($aSearch['aName'] == array(282=>'282')) continue;
637 if (CONST_Debug) var_dump('<hr>',$aSearch);
638 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
639 $aPlaceIDs = array();
641 // First we need a position, either aName or fLat or both
644 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
645 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
646 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
647 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
648 if ($aSearch['fLon'] && $aSearch['fLat'])
650 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
651 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
653 if (sizeof($aExcludePlaceIDs))
655 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
657 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
658 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
659 if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
660 if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
661 $aOrder[] = "search_rank ASC";
665 $sSQL = "select place_id";
666 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
667 else $sSQL .= ",false as in_small";
668 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
669 else $sSQL .= ",false as in_large";
670 $sSQL .= " from search_name";
671 $sSQL .= " where ".join(' and ',$aTerms);
672 $sSQL .= " order by ".join(', ',$aOrder);
673 if ($aSearch['sHouseNumber'])
674 $sSQL .= " limit 50";
675 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
678 $sSQL .= " limit ".$iLimit;
680 if (CONST_Debug) var_dump($sSQL);
681 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
682 if (PEAR::IsError($aViewBoxPlaceIDs))
684 var_dump($sSQL, $aViewBoxPlaceIDs);
688 // Did we have an viewbox matches?
689 $aPlaceIDs = array();
690 $bViewBoxMatch = false;
691 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
693 if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
694 if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
695 if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
696 else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
697 $aPlaceIDs[] = $aViewBoxRow['place_id'];
701 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
703 $sPlaceIDs = join(',',$aPlaceIDs);
705 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
707 // Make sure everything nearby is indexed (if we pre-indexed houses this wouldn't be needed!)
708 $sSQL = "update placex set indexed = true from placex as f where placex.indexed = false";
709 $sSQL .= " and f.place_id in (".$sPlaceIDs.") and ST_DWithin(placex.geometry, f.geometry, 0.004)";
710 $sSQL .= " and placex.housenumber ~* E'".$sHouseNumberRegex."'";
711 $sSQL .= " and placex.class='place' and placex.type='house'";
712 if (CONST_Debug) var_dump($sSQL);
715 // Now they are indexed look for a house attached to a street we found
716 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
717 if (sizeof($aExcludePlaceIDs))
719 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
721 $sSQL .= " limit $iLimit";
722 if (CONST_Debug) var_dump($sSQL);
723 $aPlaceIDs = $oDB->getCol($sSQL);
726 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
728 $sPlaceIDs = join(',',$aPlaceIDs);
730 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
732 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
733 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
734 $sSQL .= " order by rank_search asc limit $iLimit";
735 if (CONST_Debug) var_dump($sSQL);
736 $aPlaceIDs = $oDB->getCol($sSQL);
739 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
741 $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
742 if (CONST_Debug) var_dump($sSQL);
743 $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
745 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
746 if (CONST_Debug) var_dump($sSQL);
747 $aPlaceIDs = $oDB->getCol($sSQL);
748 $sPlaceIDs = join(',',$aPlaceIDs);
751 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
752 if ($oDB->getOne($sSQL))
754 // More efficient - can make the range bigger
756 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
757 $sSQL .= ",placex as f where ";
758 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
759 if (sizeof($aExcludePlaceIDs))
761 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
763 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
764 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
765 $sSQL .= " limit $iLimit";
766 if (CONST_Debug) var_dump($sSQL);
767 $aPlaceIDs = $oDB->getCol($sSQL);
771 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
772 $sSQL = "select l.place_id from placex as l,placex as f where ";
773 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
774 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
775 if (sizeof($aExcludePlaceIDs))
777 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
779 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
780 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
781 $sSQL .= " limit $iLimit";
782 if (CONST_Debug) var_dump($sSQL);
783 $aPlaceIDs = $oDB->getCol($sSQL);
790 if (PEAR::IsError($aPlaceIDs))
792 var_dump($sSQL, $aPlaceIDs);
796 if (CONST_Debug) var_Dump($aPlaceIDs);
798 foreach($aPlaceIDs as $iPlaceID)
800 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
802 if ($iQueryLoop > 20) break;
805 if (sizeof($aResultPlaceIDs)) break;
806 if ($iGroupLoop > 4) break;
807 if ($iQueryLoop > 30) break;
810 // Did we find anything?
811 if (sizeof($aResultPlaceIDs))
813 //var_Dump($aResultPlaceIDs);exit;
814 // Get the details for display (is this a redundant extra step?)
815 $sPlaceIDs = join(',',$aResultPlaceIDs);
816 $sOrderSQL = 'CASE ';
817 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
819 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
821 $sOrderSQL .= ' ELSE 10000000 END ASC';
822 $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
823 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
824 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
825 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
826 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat ";
827 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
828 $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
829 if (!$bDeDupe) $sSQL .= ",place_id";
830 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
831 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
832 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
833 $sSQL .= "order by rank_search,rank_address,".$sOrderSQL;
834 if (CONST_Debug) var_dump('<hr>',$sSQL);
835 $aSearchResults = $oDB->getAll($sSQL);
836 //var_dump($sSQL,$aSearchResults);exit;
838 if (PEAR::IsError($aSearchResults))
840 var_dump($sSQL, $aSearchResults);
848 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
850 $sSearchResult = 'No Results Found';
853 $aClassType = getClassTypesWithImportance();
855 foreach($aSearchResults as $iResNum => $aResult)
857 if (CONST_Search_AreaPolygons || true)
859 // Get the bounding box and outline polygon
860 $sSQL = "select place_id,numfeatures,area,outline,";
861 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
862 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
863 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
864 $aPointPolygon = $oDB->getRow($sSQL);
865 if (PEAR::IsError($aPointPolygon))
867 var_dump($sSQL, $aPointPolygon);
870 if ($aPointPolygon['place_id'])
872 // Translate geometary string to point array
873 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
875 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
877 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
880 $iSteps = ($fRadius * 40000)^2;
881 $fStepSize = (2*pi())/$iSteps;
882 $aPolyPoints = array();
883 for($f = 0; $f < 2*pi(); $f += $fStepSize)
885 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
887 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
888 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
889 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
890 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
893 // Output data suitable for display (points and a bounding box)
896 $aResult['aPolyPoints'] = array();
897 foreach($aPolyPoints as $aPoint)
899 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
902 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
906 if (!isset($aResult['aBoundingBox']))
911 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
912 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
914 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
916 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
917 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
919 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
921 $fRadius = $fDiameter / 2;
923 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
924 $fStepSize = (2*pi())/$iSteps;
925 $aPolyPoints = array();
926 for($f = 0; $f < 2*pi(); $f += $fStepSize)
928 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
930 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
931 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
932 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
933 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
935 // Output data suitable for display (points and a bounding box)
938 $aResult['aPolyPoints'] = array();
939 foreach($aPolyPoints as $aPoint)
941 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
944 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
947 // Is there an icon set for this type of result?
948 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
949 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
951 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
954 if ($bShowAddressDetails)
956 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
959 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
960 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
962 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
966 $aResult['importance'] = 1000000000000000;
969 $aResult['name'] = $aResult['langaddress'];
970 $aResult['foundorder'] = $iResNum;
971 $aSearchResults[$iResNum] = $aResult;
974 uasort($aSearchResults, 'byImportance');
976 $aOSMIDDone = array();
977 $aClassTypeNameDone = array();
978 $aToFilter = $aSearchResults;
979 $aSearchResults = array();
982 foreach($aToFilter as $iResNum => $aResult)
984 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
985 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
988 $fLat = $aResult['lat'];
989 $fLon = $aResult['lon'];
990 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
993 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
994 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
996 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
997 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
998 $aSearchResults[] = $aResult;
1002 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1004 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1006 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1011 logEnd($oDB, $hLog, sizeof($aToFilter));
1013 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1014 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1015 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1016 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1017 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1018 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1021 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1023 $sMoreURL .= '&q='.urlencode($sQuery);
1025 if (CONST_Debug) exit;
1027 include('.htlib/output/search-'.$sOutputFormat.'.php');