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