]> git.openstreetmap.org Git - nominatim.git/blob - lib/PlaceLookup.php
use chksql everywhere in lib/
[nominatim.git] / lib / PlaceLookup.php
1 <?php
2         class PlaceLookup
3         {
4                 protected $oDB;
5
6                 protected $iPlaceID;
7
8                 protected $sType = false;
9
10                 protected $fTigerFraction = -1;
11
12                 protected $aLangPrefOrder = array();
13
14                 protected $bAddressDetails = false;
15
16                 protected $bExtraTags = false;
17
18                 protected $bNameDetails = false;
19
20                 protected $bIncludePolygonAsPoints = false;
21                 protected $bIncludePolygonAsText = false;
22                 protected $bIncludePolygonAsGeoJSON = false;
23                 protected $bIncludePolygonAsKML = false;
24                 protected $bIncludePolygonAsSVG = false;
25                 protected $fPolygonSimplificationThreshold = 0.0;
26
27
28                 function PlaceLookup(&$oDB)
29                 {
30                         $this->oDB =& $oDB;
31                 }
32
33                 function setLanguagePreference($aLangPrefOrder)
34                 {
35                         $this->aLangPrefOrder = $aLangPrefOrder;
36                 }
37
38                 function setIncludeAddressDetails($bAddressDetails = true)
39                 {
40                         $this->bAddressDetails = $bAddressDetails;
41                 }
42
43                 function setIncludeExtraTags($bExtraTags = false)
44                 {
45                         $this->bExtraTags = $bExtraTags;
46                 }
47
48                 function setIncludeNameDetails($bNameDetails = false)
49                 {
50                         $this->bNameDetails = $bNameDetails;
51                 }
52
53
54                 function setIncludePolygonAsPoints($b = true)
55                 {
56                         $this->bIncludePolygonAsPoints = $b;
57                 }
58
59                 function getIncludePolygonAsPoints()
60                 {
61                         return $this->bIncludePolygonAsPoints;
62                 }
63
64                 function setIncludePolygonAsText($b = true)
65                 {
66                         $this->bIncludePolygonAsText = $b;
67                 }
68
69                 function getIncludePolygonAsText()
70                 {
71                         return $this->bIncludePolygonAsText;
72                 }
73
74                 function setIncludePolygonAsGeoJSON($b = true)
75                 {
76                         $this->bIncludePolygonAsGeoJSON = $b;
77                 }
78
79                 function setIncludePolygonAsKML($b = true)
80                 {
81                         $this->bIncludePolygonAsKML = $b;
82                 }
83
84                 function setIncludePolygonAsSVG($b = true)
85                 {
86                         $this->bIncludePolygonAsSVG = $b;
87                 }
88
89                 function setPolygonSimplificationThreshold($f)
90                 {
91                         $this->fPolygonSimplificationThreshold = $f;
92                 }
93
94
95                 function setPlaceID($iPlaceID)
96                 {
97                         $this->iPlaceID = $iPlaceID;
98                 }
99
100                 function setOSMID($sType, $iID)
101                 {
102                         $sSQL = "select place_id from placex where osm_type = '".pg_escape_string($sType)."' and osm_id = ".(int)$iID." order by type = 'postcode' asc";
103                         $this->iPlaceID = chksql($this->oDB->getOne($sSQL));
104                 }
105
106                 function lookupPlace($details)
107                 {
108                         if (isset($details['place_id'])) $this->iPlaceID = $details['place_id'];
109                         if (isset($details['type'])) $this->sType = $details['type'];
110                         if (isset($details['osm_type']) && isset($details['osm_id']))
111                         {
112                                 $this->setOSMID($details['osm_type'], $details['osm_id']);
113                         }
114                         if (isset($details['fraction'])) $this->fInterpolFraction = $details['fraction'];
115
116                         return $this->lookup();
117                 }
118
119                 function lookup()
120                 {
121                         if (!$this->iPlaceID) return null;
122
123                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
124
125                         if (CONST_Use_US_Tiger_Data && $this->sType == 'tiger')
126                         {
127                                 $sSQL = "select place_id,partition, 'T' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, housenumber, null as street, null as isin, postcode,";
128                                 $sSQL .= " 'us' as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
129                                 $sSQL .= " coalesce(null,0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, 'us' as calculated_country_code, ";
130                                 $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
131                                 $sSQL .= " null as placename,";
132                                 $sSQL .= " null as ref,";
133                                 if ($this->bExtraTags) $sSQL .= " null as extra,";
134                                 if ($this->bNameDetails) $sSQL .= " null as names,";
135                                 $sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from ";
136                                 $sSQL .= " (select *, ";
137                                 $sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
138                                 $sSQL .= " WHEN interpolationtype='even' THEN ((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
139                                 $sSQL .= " WHEN interpolationtype='all' THEN (".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
140                                 $sSQL .= " END as housenumber";
141                                 $sSQL .= " from location_property_tiger where place_id = ".(int)$this->iPlaceID.") as blub1) as blub2";
142                         }
143                         else if ($this->sType == 'interpolation')
144                         {
145                                 $sSQL = "select place_id, partition, 'W' as osm_type, osm_id, 'place' as class, 'house' as type, null admin_level, housenumber, null as street, null as isin, postcode,";
146                                 $sSQL .= " calculated_country_code as country_code, parent_place_id, null as linked_place_id, 30 as rank_address, 30 as rank_search,";
147                                 $sSQL .= " (0.75-(30::float/40)) as importance, null as indexed_status, null as indexed_date, null as wikipedia, calculated_country_code, ";
148                                 $sSQL .= " get_address_by_language(place_id, housenumber, $sLanguagePrefArraySQL) as langaddress,";
149                                 $sSQL .= " null as placename,";
150                                 $sSQL .= " null as ref,";
151                                 if ($this->bExtraTags) $sSQL .= " null as extra,";
152                                 if ($this->bNameDetails) $sSQL .= " null as names,";
153                                 $sSQL .= " ST_X(point) as lon, ST_Y(point) as lat from (select *, ST_LineInterpolatePoint(linegeo, (housenumber-startnumber::float)/(endnumber-startnumber)::float) as point from ";
154                                 $sSQL .= " (select *, ";
155                                 $sSQL .= " CASE WHEN interpolationtype='odd' THEN floor((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2+1";
156                                 $sSQL .= " WHEN interpolationtype='even' THEN ((".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)/2)::int*2";
157                                 $sSQL .= " WHEN interpolationtype='all' THEN (".$this->fInterpolFraction."*(endnumber-startnumber)+startnumber)::int";
158                                 $sSQL .= " END as housenumber";
159                                 $sSQL .= " from location_property_osmline where place_id = ".(int)$this->iPlaceID.") as blub1) as blub2";
160                                 // testcase: interpolationtype=odd, startnumber=1000, endnumber=1006, fInterpolFraction=1 => housenumber=1007 => error in st_lineinterpolatepoint
161                                 // but this will never happen, because if the searched point is that close to the endnumber, the endnumber house will be directly taken from placex (in ReverseGeocode.php line 220)
162                                 // and not interpolated
163                         }
164                         else
165                         {
166                                 $sSQL = "select placex.place_id, partition, osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode, country_code, parent_place_id, linked_place_id, rank_address, rank_search, ";
167                                 $sSQL .= " coalesce(importance,0.75-(rank_search::float/40)) as importance, indexed_status, indexed_date, wikipedia, calculated_country_code, ";
168                                 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
169                                 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
170                                 $sSQL .= " get_name_by_language(name, ARRAY['ref']) as ref,";
171                                 if ($this->bExtraTags) $sSQL .= " hstore_to_json(extratags) as extra,";
172                                 if ($this->bNameDetails) $sSQL .= " hstore_to_json(name) as names,";
173                                 $sSQL .= " (case when centroid is null then st_y(st_centroid(geometry)) else st_y(centroid) end) as lat,";
174                                 $sSQL .= " (case when centroid is null then st_x(st_centroid(geometry)) else st_x(centroid) end) as lon";
175                                 $sSQL .= " from placex where place_id = ".(int)$this->iPlaceID;
176                         }
177
178                         $aPlace = chksql($this->oDB->getRow($sSQL), "Could not lookup place");
179
180                         if (!$aPlace['place_id']) return null;
181
182                         if ($this->bAddressDetails)
183                         {
184                                 if(CONST_Use_US_Tiger_Data && $this->sType == 'tiger' || $this->sType == 'interpolation') // to get addressdetails for tiger data, the housenumber is needed
185                                         $aAddress = $this->getAddressNames($aPlace['housenumber']);
186                                 else
187                                         $aAddress = $this->getAddressNames();
188                                 $aPlace['aAddress'] = $aAddress;
189                         }
190
191                         if ($this->bExtraTags)
192                         {
193                                 if ($aPlace['extra'])
194                                 {
195                                         $aPlace['sExtraTags'] = json_decode($aPlace['extra']);
196                                 }
197                                 else
198                                 {
199                                         $aPlace['sExtraTags'] = (object) array();
200                                 }
201                         }
202
203                         if ($this->bNameDetails)
204                         {
205                                 if ($aPlace['names'])
206                                 {
207                                         $aPlace['sNameDetails'] = json_decode($aPlace['names']);
208                                 }
209                                 else
210                                 {
211                                         $aPlace['sNameDetails'] = (object) array();
212                                 }
213                         }
214
215                         $aClassType = getClassTypes();
216                         $sAddressType = '';
217                         $sClassType = $aPlace['class'].':'.$aPlace['type'].':'.$aPlace['admin_level'];
218                         if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
219                         {
220                                 $sAddressType = $aClassType[$aClassType]['simplelabel'];
221                         }
222                         else
223                         {
224                                 $sClassType = $aPlace['class'].':'.$aPlace['type'];
225                                 if (isset($aClassType[$sClassType]) && isset($aClassType[$sClassType]['simplelabel']))
226                                         $sAddressType = $aClassType[$sClassType]['simplelabel'];
227                                 else $sAddressType = $aPlace['class'];
228                         }
229
230                         $aPlace['addresstype'] = $sAddressType;
231
232                         return $aPlace;
233                 }
234
235                 function getAddressDetails($bAll = false, $housenumber = -1)
236                 {
237                         if (!$this->iPlaceID) return null;
238
239                         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted", $this->aLangPrefOrder))."]";
240
241                         $sSQL = "select *,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(".$this->iPlaceID.",".$housenumber.")";
242                         if (!$bAll) $sSQL .= " WHERE isaddress OR type = 'country_code'";
243                         $sSQL .= " order by rank_address desc,isaddress desc";
244
245                         return chksql($this->oDB->getAll($sSQL));
246                 }
247
248                 function getAddressNames($housenumber = -1)
249                 {
250                         $aAddressLines = $this->getAddressDetails(false, $housenumber);
251
252                         $aAddress = array();
253                         $aFallback = array();
254                         $aClassType = getClassTypes();
255                         foreach($aAddressLines as $aLine)
256                         {
257                                 $bFallback = false;
258                                 $aTypeLabel = false;
259                                 if (isset($aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type'].':'.$aLine['admin_level']];
260                                 elseif (isset($aClassType[$aLine['class'].':'.$aLine['type']])) $aTypeLabel = $aClassType[$aLine['class'].':'.$aLine['type']];
261                                 elseif (isset($aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))]))
262                                 {
263                                         $aTypeLabel = $aClassType['boundary:administrative:'.((int)($aLine['rank_address']/2))];
264                                         $bFallback = true;
265                                 }
266                                 else
267                                 {
268                                         $aTypeLabel = array('simplelabel'=>'address'.$aLine['rank_address']);
269                                         $bFallback = true;
270                                 }
271                                 if ($aTypeLabel && ((isset($aLine['localname']) && $aLine['localname']) || (isset($aLine['housenumber']) && $aLine['housenumber'])))
272                                 {
273                                         $sTypeLabel = strtolower(isset($aTypeLabel['simplelabel'])?$aTypeLabel['simplelabel']:$aTypeLabel['label']);
274                                         $sTypeLabel = str_replace(' ','_',$sTypeLabel);
275                                         if (!isset($aAddress[$sTypeLabel]) || (isset($aFallback[$sTypeLabel]) && $aFallback[$sTypeLabel]) || $aLine['class'] == 'place')
276                                         {
277                                                 $aAddress[$sTypeLabel] = $aLine['localname']?$aLine['localname']:$aLine['housenumber'];
278                                         }
279                                         $aFallback[$sTypeLabel] = $bFallback;
280                                 }
281                         }
282                         return $aAddress;
283                 }
284
285
286
287                 // returns an array which will contain the keys
288                 //   aBoundingBox
289                 // and may also contain one or more of the keys
290                 //   asgeojson
291                 //   askml
292                 //   assvg
293                 //   astext
294                 //   lat
295                 //   lon
296                 function getOutlines($iPlaceID, $fLon=null, $fLat=null, $fRadius=null)
297                 {
298
299                         $aOutlineResult = array();
300                         if (!$iPlaceID) return $aOutlineResult;
301
302                         if (CONST_Search_AreaPolygons)
303                         {
304                                 // Get the bounding box and outline polygon
305                                 $sSQL  = "select place_id,0 as numfeatures,st_area(geometry) as area,";
306                                 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
307                                 $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
308                                 $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
309                                 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
310                                 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
311                                 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
312                                 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
313                                 $sFrom = " from placex where place_id = ".$iPlaceID;
314                                 if ($this->fPolygonSimplificationThreshold > 0)
315                                 {
316                                         $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
317                                 }
318                                 else
319                                 {
320                                         $sSQL .= $sFrom;
321                                 }
322
323                                 $aPointPolygon = chksql($this->oDB->getRow($sSQL),
324                                                         "Could not get outline");
325
326                                 if ($aPointPolygon['place_id'])
327                                 {
328                                         if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
329                                         {
330                                                 $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
331                                                 $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
332                                         }
333
334                                         if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
335                                         if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
336                                         if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
337                                         if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
338                                         if ($this->bIncludePolygonAsPoints) $aOutlineResult['aPolyPoints'] = geometryText2Points($aPointPolygon['astext'], $fRadius);
339
340
341                                         if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
342                                         {
343                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
344                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
345                                         }
346                                         if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
347                                         {
348                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
349                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
350                                         }
351
352                                         $aOutlineResult['aBoundingBox'] = array(
353                                                                           (string)$aPointPolygon['minlat'],
354                                                                           (string)$aPointPolygon['maxlat'],
355                                                                           (string)$aPointPolygon['minlon'],
356                                                                           (string)$aPointPolygon['maxlon']
357                                                                          );
358                                 }
359                         } // CONST_Search_AreaPolygons
360
361                         // as a fallback we generate a bounding box without knowing the size of the geometry
362                         if ( (!isset($aOutlineResult['aBoundingBox'])) && isset($fLon) )
363                         {
364
365                                 if ($this->bIncludePolygonAsPoints)
366                                 {
367                                         $sGeometryText = 'POINT('.$fLon.','.$fLat.')';
368                                         $aOutlineResult['aPolyPoints'] = geometryText2Points($sGeometryText, $fRadius);
369                                 }
370
371                                 $aBounds = array();
372                                 $aBounds['minlat'] = $fLat - $fRadius;
373                                 $aBounds['maxlat'] = $fLat + $fRadius;
374                                 $aBounds['minlon'] = $fLon - $fRadius;
375                                 $aBounds['maxlon'] = $fLon + $fRadius;
376
377                                 $aOutlineResult['aBoundingBox'] = array(
378                                                                   (string)$aBounds['minlat'],
379                                                                   (string)$aBounds['maxlat'],
380                                                                   (string)$aBounds['minlon'],
381                                                                   (string)$aBounds['maxlon']
382                                                                  );
383                         }
384                         return $aOutlineResult;
385                 }
386         }
387 ?>