]> git.openstreetmap.org Git - nominatim.git/blob - lib/lib.php
Merge pull request #2135 from lonvia/python-frontend
[nominatim.git] / lib / lib.php
1 <?php
2
3 function loadSettings($sProjectDir)
4 {
5     @define('CONST_InstallDir', $sProjectDir);
6     // Temporary hack to set the direcory via environment instead of
7     // the installed scripts. Neither setting is part of the official
8     // set of settings.
9     defined('CONST_DataDir') or define('CONST_DataDir', $_SERVER['NOMINATIM_DATADIR']);
10     defined('CONST_BinDir') or define('CONST_BinDir', $_SERVER['NOMINATIM_BINDIR']);
11 }
12
13 function getSetting($sConfName, $sDefault = null)
14 {
15     $sValue = $_SERVER['NOMINATIM_'.$sConfName];
16
17     if ($sDefault !== null && !$sValue) {
18         return $sDefault;
19     }
20
21     return $sValue;
22 }
23
24 function getSettingBool($sConfName)
25 {
26     $sVal = strtolower(getSetting($sConfName));
27
28     return strcmp($sVal, 'yes') == 0
29            || strcmp($sVal, 'true') == 0
30            || strcmp($sVal, '1') == 0;
31 }
32
33 function getSettingConfig($sConfName, $sSystemConfig)
34 {
35     $sValue = $_SERVER['NOMINATIM_'.$sConfName];
36
37     if (!$sValue) {
38         return CONST_DataDir.'/settings/'.$sSystemConfig;
39     }
40
41     return $sValue;
42 }
43
44 function fail($sError, $sUserError = false)
45 {
46     if (!$sUserError) $sUserError = $sError;
47     error_log('ERROR: '.$sError);
48     var_dump($sUserError)."\n";
49     exit(-1);
50 }
51
52
53 function getProcessorCount()
54 {
55     $sCPU = file_get_contents('/proc/cpuinfo');
56     preg_match_all('#processor\s+: [0-9]+#', $sCPU, $aMatches);
57     return count($aMatches[0]);
58 }
59
60
61 function getTotalMemoryMB()
62 {
63     $sCPU = file_get_contents('/proc/meminfo');
64     preg_match('#MemTotal: +([0-9]+) kB#', $sCPU, $aMatches);
65     return (int)($aMatches[1]/1024);
66 }
67
68
69 function getCacheMemoryMB()
70 {
71     $sCPU = file_get_contents('/proc/meminfo');
72     preg_match('#Cached: +([0-9]+) kB#', $sCPU, $aMatches);
73     return (int)($aMatches[1]/1024);
74 }
75
76 function getDatabaseDate(&$oDB)
77 {
78     // Find the newest node in the DB
79     $iLastOSMID = $oDB->getOne("select max(osm_id) from place where osm_type = 'N'");
80     // Lookup the timestamp that node was created
81     $sLastNodeURL = 'https://www.openstreetmap.org/api/0.6/node/'.$iLastOSMID.'/1';
82     $sLastNodeXML = file_get_contents($sLastNodeURL);
83
84     if ($sLastNodeXML === false) {
85         return false;
86     }
87
88     preg_match('#timestamp="(([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z)"#', $sLastNodeXML, $aLastNodeDate);
89
90     return $aLastNodeDate[1];
91 }
92
93
94 function byImportance($a, $b)
95 {
96     if ($a['importance'] != $b['importance'])
97         return ($a['importance'] > $b['importance']?-1:1);
98
99     return $a['foundorder'] <=> $b['foundorder'];
100 }
101
102
103 function javascript_renderData($xVal, $iOptions = 0)
104 {
105     $sCallback = isset($_GET['json_callback']) ? $_GET['json_callback'] : '';
106     if ($sCallback && !preg_match('/^[$_\p{L}][$_\p{L}\p{Nd}.[\]]*$/u', $sCallback)) {
107         // Unset, we call javascript_renderData again during exception handling
108         unset($_GET['json_callback']);
109         throw new Exception('Invalid json_callback value', 400);
110     }
111
112     $iOptions |= JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
113     if (isset($_GET['pretty']) && in_array(strtolower($_GET['pretty']), array('1', 'true'))) {
114         $iOptions |= JSON_PRETTY_PRINT;
115     }
116
117     $jsonout = json_encode($xVal, $iOptions);
118
119     if ($sCallback) {
120         header('Content-Type: application/javascript; charset=UTF-8');
121         echo $_GET['json_callback'].'('.$jsonout.')';
122     } else {
123         header('Content-Type: application/json; charset=UTF-8');
124         echo $jsonout;
125     }
126 }
127
128 function addQuotes($s)
129 {
130     return "'".$s."'";
131 }
132
133 function fwriteConstDef($rFile, $sConstName, $value)
134 {
135     $sEscapedValue;
136
137     if (is_bool($value)) {
138         $sEscapedValue = $value ? 'true' : 'false';
139     } elseif (is_numeric($value)) {
140         $sEscapedValue = strval($value);
141     } elseif (!$value) {
142         $sEscapedValue = 'false';
143     } else {
144         $sEscapedValue = addQuotes(str_replace("'", "\\'", (string)$value));
145     }
146
147     fwrite($rFile, "@define('CONST_$sConstName', $sEscapedValue);\n");
148 }
149
150
151 function parseLatLon($sQuery)
152 {
153     $sFound    = null;
154     $fQueryLat = null;
155     $fQueryLon = null;
156
157     if (preg_match('/\\s*([NS])[\s]+([0-9]+[0-9.]*)[°\s]+([0-9.]+)?[′\']*[,\s]+([EW])[\s]+([0-9]+)[°\s]+([0-9]+[0-9.]*)[′\']*\\s*/', $sQuery, $aData)) {
158         /*               1          2                    3                     4          5             6
159          * degrees decimal minutes
160          * N 40 26.767, W 79 58.933
161          * N 40°26.767′, W 79°58.933′
162          */
163         $sFound    = $aData[0];
164         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
165         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
166     } elseif (preg_match('/\\s*([0-9]+)[°\s]+([0-9]+[0-9.]*)?[′\']*[\s]+([NS])[,\s]+([0-9]+)[°\s]+([0-9]+[0-9.]*)?[′\'\s]+([EW])\\s*/', $sQuery, $aData)) {
167         /*                     1             2                          3           4             5                       6
168          * degrees decimal minutes
169          * 40 26.767 N, 79 58.933 W
170          * 40° 26.767′ N 79° 58.933′ W
171          */
172         $sFound    = $aData[0];
173         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
174         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
175     } elseif (preg_match('/\\s*([NS])[\s]+([0-9]+)[°\s]+([0-9]+)[′\'\s]+([0-9]+)[″"]*[,\s]+([EW])[\s]+([0-9]+)[°\s]+([0-9]+)[′\'\s]+([0-9]+)[″"]*\\s*/', $sQuery, $aData)) {
176         /*                     1          2             3               4                  5          6             7               8
177          * degrees decimal seconds
178          * N 40 26 46 W 79 58 56
179          * N 40° 26′ 46″, W 79° 58′ 56″
180          */
181         $sFound    = $aData[0];
182         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60 + $aData[4]/3600);
183         $fQueryLon = ($aData[5]=='E'?1:-1) * ($aData[6] + $aData[7]/60 + $aData[8]/3600);
184     } elseif (preg_match('/\\s*([0-9]+)[°\s]+([0-9]+)[′\'\s]+([0-9]+[0-9.]*)[″"\s]+([NS])[,\s]+([0-9]+)[°\s]+([0-9]+)[′\'\s]+([0-9]+[0-9.]*)[″"\s]+([EW])\\s*/', $sQuery, $aData)) {
185         /*                     1             2               3                     4           5             6               7                     8
186          * degrees decimal seconds
187          * 40 26 46 N 79 58 56 W
188          * 40° 26′ 46″ N, 79° 58′ 56″ W
189          * 40° 26′ 46.78″ N, 79° 58′ 56.89″ W
190          */
191         $sFound    = $aData[0];
192         $fQueryLat = ($aData[4]=='N'?1:-1) * ($aData[1] + $aData[2]/60 + $aData[3]/3600);
193         $fQueryLon = ($aData[8]=='E'?1:-1) * ($aData[5] + $aData[6]/60 + $aData[7]/3600);
194     } elseif (preg_match('/\\s*([NS])[\s]+([0-9]+[0-9]*\\.[0-9]+)[°]*[,\s]+([EW])[\s]+([0-9]+[0-9]*\\.[0-9]+)[°]*\\s*/', $sQuery, $aData)) {
195         /*                     1          2                                3          4
196          * degrees decimal
197          * N 40.446° W 79.982°
198          */
199         $sFound    = $aData[0];
200         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2]);
201         $fQueryLon = ($aData[3]=='E'?1:-1) * ($aData[4]);
202     } elseif (preg_match('/\\s*([0-9]+[0-9]*\\.[0-9]+)[°\s]+([NS])[,\s]+([0-9]+[0-9]*\\.[0-9]+)[°\s]+([EW])\\s*/', $sQuery, $aData)) {
203         /*                     1                            2           3                            4
204          * degrees decimal
205          * 40.446° N 79.982° W
206          */
207         $sFound    = $aData[0];
208         $fQueryLat = ($aData[2]=='N'?1:-1) * ($aData[1]);
209         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[3]);
210     } elseif (preg_match('/(\\s*\\[|^\\s*|\\s*)(-?[0-9]+[0-9]*\\.[0-9]+)[,\s]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]\\s*|\\s*$|\\s*)/', $sQuery, $aData)) {
211         /*                 1                   2                              3                        4
212          * degrees decimal
213          * 12.34, 56.78
214          * 12.34 56.78
215          * [12.456,-78.90]
216          */
217         $sFound    = $aData[0];
218         $fQueryLat = $aData[2];
219         $fQueryLon = $aData[3];
220     } else {
221         return false;
222     }
223
224     return array($sFound, $fQueryLat, $fQueryLon);
225 }
226
227 function createPointsAroundCenter($fLon, $fLat, $fRadius)
228 {
229     $iSteps = max(8, min(100, ($fRadius * 40000)^2));
230     $fStepSize = (2*pi())/$iSteps;
231     $aPolyPoints = array();
232     for ($f = 0; $f < 2*pi(); $f += $fStepSize) {
233         $aPolyPoints[] = array('', $fLon+($fRadius*sin($f)), $fLat+($fRadius*cos($f)) );
234     }
235     return $aPolyPoints;
236 }
237
238 function closestHouseNumber($aRow)
239 {
240     $fHouse = $aRow['startnumber']
241                 + ($aRow['endnumber'] - $aRow['startnumber']) * $aRow['fraction'];
242
243     switch ($aRow['interpolationtype']) {
244         case 'odd':
245             $iHn = (int)($fHouse/2) * 2 + 1;
246             break;
247         case 'even':
248             $iHn = (int)(round($fHouse/2)) * 2;
249             break;
250         default:
251             $iHn = (int)(round($fHouse));
252             break;
253     }
254
255     return max(min($aRow['endnumber'], $iHn), $aRow['startnumber']);
256 }
257
258 function getSearchRankLabel($iRank)
259 {
260     if (!isset($iRank)) return 'unknown';
261     if ($iRank < 2) return 'continent';
262     if ($iRank < 4) return 'sea';
263     if ($iRank < 8) return 'country';
264     if ($iRank < 12) return 'state';
265     if ($iRank < 16) return 'county';
266     if ($iRank == 16) return 'city';
267     if ($iRank == 17) return 'town / island';
268     if ($iRank == 18) return 'village / hamlet';
269     if ($iRank == 20) return 'suburb';
270     if ($iRank == 21) return 'postcode area';
271     if ($iRank == 22) return 'croft / farm / locality / islet';
272     if ($iRank == 23) return 'postcode area';
273     if ($iRank == 25) return 'postcode point';
274     if ($iRank == 26) return 'street / major landmark';
275     if ($iRank == 27) return 'minory street / path';
276     if ($iRank == 28) return 'house / building';
277     return 'other: ' . $iRank;
278 }