/
ftpsync.php
385 lines (366 loc) · 9.28 KB
/
ftpsync.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
/*
ftpsync
ver 0.2.5
by rek@rek.me
You can use this script under the GPLv3 license.
The full-text of GPLv3 is here http://www.gnu.org/licenses/gpl-3.0.txt
*/
$ftpUser = 'anonymous';
$ftpHost = 'localhost';
$ftpPass = 'abc@example.com';
$ftpPort = 21;
$activeMode = false;
$remoteRoot = '/';
$localRoot = getcwd();
$chmod = false;
if($argc <= 1) {
echoUsage();
}
for($i = 1; $i < $argc; $i++) {
if($argv[$i][0] == '-') {
switch($argv[$i]) {
case '-u': case '--user':
$ftpUser = $argv[++$i];
break;
case '-h': case '--host':
$ftpHost = $argv[++$i];
break;
case '-o': case '--port':
$ftpPort = $argv[++$i];
break;
case '-p': case '--pass':
$ftpPass = $argv[++$i];
break;
case '-t': case '--active':
$activeMode = true;
break;
case '-c': case '--chdir':
$remoteRoot = $argv[++$i];
break;
case '-r': case '--root':
$localRoot = $argv[++$i];
break;
case '-f': case '--sync-file':
$fileName = $argv[++$i];
$syncMode = 'f';
break;
case '-i': case '--sync-incremental':
$syncMode = 'i';
break;
case '-a': case '--sync-whole-site':
$syncMode = 'a';
break;
case '-m': case '--chmod':
$chmod = true;
break;
case '--help':
echoUsage();
break;
default:
echoUsage();
}
} else {
echoUsage();
}
}
if(!isset($syncMode)) $syncMode = 'i';
/*
echo $ftpUser."\n";
echo $ftpHost."\n";
echo $ftpPass."\n";
echo $ftpPort."\n";
var_dump($activeMode)."\n";
echo $remoteRoot."\n";
echo $localRoot."\n";
echo $syncMode."\n";
echo $fileName;
*/
switch($syncMode) {
case 'f':
echo "Doing single file sync.\n";
if(basename($fileName) == $fileName) {
$fileName = clearPath(getcwd()).$fileName;
}
if(!is_file($fileName)) {
echo "$fileName is not a valid file.\n";
die();
}
$localRoot = clearPath($localRoot);
if(substr($fileName, 0, strlen($localRoot) -1) != substr($localRoot, 0, strlen($localRoot) -1)) {
echo "$fileName is not in the local root, skip upload.\n";
break;
}
echo "Loading file cache...";
//Check local file cache, if failed, do incremental sync.
$cache = loadCache($localRoot);
if($cache !== false) {
echo "OK\n";
//Upload single file.
$t = filemtime($fileName);
$f = substr($fileName, strlen($localRoot));
$files = array($f);
$ftp = getFtpConnection($ftpHost, $ftpPort, $ftpUser, $ftpPass, $activeMode);
upload($ftp, $remoteRoot, $localRoot, $files);
ftp_close($ftp);
//Update local file cache
$cache[md5($f)] = $t;
echo "Saving local file cache...";
if(saveCache($cache, $localRoot, false))
echo "OK\n";
else
echo "Failed\n";
break;
} else {
echo "Failed! ";
}
case 'i':
echo "Doing incremental sync.\n";
echo "Scanning local files...";
$localFiles = scanLocal($localRoot); //Scan local files.
if($localFiles === false) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
echo "Loading file cache...";
$fileCache = loadCache($localRoot); //Load local file cache if exists.
echo "OK\n";
//Find out newer files and upload them.
$newCache = $localFiles;
echo "Comparing files...";
foreach($localFiles as $f => $t) {
$mf = md5($f);
if(isset($fileCache[$mf]) && $t <= $fileCache[$mf])
unset($localFiles[$f]);
}
echo "OK\n";
if(count($localFiles) == 0) {
echo "No files need to upload.\n";
die();
}
$ftp = getFtpConnection($ftpHost, $ftpPort, $ftpUser, $ftpPass, $activeMode);
upload($ftp, $remoteRoot, $localRoot, array_keys($localFiles));
ftp_close($ftp);
echo "Saving local file cache...";
if(saveCache($newCache, $localRoot))
echo "OK\n";
else
echo "Failed\n";
break;
case 'a':
echo "Doing whole site sync.\n";
echo "Scanning local files...";
$localFiles = scanLocal($localRoot); // Scan local files
if($localFiles === false) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
$ftp = getFtpConnection($ftpHost, $ftpPort, $ftpUser, $ftpPass, $activeMode);
echo "Scanning remote files...";
$remoteFiles = scanRemote($ftp, $remoteRoot); //Scan remote files.
if($remoteFiles === false) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
//Find out and upload newer files.
echo "Comparing files...";
$cache = $localFiles;
foreach($localFiles as $f => $t) {
if(isset($remoteFiles[$f]) && $t <= $remoteFiles[$f])
unset($localFiles[$f]);
/* else {
echo $f;
echo date(" Y-m-d H:i:s ", $t);
echo date("Y-m-d H:i:s\n", $remoteFiles[$f]);
}*/
}
echo "OK\n";
if(count($localFiles) == 0) {
echo "No files need to upload.\n";
die();
}
upload($ftp, $remoteRoot, $localRoot, array_keys($localFiles));
ftp_close($ftp);
echo "Saving local file cache...";
if(saveCache($cache, $localRoot))
echo "OK\n";
else
echo "Failed\n";
}
function getFtpConnection($host, $port, $user, $pass, $active) {
echo "Connecting to FTP server...";
$ftp = @ftp_connect($host, $port);
if($ftp === false) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
echo "Logging in...";
if(!@ftp_login($ftp, $user, $pass)) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
echo "Switching to ".($active?"ACTIVE":"PASV")." mode...";
if(!@ftp_pasv($ftp, !$active)) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
return $ftp;
}
function upload($ftp, $remoteRoot, $localRoot, $uploadFiles) {
global $chmod;
if(count($uploadFiles) == 0) {
echo "No files need to upload.\n";
return;
}
$remoteRoot = clearPath($remoteRoot);
$localRoot = clearPath($localRoot);
echo "Changing directory to $remoteRoot...";
if(!@ftp_chdir($ftp, $remoteRoot)) {
echo "Failed!\n";
die();
} else {
echo "OK\n";
}
foreach($uploadFiles as $f) {
if(empty($f)) continue;
if(is_file($localRoot.$f)) {
echo "Uploading $f...";
$d = dirname($f);
if(!@ftp_chdir($ftp, $remoteRoot.$d)) { // if cannot chdir, try to create so
ftp_chdir($ftp, $remoteRoot);
$dir = strtok($d, '/\\');
do {
if($dir == '') continue;
@ftp_mkdir($ftp, $dir);
ftp_chdir($ftp, $dir);
} while($dir = strtok('/\\'));
}
if(ftp_put($ftp, basename($f), $localRoot.$f, FTP_BINARY)) {
echo "OK\n";
} else {
echo "Failed!Skip it.\n";
}
} else if(is_dir($localRoot.$f)) {
echo "Making dir $f ";
if(!@ftp_chdir($ftp, $remoteRoot.$f)) {
if(@ftp_mkdir($ftp, $remoteRoot.$f)) {
echo "OK\n";
} else {
echo "Failed\n";
}
} else {
echo "Exist!Skip it.\n";
}
}
if($chmod) {
$mod = fileperms($localRoot.$f)&0777;
echo "chmod ".decoct($mod)." for $f\n";
ftp_chmod($ftp, $mod, $remoteRoot.$f);
}
}
}
function saveCache($localFiles, $root, $hash=true) {
$root = clearPath($root);
$fp = @fopen($root.'.sync', 'w');
if($fp === false) return false;
foreach($localFiles as $f => $t) {
fprintf($fp, "%s\t%d\n", $hash?md5($f):$f, $t);
}
fclose($fp);
return true;
}
function loadCache($root) {
$root = clearPath($root);
$fp = @fopen($root.'.sync', 'r');
if($fp === false) return false;
$cache = array();
while($n = fscanf($fp, "%s\t%d\n")) {
list($fileHash, $modTime) = $n;
$cache[$fileHash] = $modTime;
}
fclose($fp);
return $cache;
}
function scanRemote($ftp, $dir, $rootLength=null) {
$dir = clearPath($dir);
if(is_null($rootLength)) $rootLength = strlen($dir);
$files = array();
$curDirList = ftp_rawlist($ftp, $dir);
foreach($curDirList as $n) {
if(!preg_match('/^(\S)[rwx\-]{9}[ 0-9]+\w+\s+\d+\s+[0-9:]+\s+(.+)$/', $n, $m)) continue;
$isFile = $m[1] == '-';
$isDir = $m[1] == 'd';
$n = $dir.$m[2];
if($isFile) {
$fileName = substr($n, $rootLength);
$files[$fileName] = ftp_mdtm($ftp, $n);
} else if($isDir){
$files[$fileName] = ftp_mdtm($ftp, $n);
$subDirFiles = scanRemote($ftp, $n, $rootLength);
$files = array_merge($files, $subDirFiles);
}
}
return $files;
}
function scanLocal($dir, $rootLength=null) {
$dir = clearPath($dir);
if(is_null($rootLength)) $rootLength = strlen($dir);
// check whether $root is a valid directory
if(!is_dir($dir)) {
echo "$dir is not a valid directory\n";
die();
}
//scan dir, create file modification time view
$files = array();
$curDirList = scandir($dir) ;
foreach($curDirList as $n) {
if($n[0] == '.') continue; // jump the hidden directory and file
$n = $dir.$n;
$fileName = substr($n, $rootLength);
$files[$fileName] = filemtime($n);
if(is_dir($n)){
$files = array_merge($files, scanLocal($n, $rootLength));
}
}
return $files;
}
function clearPath($p) {
$length = strlen($p);
if($p[$length - 1] != '\\' && $p[$length - 1] != '/')
$p .= '/';
return $p;
}
function echoUsage() {
echo <<<USAGE
Usage: ftpsync [OPTIONS] [FLAG] [file]
Options:
-u, --user FTP login user Default is anonymous
-h, --host FTP host Default is localhost
-o, --port FTP port Default is 21
-p, --pass FTP login password Default is abc@example.com
-c, --chdir Change to such remote dir when start to sync
-r, --root Local site root Default is current working directory
-f, --sync-file Upload a single file
Flags:
-m, --chmod Change remote file mode as local
--help Show this usage
Only one of flags below can be used in a time
-t, --active Turn off PASV mode
-i, --sync-incremental Upload files that newer then last upload
-a, --sync-whole-site Compare FTP files and upload newer file
USAGE;
exit();
}
?>