<?php
/* This is an experimental HTTP_Download bandwidth limiting script
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @license GPLv2
 * @author apoc <apoc@sixserv.org>
**/

require("Download.php");

$file "path/to/some/big/file/for/testing";

$track_folder "tracks/";

$bandwidth 100// in KiB/s
$throttle_delay 1// in seconds
$buffer_size $bandwidth 1024 $throttle_delay;
$track_expire 5// time in seconds before a trackfile expires

$dl = &new HTTP_Download();
$dl->setFile($file);
$dl->setGzip(false);
$dl->setBufferSize($buffer_size);
$dl->setThrottleDelay($throttle_delay);

if(!
is_dir($track_folder))
    
mkdir($track_folder);

if(!
is_dir($track_folder) || !is_writeable($track_folder))
    die(
"Could not write to track folder.");

$chars "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
do 
// okay lets make sure the file doesnt exists..
{
    
$rcid "";
    for(
$i 0$i 10$i++)
    {
        
$rcid .= $chars[rand(0strlen($chars)-1)];
    }
}
while(
file_exists($track_folder."/".$rcid));

$dl->setThrottleCallback("tracking");
function 
tracking(&$dl)
{
    global 
$track_folder$rcid$bandwidth$throttle_delay$track_expire;

    
// active tracked connections:
    
$active_conns 1;

    
// search for other trackfiles
    
foreach(scandir($track_folder) as $other_rcid)
    {
        if(
$other_rcid != "." && $other_rcid != ".." && $other_rcid != $rcid)
        {
            
// load trackfile
            
$last_seen trim(file_get_contents($track_folder."/".$other_rcid));

            
// older then <n> seconds? -> delete trackfile
            
if(time() - $last_seen >= $track_expire)
                
unlink($track_folder."/".$other_rcid);
            else 
// this looks like an active connection:
                
$active_conns++;
        }
    }

    
// write/overwrite own trackerdata
    
file_put_contents($track_folder."/".$rcidtime());

    
// now adjust buffer size
    // TODO: whats with to many connections?
    
$dl->setBufferSize( ($bandwidth 1024 $throttle_delay) / $active_conns );
}

$dl->setContentDisposition(HTTP_DOWNLOAD_ATTACHMENTbasename($file));
$dl->guessContentType();
$dl->send();

unlink($track_folder."/".$rcid);

?>