Jacek Kowalski
2019-06-20 978f77a82328250542c2baa73bc96a383501a269
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     
33     $ftp = ftp_connect($url['host'], $url['port'], 10);
34     if($ftp === FALSE) {
35         throw new Exception('FTP connection failed');
36     }
37     if(!ftp_login($ftp, $url['user'], $url['pass'])) {
38         throw new Exception('FTP login failed');
39     }
40     if(!ftp_pasv($ftp, TRUE)) {
41         throw new Exception('Passive FTP request failed');
42     }
43     $remoteSize = ftp_size($ftp, $url['path']);
44     if($remoteSize < 0) {
45         throw new Exception('FTP file size fetch failed');
46     }
47     $remoteTime = ftp_mdtm($ftp, $url['path']);
48     if($remoteTime < 0) {
49         throw new Exception('FTP modification time fetch failed');
50     }
51     
52     $updated = FALSE;
53     
978f77 54     if($localTime < $remoteTime || ($localTime == $remoteTime && $localSize != $remoteSize)) {
4673cc 55         if(file_exists($file.'.tmp')) {
JK 56             unlink($file.'.tmp');
57         }
58         if(ftp_get($ftp, $file.'.tmp', $url['path'], FTP_BINARY)) {
59             touch($file.'.tmp', $remoteTime);
60             if(!rename($file.'.tmp', $file)) {
61                 throw new Exception('Temporary file rename failed');
62             }
63             $updated = TRUE;
64         }
65     }
66     
67     ftp_close($ftp);
68     
69     return $updated;
70 }
71
72 function fetch($url, $file = NULL) {
73     if($file == NULL) {
74         $file = basename($url['url']);
75     }
76     $data = file_get_contents($url);
77     if($data === FALSE) {
78         throw new Exception('URL fetch failed');
79     }
80     if(file_put_contents($file.'.tmp', $data) === FALSE) {
81         throw new Exception('Temporary file creation failed');
82     }
83     if(!rename($file.'.tmp', $file)) {
84         throw new Exception('Temporary file rename failed');
85     }
86 }