<?php
/**
 * DokuWiki Plugin crossdbsqlclient (Syntax Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Heiko Heinz <heiko.heinz@soft2c.de>
 */

// must be run within Dokuwiki
if (! defined ( 'DOKU_INC' ))
	die ();

class syntax_plugin_crossdbsqlclient_crossdbsqlclient extends DokuWiki_Syntax_Plugin {
	/**
	 *
	 * @return string Syntax mode type
	 */
	public function getType() {
		return 'container';
	}
	/**
	 *
	 * @return string Paragraph type
	 */
	public function getPType() {
		return 'block';
	}
	/**
	 *
	 * @return int Sort order - Low numbers go before high numbers
	 */
	public function getSort() {
		return 260;
	}
	
	/**
	 * Connect lookup pattern to lexer.
	 *
	 * @param string $mode
	 *        	Parser mode
	 */
	public function connectTo($mode) {
		// case 1: crossdbsqlclient
		// case 2: crossdbsqlclient>type|server|database|user|password
 		$this->Lexer->addSpecialPattern ( '\{\{crossdbsqlclient\}\}', $mode, 'plugin_crossdbsqlclient_crossdbsqlclient' );
		$this->Lexer->addSpecialPattern ( '\{\{crossdbsqlclient>.+\|.+\|.+\|.+\|.+\}\}', $mode, 'plugin_crossdbsqlclient_crossdbsqlclient' );
	}
	
	// public function postConnect() {
	// $this->Lexer->addExitPattern('</FIXME>','plugin_crossdbsqlclient_crossdbsqlclient');
	// }
	
	/**
	 * Handle matches of the crossdbsqlclient syntax
	 *
	 * @param string $match
	 *        	The match of the syntax
	 * @param int $state
	 *        	The state of the handler
	 * @param int $pos
	 *        	The position in the document
	 * @param Doku_Handler $handler
	 *        	The handler
	 * @return array Data for the renderer
	 */
	public function handle($match, $state, $pos, Doku_Handler &$handler) {
		
		$pos = strpos($match, "{{crossdbsqlclient>");
		if($pos !== FALSE){
			$data = explode("|",preg_replace("/{{crossdbsqlclient>(.*?)}}/","\\1",$match));
			return $data;
		}
		
		$data = array ();
		return $data;
	}
	
	/**
	 * Render xhtml output or metadata
	 *
	 * @param string $mode
	 *        	Renderer mode (supported modes: xhtml)
	 * @param Doku_Renderer $renderer
	 *        	The renderer
	 * @param array $data
	 *        	The data from the handler() function
	 * @return bool If rendering was successful.
	 */
	public function render($mode, Doku_Renderer &$renderer, $data) {

		if ($mode != 'xhtml')
			return false;
		
		$renderer->info ['cache'] = false;
		
		if (! $this->isAuthorized ()) {
			echo '<div class="error">' . $this->getLang ( 'missingpermission' ) . '</div>';
			return true;
		}
		
		$button = $this->getLang ( 'submit_button' );
		
		$query='';
		if(isset($_GET ['q']))
		$query = trim ( $_GET ['q'] );
		
		$queryEsc = strtr ( $query, array (
				'<' => '&lt;' 
		) );
		
		$templates = $this->getTemplates ();
		
		$emptyresult = $this->getLang ( 'emptyresult' );
		
		echo <<<EOT
<script type="text/javascript"><!--
function crossdbsqlclient_load(query)
{
	with ( document.crossdbsqlclient.q )
	{
		value = query;
		focus();
	}

	return false;
}
//--></script>
<form action="$_SERVER[PHP_SELF]" method="GET" name="crossdbsqlclient" id="crossdbsqlclient">
 <input type="hidden" name="do" value="$_REQUEST[do]" />
 <input type="hidden" name="page" value="$_REQUEST[page]" />
 <input type="hidden" name="id" value="$_REQUEST[id]" />
 <div>
  $templates
 </div>
 $history
 <textarea name="q" rows="5" cols="100" style="width: 100%;">$queryEsc</textarea>
 <div>
  <input style="float:right;padding:4px;margin:10px" type="submit" value="$button" />
 </div>
</form>
<script type="text/javascript"><!--
document.crossdbsqlclient.q.focus();
document.crossdbsqlclient.q.select();  		
//--></script>
EOT;
		$db = $this->connectToDb ($data);
		
		$db->executeQuery($query);

		return true;
	}
	


	
	private function getTemplates() {
		$ret = '<u><b>' . $this->getLang ( 'templatesLabel' ) . '</b></u><br>';
		
		$text = $this->getLang ( 'template.1.text' );
		if ($text == '') {
			return '';
		}
		
		for($i = 1; $i <= true; $i ++) {
			$text = $this->getLang ( 'template.' . $i . '.text' );
			if ($text == '') {
				return $ret;
			}
			
			$sql = $this->getLang ( 'template.' . $i . '.sql' );
			$ret = $ret . '<button style="margin:4px" onclick="return crossdbsqlclient_load(\'' . $sql . '\')">' . $text . '</button>';
		}
		
		return $ret;
	}
	
	private function connectToDb($data) { // DB-Verbindung herstellen - eRent
		if(isset($data) && empty($data)==FALSE){
			//type@server@database@user@password
			$dbtype = $data[0];
			$serverName = $data[1];
			$dbName = $data[2];
			$userName = $data[3];
			$passWord = $data[4];
			return $this->connectToDbWrapper($dbtype, $serverName, $userName, $passWord, $dbName);
		}

		return $this->connectToDefaultDb();
	}
	
	
	private function connectToDefaultDb() { // DB-Verbindung herstellen - eRent
		$dbtype = $this->getConf ('dbtype');
		$serverName = $this->getConf ( 'serverName' );
		$userName = $this->getConf ( 'userName' );
		$passWord = $this->getConf ( 'passWord' );
		$dbName = $this->getConf ( 'dbName' );
	
		return $this->connectToDbWrapper($dbtype, $serverName, $userName, $passWord, $dbName);
	}

	private function connectToDbWrapper($dbtype, $serverName, $userName, $passWord, $dbName) { 
		
		self::includeLib();
		
		$dbWrapper = new DbWrapper($this, $dbtype, $serverName, $userName, $passWord, $dbName );
		
		return $dbWrapper;
	}
	
	protected function isAuthorized() {
		global $INPUT;
		$remoteUser = $INPUT->server->str ( 'REMOTE_USER' );
	
		if (! $remoteUser) {
			return false;
		}
	
		global $USERINFO;
		$groups = $USERINFO ['grps'];
		$allowedUserGroups = $this->getConf ( 'allowedUserGroups' );
	
		$allowedUserGroups = utf8_strtolower ( $allowedUserGroups );
		$members = explode ( ',', $allowedUserGroups );
		$members = array_map ( 'trim', $members );
		$members = array_unique ( $members );
		$members = array_filter ( $members );
	
		// compare cleaned values
		foreach ( $members as $member ) {
			if ($member == 'ALL')
				return true;
			if (in_array ( $member, $groups ))
				return true;
			else {
				if ($member == $remoteUser)
					return true;
			}
		}
		return false;
	}
	
	public static function includeLib()
	{
	
		if ( !class_exists( 'DbWrapper' ) )
		{
	
			$libFile = dirname( __FILE__ ) . '/dbwrapper.php';
	

			{ include_once( $libFile ); }
	
		}
	}
}

// vim:ts=4:sw=4:et:
