<?php
/**
 * Plugin Now: Inserts a timestamp.
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Christoph Lang <calbity@gmx.de>
 */

// based on http://wiki.splitbrain.org/plugin:tutorial

// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();

if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
require_once(DOKU_PLUGIN . 'syntax.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_webthumbs extends DokuWiki_Syntax_Plugin {
		 
   function getInfo() {
        return array(
        'author'  => 'Christoph Lang',
        'email'   => 'calbity@gmx.de',
        'date'    => '2011-02-21',
        'name'    => 'Webthumbnails Plugin',
        'desc'    => 'Shows Thumbnails of Websites.',
        'url'     => 'https://www.dokuwiki.org/plugin:webthumbs'
        );
    }
    					
    function connectTo($mode) {
        $this->Lexer->addSpecialPattern('\<webthumb\:.*?\>', $mode, 'plugin_webthumbs');
    }

    function getType() { return 'substition'; }

    function getSort() { return 267; }

    function handle($match, $state, $pos, &$handler) {
    	
			$match = substr($match,10,-1);
			list($url,$link) = explode('|',$match,2);
			$url  = trim($url);
			$link = trim($link);
			if(!$link)
				$link = $url;
			
			return array($url,$link);
                		
    }
    
    function validateURL($url) {
    	return filter_var($url, FILTER_VALIDATE_URL); 
    }     			
    			
    function _preview($data) {
    	
			foreach($data as $url){
				if(!$this->validateURL($url)){
					$sError = str_replace("$1",htmlentities($url),$this->getLang('error'));
					return $sError;
				}
			}
			
			$type = $this->getConf('url');
			switch($type){
				case 3: $sWebService = "http://www.artviper.net/screenshots/screener.php?sdx=1024&sdy=768&w=120&h=80&q=100&url="; break;
				case 2: $sWebService = "http://images.websnapr.com/?size=s&nocache=81&url="; break;
				case 1: $sWebService = "http://www.thumbshots.de/cgi-bin/show.cgi?url="; break;
				case 0: 
				default: $sWebService = "http://open.thumbshots.org/image.pxf?url="; break;
			}
			$image = array(
  									'src'   => $sWebService.rawurlencode($data[0]).'&.png',
  									'cache' => 'nocache',
  									);
      									
			return array($data[1],$image);
    	
    }

    function render($mode, &$renderer, $data) {

      if ($mode == 'xhtml') {
      		$response = $this->_preview($data);
      		if(is_string($response)){
	      		$renderer->doc .= $response;
	      	}else{
	      	
						list($link,$image) = $response;
	      		
	      		$renderer->externallink($link,$image);
	      	
	          return true;
	        }
      }
      return false;
    }
}