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