<?php
class FileCache
{
  public function store( $key, $data, $ttl = 'l', $dir = '' )
  {
    switch ( $ttl )
    {
      case 's': $time = 60; break;
      case 'n': $time = 60 * 60; break;
      case 'l': default: $time = 60 * 60 * 24; break;
      
    }
    
    $h = fopen( self::getFileName( $key, $dir ) , 'w' );
    $data = base64_encode( serialize( array( time() + $time , $data ) ) );    
    @fwrite( $h, $data );
    
    fclose($h);
  }

  public function getFileName( $key, $dir = '' )
  {
    $md5 = md5( $key );
    
    if ( !$dir )
      $dir = 'temp/' . $md5[0] . '/';
    else
      $dir = $dir . '/' . $md5[0] . '/';
    
    if ( !is_dir( $dir ) )
      mkdir( $dir , 0770 , true );
    return $dir . 's_cache' . $md5;
  }

  public function fetch( $key, $dir = '' )
  {
    $filename = self::getFileName( $key, $dir );
      if ( !file_exists( $filename ) || !is_readable( $filename ) )
    return false;

    $data = base64_decode( file_get_contents( $filename ) );

    $data = @unserialize( $data );
    if ( !$data )
    {
      unlink($filename);
      return false;
    }

    if ( time() > $data[0] )
    {
      if ( file_exists( $filename ) )
        unlink( $filename );
      return false;
    }
    return $data[1];
  }
}
?>