commit | author | age
|
4673cc
|
1 |
<?php |
JK |
2 |
function ftp_fetch_if_newer($url, $file = NULL) { |
|
3 |
$url = parse_url($url); |
|
4 |
if(!isset($url['scheme']) || $url['scheme'] != 'ftp') { |
|
5 |
throw new Exception('Only FTP URLs are supported'); |
|
6 |
} |
|
7 |
if(!isset($url['host'])) { |
|
8 |
throw new Exception('Hostname not present in the URL'); |
|
9 |
} |
|
10 |
if(!isset($url['path'])) { |
|
11 |
throw new Exception('Path component not present in the URL'); |
|
12 |
} |
|
13 |
if(!isset($url['port'])) { |
|
14 |
$url['port'] = 21; |
|
15 |
} |
|
16 |
if(!isset($url['user'])) { |
|
17 |
$url['user'] = 'anonymous'; |
|
18 |
} |
|
19 |
if(!isset($url['pass'])) { |
|
20 |
$url['pass'] = 'anonymous@mpk.jacekk.net'; |
|
21 |
} |
|
22 |
if($file == NULL) { |
|
23 |
$file = basename($url['path']); |
|
24 |
} |
|
25 |
|
|
26 |
$localTime = -1; |
|
27 |
$localSize = -1; |
|
28 |
if(is_file($file)) { |
|
29 |
$localTime = filemtime($file); |
|
30 |
$localSize = filesize($file); |
|
31 |
} |
|
32 |
|
75471e
|
33 |
$ftp = FtpConnection::create($url['host'], $url['port'], $url['user'], $url['pass']); |
JK |
34 |
$remoteSize = $ftp->size($url['path']); |
|
35 |
$remoteTime = $ftp->mdtm($url['path']); |
4673cc
|
36 |
|
JK |
37 |
$updated = FALSE; |
|
38 |
|
978f77
|
39 |
if($localTime < $remoteTime || ($localTime == $remoteTime && $localSize != $remoteSize)) { |
4673cc
|
40 |
if(file_exists($file.'.tmp')) { |
JK |
41 |
unlink($file.'.tmp'); |
|
42 |
} |
75471e
|
43 |
$ftp->get($file.'.tmp', $url['path'], FTP_BINARY); |
JK |
44 |
touch($file.'.tmp', $remoteTime); |
|
45 |
if(!rename($file.'.tmp', $file)) { |
|
46 |
throw new Exception('Temporary file rename failed'); |
4673cc
|
47 |
} |
75471e
|
48 |
$updated = TRUE; |
4673cc
|
49 |
} |
JK |
50 |
|
|
51 |
return $updated; |
|
52 |
} |
|
53 |
|
|
54 |
function fetch($url, $file = NULL) { |
|
55 |
if($file == NULL) { |
|
56 |
$file = basename($url['url']); |
|
57 |
} |
|
58 |
$data = file_get_contents($url); |
|
59 |
if($data === FALSE) { |
|
60 |
throw new Exception('URL fetch failed'); |
|
61 |
} |
|
62 |
if(file_put_contents($file.'.tmp', $data) === FALSE) { |
|
63 |
throw new Exception('Temporary file creation failed'); |
|
64 |
} |
|
65 |
if(!rename($file.'.tmp', $file)) { |
|
66 |
throw new Exception('Temporary file rename failed'); |
|
67 |
} |
|
68 |
} |