<?php

class Plugin_bbsres extends Plugin
{
	static protected $count = array();
	
	
	function do_block($pagename, $param1, $param2)
	{
		$cookie = KinoWiki::getinstance()->getCOOKIE();
		
		$smarty = new PluginSmarty('bbsres');
		if(!isset(Plugin_bbsres::$count["$pagename"])){
			Plugin_bbsres::$count["$pagename"] = 0;
		}
		$smarty->assign('num', Plugin_bbsres::$count["$pagename"]++);
		$smarty->assign('pagename', $pagename);
		$smarty->assign('name', isset($cookie['name']) ? $cookie['name'] : '');
		return $smarty->fetch('form.tpl.htm');
	}
	
	
	function do_url()
	{
		$post = KinoWiki::getinstance()->getPOST();
		
		if(!isset($post['num']) || !isset($post['pagename'])){
			throw new PluginException('パラメータが足りません。', 'bbsres');
		}
		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('^#bbsres(?:\s*\(.*?\))?(?:\s*{.*)?', $source[$i])){
				if($count == $post['num']){
					$name = isset($post['name']) ? $post['name'] : '';
					$smarty = new PluginSmarty('bbsres');
					$smarty->assign('name', $name);
					$smarty->assign('text', $post['text']);
					$smarty->assign('timestamp', TIME);
					array_splice($source, $i, 0, $smarty->fetch('bbsres.tpl'));
					Page::getinstance($post['pagename'])->write(join("\n", $source));
					setcookie('name', $name, time()+60*60*24*30);
					redirect($post['pagename']);
				}
				$count++;
			}
		}
		
		$ret['title'] = 'error';
		$smarty = new PluginSmarty('bbsres');
		$smarty->assign('text', $post['text']);
		$ret['body'] = $smarty->fetch('error.tpl.htm');
		return $ret;
	}
}

?>