<?php
/**
 * JGraphX diagram editor plugin, based on Hotdraw Plugin
 */

if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

class syntax_plugin_jdraw extends DokuWiki_Syntax_Plugin {

    function getInfo() {
        return array(
            'author' => 'Pavel Vlasov',
            'email'  => 'Pavel.Vlasov@hammurapi.com',
            'date'   => '2010-04-06',
            'name'   => 'jDraw Plugin',
            'desc'   => 'Uses JGraphX diagram editor to draw diagrams - Based on draw plug-in.',
            'url'    => 'http://wiki.splitbrain.org/plugin:jdraw',
        );
    }

    function getType() { 
    	return 'substition'; 
    }
    
    function getSort() { 
    	return 303;
    }
    
    function connectTo($mode) { 
    	$this->Lexer->addSpecialPattern("{{jdraw>.+?}}",$mode,'plugin_jdraw'); 
    }
    
    /**
     * Handle the match
     */
    function handle($match, $state, $pos, &$handler) {
        return substr($match,8,-2); 
    }

    /**
     * Create output
     */
    function render($mode, &$renderer, $indata) {
    	$name = $indata;
    	
    	global $conf;
    	
      	if($mode != 'xhtml') {
      		return false;
      	}
      	
        //check name 
        $name = strtolower($name);
        if (strlen($name)==0) {
          $renderer->doc.="---INVALID_DIAGRAM---";
          return true;
        }
        
        $namespace="";
        $lastColonPos = strripos($name,":");
        if ($lastColonPos>0) {
        	$namespace=substr($name, 0, $lastColonPos);
        	$name = substr($name, $lastColonPos+1);
        }
                
        $namespace.=':';
        $media_dir = $conf['mediadir'].'/'.str_replace(":","/",$namespace);
        if (! file_exists($media_dir)) {
        	mkdir ($media_dir);
	        chmod ($media_dir, 0777);
        }
        
        $image_file = $name.'.'.$this->getConf('image_format');
        
		if (! is_readable($media_dir.$image_file)) { 
			$image_file = $name.'.gif'; // for seamless migration from the previous version.
		}
        
        
		$types=getMimeTypes();
		if (! $types['mxe']) { 
			msg("jDraw plugin needs entry in mime.conf: \"mxe text/xml\"",-1); 
		}

		$random = rand(0,100000); //to prevent JS errors if one diagram is on a page mupltiple times

        //base URL to fetch every file
        $fetchpath = DOKU_BASE."lib/exe/fetch.php?media=$namespace";        
        $image_id = "jdraw_image__$random";
        $renderer->doc.="<img src={$fetchpath}{$image_file}' id='{$image_id}' alt=' [diagram] '>";
        
		$auth = auth_quickaclcheck("{$namespace}*");
		if ($auth >= AUTH_DELETE) {
			$appletQueryString="dokuBase=".bin2hex(DOKU_BASE);
			$appletQueryString.="&authtok=".auth_createToken();
			$appletQueryString.="&sectok=".getSecurityToken();
			$appletQueryString.="&sessionName=".session_name();
			$appletQueryString.="&sessionId=".session_id();
			$appletQueryString.="&name=".bin2hex($indata);
			$appletQueryString.="&image_format=".$this->getConf("image_format");
			$appletQueryString.="&palettes=".bin2hex($this->getConf("palettes"));
			//$appletQueryString.="&dokuCookie=".bin2hex(DOKU_COOKIE);
			//$appletQueryString.="&dokuCookieValue=".bin2hex($_COOKIE[DOKU_COOKIE]);        
			
			if (! is_readable($media_dir.$name.".mxe")) { 
				$appletQueryString.="&isNew=yes";
			}
			
			$appletQueryString.="&rnd=".$random; // To prevent serving of cached page.
	        
	        $renderer->doc.="<a class='diagbutton' target='_jdraw_{$random}' href='".DOKU_BASE."lib/plugins/jdraw/jdraw.php?".$appletQueryString."'>Edit</a><br>";
	    }
	    
	    return true;
    }
}
