<?php
/**
 * @version $Id: tpl.inc.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

if(!defined('IN_ADMIN') || !isset($_PBDEV['PHP_SELF']) || !preg_match('/[\/\\\\]admincp\.php$/i', $_PBDEV['PHP_SELF']))
{
	exit('Access Denied');
}
define('PB_CSCRIPT', 'tpl');
allowdo('settpl');
$baseurl = 'admincp.php?action=tpl&type=';

if ($type == 'view' || empty($type))
{
	require_once(PBDIGG_ROOT.'include/PDirectory.class.php');
	$directory = $_GET['directory'];
	if (strpos($directory, '..') !== FALSE)
	{
		showMsg($a_message['parameter_error'], $actionurl);
	}
	$DIR = PDirectory::getInstance();
	$DIR->setRoot(PBDIGG_ROOT.'templates');
	$DIR->setCDir($directory);
	$icon = array(
		'dir' => array('dir'),
		'html' => array('html', 'htm', 'shtml', 'tpl'),
		'php' => array('php', 'php3'),
		'img' => array('gif', 'jpg', 'jpeg', 'png', 'bmp', 'psd'),
		'doc' => array('doc'),
		'xls' => array('xls'),
		'txt' => array('txt'),
		'js' => array('js'),
		'xml' => array('xml'),
		'css' => array('css'),
		'rm' => array('rm', 'rmvb'),
		'wmv' => array('wmv', 'wma', 'avi'),
		'zip' => array('zip', 'rar', 'gz', 'tar')
	);
	$DIR->setIcon(PBDIGG_ROOT.'images/file/', $icon, 'gif');
//	$DIR->setExt(array('html'));
	$DIR->listDir();
	$DIR->upDir();
//	var_dump($DIR->getDirs());
//	var_dump($DIR->getFiles());

	$TPL->assign('dirs', $DIR->getDirs());
	$TPL->assign('files', $DIR->getFiles());
	$TPL->assign('updir', $DIR->getUpDir());
	$TPL->assign('cdir', $directory);
	$TPL->assign('baseurl', $_PBENV['PB_URL'].'templates'.$directory);
	$type = 'view';
}
elseif ($type == 'del')
{
	$directory = $_GET['directory'];
	if (strpos($directory, '..') !== FALSE || !preg_match('/[a-zA-Z0-9]+?\.(html|htm|gif|png|bmp|jpg|jpeg|css|js)/i', $filename))
	{
		showMsg($a_message['parameter_error'], $baseurl.'view');
	}
	$filepath = PBDIGG_ROOT.'templates'.$directory.'/'.$filename;
	if (file_exists($filepath))
	{
		PDel($filepath);
	}
	showMsg($a_message['del_success'], $baseurl.'view');
}
elseif ($type == 'mod')
{
	if (strpos($directory, '..') !== FALSE || !preg_match('/^[a-zA-Z0-9]+?\.(html|htm|css|js)$/i', $filename))
	{
		showMsg($a_message['parameter_error'], $baseurl.'view');
	}
	$filepath = PBDIGG_ROOT.'templates'.$directory.'/'.$filename;
	$filedate = '';
	if (file_exists($filepath))
	{
		if ($submitted)
		{
			$template = str_replace(array('\\"', '\\\'', '\\\\'), array('"', '\'', '\\'), $template);
			if (PWriteFile($filepath, $template, 'wb'))
			{
				redirect($a_message['mod_tpl_success'], $baseurl.'view&directory='.$directory);
			}
			else
			{
				showMsg($a_message['tpl_writein_failed'], $baseurl.'view');
			}
		}
		else
		{
			$filedate = PReadFile($filepath);			
			$filedate = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;', '&#', '<', '>'), array('&amp;amp;', '&amp;quot;', '&amp;lt;', '&amp;gt;', '&amp;#', '&lt;', '&gt;'), $filedate);
		}
	}
	else
	{
		showMsg($a_message['file_not_exist'], $baseurl.'view');
	}
	$TPL->assign('template', $filedate);
	$TPL->assign('filename', $filename);
	$TPL->assign('directory', $directory);
}
elseif ($type == 'define')
{
	if ($submitted)
	{
		$tplid = (int)$tplid;
		$template = trim($_POST['template']);
		$DB->db_query("UPDATE {$db_prefix}tplvar SET tplcontent = '$template' WHERE tplid = $tplid");
		$Cache->tplvar();
		redirect($a_message['tpl_define_success'], $actionurl.'&type=define&step='.$step);
	}
	else
	{
		if (!in_array($step, array('topped', 'first')))
		{
			redirect($a_message['parameter_error'], $actionurl.'&type=define&step=topped');
		}
		$definetpl = $DB->db_fetch_one_array("SELECT * FROM {$db_prefix}tplvar WHERE tplmark = '$step'");
		$definetpl['define_tpl_content_intro'] = $cp_message['define_tpl_content_'.$step.'_intro'];
		$actionurl .= '&step='.$step.'&tplid='.$definetpl['tplid'];
		$TPL->assign('definetpl', $definetpl);
	}
}
elseif ($type == 'guide')
{
	if ($submitted)
	{
		$trancid = $trantype = $tranattribute = '';
		$tplname = trim($_POST['tplname']);
		if (!preg_match('/^[_\x80-\xff\d]{1,255}$/i', $tplname))
		{
			showMsg($a_message['tpl_guide_illegal_tplname'], $actionurl);
		}
		
		if ($tpl_cid && $tpl_cid[0] !== '0')
		{
			foreach ($tpl_cid as $v)
			{
				$trancid .= $v.',';
			}
			$trancid = substr($trancid, 0, -1);
		}
		if (in_array($tpltype, array('thread', 'comment', 'member')))
		{
			$trantype = $tpltype{0};
		}
		else
		{
			redirect($a_message['tpl_guide_illegal_tpltype'], 'admincp.php?action=logout');
		}
		$tplnum = is_numeric($tplnum) ? (int)$tplnum : 10;
		switch ($trantype)
		{
			case 't':
				$tranattribute = $thread_tplattribute;
				break;
			case 'c':
				$tranattribute = $comment_tplattribute;
				break;
			case 'm':
				$tranattribute = $member_tplattribute;
				break;
		}
		$order = ($order == 'desc') ? '1' : '0';
		$timelimit = (int)$timelimit;
		$titlelimit = (int)$titlelimit;
		$cotentlimit = (int)$cotentlimit;
		$topicimglimit = (int)$topicimglimit;
		$commendlimit = (int)$commendlimit;
		$commendlimitpic = (int)$commendlimitpic;
		if ($timeformatlimit != '-1' && !preg_match('/^(Y-)?m-d( H:i:s)?$/i', $timeformatlimit))
		{
			redirect($a_message['tpl_guide_illegal_timeformat'], 'admincp.php?action=logout');
		}
		$template = SafeConvert(trim($_POST['template']));
		if ($tpl_cid[0] === '0' && $trantype != 'm')
		{
			$tplmark = 'self_'.substr(md5($tplname.random(8)), 0, 8);
			while (1)
			{
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}templates WHERE tplmark = '$tplmark'");
				if ($rs['num'])
				{
					$tplmark = 'self_'.substr(md5($tplname.random(8)), 0, 8);
				}
				else
				{
					break;
				}
			}
			foreach ($categories as $k => $v)
			{
				$DB->db_query("INSERT INTO {$db_prefix}templates (tplid, tplname, tplmark, trancid, trannum, tranattribute, cotentlimit, titlelimit, iftopicimg, ifcommend, ifcommendpic, timelimit, timeformat, trantype, displayorder, ifself, tplcontent) VALUES (NULL, '$tplname', '".$tplmark.'_'.$k."', '$k', $tplnum, '$tranattribute', $cotentlimit, $titlelimit, $topicimglimit, $commendlimit, $commendlimitpic, $timelimit, '$timeformatlimit', '$trantype', $order, 1, '$template')");
			}
		}
		else
		{
			$tplmark = 'tpl_'.substr(md5($tplname.random(8)), 0, 8);
			while (1)
			{
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}templates WHERE tplmark = '$tplmark'");
				if ($rs['num'])
				{
					$tplmark = 'tpl_'.substr(md5($tplname.random(8)), 0, 8);
				}
				else
				{
					break;
				}
			}
			$DB->db_query("INSERT INTO {$db_prefix}templates (tplid, tplname, tplmark, trancid, trannum, tranattribute, cotentlimit, titlelimit, iftopicimg, ifcommend, ifcommendpic, timelimit, timeformat, trantype, displayorder, ifself, tplcontent) VALUES (NULL, '$tplname', '$tplmark', '$trancid', $tplnum, '$tranattribute', $cotentlimit, $titlelimit, $topicimglimit, $commendlimit, $commendlimitpic, $timelimit, '$timeformatlimit', '$trantype', $order, 0, '$template')");
		}
		$Cache->mktrantpl();
		$Cache->mktran();
		redirect($a_message['tpl_guide_mksuccess'], $actionurl);
	}
	else
	{
		$tpl_cid = array();
		foreach ($categories as $key => $value)
		{
			$tpl_cid[$key] = $value['name'];
		}
		$TPL->assign('tpl_cid', html_checkbox($tpl_cid, 'tpl_cid[]', array(), 5));
		$guide = array('type_thread'=>' checked="checked"', 'thread_digg'=>' checked="checked"', 'comment_digg'=>' checked="checked"', 'member_newmember'=>' checked="checked"', 'timelimit0'=>' checked="checked"', 'topicimglimit0'=>' checked="checked"', 'tpl_thread'=>'block', 'tpl_comment'=>'none', 'tpl_member'=>'none', 'commendlimit0'=>' checked="checked"', 'ifcommendpic0'=>' checked="checked"');
		$TPL->assign('guide', $guide);
	}
}
elseif ($type == 'list')
{
	if ($job == 'edit')
	{
		$tplid = (int)$tplid;
		$rs = $DB->db_fetch_one_array("SELECT * FROM {$db_prefix}templates WHERE tplid = $tplid");
		if (!$rs)
		{
			showMsg($a_message['parameter_error'], $actionurl);
		}
		if ($submitted)
		{
			$trancid = $trantype = $tranattribute = '';
			$tplname = trim($_POST['tplname']);
			if (!preg_match('/^[_\x80-\xff\d]{1,255}$/i', $tplname))
			{
				showMsg($a_message['tpl_guide_illegal_tplname'], $actionurl);
			}
			
			if (!$rs['ifself'] && $tpl_cid && $tpl_cid[0] !== '0')
			{
				foreach ($tpl_cid as $v)
				{
					$trancid .= $v.',';
				}
				$trancid = substr($trancid, 0, -1);
			}
			if (in_array($tpltype, array('thread', 'comment', 'member')))
			{
				$trantype = $tpltype{0};
			}
			else
			{
				redirect($a_message['tpl_guide_illegal_tpltype'], 'admincp.php?action=logout');
			}
			$tplnum = is_numeric($tplnum) ? (int)$tplnum : 10;
			switch ($trantype)
			{
				case 't':
					$tranattribute = $thread_tplattribute;
					break;
				case 'c':
					$tranattribute = $comment_tplattribute;
					break;
				case 'm':
					$tranattribute = $member_tplattribute;
					break;
			}
			$order = ($order == 'desc') ? '1' : '0';
			$timelimit = (int)$timelimit;
			$titlelimit = (int)$titlelimit;
			$cotentlimit = (int)$cotentlimit;
			$topicimglimit = (int)$topicimglimit;
			$commendlimit = (int)$commendlimit;
			$commendlimitpic = (int)$commendlimitpic;
			if ($timeformatlimit != '-1' && !preg_match('/^(Y-)?m-d( H:i:s)?$/i', $timeformatlimit))
			{
				redirect($a_message['tpl_guide_illegal_timeformat'], 'admincp.php?action=logout');
			}
			$template = SafeConvert(trim($_POST['template']));
			if ($rs['ifself'])
			{
				$DB->db_query("UPDATE {$db_prefix}templates SET tplname = '$tplname', trannum = '$tplnum', tranattribute = '$tranattribute', cotentlimit = '$cotentlimit', titlelimit = '$titlelimit', iftopicimg = '$topicimglimit', ifcommend = '$ifcommend', ifcommendpic = '$ifcommendpic', timelimit = '$timelimit', timeformat = '$timeformatlimit', trantype = '$trantype', displayorder = '$order', tplcontent = '$template' WHERE ifself =1 AND tplmark LIKE '".substr($rs['tplmark'], 0, strrpos($rs['tplmark'], '_'))."%'");
			}
			else
			{
				$DB->db_query("UPDATE {$db_prefix}templates SET tplname = '$tplname', trancid = '$trancid', trannum = '$tplnum', tranattribute = '$tranattribute', cotentlimit = '$cotentlimit', titlelimit = '$titlelimit', iftopicimg = '$topicimglimit', ifcommend = '$commendlimit', ifcommendpic = '$commendlimitpic', timelimit = '$timelimit', timeformat = '$timeformatlimit', trantype = '$trantype', displayorder = '$order', tplcontent = '$template' WHERE tplid = $tplid");
			}
			$Cache->mktrantpl();
			$Cache->mktran();
			redirect($a_message['tpl_guide_mksuccess'], $actionurl);
		}
		else
		{
			$actionurl .= '&amp;job=edit&amp;submitted=1&amp;tplid='.$tplid;
			$type = 'guide';
			$tpl_cid = $index = array();
			$extra = '';
			$guide = array('tplname'=>$rs['tplname'], 'tplnum'=>$rs['trannum'], 'titlelimit'=>$rs['titlelimit'], 'cotentlimit'=>$rs['cotentlimit'], 'tplcontent'=>$rs['tplcontent'], 'tpl_thread'=>'none', 'tpl_comment'=>'none', 'tpl_member'=>'none');
			foreach ($categories as $key => $value)
			{
				$tpl_cid[$key] = $value['name'];
			}
			if ($rs['ifself'])
			{
				$guide['cate_self'] = ' checked="checked" disabled = "disabled"';
				$extra = ' disabled = "disabled"';
			}
			else
			{
				$guide['cate_self'] = ' disabled = "disabled"';
				$index = explode(',', $rs['trancid']);
			}
			$TPL->assign('tpl_cid', html_checkbox($tpl_cid, 'tpl_cid[]', $index, 5, $extra));
			switch ($rs['trantype'])
			{
				case 't':
					$guide['type_thread'] = ' checked="checked"';
					$guide['thread_'.$rs['tranattribute']] = ' checked="checked"';
					$guide['tpl_thread'] = 'block';
					break;
				case 'c':
					$guide['type_comment'] = ' checked="checked"';
					$guide['comment_'.$rs['tranattribute']] = ' checked="checked"';
					$guide['tpl_comment'] = 'block';
					break;
				case 'm':
					$guide['type_member'] = ' checked="checked"';
					$guide['member_'.$rs['tranattribute']] = ' checked="checked"';
					$guide['tpl_member'] = 'block';
					break;
			}
			if ($rs['displayorder'])
			{
				$guide['order_desc'] = ' selected="selected"';
			}
			else
			{
				$guide['order_asc'] = ' selected="selected"';
			}
			$guide['timelimit'.$rs['timelimit']] = ' checked="checked"';
			$guide['topicimglimit'.$rs['iftopicimg']] = ' checked="checked"';
			$guide['commendlimit'.$rs['ifcommend']] = ' checked="checked"';
			$guide['ifcommendpic'.$rs['ifcommendpic']] = ' checked="checked"';
			switch ($rs['timeformat'])
			{
				case 'Y-m-d H:i:s':
					$guide['timeformatlimit1'] = ' selected="selected"';
					break;
				case 'Y-m-d':
					$guide['timeformatlimit2'] = ' selected="selected"';
					break;
				case 'm-d':
					$guide['timeformatlimit3'] = ' selected="selected"';
					break;
				case '-1':
					$guide['timeformatlimit4'] = ' selected="selected"';
					break;
			}
			$TPL->assign('guide', $guide);
		}
	}
	elseif ($job == 'del')
	{
		$tplid = (int)$tplid;
		$rs = $DB->db_fetch_one_array("SELECT * FROM {$db_prefix}templates WHERE tplid = $tplid");
		if (!$rs)
		{
			showMsg($a_message['parameter_error'], $actionurl);
		}
		if ($rs['ifself'])
		{
			$DB->db_query("SELECT tplid, tplmark FROM {$db_prefix}templates WHERE ifself =1 AND tplmark LIKE '".substr($rs['tplmark'], 0, strrpos($rs['tplmark'], '_'))."%'");
			while ($rs = $DB->db_fetch_array())
			{
				PDel(PBDIGG_ROOT.'data/cache/cache_'.$rs['tplmark'].'.php');
				$tplid .= ','.$rs['tplid'];
			}
			$DB->db_query("DELETE FROM {$db_prefix}templates WHERE ifself =1 AND tplid IN ($tplid)");
		}
		else
		{
			PDel(PBDIGG_ROOT.'data/cache/cache_'.$rs['tplmark'].'.php');
			$DB->db_query("DELETE FROM {$db_prefix}templates WHERE tplid = $tplid LIMIT 1");
		}
		$Cache->mktrantpl();
		$Cache->mktran();
		redirect($a_message['tpl_del_success'], $actionurl);
	}
	else
	{
		$tpllist = $selflist = array();
		$DB->db_query("SELECT * FROM {$db_prefix}templates");
		while ($rs = $DB->db_fetch_array())
		{
			if ($rs['ifself'])
			{
				$selfmark = substr($rs['tplmark'], 0, strrpos($rs['tplmark'], '_'));
				if (!in_array($selfmark, $selflist))
				{
					$selflist[] = $rs['tplmark'] = $selfmark;
				}
				else
				{
					continue;
				}
			}
			switch ($rs['trantype'])
			{
				case 't':
					$rs['tpltype'] = $a_message['tpl_thread'];
					break;
				case 'c':
					$rs['tpltype'] = $a_message['tpl_comment'];
					break;
				case 'm':
					$rs['tpltype'] = $a_message['tpl_member'];
					break;
			}
			$tpllist[] = $rs;
		}
		$TPL->assign('tpllist', $tpllist);
	}
}
else
{
	redirect($a_message['unknow_operate'], 'admincp.php?action=main');
}

$TPL->assign('menu', $m_tpl);

?>
