<?php

class Plugin_bbs extends Plugin
{
	protected $bbsname;
	protected $name;
	protected $text = '';
	
	protected static $sqlite_pattern;
	
	
	function do_block($pagename, $param1, $param2)
	{
		if(trim($param1) == ''){
			throw new PluginException('引数がありません。', 'bbs');
		}
		
		$cookie = KinoWiki::getinstance()->getCOOKIE();
		$smarty = new PluginSmarty('bbs');
		$smarty->assign('pagename', trim($pagename));
		$smarty->assign('bbsname', trim($param1));
		$smarty->assign('name', isset($cookie['name']) ? $cookie['name'] : '');
		return $smarty->fetch('form.tpl.htm');
	}
	
	
	function do_url()
	{
		$post = KinoWiki::getinstance()->getPOST();
		
		$pagename = isset($post['pagename']) ? $post['pagename'] : '';
		if(!isset($post['bbsname']) || $post['bbsname'] == ''){
			throw new PluginException('パラメータが足りません。', 'bbs');
		}
		if(!isset($post['text']) || $post['text'] == ''){
			redirect($pagename);
		}
		$subject = (!isset($post['subject']) || $post['subject'] == '') ? '（無題）' : $post['subject'];
		$name = isset($post['name']) ? $post['name'] : '';
		
		$db = DataBase::getinstance();
		Plugin_bbs::$sqlite_pattern = '^' . mb_ereg_quote($post['bbsname']) . '/(\d+)/.+$';
		$db->create_aggregate('maxbbsnum', array('Plugin_bbs', 'sqlite_maxbbsnum'), array('Plugin_bbs', 'sqlite_maxbbsnum_finalize'), 1);
		$row = $db->fetch($db->query("SELECT maxbbsnum(pagename) FROM page"));
		$num = $row[0] + 1;
		
		$page = Page::getinstance("{$post['bbsname']}/{$num}/{$subject}");
		$smarty = new PluginSmarty('bbs');
		$smarty->assign('timestamp', TIME);
		$smarty->assign('name', $name);
		$smarty->assign('text', $post['text']);
		$page->write($smarty->fetch('bbs.tpl'));
		setcookie('name', $name, time()+60*60*24*30);
		redirect($pagename);
	}
	
	
	function sqlite_maxbbsnum(&$context, $string)
	{
		if(mb_ereg(Plugin_bbs::$sqlite_pattern, $string, $m)){
			if($m[1] > $context){
				$context = $m[1];
			}
		}
	}
	
	
	function sqlite_maxbbsnum_finalize(&$context)
	{
		return (int)$context;
	}
}


?>