first set of actually fully working code (against the centos and
[glcas.git] / bin / downloadfile.php
diff --git a/bin/downloadfile.php b/bin/downloadfile.php
new file mode 100644 (file)
index 0000000..4760627
--- /dev/null
@@ -0,0 +1,76 @@
+<?php
+
+$url = "";
+$file = "";
+if(isset($argv[1])) {
+       $url = $argv[1];
+}
+
+if(isset($argv[2])) {
+       $file = $argv[2];
+}
+
+if($url == "" || $file == "") {
+       echo "need a url and file\n";
+       exit(0);
+}
+
+
+// ok, we kick off a download
+if(file_exists("$file")) {
+       // a download exists, does it still work
+       error_log("DOWNLOADER: file exists for current download, hope it works, attempting lock");
+       $localtmpfh = fopen("$file", "r");
+       $lockres = flock($localtmpfh, LOCK_EX|LOCK_NB);
+       if(!$lockres) {
+               error_log("flock did fail, all is right with the world a download is in progress");
+               exit(0);
+       } else {
+               error_log("lock succeeded, dieing in the arse");
+               unlink("$file");
+               unlink("$file.size");
+       }
+}
+
+$remotefile = fopen($url, "r");
+$localfile = fopen($file, "w");
+$lockres = flock($localfile, LOCK_EX);
+if(!$localfile) {
+       erorr_log("something went plop");
+       return;
+}
+// get the headers from the remote request and use them to hurt people
+$contentlen = 0;
+$contenttype = "";
+foreach($http_response_header as $key => $val) {
+       if(preg_match("/HTTP.*30[1-9].*/", $val)) {
+               mkdir($file);
+               exit(0);
+       }
+       // get content length form upstream and print
+       if(preg_match("/^Content-Length:.*/", $val)) {
+               $clentemp = preg_split("/[: ]+/", $val);
+               $contentlen = $clentemp[1];
+               //header($val);
+       }
+       // get content type from upstream and print
+       if(preg_match("/^Content-Type:.*/", $val)) {
+               $contenttype = $val;    
+       }
+       if(!$remotefile) {
+               return;
+       }
+        
+}
+
+file_put_contents("$file.size", $contentlen);
+
+while(!feof($remotefile)) {
+       $data = fread($remotefile, 2048);
+       fwrite($localfile, $data);
+}
+
+//rename("$file.tmp.data.deleteme", $file);
+unlink("$file.size");
+
+?>
\ No newline at end of file