<?php

class Plugin_comment extends Plugin
{
	static protected $count = array();
	
	
	function do_block($pagename, $param1, $param2)
	{
		$cookie = KinoWiki::getinstance()->getCOOKIE();
		if(mb_ereg('^(.*?),(.*)$', $param1, $m)){
			$type = trim($m[1]) == 'below' ? 'below' : 'above';
			$input = trim($m[2]) == 'textarea' ? 'textarea' : 'line';
		}
		else{
			$type = 'above';
			$input = 'line';
		}
		
		$smarty = new PluginSmarty('comment');
		if(!isset(Plugin_comment::$count["$pagename"])){
			Plugin_comment::$count["$pagename"] = 0;
		}
		$smarty->assign('num', Plugin_comment::$count["$pagename"]++);
		$smarty->assign('type', $type);
		$smarty->assign('pagename', $pagename);
		$smarty->assign('name', isset($cookie['name']) ? $cookie['name'] : '');
		if($input == 'textarea'){
			return $smarty->fetch('textarea.tpl.htm');
		}
		else{
			return $smarty->fetch('line.tpl.htm');
		}
	}
	
	
	function do_url()
	{
		$post = KinoWiki::getinstance()->getPOST();
		
		if(!isset($post['num']) || !isset($post['type']) || !isset($post['pagename'])){
			throw new PluginException('パラメータが足りません。', 'comment');
		}
		if(trim($post['text']) == ''){
			redirect($post['pagename']);
		}
		
		$source = explode("\n", Page::getinstance($post['pagename'])->getsource());
		$count = 0;
		for($i = 0; $i < count($source); $i++){
			if(mb_ereg('^#comment(?!style)(?:\s*\(.*?\))?(?:\s*{.*)?', $source[$i])){
				if($count == $post['num']){
					$name = $post['name'];
					$text = mb_ereg_replace('{', '&173;', $post['text']);
					$text = mb_ereg_replace('}', '&175;', $text);
					$time = date('Y-m-d H:i:s', TIME);
					$str = "#commentstyle($name, $time){{$text}}";
					$n = $i + ($post['type'] == 'below' ? 1 : 0);
					array_splice($source, $n, 0, $str);
					Page::getinstance($post['pagename'])->write(join("\n", $source));
					setcookie('name', $post['name'], time()+60*60*24*30);
					redirect($post['pagename']);
				}
				$count++;
			}
		}
		
		$ret['title'] = 'error';
		$smarty = new PluginSmarty('comment');
		$smarty->assign('text', $post['text']);
		$ret['body'] = $smarty->fetch('error.tpl.htm');
		return $ret;
	}
}

?>