<?php
/**
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     René Drießel <rene@driessel.de>
 */

// 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_crypto extends DokuWiki_Syntax_Plugin {

	function getType() {
		return 'disabled';
	}

	function getPType() {
		return 'normal';
	}

	function getAllowedTypes() {
		return array();
	}

	function getSort() {
		return 999;
	}

	function connectTo($mode) {
		$this->Lexer->addEntryPattern('<decrypt.*?>(?=.*?</decrypt>)', $mode,'plugin_crypto');
	}

	function postConnect() {
		$this->Lexer->addExitPattern('</decrypt>','plugin_crypto');
	}

	/**
	 * Handle the match
	 */
	function handle($match, $state, $pos, &$handler) {
		return array($state, trim($match));
	}

	function render($mode, &$renderer, $data) {
		if($mode == 'xhtml') {
			list($state, $match) = $data;
			switch ($state) {
			case DOKU_LEXER_ENTER:
				if (!is_ssl()) msg($this->getLang("no_ssl"), -1);

				$id     = $this->xml_property($match, "id", uniqid(""));
				$inline = $this->xml_property($match, "inline", "true");
				$hint   = $this->xml_property($match, "hint", $this->getLang('standard_hint'));
				$renderer->doc .= '<span>';
				$renderer->doc .= '<button class="toolbutton" title="Toogle encryption" onclick="pg_toggle_encryption(this, \''.$id.'\')">';
				$renderer->doc .= '<img src="'.DOKU_BASE."lib/plugins/crypto/lock.png".'"/>';
				$renderer->doc .= '</button>';
				$options = 'id="'.$id.'" class="encrypted" hint="'.$hint.'"';
				if ($inline == "true") {
					$options .= ' inline="true"';
				} else {
					$options .= ' inline="false"';
				}

				$renderer->doc .= '<span '.$options.'>';
				break;
			case DOKU_LEXER_UNMATCHED:
				$renderer->doc .= $match;
				break;
			case DOKU_LEXER_EXIT:
				$renderer->doc .= '</span>';
				$renderer->doc .= '</span>';
				break;
			}

			return true;
		}

		return false;
	}

	function xml_content($xml) {
		$pattern = '>(.*)<';
		if (ereg($pattern, $xml, $matches)) {
			return $matches[1];
		}

		return "";
	}

	function xml_property($xml, $name, $default = "") {
		// dbglog("xml_property($xml, $name, $default)");
		$pattern = $name ."='([^']*)')";
		if (ereg($pattern, $xml, $matches)) {
			return $matches[1];
		}

		$pattern = $name .'="([^"]*)"';
		if (ereg($pattern, $xml, $matches)) {
			return $matches[1];
		}

		return $default;
	}
}
