<?php

/*======================================================================
 * 
 * ARTVIPER THUMB CLASS
 * ---------------------------------------------------------------------
 * Benjamin Anseaume - le 24 avril 2009 - April 24th 2009
 * http://www.anseaume.com
 * http://www.anseaume.com/p/devs/
 * http://www.artviper.net/website-thumbnails.php
 * ---------------------------------------------------------------------
 * 
 * This class allow you to use the ArtViper system and handle for you
 * thumbnail generation. You can cache the pictures and choose how long
 * you'll cache it.
 * The class also use an alternative output for better performances.
 * 
 * BEFORE USING THIS CLASS
 * ---------------------------------------------------------------------
 * You have to create an account on ArtViper website
 * http://www.artviper.net/website-thumbnails.php in order to obtain a
 * user ID (called uid in this class).
 * You can use this class with a free account user ID or with a pro 
 * account (but in this case you can also use the pro API).
 * 
 * INSTALLATION
 * ---------------------------------------------------------------------
 * Just link this class with
 * require_once('path/to/artviperthumb.class.php');
 * Instantiate the class with
 * $image = new ArtViperThumb($config);
 * Where config is an ASSOCIATED ARRAY containing the following elements
 * 'uid' => 'Your user ID' : you ArtViper user ID. If you don't add this
 *     key, the class will fail.
 * 'use_cache' => true / false : do you want to cache your thumbnails ?
 *     (default : false)
 * 'cache_dir' => 'path/to/cache_dir' : don't forget to CHMOD this dir
 *     to 777 so the class can write in. (default './cache')
 * 'cache_duration' => 12 : how long (in hour) do you want to cache the
 *     generated files ? 24 is a good timing. (default : 24)
 * 'output' => true / false : display the generated thumb after process
 *     is over ? (default : true) If false, the class returns TRUE as a
 *     result. If true the class returns THE FILE.
 * 
 * GENERATION
 * ---------------------------------------------------------------------
 * $image = new ArtViperThumb($config_array);
 * echo '<img src="'.$image->getThumb($_POST['url']).'" />';
 * 
 * DISCLAIMER
 * ---------------------------------------------------------------------
 * Please refer to the ArtViper website and respect the terms and
 * conditions.
 * All comments in the class are in french. Sorry :)
 * 
======================================================================*/


class ArtViperThumb
{
    public 
$uid;
    
    public 
$use_cache;
    public 
$cache_dir;
    public 
$cache_duration;
    public 
$output;
    
    private 
$service_url 'http://www.artviper.net/screenshots/screener.php';
    
    
// Fonction constructeur
    
public function __construct ($config)
    {
        
// Erreurs fatales : la variable config n'est pas un tableau ou l'UID n'est pas présent
        // Dans ce cas pas la peine de continuer, on ne pourra rien faire
        
if (!is_array($config) || !isset($config['uid']))
            return 
false;
        else
            
$this->uid $config['uid'];
        
        
// On récupère tous les paramètres et on place les défauts si ils n'existent pas
        
if (isset($config['use_cache']) && is_bool($config['use_cache']))
            
$this->use_cache $config['use_cache'];
        else
            
$this->use_cache false;
            
        if (isset(
$config['cache_dir']) && is_string($config['cache_dir']))
            
$this->cache_dir $config['cache_dir'];
        else
            
$this->cache_dir 'cache';
        
        if (isset(
$config['cache_duration']) && is_numeric($config['cache_duration']))
            
$this->cache_duration $config['cache_duration'];
        else
            
$this->cache_duration 24;
            
        if (isset(
$config['output']) && is_bool($config['output']))
            
$this->output $config['output'];
        else
            
$this->output true;
    }
    
    
// Fonction d'execution
    
public function getThumb ($site$w 240$h 180$sdx 1024$sdy 768$q 90)
    {
        
// Je gère le nom. Il est constitué de tout ce qui va après le http:// ou le https:// encodé en MD5
        
$nom =  str_replace("http://"""$site);
        
$nom str_replace("https://"""$site);
        
$nom md5($nom);
        
        
// Je créé le nom du fichier, composé du nom encodé et des dimensions
        
$file $nom.'_'.$w.'_'.$h.'.jpeg';
        
        
// Je construis la requete
        
$req $this->service_url.'?';
        
$req .= http_build_query(array(
            
'url' => $site,
            
'w' => $w,
            
'h' => $h,
            
'sdx' => $sdx,
            
'sdy' => $sdy,
            
'q' => $q,
            
'userID' => $this->uid,
        ));
        
        
// Si je ne cache pas, j'affiche simplement le fichier
        
if (!$this->use_cache) :
            return 
$this->do_output ($req);
        else :
        
            
// Si le fichier existe, je regarde le temps qu'il lui reste à être caché
            
if (file_exists($this->cache_dir.'/'.$file)) :
                
$cachetime time() - filemtime ($this->cache_dir.'/'.$file) - ($this->cache_duration 60 60);
            else :
                
$cachetime = -1;
            endif;
        
            
// Si le fichier n'existe pas ou s'il a expiré, j'en recréée un autre
            
if (!file_exists($this->cache_dir.'/'.$file) || $cachetime >= 0) :
                
// Je récupère le fichier
                
$image = @file_get_contents($req);
                
$this->save_img($image$file);
                return 
$this->do_output ($this->cache_dir.'/'.$file);
            
            
// Sinon le fichier existe, je l'envoie
            
else :
                return 
$this->do_output ($this->cache_dir.'/'.$file);
            endif;
        endif;
    }
    
    private function 
save_img ($image$fichier)
    {
        
$fp fopen($this->cache_dir.'/'.$fichier,'w');
        
fwrite($fp$image);
        
fclose($fp);
    }
    
    private function 
do_output ($file)
    {
        if (
$this->output) :
            return 
$file;
        else :
            return 
true;
        endif;
    }
}


?>