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