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