]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/admin/export.php
Merge pull request #2391 from lonvia/fix-sonar-issues
[nominatim.git] / lib-php / admin / export.php
1 <?php
2     @define('CONST_LibDir', dirname(dirname(__FILE__)));
3     // Script to extract structured city and street data
4     // from a running nominatim instance as CSV data
5
6
7     require_once(CONST_LibDir.'/init-cmd.php');
8     require_once(CONST_LibDir.'/ParameterParser.php');
9     ini_set('memory_limit', '800M');
10
11     $aCMDOptions = array(
12                     'Export addresses as CSV file from a Nominatim database',
13                     array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
14                     array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
15                     array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
16
17                     array('output-type', '', 0, 1, 1, 1, 'str', 'Type of places to output (see below)'),
18                     array('output-format', '', 0, 1, 1, 1, 'str', 'Column mapping (see below)'),
19                     array('output-all-postcodes', '', 0, 1, 0, 0, 'bool', 'List all postcodes for address instead of just the most likely one'),
20                     array('language', '', 0, 1, 1, 1, 'str', 'Preferred language for output (local name, if omitted)'),
21                     array('restrict-to-country', '', 0, 1, 1, 1, 'str', 'Export only objects within country (country code)'),
22                     array('restrict-to-osm-node', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM node'),
23                     array('restrict-to-osm-way', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM way'),
24                     array('restrict-to-osm-relation', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM relation'),
25                     array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
26                     "\nAddress ranks: continent, country, state, county, city, suburb, street, path",
27                     'Additional output types: postcode, placeid (placeid for each object)',
28                     "\noutput-format must be a semicolon-separated list of address ranks. Multiple ranks",
29                     'can be merged into one column by simply using a comma-separated list.',
30                     "\nDefault output-type: street",
31         'Default output format: street;suburb;city;county;state;country'
32                    );
33     getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
34
35     loadSettings($aCMDResult['project-dir'] ?? getcwd());
36
37     $aRankmap = array(
38                  'continent' => 1,
39                  'country' => 4,
40                  'state' => 8,
41                  'county' => 12,
42                  'city' => 16,
43                  'suburb' => 20,
44                  'street' => 26,
45                  'path' => 27
46                 );
47
48     $oDB = new Nominatim\DB();
49     $oDB->connect();
50
51     if (isset($aCMDResult['output-type'])) {
52         if (!isset($aRankmap[$aCMDResult['output-type']])) {
53             fail('unknown output-type: '.$aCMDResult['output-type']);
54         }
55         $iOutputRank = $aRankmap[$aCMDResult['output-type']];
56     } else {
57         $iOutputRank = $aRankmap['street'];
58     }
59
60
61     // Preferred language
62     $oParams = new Nominatim\ParameterParser();
63     if (!isset($aCMDResult['language'])) {
64         $aCMDResult['language'] = 'xx';
65     }
66     $aLangPrefOrder = $oParams->getPreferredLanguages($aCMDResult['language']);
67     $sLanguagePrefArraySQL = $oDB->getArraySQL($oDB->getDBQuotedList($aLangPrefOrder));
68
69     // output formatting: build up a lookup table that maps address ranks to columns
70     $aColumnMapping = array();
71     $iNumCol = 0;
72     if (!isset($aCMDResult['output-format'])) {
73         $aCMDResult['output-format'] = 'street;suburb;city;county;state;country';
74     }
75     foreach (preg_split('/\s*;\s*/', $aCMDResult['output-format']) as $sColumn) {
76         $bHasData = false;
77         foreach (preg_split('/\s*,\s*/', $sColumn) as $sRank) {
78             if ($sRank == 'postcode' || $sRank == 'placeid') {
79                 $aColumnMapping[$sRank] = $iNumCol;
80                 $bHasData = true;
81             } elseif (isset($aRankmap[$sRank])) {
82                 $iRank = $aRankmap[$sRank];
83                 if ($iRank <= $iOutputRank) {
84                     $aColumnMapping[(string)$iRank] = $iNumCol;
85                     $bHasData = true;
86                 }
87             }
88         }
89         if ($bHasData) {
90             $iNumCol++;
91         }
92     }
93
94     // build the query for objects
95     $sPlacexSQL = 'select min(place_id) as place_id, ';
96     $sPlacexSQL .= 'array_agg(place_id) as place_ids, ';
97     $sPlacexSQL .= 'country_code as cc, ';
98     $sPlacexSQL .= 'postcode, ';
99     // get the address places excluding postcodes
100     $sPlacexSQL .= 'array(select address_place_id from place_addressline a';
101     $sPlacexSQL .= ' where a.place_id = placex.place_id and isaddress';
102     $sPlacexSQL .= '  and address_place_id != placex.place_id';
103     $sPlacexSQL .= '  and not cached_rank_address in (5,11)';
104     $sPlacexSQL .= '  and cached_rank_address > 2 order by cached_rank_address)';
105     $sPlacexSQL .= ' as address';
106     $sPlacexSQL .= ' from placex where name is not null and linked_place_id is null';
107
108     $sPlacexSQL .= ' and rank_address = '.$iOutputRank;
109
110     if (isset($aCMDResult['restrict-to-country'])) {
111         $sPlacexSQL .= ' and country_code = '.$oDB->getDBQuoted($aCMDResult['restrict-to-country']);
112     }
113
114     // restriction to parent place id
115     $sParentId = false;
116     $sOsmType = false;
117
118     if (isset($aCMDResult['restrict-to-osm-node'])) {
119         $sOsmType = 'N';
120         $sOsmId = $aCMDResult['restrict-to-osm-node'];
121     }
122     if (isset($aCMDResult['restrict-to-osm-way'])) {
123         $sOsmType = 'W';
124         $sOsmId = $aCMDResult['restrict-to-osm-way'];
125     }
126     if (isset($aCMDResult['restrict-to-osm-relation'])) {
127         $sOsmType = 'R';
128         $sOsmId = $aCMDResult['restrict-to-osm-relation'];
129     }
130     if ($sOsmType) {
131         $sSQL = 'select place_id from placex where osm_type = :osm_type and osm_id = :osm_id';
132         $sParentId = $oDB->getOne($sSQL, array('osm_type' => $sOsmType, 'osm_id' => $sOsmId));
133         if (!$sParentId) {
134             fail('Could not find place '.$sOsmType.' '.$sOsmId);
135         }
136     }
137     if ($sParentId) {
138         $sPlacexSQL .= ' and place_id in (select place_id from place_addressline where address_place_id = '.$sParentId.' and isaddress)';
139     }
140
141     $sPlacexSQL .= " group by name->'name', address, postcode, country_code, placex.place_id";
142
143     // Iterate over placeids
144     // to get further hierarchical information
145     //var_dump($sPlacexSQL);
146     $oResults = $oDB->getQueryStatement($sPlacexSQL);
147     $fOutstream = fopen('php://output', 'w');
148     while ($aRow = $oResults->fetch()) {
149         $iPlaceID = $aRow['place_id'];
150         $sSQL = "select rank_address,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata(:place_id, -1)";
151         $sSQL .= ' WHERE isaddress';
152         $sSQL .= ' order by rank_address desc,isaddress desc';
153         $aAddressLines = $oDB->getAll($sSQL, array('place_id' => $iPlaceID));
154
155         $aOutput = array_fill(0, $iNumCol, '');
156         // output address parts
157         foreach ($aAddressLines as $aAddress) {
158             if (isset($aColumnMapping[$aAddress['rank_address']])) {
159                 $aOutput[$aColumnMapping[$aAddress['rank_address']]] = $aAddress['localname'];
160             }
161         }
162         // output postcode
163         if (isset($aColumnMapping['postcode'])) {
164             if ($aCMDResult['output-all-postcodes']) {
165                 $sSQL = 'select array_agg(px.postcode) from placex px join place_addressline pa ';
166                 $sSQL .= 'on px.place_id = pa.address_place_id ';
167                 $sSQL .= 'where pa.cached_rank_address in (5,11) ';
168                 $sSQL .= 'and pa.place_id in (select place_id from place_addressline where address_place_id in (:first_place_id)) ';
169                 $sSQL .= 'group by postcode order by count(*) desc limit 1';
170                 $sRes = $oDB->getOne($sSQL, array('first_place_id' => substr($aRow['place_ids'], 1, -1)));
171
172                 $aOutput[$aColumnMapping['postcode']] = substr($sRes, 1, -1);
173             } else {
174                 $aOutput[$aColumnMapping['postcode']] = $aRow['postcode'];
175             }
176         }
177         if (isset($aColumnMapping['placeid'])) {
178             $aOutput[$aColumnMapping['placeid']] = substr($aRow['place_ids'], 1, -1);
179         }
180         fputcsv($fOutstream, $aOutput);
181     }
182     fclose($fOutstream);