modified the way the directory detection works... its not foolproof,
[glcas.git] / bin / downloadfile.php
index 4760627..818dead 100644 (file)
@@ -15,6 +15,17 @@ if($url == "" || $file == "") {
        exit(0);
 }
 
+// first check any directories in $file are in existence
+$splfile = explode("/", $file);
+if(count($splfile) > 1) {
+       $tomake = "";
+       for($i = 0; $i < count($splfile)-1; $i++) {
+               $tomake .= "/".$splfile[$i];
+               echo("making directory $tomake");
+               if(!is_dir($tomake)) mkdir($tomake);
+       }
+}
+
 
 // ok, we kick off a download
 if(file_exists("$file")) {
@@ -28,24 +39,52 @@ if(file_exists("$file")) {
        } else {
                error_log("lock succeeded, dieing in the arse");
                unlink("$file");
-               unlink("$file.size");
+               if(file_exists("$file.size")) unlink("$file.size");
        }
 }
 
 $remotefile = fopen($url, "r");
+
+// check if ther mote file started
+if(!$remotefile) {
+       foreach($http_response_header as $key => $val) {
+               if(preg_match("/HTTP.*404.*/", $val)) {
+                       echo "got a 404 touching 404 file\n";
+                       touch("$file.404");
+                       exit(0);
+               }
+       }
+} else {
+       if(file_exists("$file.404")) {
+               unlink("$file.404");
+       }
+}
+
 $localfile = fopen($file, "w");
 $lockres = flock($localfile, LOCK_EX);
 if(!$localfile) {
-       erorr_log("something went plop");
+       echo "something went plop\n";
        return;
 }
+
+
 // get the headers from the remote request and use them to hurt people
 $contentlen = 0;
 $contenttype = "";
+
+// detecting a remote directory on a web session is near impossible, this is the best i can come up with
+// - check for a redirection header, then look for a trailing / on the url... best of luck to me
 foreach($http_response_header as $key => $val) {
-       if(preg_match("/HTTP.*30[1-9].*/", $val)) {
-               mkdir($file);
-               exit(0);
+       if(preg_match("/.*Location:.*/", $val)) {
+               echo "got location as $val\n";
+               $realloc = preg_replace("/.*[: ]/", "", $val);
+               if(preg_match("/.*\/$/", $realloc)) {
+                       echo "matched\n";
+                       fclose($localfile);
+                       unlink($file);
+                       mkdir($file);
+                       exit(0);
+               }
        }
        // get content length form upstream and print
        if(preg_match("/^Content-Length:.*/", $val)) {