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