<?php
/**
*
* @author Benjamin Gillissen <hide@address.com>
*
* **************************************************************
Copyright (C) 2009 Benjamin Gillissen
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
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. See the
GNU General Public License for more details at:
http://www.gnu.org/copyleft/gpl.html
* **************************************************************
*/
class ratewatch extends file_abstract {
private static $fmatch = '/%REF%_%HASH%.slot';
private $lm;
private $to;
private $ref;
public function __construct($limit, $timeout, $ref){
$this->lm = $limit;
$this->to = $timeout;
$this->ref = $ref;
//check for 'rate' file repo config, and happend if not present
parent::__construct('rate');
parent::connect();
}
private function filematch($file){ return ( ereg($this->ref, $file) AND ereg('.slot', $file) ); }
public function cleanup(){
//release expired slots.
$d=0;
while( FALSE !== ($file = $this->readdir('/')) ){
if ( TRUE === $this->filematch($file) ){
if ( (time()-$this->getmtime($file)) >= $this->to ){
$d++;
$this->remove('/'.$file, FALSE);
}
}
}
if ($d != 0 ){ errors::raise($d.' slot(s) has been released for "'.$this->ref.'"', CORE_LOG_DEBUG, 'RATEWATCH'); }
}
public function gotfree_slot(){
//how many free slot do we have ?
$c=0;
while( FALSE !== ($file = $this->readdir('/')) ){
if ( TRUE === $this->filematch($file) ){ $c++; }
}
return ( $c < $this->lm );
}
public function add_slot($did){
//lock a slot, by creating a file.
if ( $this->gotfree_slot() ){
$p = str_replace('%REF%', $this->ref, self::$fmatch);
$p = str_replace('%HASH%', CORE::hash(NULL,5), $p);
return $this->createfile($p, $did);
}
}
public function fetchslots(){
//for each slots, return the times that left before slot is released.
while( FALSE !== ($file = $this->readdir('/')) ){
if ( TRUE === $this->filematch($file) ){
errors::raise('Found rate slot file : "'.$file.'" for '.$this->ref, CORE_LOG_DEBUG, 'RATE');
$ft = $this->getmtime($file);
$o[$ft] = $this->readfile($file);
}
}
$l=0;
if ( isset($o) AND @is_array($o) ){
ksort($o);
$k = array_keys($o);
$i=0;
while($i < $this->lm){
if ( isset($k[$i]) ){
$l++;
$t[$i]['expire']= $this->to-(time() - $k[$i]);
$t[$i]['desc'] = $o[$k[$i]];
} else {
$t[$i]['expire']= '';
$t[$i]['desc'] = '-';
}
$i++;
}
} else {
$i=0;
while($i < $this->lm){
$t[$i]['expire']= '';
$t[$i]['desc'] = '-';
$i++;
}
}
errors::raise($l.' / '.$this->lm.' locked slots for '.$this->ref.'.', CORE_LOG_DEBUG, 'RATE');
return $t;
}
}