47606270e2a4a0328915c0a2fd5c985b731d54bb
[glcas.git] / bin / downloadfile.php
1 <?php
2
3 $url = "";
4 $file = "";
5 if(isset($argv[1])) {
6         $url = $argv[1];
7 }
8
9 if(isset($argv[2])) {
10         $file = $argv[2];
11 }
12
13 if($url == "" || $file == "") {
14         echo "need a url and file\n";
15         exit(0);
16 }
17
18
19 // ok, we kick off a download
20 if(file_exists("$file")) {
21         // a download exists, does it still work
22         error_log("DOWNLOADER: file exists for current download, hope it works, attempting lock");
23         $localtmpfh = fopen("$file", "r");
24         $lockres = flock($localtmpfh, LOCK_EX|LOCK_NB);
25         if(!$lockres) {
26                 error_log("flock did fail, all is right with the world a download is in progress");
27                 exit(0);
28         } else {
29                 error_log("lock succeeded, dieing in the arse");
30                 unlink("$file");
31                 unlink("$file.size");
32         }
33 }
34
35 $remotefile = fopen($url, "r");
36 $localfile = fopen($file, "w");
37 $lockres = flock($localfile, LOCK_EX);
38 if(!$localfile) {
39         erorr_log("something went plop");
40         return;
41 }
42 // get the headers from the remote request and use them to hurt people
43 $contentlen = 0;
44 $contenttype = "";
45 foreach($http_response_header as $key => $val) {
46         if(preg_match("/HTTP.*30[1-9].*/", $val)) {
47                 mkdir($file);
48                 exit(0);
49         }
50         // get content length form upstream and print
51         if(preg_match("/^Content-Length:.*/", $val)) {
52                 $clentemp = preg_split("/[: ]+/", $val);
53                 $contentlen = $clentemp[1];
54                 //header($val);
55         }
56         // get content type from upstream and print
57         if(preg_match("/^Content-Type:.*/", $val)) {
58                 $contenttype = $val;    
59         }
60         if(!$remotefile) {
61                 return;
62         }
63          
64 }
65
66 file_put_contents("$file.size", $contentlen);
67
68 while(!feof($remotefile)) {
69         $data = fread($remotefile, 2048);
70         fwrite($localfile, $data);
71 }
72
73 //rename("$file.tmp.data.deleteme", $file);
74 unlink("$file.size");
75
76 ?>