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'] += 1;
393 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
397 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
399 if ($aSearch['sClass'] === '')
401 $aSearch['sOperator'] = $aSearchTerm['operator'];
402 $aSearch['sClass'] = $aSearchTerm['class'];
403 $aSearch['sType'] = $aSearchTerm['type'];
404 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
405 else $aSearch['sOperator'] = 'near'; // near = in for the moment
407 // Do we have a shortcut id?
408 if ($aSearch['sOperator'] == 'name')
410 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
411 if ($iAmenityID = $oDB->getOne($sSQL))
413 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
414 $aSearch['aName'][$iAmenityID] = $iAmenityID;
415 $aSearch['sClass'] = '';
416 $aSearch['sType'] = '';
419 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
424 if (sizeof($aSearch['aName']))
426 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
430 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
431 $aSearch['iNamePhrase'] = $iPhrase;
433 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
437 if (isset($aValidTokens[$sToken]))
439 // Allow searching for a word - but at extra cost
440 foreach($aValidTokens[$sToken] as $aSearchTerm)
442 $aSearch = $aCurrentSearch;
443 $aSearch['iSearchRank']+=5;
444 // $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
445 if (!sizeof($aSearch['aName']) || $aSearch['iNamePhrase'] == $iPhrase)
447 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
448 $aSearch['iNamePhrase'] = $iPhrase;
450 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
455 // Allow skipping a word - but at EXTREAM cost
456 //$aSearch = $aCurrentSearch;
457 //$aSearch['iSearchRank']+=100;
458 //$aNewWordsetSearches[] = $aSearch;
462 usort($aNewWordsetSearches, 'bySearchRank');
463 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
465 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
467 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
468 usort($aNewPhraseSearches, 'bySearchRank');
469 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
472 // Re-group the searches by their score, junk anything over 20 as just not worth trying
473 $aGroupedSearches = array();
474 foreach($aNewPhraseSearches as $aSearch)
476 if ($aSearch['iSearchRank'] < $iMaxRank)
478 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
479 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
482 ksort($aGroupedSearches);
485 $aSearches = array();
486 foreach($aGroupedSearches as $iScore => $aNewSearches)
488 $iSearchCount += sizeof($aNewSearches);
489 $aSearches = array_merge($aSearches, $aNewSearches);
490 if ($iSearchCount > 50) break;
496 // Re-group the searches by their score, junk anything over 20 as just not worth trying
497 $aGroupedSearches = array();
498 foreach($aSearches as $aSearch)
500 if ($aSearch['iSearchRank'] < $iMaxRank)
502 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
503 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
506 ksort($aGroupedSearches);
509 if (CONST_Debug) var_Dump($aGroupedSearches);
513 foreach($aGroupedSearches as $iGroup => $aSearches)
515 foreach($aSearches as $iSearch => $aSearch)
517 if (sizeof($aSearch['aAddress']))
519 $aReverseSearch = $aSearch;
520 $iReverseItem = array_pop($aSearch['aAddress']);
521 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
522 $aGroupedSearches[$iGroup][] = $aReverseSearch;
528 //var_Dump($aGroupedSearches); exit;
530 // Filter out duplicate searches
531 $aSearchHash = array();
532 foreach($aGroupedSearches as $iGroup => $aSearches)
534 foreach($aSearches as $iSearch => $aSearch)
536 $sHash = serialize($aSearch);
537 if (isset($aSearchHash[$sHash]))
539 unset($aGroupedSearches[$iGroup][$iSearch]);
540 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
544 $aSearchHash[$sHash] = 1;
549 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
553 foreach($aGroupedSearches as $iGroup => $aSearches)
555 foreach($aSearches as $iSearch => $aSearch)
557 if (sizeof($aSearch['aAddress']))
559 $aReverseSearch = $aSearch;
560 $iReverseItem = array_pop($aSearch['aAddress']);
561 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
562 $aGroupedSearches[$iGroup][] = $aReverseSearch;
568 // Filter out duplicate searches
569 $aSearchHash = array();
570 foreach($aGroupedSearches as $iGroup => $aSearches)
572 foreach($aSearches as $iSearch => $aSearch)
574 $sHash = serialize($aSearch);
575 if (isset($aSearchHash[$sHash]))
577 unset($aGroupedSearches[$iGroup][$iSearch]);
578 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
582 $aSearchHash[$sHash] = 1;
587 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
591 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
594 foreach($aSearches as $aSearch)
598 // Must have a location term
599 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
601 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
602 if (!$aSearch['sClass']) continue;
603 if (CONST_Debug) var_dump('<hr>',$aSearch);
604 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
606 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
607 if ($oDB->getOne($sSQL))
609 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
610 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
611 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
612 $sSQL .= " limit $iLimit";
613 if (CONST_Debug) var_dump($sSQL);
614 $aPlaceIDs = $oDB->getCol($sSQL);
616 if (!sizeof($aPlaceIDs))
618 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
619 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
620 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
621 $sSQL .= " limit $iLimit";
622 if (CONST_Debug) var_dump($sSQL);
623 $aPlaceIDs = $oDB->getCol($sSQL);
628 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
629 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
630 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
631 $sSQL .= " limit $iLimit";
632 if (CONST_Debug) var_dump($sSQL);
633 $aPlaceIDs = $oDB->getCol($sSQL);
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 $aRoadPlaceIDs = $aPlaceIDs;
705 $sPlaceIDs = join(',',$aPlaceIDs);
707 // Now they are indexed look for a house attached to a street we found
708 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
709 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
710 if (sizeof($aExcludePlaceIDs))
712 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
714 $sSQL .= " limit $iLimit";
715 if (CONST_Debug) var_dump($sSQL);
716 $aPlaceIDs = $oDB->getCol($sSQL);
718 // If not try the tiger fallback table
719 if (!sizeof($aPlaceIDs))
721 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
722 if (sizeof($aExcludePlaceIDs))
724 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
726 // $sSQL .= " limit $iLimit";
727 if (CONST_Debug) var_dump($sSQL);
728 $aPlaceIDs = $oDB->getCol($sSQL);
731 // Fallback to the road
732 if (!sizeof($aPlaceIDs))
734 $aPlaceIDs = $aRoadPlaceIDs;
739 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
741 $sPlaceIDs = join(',',$aPlaceIDs);
743 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
745 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
746 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
747 $sSQL .= " order by rank_search asc limit $iLimit";
748 if (CONST_Debug) var_dump($sSQL);
749 $aPlaceIDs = $oDB->getCol($sSQL);
752 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
754 $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
755 if (CONST_Debug) var_dump($sSQL);
756 $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
758 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
759 if (CONST_Debug) var_dump($sSQL);
760 $aPlaceIDs = $oDB->getCol($sSQL);
761 $sPlaceIDs = join(',',$aPlaceIDs);
764 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
765 if ($oDB->getOne($sSQL))
767 // More efficient - can make the range bigger
769 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
770 $sSQL .= ",placex as f where ";
771 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
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.centroid, f.geometry) asc";
778 $sSQL .= " limit $iLimit";
779 if (CONST_Debug) var_dump($sSQL);
780 $aPlaceIDs = $oDB->getCol($sSQL);
784 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
785 $sSQL = "select l.place_id from placex as l,placex as f where ";
786 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
787 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
788 if (sizeof($aExcludePlaceIDs))
790 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
792 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
793 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
794 $sSQL .= " limit $iLimit";
795 if (CONST_Debug) var_dump($sSQL);
796 $aPlaceIDs = $oDB->getCol($sSQL);
803 if (PEAR::IsError($aPlaceIDs))
805 var_dump($sSQL, $aPlaceIDs);
809 if (CONST_Debug) var_Dump($aPlaceIDs);
811 foreach($aPlaceIDs as $iPlaceID)
813 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
815 if ($iQueryLoop > 20) break;
818 if (sizeof($aResultPlaceIDs)) break;
819 if ($iGroupLoop > 4) break;
820 if ($iQueryLoop > 30) break;
823 // Did we find anything?
824 if (sizeof($aResultPlaceIDs))
826 //var_Dump($aResultPlaceIDs);exit;
827 // Get the details for display (is this a redundant extra step?)
828 $sPlaceIDs = join(',',$aResultPlaceIDs);
829 $sOrderSQL = 'CASE ';
830 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
832 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
834 $sOrderSQL .= ' ELSE 10000000 END';
835 $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
836 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
837 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
838 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
839 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
840 $sSQL .= $sOrderSQL." as porder ";
841 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
842 $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
843 if (!$bDeDupe) $sSQL .= ",place_id";
844 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
845 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
846 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
848 $sSQL .= "select 'T' as osm_type,place_id as osm_id,'place' as class,'house' as type,30 as rank_search,30 as rank_address,min(place_id) as place_id,'us' as country_code,";
849 $sSQL .= "get_tiger_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
850 $sSQL .= "null as placename,";
851 $sSQL .= "null as ref,";
852 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
853 $sSQL .= $sOrderSQL." as porder ";
854 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
855 $sSQL .= "group by place_id";
856 if (!$bDeDupe) $sSQL .= ",place_id";
857 $sSQL .= ",get_tiger_address_by_language(place_id, $sLanguagePrefArraySQL) ";
858 $sSQL .= "order by rank_search,rank_address,porder asc";
859 if (CONST_Debug) var_dump('<hr>',$sSQL);
860 $aSearchResults = $oDB->getAll($sSQL);
861 //var_dump($sSQL,$aSearchResults);exit;
863 if (PEAR::IsError($aSearchResults))
865 var_dump($sSQL, $aSearchResults);
873 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
875 $sSearchResult = 'No Results Found';
878 $aClassType = getClassTypesWithImportance();
880 foreach($aSearchResults as $iResNum => $aResult)
882 if (CONST_Search_AreaPolygons || true)
884 // Get the bounding box and outline polygon
885 $sSQL = "select place_id,numfeatures,area,outline,";
886 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
887 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
888 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
889 $aPointPolygon = $oDB->getRow($sSQL);
890 if (PEAR::IsError($aPointPolygon))
892 var_dump($sSQL, $aPointPolygon);
895 if ($aPointPolygon['place_id'])
897 // Translate geometary string to point array
898 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
900 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
902 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
905 $iSteps = ($fRadius * 40000)^2;
906 $fStepSize = (2*pi())/$iSteps;
907 $aPolyPoints = array();
908 for($f = 0; $f < 2*pi(); $f += $fStepSize)
910 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
912 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
913 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
914 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
915 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
918 // Output data suitable for display (points and a bounding box)
921 $aResult['aPolyPoints'] = array();
922 foreach($aPolyPoints as $aPoint)
924 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
927 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
931 if (!isset($aResult['aBoundingBox']))
936 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
937 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
939 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
941 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
942 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
944 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
946 $fRadius = $fDiameter / 2;
948 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
949 $fStepSize = (2*pi())/$iSteps;
950 $aPolyPoints = array();
951 for($f = 0; $f < 2*pi(); $f += $fStepSize)
953 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
955 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
956 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
957 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
958 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
960 // Output data suitable for display (points and a bounding box)
963 $aResult['aPolyPoints'] = array();
964 foreach($aPolyPoints as $aPoint)
966 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
969 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
972 // Is there an icon set for this type of result?
973 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
974 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
976 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
979 if ($bShowAddressDetails)
981 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
982 //var_dump($aResult['address']);
986 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
987 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
989 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
993 $aResult['importance'] = 1000000000000000;
996 $aResult['name'] = $aResult['langaddress'];
997 $aResult['foundorder'] = $iResNum;
998 $aSearchResults[$iResNum] = $aResult;
1001 //var_dump($aSearchResults);exit;
1003 uasort($aSearchResults, 'byImportance');
1005 $aOSMIDDone = array();
1006 $aClassTypeNameDone = array();
1007 $aToFilter = $aSearchResults;
1008 $aSearchResults = array();
1011 foreach($aToFilter as $iResNum => $aResult)
1013 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1014 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1017 $fLat = $aResult['lat'];
1018 $fLon = $aResult['lon'];
1019 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1022 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1023 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1025 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1026 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1027 $aSearchResults[] = $aResult;
1031 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1033 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1035 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1040 logEnd($oDB, $hLog, sizeof($aToFilter));
1042 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1043 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1044 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1045 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1046 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1047 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1050 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1052 $sMoreURL .= '&q='.urlencode($sQuery);
1054 if (CONST_Debug) exit;
1056 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');