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 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
423 if (!sizeof($aSearch['aName']))
425 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
426 $aSearch['iNamePhrase'] = $iPhrase;
428 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
432 if (isset($aValidTokens[$sToken]))
434 // Allow searching for a word - but at extra cost
435 foreach($aValidTokens[$sToken] as $aSearchTerm)
437 $aSearch = $aCurrentSearch;
438 $aSearch['iSearchRank']+=5;
439 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
440 if (!sizeof($aSearch['aName']) || $aSearch['iNamePhrase'] == $iPhrase)
442 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
443 $aSearch['iNamePhrase'] = $iPhrase;
445 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
450 // Allow skipping a word - but at EXTREAM cost
451 //$aSearch = $aCurrentSearch;
452 //$aSearch['iSearchRank']+=100;
453 //$aNewWordsetSearches[] = $aSearch;
457 usort($aNewWordsetSearches, 'bySearchRank');
458 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
460 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
462 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
463 usort($aNewPhraseSearches, 'bySearchRank');
464 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
467 // Re-group the searches by their score, junk anything over 20 as just not worth trying
468 $aGroupedSearches = array();
469 foreach($aNewPhraseSearches as $aSearch)
471 if ($aSearch['iSearchRank'] < $iMaxRank)
473 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
474 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
477 ksort($aGroupedSearches);
480 $aSearches = array();
481 foreach($aGroupedSearches as $iScore => $aNewSearches)
483 $iSearchCount += sizeof($aNewSearches);
484 $aSearches = array_merge($aSearches, $aNewSearches);
485 if ($iSearchCount > 50) break;
491 // Re-group the searches by their score, junk anything over 20 as just not worth trying
492 $aGroupedSearches = array();
493 foreach($aSearches as $aSearch)
495 if ($aSearch['iSearchRank'] < $iMaxRank)
497 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
498 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
501 ksort($aGroupedSearches);
504 if (CONST_Debug) var_Dump($aGroupedSearches);
508 foreach($aGroupedSearches as $iGroup => $aSearches)
510 foreach($aSearches as $iSearch => $aSearch)
512 if (sizeof($aSearch['aAddress']))
514 $aReverseSearch = $aSearch;
515 $iReverseItem = array_pop($aSearch['aAddress']);
516 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
517 $aGroupedSearches[$iGroup][] = $aReverseSearch;
523 //var_Dump($aGroupedSearches); exit;
525 // Filter out duplicate searches
526 $aSearchHash = array();
527 foreach($aGroupedSearches as $iGroup => $aSearches)
529 foreach($aSearches as $iSearch => $aSearch)
531 $sHash = serialize($aSearch);
532 if (isset($aSearchHash[$sHash]))
534 unset($aGroupedSearches[$iGroup][$iSearch]);
535 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
539 $aSearchHash[$sHash] = 1;
544 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
548 foreach($aGroupedSearches as $iGroup => $aSearches)
550 foreach($aSearches as $iSearch => $aSearch)
552 if (sizeof($aSearch['aAddress']))
554 $aReverseSearch = $aSearch;
555 $iReverseItem = array_pop($aSearch['aAddress']);
556 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
557 $aGroupedSearches[$iGroup][] = $aReverseSearch;
563 // Filter out duplicate searches
564 $aSearchHash = array();
565 foreach($aGroupedSearches as $iGroup => $aSearches)
567 foreach($aSearches as $iSearch => $aSearch)
569 $sHash = serialize($aSearch);
570 if (isset($aSearchHash[$sHash]))
572 unset($aGroupedSearches[$iGroup][$iSearch]);
573 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
577 $aSearchHash[$sHash] = 1;
582 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
586 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
589 foreach($aSearches as $aSearch)
592 // Must have a location term
593 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']))
595 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
596 if (!$aSearch['sClass']) continue;
597 if (CONST_Debug) var_dump('<hr>',$aSearch);
598 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
600 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
601 if ($oDB->getOne($sSQL))
603 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
604 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
605 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
606 $sSQL .= " limit $iLimit";
607 if (CONST_Debug) var_dump($sSQL);
608 $aPlaceIDs = $oDB->getCol($sSQL);
610 if (!sizeof($aPlaceIDs))
612 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
613 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
614 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
615 $sSQL .= " limit $iLimit";
616 if (CONST_Debug) var_dump($sSQL);
617 $aPlaceIDs = $oDB->getCol($sSQL);
622 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
623 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
624 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
625 $sSQL .= " limit $iLimit";
626 if (CONST_Debug) var_dump($sSQL);
627 $aPlaceIDs = $oDB->getCol($sSQL);
632 if ($aSearch['aName'] == array(282=>'282')) continue;
634 if (CONST_Debug) var_dump('<hr>',$aSearch);
635 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
636 $aPlaceIDs = array();
638 // First we need a position, either aName or fLat or both
641 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
642 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
643 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
644 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
645 if ($aSearch['fLon'] && $aSearch['fLat'])
647 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
648 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
650 if (sizeof($aExcludePlaceIDs))
652 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
654 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
655 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
656 if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
657 if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
658 $aOrder[] = "search_rank ASC";
662 $sSQL = "select place_id";
663 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
664 else $sSQL .= ",false as in_small";
665 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
666 else $sSQL .= ",false as in_large";
667 $sSQL .= " from search_name";
668 $sSQL .= " where ".join(' and ',$aTerms);
669 $sSQL .= " order by ".join(', ',$aOrder);
670 if ($aSearch['sHouseNumber'])
671 $sSQL .= " limit 50";
672 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
675 $sSQL .= " limit ".$iLimit;
677 if (CONST_Debug) var_dump($sSQL);
678 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
679 if (PEAR::IsError($aViewBoxPlaceIDs))
681 var_dump($sSQL, $aViewBoxPlaceIDs);
685 // Did we have an viewbox matches?
686 $aPlaceIDs = array();
687 $bViewBoxMatch = false;
688 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
690 if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
691 if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
692 if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
693 else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
694 $aPlaceIDs[] = $aViewBoxRow['place_id'];
698 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
700 $sPlaceIDs = join(',',$aPlaceIDs);
702 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
704 // Make sure everything nearby is indexed (if we pre-indexed houses this wouldn't be needed!)
705 $sSQL = "update placex set indexed = true from placex as f where placex.indexed = false";
706 $sSQL .= " and f.place_id in (".$sPlaceIDs.") and ST_DWithin(placex.geometry, f.geometry, 0.004)";
707 $sSQL .= " and placex.housenumber ~* E'".$sHouseNumberRegex."'";
708 $sSQL .= " and placex.class='place' and placex.type='house'";
709 if (CONST_Debug) var_dump($sSQL);
712 // Now they are indexed look for a house attached to a street we found
713 $sSQL = "select place_id from placex where street_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
714 if (sizeof($aExcludePlaceIDs))
716 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
718 $sSQL .= " limit $iLimit";
719 if (CONST_Debug) var_dump($sSQL);
720 $aPlaceIDs = $oDB->getCol($sSQL);
723 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
725 $sPlaceIDs = join(',',$aPlaceIDs);
727 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
729 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
730 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
731 $sSQL .= " order by rank_search asc limit $iLimit";
732 if (CONST_Debug) var_dump($sSQL);
733 $aPlaceIDs = $oDB->getCol($sSQL);
736 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
738 $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
739 if (CONST_Debug) var_dump($sSQL);
740 $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
742 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
743 if (CONST_Debug) var_dump($sSQL);
744 $aPlaceIDs = $oDB->getCol($sSQL);
745 $sPlaceIDs = join(',',$aPlaceIDs);
748 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
749 if ($oDB->getOne($sSQL))
751 // More efficient - can make the range bigger
753 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
754 $sSQL .= ",placex as f where ";
755 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
756 if (sizeof($aExcludePlaceIDs))
758 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
760 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
761 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
762 $sSQL .= " limit $iLimit";
763 if (CONST_Debug) var_dump($sSQL);
764 $aPlaceIDs = $oDB->getCol($sSQL);
768 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
769 $sSQL = "select l.place_id from placex as l,placex as f where ";
770 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
771 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
772 if (sizeof($aExcludePlaceIDs))
774 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
776 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
777 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
778 $sSQL .= " limit $iLimit";
779 if (CONST_Debug) var_dump($sSQL);
780 $aPlaceIDs = $oDB->getCol($sSQL);
787 if (PEAR::IsError($aPlaceIDs))
789 var_dump($sSQL, $aPlaceIDs);
793 if (CONST_Debug) var_Dump($aPlaceIDs);
795 foreach($aPlaceIDs as $iPlaceID)
797 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
799 if ($iQueryLoop > 20) break;
802 if (sizeof($aResultPlaceIDs)) break;
803 if ($iGroupLoop > 4) break;
804 if ($iQueryLoop > 30) break;
807 // Did we find anything?
808 if (sizeof($aResultPlaceIDs))
810 //var_Dump($aResultPlaceIDs);exit;
811 // Get the details for display (is this a redundant extra step?)
812 $sPlaceIDs = join(',',$aResultPlaceIDs);
813 $sOrderSQL = 'CASE ';
814 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
816 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
818 $sOrderSQL .= ' ELSE 10000000 END ASC';
819 $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
820 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
821 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
822 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
823 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat ";
824 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
825 $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
826 if (!$bDeDupe) $sSQL .= ",place_id";
827 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
828 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
829 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
830 $sSQL .= "order by rank_search,rank_address,".$sOrderSQL;
831 if (CONST_Debug) var_dump('<hr>',$sSQL);
832 $aSearchResults = $oDB->getAll($sSQL);
833 //var_dump($sSQL,$aSearchResults);exit;
835 if (PEAR::IsError($aSearchResults))
837 var_dump($sSQL, $aSearchResults);
845 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
847 $sSearchResult = 'No Results Found';
850 $aClassType = getClassTypesWithImportance();
852 foreach($aSearchResults as $iResNum => $aResult)
854 if (CONST_Search_AreaPolygons || true)
856 // Get the bounding box and outline polygon
857 $sSQL = "select place_id,numfeatures,area,outline,";
858 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
859 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
860 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
861 $aPointPolygon = $oDB->getRow($sSQL);
862 if (PEAR::IsError($aPointPolygon))
864 var_dump($sSQL, $aPointPolygon);
867 if ($aPointPolygon['place_id'])
869 // Translate geometary string to point array
870 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
872 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
874 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
877 $iSteps = ($fRadius * 40000)^2;
878 $fStepSize = (2*pi())/$iSteps;
879 $aPolyPoints = array();
880 for($f = 0; $f < 2*pi(); $f += $fStepSize)
882 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
884 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
885 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
886 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
887 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
890 // Output data suitable for display (points and a bounding box)
893 $aResult['aPolyPoints'] = array();
894 foreach($aPolyPoints as $aPoint)
896 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
899 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
903 if (!isset($aResult['aBoundingBox']))
908 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
909 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
911 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
913 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
914 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
916 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
918 $fRadius = $fDiameter / 2;
920 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
921 $fStepSize = (2*pi())/$iSteps;
922 $aPolyPoints = array();
923 for($f = 0; $f < 2*pi(); $f += $fStepSize)
925 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
927 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
928 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
929 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
930 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
932 // Output data suitable for display (points and a bounding box)
935 $aResult['aPolyPoints'] = array();
936 foreach($aPolyPoints as $aPoint)
938 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
941 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
944 // Is there an icon set for this type of result?
945 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
946 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
948 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
951 if ($bShowAddressDetails)
953 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
956 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
957 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
959 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
963 $aResult['importance'] = 1000000000000000;
966 $aResult['name'] = $aResult['langaddress'];
967 $aResult['foundorder'] = $iResNum;
968 $aSearchResults[$iResNum] = $aResult;
971 uasort($aSearchResults, 'byImportance');
973 $aOSMIDDone = array();
974 $aClassTypeNameDone = array();
975 $aToFilter = $aSearchResults;
976 $aSearchResults = array();
979 foreach($aToFilter as $iResNum => $aResult)
981 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
982 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
985 $fLat = $aResult['lat'];
986 $fLon = $aResult['lon'];
987 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
990 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
991 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
993 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
994 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
995 $aSearchResults[] = $aResult;
999 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1001 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1003 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1008 logEnd($oDB, $hLog, sizeof($aToFilter));
1010 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1011 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1012 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1013 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1014 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1015 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1018 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1020 $sMoreURL .= '&q='.urlencode($sQuery);
1022 if (CONST_Debug) exit;
1024 include('.htlib/output/search-'.$sOutputFormat.'.php');