forked from zipcodes/zipcodes.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.php
215 lines (192 loc) · 7.01 KB
/
update.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
/**
* Generate folders and repos for each country to each serve as a database.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
$cwd = dirname(realpath(__FILE__));
$zipfile = $cwd.'/allCountries.zip';
$txtfile = $cwd.'/allCountries.txt';
$statsOnly = false;
$regenKey = false;
$keyArr = $regenKey ? [] : json_decode(file_get_contents($cwd.'/key.json'), true);
// Download http://download.geonames.org/export/zip/allCountries.zip
if (!file_exists($txtfile)) {
echo "Downloading zipcodes...";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://download.geonames.org/export/zip/allCountries.zip');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$file = fopen($zipfile, "w+");
fputs($file, $data);
fclose($file);
$zip = new ZipArchive;
$res = $zip->open($zipfile);
if ($res === true) {
$zip->extractTo('.');
$zip->close();
unlink($zipfile);
} else {
die('Unable to unzip.');
}
}
echo "Cleaning up from previous build...\n";
clean($cwd);
$row = 0;
$headers = [
'countryCode', // iso country code, 2 characters
'postalCode', // varchar(20)
'placeName', // varchar(180)
'adminName1', // 1. order subdivision (state) varchar(100)
'adminCode1', // 1. order subdivision (state) varchar(20)
'adminName2', // 2. order subdivision (county/province) varchar(100)
'adminCode2', // 2. order subdivision (county/province) varchar(20)
'adminName3', // 3. order subdivision (community) varchar(100)
'adminCode3', // 3. order subdivision (community) varchar(20)
'latitude', // estimated latitude (wgs84)
'longitude', // estimated longitude (wgs84)
'accuracy', // accuracy of lat/lng from 1=estimated to 6=centroid
];
$stats = [];
if (($handle = fopen($txtfile, 'r')) !== false) {
while (($data = fgetcsv($handle, 1000, "\t")) !== false) {
$place = new stdClass();
foreach ($data as $key => $value) {
$keyname = $headers[$key];
$place->{$keyname} = $value;
}
if (!empty($place->countryCode) && !empty($place->postalCode)) {
$countryCode = strtoupper($place->countryCode);
if ($statsOnly) {
$minCode = minPostal($place->postalCode);
// Two countries have too much numerical variance to list all zip-codes independently
// given Github's current repository limits. For these we will only include the min JSON/JSONP.
$length = strlen($place->postalCode);
if (!isset($stats[$countryCode])) {
$stats[$countryCode] = [
'count' => 1,
'lowest' => $minCode,
'highest' => $minCode,
];
} else {
$stats[$countryCode]['count']++;
if ($minCode < $stats[$countryCode]['lowest']) {
$stats[$countryCode]['lowest'] = $minCode;
} elseif ($minCode > $stats[$countryCode]['highest']) {
$stats[$countryCode]['highest'] = $minCode;
}
}
continue;
}
$minOnly = in_array($countryCode, ['JP', 'PT']);
echo 'Creating entry for '.$place->countryCode.' '.$place->postalCode.($minOnly ? ' (min only)' : '').' in index '.$minCodeRounded."\n";
if (!is_dir($cwd.'/'.$countryCode)) {
mkdir($cwd.'/'.$countryCode);
}
if (!file_exists($cwd.'/'.$countryCode.'/test.jsonp')) {
$test = new stdClass();
$test->success = true;
file_put_contents($cwd.'/'.$countryCode.'/test.jsonp', 'zipCodesTestCallback('.json_encode($test).');');
}
if (!$minOnly) {
file_put_contents(
$cwd.'/'.$countryCode.'/'.$place->postalCode.'.json',
json_encode($place)
);
}
if (!is_dir($cwd.'/'.$countryCode.'/min')) {
mkdir($cwd.'/'.$countryCode.'/min');
}
$minCodeRounded = minPostalRounded($place->postalCode, $place->countryCode, $keyArr);
$codes = [];
if (file_exists($cwd.'/'.$countryCode.'/min/'.$minCodeRounded.'.json')) {
$codes = json_decode(file_get_contents($cwd.'/'.$countryCode.'/min/'.$minCodeRounded.'.json'), true);
}
$codes[$place->postalCode] = $data;
$codesJSON = json_encode($codes);
file_put_contents(
$cwd.'/'.$countryCode.'/min/'.$minCodeRounded.'.json',
$codesJSON
);
file_put_contents(
$cwd.'/'.$countryCode.'/min/'.$minCodeRounded.'.jsonp',
'zipCodesCallback('.$codesJSON.');'
);
}
$row++;
}
fclose($handle);
}
// floor((X - lowest) / ((highest - lowest) / ceil(count / 1000))),
// if (a > 1) { file = floor((X - b) / c); }
if ($regenKey) {
$key = [];
foreach ($stats as $country => $stat) {
$key[$country] = [];
if ($stat['count'] > 100000) {
$chars = 3;
} elseif($stat['count'] > 10000) {
$chars = 2;
} elseif($stat['count'] > 1000) {
$chars = 1;
} else {
$chars = 0;
}
$key[$country] = $chars;
}
file_put_contents(
$cwd.'/key.json',
json_encode($key)
);
file_put_contents(
$cwd.'/key.js',
'var key = '.json_encode($key).';'
);
die(var_export($key, true));
}
/**
* Recursively delete files within a directory based on type.
* @param $dir
* @param array $types
*/
function clean($dir, $types = ['json', 'jsonp'])
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != ".." && $object != "key.json") {
if (is_dir($dir."/".$object)) {
clean($dir."/".$object, $types);
} else {
$ext = pathinfo($object, PATHINFO_EXTENSION);
if (in_array($ext, $types)) {
unlink($dir."/".$object);
}
}
}
}
}
}
function minPostal($postalCode)
{
// Only allow uppercase.
$postalCode = strtoupper($postalCode);
// Remove non-alphanumeric characters.
$postalCode = preg_replace("/[^A-Z0-9]/", '', $postalCode);
// Convert from base 36 to an integer.
$postalCode = base_convert($postalCode, 36, 10);
return $postalCode;
}
function minPostalRounded($postalCode, $country, $keyArr = [])
{
$result = 0;
if ($keyArr[$country] > 1) {
// Only allow uppercase.
$postalCode = strtoupper($postalCode);
// Remove non-alphanumeric characters.
$postalCode = preg_replace("/[^A-Z0-9]/", '', $postalCode);
$result = substr($postalCode, 0, $keyArr[$country]);
}
return $result;
}