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;
20 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
22 if ($iLimit > 100) $iLimit = 100;
25 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
27 $sOutputFormat = $_GET['format'];
30 // Show / use polygons
31 $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
33 // Show address breakdown
34 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
37 $aLangPrefOrder = getPrefferedLangauges();
38 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
39 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
41 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
43 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
45 $iExcludedPlaceID = (int)$iExcludedPlaceID;
46 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
51 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
52 if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
54 $sQuery = substr($_SERVER['PATH_INFO'], 1);
56 // reverse order of '/' seperated string
57 $aPhrases = explode('/', $sQuery);
58 $aPhrases = array_reverse($aPhrases);
59 $sQuery = join(', ',$aPhrases);
64 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
66 // If we have a view box create the SQL
67 // Small is the actual view box, Large is double (on each axis) that
68 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
69 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
71 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
72 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
74 if (isset($_GET['viewbox']) && $_GET['viewbox'])
76 $aCoOrdinates = explode(',',$_GET['viewbox']);
77 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
78 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
79 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
80 $aCoOrdinates[0] += $fHeight;
81 $aCoOrdinates[2] -= $fHeight;
82 $aCoOrdinates[1] += $fWidth;
83 $aCoOrdinates[3] -= $fWidth;
84 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
86 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
88 $aPoints = explode(',',$_GET['route']);
89 if (sizeof($aPoints) % 2 != 0)
91 echo "Uneven number of points";
94 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
96 foreach($aPoints as $i => $fPoint)
100 if ($i != 1) $sViewboxCentreSQL .= ",";
101 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
105 $fPrevCoord = (float)$fPoint;
108 $sViewboxCentreSQL .= ")'::geometry,4326)";
110 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
111 $sViewboxSmallSQL = $oDB->getOne($sSQL);
112 if (PEAR::isError($sViewboxSmallSQL))
114 var_dump($sViewboxSmallSQL);
117 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
119 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
120 $sViewboxLargeSQL = $oDB->getOne($sSQL);
121 if (PEAR::isError($sViewboxLargeSQL))
123 var_dump($sViewboxLargeSQL);
126 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
129 // Do we have anything that looks like a lat/lon pair?
130 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
132 $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
133 $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
134 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
136 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
138 $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
139 $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
140 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
142 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b])/', $sQuery, $aData))
144 $_GET['nearlat'] = $aData[2];
145 $_GET['nearlon'] = $aData[3];
146 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
152 // Start with a blank search
154 array('iSearchRank' => 0, 'iNamePhrase' => 0, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
155 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
158 $sNearPointSQL = false;
159 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
161 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
162 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
163 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
164 $aSearches[0]['fRadius'] = 0.1;
167 $bSpecialTerms = false;
168 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
169 $aSpecialTerms = array();
170 foreach($aSpecialTermsRaw as $aSpecialTerm)
172 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
173 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
176 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
177 $aSpecialTerms = array();
178 foreach($aSpecialTermsRaw as $aSpecialTerm)
180 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
181 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
182 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
183 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class != \'place\') or country_code is not null';
184 $aSearchWords = $oDB->getAll($sSQL);
185 $aNewSearches = array();
186 foreach($aSearches as $aSearch)
188 foreach($aSearchWords as $aSearchTerm)
190 $aNewSearch = $aSearch;
191 if ($aSearchTerm['country_code'])
193 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
194 $aNewSearches[] = $aNewSearch;
195 $bSpecialTerms = true;
197 if ($aSearchTerm['class'])
199 $aNewSearch['sClass'] = $aSearchTerm['class'];
200 $aNewSearch['sType'] = $aSearchTerm['type'];
201 $aNewSearches[] = $aNewSearch;
202 $bSpecialTerms = true;
206 $aSearches = $aNewSearches;
209 // Split query into phrases
210 // Commas are used to reduce the search space by indicating where phrases split
211 $aPhrases = explode(',',$sQuery);
213 // Convert each phrase to standard form
214 // Create a list of standard words
215 // Get all 'sets' of words
216 // Generate a complete list of all
218 foreach($aPhrases as $iPhrase => $sPhrase)
220 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
221 if (PEAR::isError($aPhrase))
226 if (trim($aPhrase['string']))
228 $aPhrases[$iPhrase] = $aPhrase;
229 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
230 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
231 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
235 unset($aPhrases[$iPhrase]);
239 // reindex phrases - we make assumptions later on
240 $aPhrases = array_values($aPhrases);
242 if (sizeof($aTokens))
245 // Check which tokens we have, get the ID numbers
246 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
247 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
248 // $sSQL .= ' group by word_token, word, class, type, location,country_code';
250 if (CONST_Debug) var_Dump($sSQL);
252 $aValidTokens = array();
253 if (sizeof($aTokens))
254 $aDatabaseWords = $oDB->getAll($sSQL);
256 $aDatabaseWords = array();
257 if (PEAR::IsError($aDatabaseWords))
259 var_dump($sSQL, $aDatabaseWords);
262 foreach($aDatabaseWords as $aToken)
264 if (isset($aValidTokens[$aToken['word_token']]))
266 $aValidTokens[$aToken['word_token']][] = $aToken;
270 $aValidTokens[$aToken['word_token']] = array($aToken);
273 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
275 $aSuggestion = array();
276 $bSuggestion = false;
277 if (CONST_Suggestions_Enabled)
279 foreach($aPhrases as $iPhrase => $aPhrase)
281 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
283 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
284 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
285 $aRow = $aSuggestionWords[0];
286 if ($aRow && $aRow['word'])
288 $aSuggestion[] = $aRow['word'];
293 $aSuggestion[] = $aPhrase['string'];
298 $aSuggestion[] = $aPhrase['string'];
302 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
304 // Try and calculate GB postcodes we might be missing
305 foreach($aTokens as $sToken)
307 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))
309 if (substr($aData[1],-2,1) != ' ')
311 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
312 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
314 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
315 if ($aGBPostcodeLocation)
317 $aValidTokens[$sToken] = $aGBPostcodeLocation;
322 // Any words that have failed completely?
325 // Start the search process
326 $aResultPlaceIDs = array();
329 Calculate all searches using aValidTokens i.e.
331 'Wodsworth Road, Sheffield' =>
335 0 1 (wodsworth)(road)
338 Score how good the search is so they can be ordered
341 foreach($aPhrases as $iPhrase => $sPhrase)
343 $aNewPhraseSearches = array();
345 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
347 $aWordsetSearches = $aSearches;
349 // Add all words from this wordset
350 foreach($aWordset as $sToken)
352 $aNewWordsetSearches = array();
354 foreach($aWordsetSearches as $aCurrentSearch)
356 // If the token is valid
357 if (isset($aValidTokens[' '.$sToken]))
359 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
361 $aSearch = $aCurrentSearch;
362 $aSearch['iSearchRank']++;
363 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
365 if ($aSearch['sCountryCode'] === false)
367 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
368 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
369 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
370 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
373 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
375 if ($aSearch['fLat'] === '')
377 $aSearch['fLat'] = $aSearchTerm['lat'];
378 $aSearch['fLon'] = $aSearchTerm['lon'];
379 $aSearch['fRadius'] = $aSearchTerm['radius'];
380 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
383 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
385 if ($aSearch['sHouseNumber'] === '')
387 $aSearch['sHouseNumber'] = $sToken;
388 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
390 // Fall back to not searching for this item (better than nothing)
391 $aSearch = $aCurrentSearch;
392 $aSearch['iSearchRank'] += 2;
393 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
396 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
398 if ($aSearch['sClass'] === '')
400 $aSearch['sOperator'] = $aSearchTerm['operator'];
401 $aSearch['sClass'] = $aSearchTerm['class'];
402 $aSearch['sType'] = $aSearchTerm['type'];
403 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
404 else $aSearch['sOperator'] = 'near'; // near = in for the moment
406 // Do we have a shortcut id?
407 if ($aSearch['sOperator'] == 'name')
409 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
410 if ($iAmenityID = $oDB->getOne($sSQL))
412 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
413 $aSearch['aName'][$iAmenityID] = $iAmenityID;
414 $aSearch['sClass'] = '';
415 $aSearch['sType'] = '';
418 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
423 if (sizeof($aSearch['aName']))
425 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
429 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
430 $aSearch['iNamePhrase'] = $iPhrase;
432 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
436 if (isset($aValidTokens[$sToken]))
438 // Allow searching for a word - but at extra cost
439 foreach($aValidTokens[$sToken] as $aSearchTerm)
441 $aSearch = $aCurrentSearch;
442 $aSearch['iSearchRank']+=5;
443 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
444 if (!sizeof($aSearch['aName']) || $aSearch['iNamePhrase'] == $iPhrase)
446 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
447 $aSearch['iNamePhrase'] = $iPhrase;
449 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
454 // Allow skipping a word - but at EXTREAM cost
455 //$aSearch = $aCurrentSearch;
456 //$aSearch['iSearchRank']+=100;
457 //$aNewWordsetSearches[] = $aSearch;
461 usort($aNewWordsetSearches, 'bySearchRank');
462 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
464 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
466 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
467 usort($aNewPhraseSearches, 'bySearchRank');
468 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
471 // Re-group the searches by their score, junk anything over 20 as just not worth trying
472 $aGroupedSearches = array();
473 foreach($aNewPhraseSearches as $aSearch)
475 if ($aSearch['iSearchRank'] < $iMaxRank)
477 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
478 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
481 ksort($aGroupedSearches);
484 $aSearches = array();
485 foreach($aGroupedSearches as $iScore => $aNewSearches)
487 $iSearchCount += sizeof($aNewSearches);
488 $aSearches = array_merge($aSearches, $aNewSearches);
489 if ($iSearchCount > 50) break;
495 // Re-group the searches by their score, junk anything over 20 as just not worth trying
496 $aGroupedSearches = array();
497 foreach($aSearches as $aSearch)
499 if ($aSearch['iSearchRank'] < $iMaxRank)
501 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
502 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
505 ksort($aGroupedSearches);
508 if (CONST_Debug) var_Dump($aGroupedSearches);
512 foreach($aGroupedSearches as $iGroup => $aSearches)
514 foreach($aSearches as $iSearch => $aSearch)
516 if (sizeof($aSearch['aAddress']))
518 $aReverseSearch = $aSearch;
519 $iReverseItem = array_pop($aSearch['aAddress']);
520 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
521 $aGroupedSearches[$iGroup][] = $aReverseSearch;
527 //var_Dump($aGroupedSearches); exit;
529 // Filter out duplicate searches
530 $aSearchHash = array();
531 foreach($aGroupedSearches as $iGroup => $aSearches)
533 foreach($aSearches as $iSearch => $aSearch)
535 $sHash = serialize($aSearch);
536 if (isset($aSearchHash[$sHash]))
538 unset($aGroupedSearches[$iGroup][$iSearch]);
539 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
543 $aSearchHash[$sHash] = 1;
548 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
552 foreach($aGroupedSearches as $iGroup => $aSearches)
554 foreach($aSearches as $iSearch => $aSearch)
556 if (sizeof($aSearch['aAddress']))
558 $aReverseSearch = $aSearch;
559 $iReverseItem = array_pop($aSearch['aAddress']);
560 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
561 $aGroupedSearches[$iGroup][] = $aReverseSearch;
567 // Filter out duplicate searches
568 $aSearchHash = array();
569 foreach($aGroupedSearches as $iGroup => $aSearches)
571 foreach($aSearches as $iSearch => $aSearch)
573 $sHash = serialize($aSearch);
574 if (isset($aSearchHash[$sHash]))
576 unset($aGroupedSearches[$iGroup][$iSearch]);
577 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
581 $aSearchHash[$sHash] = 1;
586 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
590 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
593 foreach($aSearches as $aSearch)
596 // Must have a location term
597 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress'] && !$aSearch['fLon']))
599 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
600 if (!$aSearch['sClass']) continue;
601 if (CONST_Debug) var_dump('<hr>',$aSearch);
602 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
604 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
605 if ($oDB->getOne($sSQL))
607 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
608 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
609 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
610 $sSQL .= " limit $iLimit";
611 if (CONST_Debug) var_dump($sSQL);
612 $aPlaceIDs = $oDB->getCol($sSQL);
614 if (!sizeof($aPlaceIDs))
616 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
617 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
618 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
619 $sSQL .= " limit $iLimit";
620 if (CONST_Debug) var_dump($sSQL);
621 $aPlaceIDs = $oDB->getCol($sSQL);
626 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
627 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
628 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
629 $sSQL .= " limit $iLimit";
630 if (CONST_Debug) var_dump($sSQL);
631 $aPlaceIDs = $oDB->getCol($sSQL);
636 if ($aSearch['aName'] == array(282=>'282')) continue;
638 if (CONST_Debug) var_dump('<hr>',$aSearch);
639 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
640 $aPlaceIDs = array();
642 // First we need a position, either aName or fLat or both
645 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
646 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
647 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
648 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
649 if ($aSearch['fLon'] && $aSearch['fLat'])
651 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
652 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
654 if (sizeof($aExcludePlaceIDs))
656 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
658 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
659 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
660 if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
661 if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
662 $aOrder[] = "search_rank ASC";
666 $sSQL = "select place_id";
667 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
668 else $sSQL .= ",false as in_small";
669 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
670 else $sSQL .= ",false as in_large";
671 $sSQL .= " from search_name";
672 $sSQL .= " where ".join(' and ',$aTerms);
673 $sSQL .= " order by ".join(', ',$aOrder);
674 if ($aSearch['sHouseNumber'])
675 $sSQL .= " limit 50";
676 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
679 $sSQL .= " limit ".$iLimit;
681 if (CONST_Debug) var_dump($sSQL);
682 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
683 if (PEAR::IsError($aViewBoxPlaceIDs))
685 var_dump($sSQL, $aViewBoxPlaceIDs);
689 // Did we have an viewbox matches?
690 $aPlaceIDs = array();
691 $bViewBoxMatch = false;
692 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
694 if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
695 if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
696 if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
697 else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
698 $aPlaceIDs[] = $aViewBoxRow['place_id'];
702 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
704 $sPlaceIDs = join(',',$aPlaceIDs);
706 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
708 // Make sure everything nearby is indexed (if we pre-indexed houses this wouldn't be needed!)
709 $sSQL = "update placex set indexed = true from placex as f where placex.indexed = false";
710 $sSQL .= " and f.place_id in (".$sPlaceIDs.") and ST_DWithin(placex.geometry, f.geometry, 0.004)";
711 $sSQL .= " and placex.housenumber ~* E'".$sHouseNumberRegex."'";
712 $sSQL .= " and placex.class='place' and placex.type='house'";
713 if (CONST_Debug) var_dump($sSQL);
716 // Now they are indexed look for a house attached to a street we found
717 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
718 if (sizeof($aExcludePlaceIDs))
720 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
722 $sSQL .= " limit $iLimit";
723 if (CONST_Debug) var_dump($sSQL);
724 $aPlaceIDs = $oDB->getCol($sSQL);
727 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
729 $sPlaceIDs = join(',',$aPlaceIDs);
731 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
733 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
734 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
735 $sSQL .= " order by rank_search asc limit $iLimit";
736 if (CONST_Debug) var_dump($sSQL);
737 $aPlaceIDs = $oDB->getCol($sSQL);
740 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
742 $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
743 if (CONST_Debug) var_dump($sSQL);
744 $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
746 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
747 if (CONST_Debug) var_dump($sSQL);
748 $aPlaceIDs = $oDB->getCol($sSQL);
749 $sPlaceIDs = join(',',$aPlaceIDs);
752 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
753 if ($oDB->getOne($sSQL))
755 // More efficient - can make the range bigger
757 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
758 $sSQL .= ",placex as f where ";
759 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
760 if (sizeof($aExcludePlaceIDs))
762 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
764 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
765 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
766 $sSQL .= " limit $iLimit";
767 if (CONST_Debug) var_dump($sSQL);
768 $aPlaceIDs = $oDB->getCol($sSQL);
772 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
773 $sSQL = "select l.place_id from placex as l,placex as f where ";
774 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
775 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
776 if (sizeof($aExcludePlaceIDs))
778 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
780 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
781 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
782 $sSQL .= " limit $iLimit";
783 if (CONST_Debug) var_dump($sSQL);
784 $aPlaceIDs = $oDB->getCol($sSQL);
791 if (PEAR::IsError($aPlaceIDs))
793 var_dump($sSQL, $aPlaceIDs);
797 if (CONST_Debug) var_Dump($aPlaceIDs);
799 foreach($aPlaceIDs as $iPlaceID)
801 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
803 if ($iQueryLoop > 20) break;
806 if (sizeof($aResultPlaceIDs)) break;
807 if ($iGroupLoop > 4) break;
808 if ($iQueryLoop > 30) break;
811 // Did we find anything?
812 if (sizeof($aResultPlaceIDs))
814 //var_Dump($aResultPlaceIDs);exit;
815 // Get the details for display (is this a redundant extra step?)
816 $sPlaceIDs = join(',',$aResultPlaceIDs);
817 $sOrderSQL = 'CASE ';
818 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
820 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
822 $sOrderSQL .= ' ELSE 10000000 END ASC';
823 $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
824 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
825 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
826 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
827 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat ";
828 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
829 $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
830 if (!$bDeDupe) $sSQL .= ",place_id";
831 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
832 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
833 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
834 $sSQL .= "order by rank_search,rank_address,".$sOrderSQL;
835 if (CONST_Debug) var_dump('<hr>',$sSQL);
836 $aSearchResults = $oDB->getAll($sSQL);
837 //var_dump($sSQL,$aSearchResults);exit;
839 if (PEAR::IsError($aSearchResults))
841 var_dump($sSQL, $aSearchResults);
849 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
851 $sSearchResult = 'No Results Found';
854 $aClassType = getClassTypesWithImportance();
856 foreach($aSearchResults as $iResNum => $aResult)
858 if (CONST_Search_AreaPolygons || true)
860 // Get the bounding box and outline polygon
861 $sSQL = "select place_id,numfeatures,area,outline,";
862 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
863 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
864 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
865 $aPointPolygon = $oDB->getRow($sSQL);
866 if (PEAR::IsError($aPointPolygon))
868 var_dump($sSQL, $aPointPolygon);
871 if ($aPointPolygon['place_id'])
873 // Translate geometary string to point array
874 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
876 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
878 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
881 $iSteps = ($fRadius * 40000)^2;
882 $fStepSize = (2*pi())/$iSteps;
883 $aPolyPoints = array();
884 for($f = 0; $f < 2*pi(); $f += $fStepSize)
886 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
888 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
889 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
890 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
891 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
894 // Output data suitable for display (points and a bounding box)
897 $aResult['aPolyPoints'] = array();
898 foreach($aPolyPoints as $aPoint)
900 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
903 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
907 if (!isset($aResult['aBoundingBox']))
912 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
913 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
915 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
917 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
918 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
920 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
922 $fRadius = $fDiameter / 2;
924 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
925 $fStepSize = (2*pi())/$iSteps;
926 $aPolyPoints = array();
927 for($f = 0; $f < 2*pi(); $f += $fStepSize)
929 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
931 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
932 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
933 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
934 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
936 // Output data suitable for display (points and a bounding box)
939 $aResult['aPolyPoints'] = array();
940 foreach($aPolyPoints as $aPoint)
942 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
945 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
948 // Is there an icon set for this type of result?
949 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
950 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
952 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
955 if ($bShowAddressDetails)
957 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
960 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
961 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
963 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
967 $aResult['importance'] = 1000000000000000;
970 $aResult['name'] = $aResult['langaddress'];
971 $aResult['foundorder'] = $iResNum;
972 $aSearchResults[$iResNum] = $aResult;
975 uasort($aSearchResults, 'byImportance');
977 $aOSMIDDone = array();
978 $aClassTypeNameDone = array();
979 $aToFilter = $aSearchResults;
980 $aSearchResults = array();
983 foreach($aToFilter as $iResNum => $aResult)
985 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
986 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
989 $fLat = $aResult['lat'];
990 $fLon = $aResult['lon'];
991 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
994 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
995 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
997 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
998 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
999 $aSearchResults[] = $aResult;
1003 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1005 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1007 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1012 logEnd($oDB, $hLog, sizeof($aToFilter));
1014 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1015 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1016 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1017 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1018 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1019 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1022 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1024 $sMoreURL .= '&q='.urlencode($sQuery);
1026 if (CONST_Debug) exit;
1028 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');