<?php
class Cache
{
  public static function store( $key, $data, $ttl = 86400, $subdir = '' )
  {
    if ( defined( 'SP_CACHE' ) and constant( "SP_CACHE" ) == false ) {
      return false;
    }
    file_put_contents( self::get_file_name( $key, $subdir ), base64_encode( serialize( array( time() + $ttl, $data ) ) ) );
  }

  private static function get_file_name( $key, $subdir )
  {
    $md5 = md5( $key );

    if ( $subdir )
      $dir = 'temp/' . $subdir . '/' . $md5[0] . '/';
    else
      $dir = 'temp/' . $md5[0] . '/';

    if ( !is_dir( $dir ) )
      mkdir( $dir , 0755 , true );

    return $dir . 's_cache_' . $md5;
  }

  static public function fetch( $key, $subdir = '' )
  {
    global $config;

    if ( !$config['cache'] )
      return false;

    $filename = self::get_file_name( $key );

    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];
  }
}
?>