<?php

/*
+--------------------------------------------------------------------------
|   Invision Power Board v1.1
|   ========================================
|   by Matthew Mecham
|   (c) 2001,2002 Invision Power Services
|   http://www.ibforums.com
|   ========================================
|   Web: http://www.ibforums.com
|   Email: phpboards@ibforums.com
|   Licence Info: phpib-licence@ibforums.com
+---------------------------------------------------------------------------
|
|   > Skin -> Templates functions
|   > Module written by Matt Mecham
|   > Date started: 15th April 2002
|
|	> Module Version Number: 1.0.0
+--------------------------------------------------------------------------
*/




$idx = new ad_settings();


class ad_settings {

	var $base_url;

	function ad_settings() {
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		//---------------------------------------
		// Kill globals - globals bad, Homer good.
		//---------------------------------------
		
		$tmp_in = array_merge( $_GET, $_POST, $_COOKIE );
		
		foreach ( $tmp_in as $k => $v )
		{
			unset($$k);
		}

		switch($IN['code'])
		{
			case 'add':
				$this->add_splash();
				break;
				
			case 'edit':
				$this->show_cats();
				break;
				
			case 'dedit':
				$this->do_form();
				break;
				
			case 'doedit':
				$this->do_edit();
				break;
				
			case 'remove':
				$this->remove();
				break;
				
			case 'tools':
				$this->tools();
				break;
				
			case 'editinfo':
				$this->edit_info();
				break;
				
			case 'export':
				$this->export();
				break;
			
			case 'edit_bit':
				$this->edit_bit();
				break;
				
			case 'download':
				$this->download_group();
				break;
				
			case 'upload':
				$this->upload_form();
				break;
				
			case 'do_upload':
				$this->upload_single();
				break;
				
			
			//-------------------------
			default:
				$this->list_current();
				break;
		}
		
	}
	
	//------------------------------------------------------
	
	function add_splash()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_FILES;
		
		$FILE_NAME = $HTTP_POST_FILES['FILE_UPLOAD']['name'];
		$FILE_SIZE = $HTTP_POST_FILES['FILE_UPLOAD']['size'];
		$FILE_TYPE = $HTTP_POST_FILES['FILE_UPLOAD']['type'];
		
		// Naughty Opera adds the filename on the end of the
		// mime type - we don't want this.
		
		$FILE_TYPE = preg_replace( "/^(.+?);.*$/", "\\1", $FILE_TYPE );
		
		// Naughty Mozilla likes to use "none" to indicate an empty upload field.
		// I love universal languages that aren't universal.
		
		if ($HTTP_POST_FILES['FILE_UPLOAD']['name'] == "" or !$HTTP_POST_FILES['FILE_UPLOAD']['name'] or ($HTTP_POST_FILES['FILE_UPLOAD']['name'] == "none") )
		{
			// We're adding new templates based on another set
			
			$this->add_templates();
			exit();
		}
		
		if (! is_dir($INFO['upload_dir']) )
		{
			$ADMIN->error("无法找到文件上传目录 - 请确认目录 'uploads' 是否存在或设置正确？");
		}
		
		//-------------------------------------------------
		// Copy the upload to the uploads directory
		//-------------------------------------------------
		
		if (! @move_uploaded_file( $HTTP_POST_FILES['FILE_UPLOAD']['tmp_name'], $INFO['upload_dir']."/".$FILE_NAME) )
		{
			$ADMIN->error("文件上传失败");
		}
		else
		{
			@chmod( $INFO['upload_dir']."/".$FILE_NAME, 0777 );
		}
		
		//-------------------------------------------------
		// Attempt to open the file..
		//-------------------------------------------------
		
		$filename = $INFO['upload_dir']."/".$FILE_NAME;
		
		if ( $FH = @fopen( $filename, 'r' ) )
		{
			$data = @fread( $FH, filesize($filename) );
			@fclose($FH);
			
			@unlink($filename);
		}
		else
		{
			$ADMIN->error("无法打开和读取上传目录里的文件！");
		}
		
		//-------------------------------------------------
		// If we're here, we'll assume that we've read the
		// file and the contents are in $data
		// So, lets make sure its the correct template file..
		//-------------------------------------------------
		
		if ( ! preg_match( "/<!--TEMPLATE_SET\|(.+?)-->/", $data, $matches ) )
		{
			$ADMIN->error("此文件不是合法的论坛论坛模板文件");
		}
		
		list($pack_name,$author,$email,$url) = explode( ",", trim($matches[1]) );
		
		//-------------------------------------------------
		// Find the new set ID by inserting the data for the
		// template names, we can always remove it later if
		// we get an error
		//-------------------------------------------------
		
		$pack_name .= "(Upload ID: ".substr( time(), -6 ).")";
		$pack_name = str_replace( "'", "", $pack_name );
		$author    = str_replace( "'", "", $author );
		$email     = str_replace( "'", "", $email );
		$url       = str_replace( "'", "", $url );
		
		$DB->query("INSERT INTO ibf_tmpl_names (skname, author, email, url) VALUES('$pack_name', '$author', '$email', '$url')");
		$setid = $DB->get_insert_id();
		
		//-------------------------------------------------
		// Divide the file up into different sections
		//-------------------------------------------------
		
		preg_match_all( "/<!--IBF_GROUP_START:(\S+?)-->(.+?)<!--IBF_GROUP_END:\S+?-->/s", $data, $match );
		
		for ($i=0; $i < count($match[0]); $i++)
		{
			$match[1][$i] = trim($match[1][$i]);
			
			$match[2][$i] = trim($match[2][$i]);
			
			// Pass it on to our handler..
		
			$this->process_upload($match[2][$i], $setid, $match[1][$i], 1 );
			
			
		}
		
		// Insert this new data into the template names thingy
	
		$ADMIN->done_screen("论坛模板文件导入完成", "论坛模板管理", "act=templ" );
		
	}
	
	//------------------------------------------------------
	
	function upload_single()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_FILES;
		
		$FILE_NAME = $HTTP_POST_FILES['FILE_UPLOAD']['name'];
		$FILE_SIZE = $HTTP_POST_FILES['FILE_UPLOAD']['size'];
		$FILE_TYPE = $HTTP_POST_FILES['FILE_UPLOAD']['type'];
		
		// Naughty Opera adds the filename on the end of the
		// mime type - we don't want this.
		
		$FILE_TYPE = preg_replace( "/^(.+?);.*$/", "\\1", $FILE_TYPE );
		
		if (! is_dir($INFO['upload_dir']) )
		{
			$ADMIN->error("无法找到文件上传目录 - 请确认目录 'uploads' 是否存在或设置正确？");
		}
							
		// Naughty Mozilla likes to use "none" to indicate an empty upload field.
		// I love universal languages that aren't universal.
		
		if ($HTTP_POST_FILES['FILE_UPLOAD']['name'] == "" or !$HTTP_POST_FILES['FILE_UPLOAD']['name'] or ($HTTP_POST_FILES['FILE_UPLOAD']['name'] == "none") )
		{
			$ADMIN->error("没有选择需要上传的文件！");
		}
		
		//-------------------------------------------------
		// Copy the upload to the uploads directory
		//-------------------------------------------------
		
		if (! @move_uploaded_file( $HTTP_POST_FILES['FILE_UPLOAD']['tmp_name'], $INFO['upload_dir']."/".$FILE_NAME) )
		{
			$ADMIN->error("文件上传失败");
		}
		else
		{
			@chmod( $INFO['upload_dir']."/".$FILE_NAME, 0777 );
		}
		
		//-------------------------------------------------
		// Attempt to open the file..
		//-------------------------------------------------
		
		$filename = $INFO['upload_dir']."/".$FILE_NAME;
		
		if ( $FH = @fopen( $filename, 'r' ) )
		{
			$data = @fread( $FH, filesize($filename) );
			@fclose($FH);
			
			@unlink($filename);
		}
		else
		{
			$ADMIN->error("无法打开和读取上传目录里的文件！");
		}
		
		//-------------------------------------------------
		// If we're here, we'll assume that we've read the
		// file and the contents are in $data
		// So, lets make sure its the correct template file..
		//-------------------------------------------------
		
		preg_match( "/<!--IBF_GROUP_START:(\S+?)-->/", $data, $matches );
		
		$found_group = trim($matches[1]);
		
		if ($found_group != $IN['group'])
		{
			$ADMIN->error("上传的文件不是合法的的论坛模板文件类型。请在论坛模板文件 '{$IN['group']}', 查找 '$found_group'");
		}
		
		//-------------------------------------------------
		// If we're here, then lets proceed, first lets
		// remove the END GROUP statement.
		//-------------------------------------------------
		
		$data = preg_replace( "/<!--IBF_GROUP_END:\S+-->/", "", $data );
		
		// Pass it on to our handler..
		
		$this->process_upload($data, $IN['setid'], $IN['group'] );
		
		$ADMIN->done_screen("论坛模板文件更新完成", "论坛模板管理", "act=templ" );
		
	}
	
	//------------------------------------------------------
	
	function upload_form()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		require './sources/Admin/skin_info.php';
		
		if ($IN['setid'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		if ($IN['group'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//-----------------------------------
		// Get the info from the DB
		//-----------------------------------
		
		$DB->query("SELECT * FROM ibf_skin_templates WHERE set_id='".$IN['setid']."' AND group_name='".$IN['group']."'");
		
		if ( ! $DB->get_num_rows() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		$DB->query("SELECT skname FROM ibf_tmpl_names WHERE skid='".$IN['setid']."'");
		
		$row = $DB->fetch_row();
		
		//+-------------------------------
	
		$ADMIN->page_detail = "请在提交前仔细审核所有信息";
		$ADMIN->page_title  = "上传论坛主题模板文件：{$row['skname']}";
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'do_upload' ),
												  2 => array( 'act'   , 'templ'     ),
												  3 => array( 'MAX_FILE_SIZE', '10000000000' ),
												  4 => array( 'setid' , $IN['setid']  ),
												  5 => array( 'group' , $IN['group']  ),
									     ) , "uploadform", " enctype='multipart/form-data'"     );
									     
		$SKIN->td_header[] = array( "&nbsp;"   , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"   , "60%" );

		$ADMIN->html .= $SKIN->start_table("上传替换论坛主题模板文件：".$skin_names[ $IN['group'] ][0]);
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>请在你的电脑里选择需要上传的文件</b><br>注意：上传的文件将替换所有当数据！",
												  $SKIN->form_upload(),
										 )      );
									     
		$ADMIN->html .= $SKIN->end_form('上传文件');
										 
		$ADMIN->html .= $SKIN->end_table();
		
		$ADMIN->nav[] = array( 'act=templ' ,'论坛模板管理首页' );
		$ADMIN->nav[] = array( "act=templ&code=edit&id={$IN['setid']}" ,$row['skname'] );
		
		$ADMIN->output();						
		
	}
	
	//------------------------------------------------------
	
	function export()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		$DB->query("SELECT * FROM ibf_tmpl_names WHERE skid='".$IN['id']."'");
			
		if ( ! $set = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的论坛模板文件ID，请检查后重试！");
		}
			
		//-----------------------------------
		// Get the info from the DB
		//-----------------------------------
		
		$groups = $DB->query("SELECT DISTINCT(group_name) FROM ibf_skin_templates WHERE set_id='".$IN['id']."'");
		
		if ( ! $DB->get_num_rows($groups) )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		// Loop and pass it to the download compiler
		
		$author = str_replace( ",", "-", $set['author'] );
		$email  = str_replace( ",", "-", $set['email'] );
		$url    = str_replace( ",", "-", $set['url'] );
		$skname = str_replace( ",", "-", $set['skname'] );
		
		$output .= "<!--TEMPLATE_SET|$skname,$author,$email,$url-->\n\n";
		
		while ( $row = $DB->fetch_row($groups) )
		{
			$output .= $this->download_group(1, $IN['id'], $row['group_name'] );
		}
		
		$name = str_replace( " ", "_", $set['skname'] );
		
		@header("Content-type: unknown/unknown");
		@header("Content-Disposition: attachment; filename={$name}.SET.html");
		
		print $output;
		
		exit();
		
	}
	
	//------------------------------------------------------
	
	//------------------------------------------------------
	
	function download_group($return=0, $setid="", $group="")
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		if ($setid != "")
		{
			$IN['setid'] = $setid;
		}
		
		if ($group != "")
		{
			$IN['group'] = $group;
		}
		
		if ($IN['setid'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		if ($IN['group'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//-----------------------------------
		// Get the info from the DB
		//-----------------------------------
		
		$aq = $DB->query("SELECT * FROM ibf_skin_templates WHERE set_id='".$IN['setid']."' AND group_name='".$IN['group']."'");
		
		if ( ! $DB->get_num_rows($aq) )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		$output = "<!-- PLEASE LEAVE ALL 'IBF' COMMENTS IN PLACE, DO NOT REMOVE THEM! -->\n<!--IBF_GROUP_START:{$IN['group']}-->\n\n";
		
		while ( $row = $DB->fetch_row($aq) )
		{
			$text = $this->convert_tags($row['section_content']);
			
			$output .= "<!--IBF_START_FUNC|{$row['func_name']}|{$row['func_data']}-->\n\n";
			$output .= $text."\n";
			$output .= "<!--IBF_END_FUNC|{$row['func_name']}-->\n\n";
		}
		
		$output .= "\n<!--IBF_GROUP_END:{$IN['group']}-->\n";
		
		if ($return == 0)
		{
			$DB->query("SELECT skname FROM ibf_tmpl_names WHERE skid='".$IN['setid']."'");
			
			$set = $DB->fetch_row();
			
			$name = str_replace( " ", "_", $set['skname'] );
			
			@header("Content-type: unknown/unknown");
			@header("Content-Disposition: attachment; filename={$name}.{$IN['group']}.html");
			
			print $output;
			
			exit();
		}
		else
		{
			return $output;
		}
		
	}
	
	//------------------------------------------------------
	
	function show_cats()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//+-------------------------------
		
		$DB->query("SELECT * from ibf_tmpl_names WHERE skid='".$IN['id']."'");
		
		if ( ! $row = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		// Get $skin_names stuff
		
		require './sources/Admin/skin_info.php';
		
		
		if ($row['author'] and $row['email'])
		{
			$author = "<br><br>论坛模板文件：<b>'{$row['skname']}'</b> 的作者是：<a href='mailto:{$row['email']}' target='_blank'>{$row['author']}</a>";
		}
		else if ($row['author'])
		{
			$author = "<br><br>论坛模板文件：<b>'{$row['skname']}'</b> 的作者是：{$row['author']}";
		}
		
		if ($row['url'])
		{
			$url = " (网站：<a href='{$row['url']}' target='_blank'>{$row['url']}</a>)";
		}
		
		//+-------------------------------
	
		$ADMIN->page_detail = "请在下面选择你需要编辑的选项。<br><br><b>下载</b> - 允许你下载所有文件的 HTML 文件格式到你的本地电脑进行编辑。<br><b>上传</b> - 允许你上传所有文件的 HTML 文件格式覆盖论坛模板文件。$author $url";
		$ADMIN->page_title  = "编辑论坛模板文件";
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->js_checkdelete();
		
		$all_cats = $DB->query("select group_name, set_id, suid, count(group_name) as number_secs, group_name FROM ibf_skin_templates WHERE set_id='".$IN['id']."' group by group_name");
		
		$SKIN->td_header[] = array( "主题界面分类名称"   , "40%" );
		$SKIN->td_header[] = array( "查看选项"          , "20%" );
		$SKIN->td_header[] = array( "管理选项"                , "30%" );
		$SKIN->td_header[] = array( "# 数据"                , "10%" );

		//+-------------------------------
		
		$ADMIN->html .= "<script language='javascript'>
						 function pop_win(theUrl) {
						 	
						 	window.open('{$SKIN->base_url}&'+theUrl,'Preview','width=400,height=450,resizable=yes,scrollbars=yes');
						 }
						 </script>";
		
		$ADMIN->html .= $SKIN->start_table("论坛模板文件：".$row['skname']);
			
		while ( $group = $DB->fetch_row($all_cats) )
		{
		
			$name = "<b>".$group['group_name']."</b>";
			$desc = "";
			
			$expand = '展开编辑';
			$eid    = $group['suid'];
			$exp_content = "";
			
			// If available, change group name to easy name
			
			if ( isset($skin_names[ $group['group_name'] ]) )
			{
				$name = "<b>".$skin_names[ $group['group_name'] ][0]."</b>";
				$desc = "<br><span id='description'>".$skin_names[ $group['group_name'] ][1]."</span>";
			}
			else
			{
				$name .= " (非默认论坛模板文件)";
				$desc = "<br>这个文件不是默认的论坛标准安装模板文件，并且没有任何相关叙述内容。";
			}
			
			// Is this section expanded?
			
			if ($IN['expand'] == $group['suid'])
			{
				$expand = 'Collapse';
				$eid    = '';
				
				$new_q = $DB->query("SELECT func_name, LENGTH(section_content) as sec_length, suid FROM ibf_skin_templates WHERE set_id='{$IN['id']}' AND group_name='{$group['group_name']}'");
				
				//----------------------------
				
				if ( $DB->get_num_rows($new_q) )
				{
					$exp_content .= $SKIN->add_td_basic( "<a name='anc{$group['suid']}'>
														  <table cellspacing='1' cellpadding='5' width='100%' align='center' bgcolor='#333333'>
														  <tr>
														   <td align='left' id='catrow2'><a style='font-weight:bold;font-size:12px;color:#000033' href='{$SKIN->base_url}&act=templ&code=edit&id={$IN['id']}&expand=' title='全部展开' alt='全部展开'>$name</a></td>
														   <td colspan='3' bgcolor='#FFFFFF'>&nbsp;</td>
														  <tr>
														   <td width='30%' id='catrow2'></td>
														   <td width='20%' id='catrow2' align='center'># Characters</td>
														   <td width='20%' id='catrow2'align='center'>编辑</td>
														   <td width='30%' id='catrow2'align='center'>预览选项</td>
														  </tr>
														  <!--CONTENT--></table>", "left", "tdrow2" );
				
				
					$temp = "";
					$sec_arry = array();
					
					// Stuff array to sort on name
					
					while ( $i = $DB->fetch_row($new_q) )
					{
						$sec_arry[ $i['suid'] ] = $i;
						$sec_arry[ $i['suid'] ]['easy_name'] = $i['func_name'];
						
						// If easy name is available, use it
						
						if ($bit_names[ $group['group_name'] ][ $i['func_name'] ] != "")
						{
							$sec_arry[ $i['suid'] ]['easy_name'] = $bit_names[ $group['group_name'] ][ $i['func_name'] ];
						}
						
					}
					
					// Sort by easy_name
					
					usort($sec_arry, array( 'ad_settings', 'perly_word_sort' ) );
					
					// Loop and print
					
					foreach( $sec_arry as $id => $sec )
					{
						$sec['easy_name'] = preg_replace( "/^(\d+)\:\s+?/", "", $sec['easy_name'] );
						
						$temp .= "
									<tr>
									 <td width='40%' id='tdrow1'><b>{$sec['easy_name']}</b></td>
									 <td width='10%' id='tdrow1' align='center'>{$sec['sec_length']}</td>
									 <td width='10%' id='tdrow1' align='center'><a href='{$SKIN->base_url}&act=templ&code=edit_bit&suid={$sec['suid']}&expand={$group['suid']}'>编辑</a></td>
									 <td width='40%' id='tdrow1' align='center' nowrap>(<a href='javascript:pop_win(\"act=rtempl&code=preview&suid={$sec['suid']}&type=html\")'>HTML</a> | <a href='javascript:pop_win(\"act=rtempl&code=preview&suid={$sec['suid']}&type=text\")'>文本</a> | <a href='javascript:pop_win(\"act=rtempl&code=preview&suid={$sec['suid']}&type=css\")'>CSS模式</a>)</td>
									</tr>
								";
					}
					
					$exp_content = str_replace( "<!--CONTENT-->", $temp, $exp_content );
					
					$desc = "";
				
				}
				
				//----------------------------
				
			}
			else
			{
			
				$ADMIN->html .= $SKIN->add_td_row( array( 
															"<span style='font-weight:bold;font-size:12px;color:#000033'><a href='{$SKIN->base_url}&act=templ&code=edit&id={$IN['id']}&expand=$eid&#anc$eid'>".$name."</a></span>".$desc,
															"<center><a href='{$SKIN->base_url}&act=templ&code=edit&id={$IN['id']}&expand=$eid'>$expand</a></center>",
															"<center><a href='{$SKIN->base_url}&act=templ&code=download&setid={$group['set_id']}&group={$group['group_name']}' title='下载 HTML 文件至本地编辑'>下载</a> | <a href='{$SKIN->base_url}&act=templ&code=upload&setid={$group['set_id']}&group={$group['group_name']}' title='上传 HTML 文件后进行覆盖'>上传</a></center>",
															"<center>".$group['number_secs']."</center>",
												 )      );
			}
											 
			$ADMIN->html .= $exp_content;
											 
		}
		
		$ADMIN->html .= $SKIN->end_table();
									     
		//+-------------------------------
		//+-------------------------------
		
		$ADMIN->nav[] = array( 'act=templ' ,'论坛模板管理首页' );
		$ADMIN->nav[] = array( '' ,'管理论坛模板文件："'.$row['skname'].'"' );
		
		$ADMIN->output();
		
		
	}
	
	// Sneaky sorting.
	// We use the format "1: name". without this hack
	// 1: name, 2: other name, 11: other name
	// will sort as 1: name, 11: other name, 2: other name
	// There is natsort and such in PHP, but it causes some
	// problems on older PHP installs, this is hackish but works
	// by simply adding '0' to a number less than 2 characters long.
	// of course, this won't work with three numerics in the hundreds
	// but we don't have to worry about more that 99 bits in a template
	// at this stage.
	
	function perly_word_sort($a, $b)
	{
		$nat_a = intval( $a['easy_name'] );
		$nat_b = intval( $b['easy_name'] );
		
		if (strlen($nat_a) < 2)
		{
			$nat_a = '0'.$nat_a;
		}
		if (strlen($nat_b) < 2)
		{
			$nat_b = '0'.$nat_b;
		}
		
		return strcmp($nat_a, $nat_b);
	}
	
	
	//+--------------------------------------------------------------------------------
	//+--------------------------------------------------------------------------------
	
	
	function edit_info()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//+-------------------------------
		
		$DB->query("SELECT * from ibf_tmpl_names WHERE skid='".$IN['id']."'");
		
		if ( ! $row = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		$final['skname'] = stripslashes($HTTP_POST_VARS['skname']);
		
		if (isset($HTTP_POST_VARS['author']))
		{
			$final['author'] = str_replace( ",", "", stripslashes($HTTP_POST_VARS['author']) );
			$final['email']  = str_replace( ",", "", stripslashes($HTTP_POST_VARS['email']) );
			$final['url']    = str_replace( ",", "", stripslashes($HTTP_POST_VARS['url']) );
		}
		
		$db_string = $DB->compile_db_update_string( $final );
		
		$DB->query("UPDATE ibf_tmpl_names SET $db_string WHERE skid='".$IN['id']."'");
		
		$ADMIN->done_screen("论坛模板文件已经更新", "论坛模板管理", "act=templ" );
		
	}
	
	//+-------------------------------
	//+-------------------------------
	
	function do_edit()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		$text = stripslashes($HTTP_POST_VARS['template']);
		
		if ($IN['suid'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//+-------------------------------
		// Get the group name, etc
		//+-------------------------------
		
		$DB->query("SELECT * FROM ibf_skin_templates WHERE suid='".$IN['suid']."'");
		
		if ( ! $template = $DB->fetch_row() )
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		$real_name = $template['group_name'];
		
		//+-------------------------------
		// Get the template set info
		//+-------------------------------
		
		$DB->query("SELECT * from ibf_tmpl_names WHERE skid='".$template['set_id']."'");
		
		if ( ! $row = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		//+-------------------------------
		
		$phpskin  = ROOT_PATH."Skin/s".$template['set_id']."/".$real_name.".php";
		
		//+-------------------------------
		
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
		
		   if ( ! is_writeable($phpskin) )
		   {
			   $ADMIN->error("无法写入目录 '$phpskin'，请检查目录属性（CHMOD 777）。");
		   }
		
		}
		
		//+-------------------------------
		// Ok, make sure we actually have
		// some info to parse here.
		//+-------------------------------
		
		if ($text == "")
		{
			$ADMIN->error("你不能删除这个论坛模板文件");
		}
		
		//+-------------------------------
		// Swop back < and >
		//+-------------------------------
		
		$text = preg_replace("/&#60;/", "<", $text);
		$text = preg_replace("/&#62;/", ">", $text);
		$text = preg_replace("/&#38;/", "&", $text);
		
		$text = str_replace( '\\n' , '\\\\\\n', $text );
		
		//+-------------------------------
		// Convert \r to nowt
		//+-------------------------------
		
		$text = preg_replace("/\r/", "", $text);
		
		$text = $this->unconvert_tags($text);
		
		//+-------------------------------
		//Update the DB
		//+-------------------------------
		
		$string = $DB->compile_db_update_string( array ( 'section_content' => $text ) );
		
		$DB->query("UPDATE ibf_skin_templates SET $string WHERE suid='".$IN['suid']."'");
		
		
		//+-------------------------------
		// Start parsing the php skin file
		//+-------------------------------
		
		$final = "<"."?php\n\n".
				 "class $real_name {\n\n";
				 
		//+------------------------------------------
		// Get all the data from the DB that matches
		// the group name (filename) and set_id
		//+------------------------------------------
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
		
			$DB->query("SELECT * FROM ibf_skin_templates WHERE group_name='$real_name' AND set_id='{$template['set_id']}'"); 
			
			while ( $data = $DB->fetch_row() )
			{
			
				$final .= "\n\nfunction {$data['func_name']}({$data['func_data']}) {\n".
					      "global \$ibforums;\n".
					      "return <<<EOF\n";
					   
				$final .= $data['section_content'];
					   
				$final .= "\nEOF;\n}\n";
			
			}
			
			$final .= "\n\n}\n?".">";
			
			if ($fh = fopen( "$phpskin", 'w' ) )
			{
				fwrite($fh, $final, strlen($final) );
				fclose($fh);
			}
			else
			{
				$ADMIN->error("无法保存信息到 $phpskin ，请检查权限是否正确（CHMOD 777）。");
			}
		
		}
		
		$ADMIN->done_screen("模板文件已经更新", "管理论坛模板文件：{$row['skname']}", "act=templ&code=edit&id={$template['set_id']}" );
		
	}
	
	//------------------------------------------------------------------------------------
	//------------------------------------------------------------------------------------
	
	function tools()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须选择一个合法的主题界面文件以执行这个操作");
		}
		
		if ($IN['tool'] == 'tmpl')
		{
			$this->tools_build_tmpl();
		}
		else
		{
			$this->tools_rebuildphp();
		}
		
	}
	
	//------------------------------------------------------------------------------------
	
	function tools_build_tmpl()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		$insert = 1;
		
		// Rebuilds the data editable files from the PHP source files
		
		$skin_dir     = ROOT_PATH."Skin/s".$IN['id'];
		
		/*$curr_groups = array();
		
		// Are we updating or inserting?
		
		$DB->query("SELECT group_name, func_name FROM ibf_skin_templates WHERE set_id='".$IN['id']."'");
		
		if ( $DB->get_num_rows() )
		{
			$insert = 0;
		
			while ( $gname = $DB->fetch_row() )
			{
				$curr_group[ $gname['group_name'] ][ $gname['func_name'] ] = 1;
			}
		}*/
		
		$errors = array();
		
		$flag = 0;
		
		//------------------------------------------------
		// Is this a safe mode only skinny poos?
		//------------------------------------------------
		
		if ( ! file_exists( $skin_dir ) )
		{
			$ADMIN->error("这个模板文件必须在安全模式下使用，不需要为模板文件运行此工具。");
		}
		
		
		if ( ! is_readable($skin_dir) )
		{
			$ADMIN->error("无法写入文件到： '$skin_dir' ，请检查目录属性（CHMOD 777）.");
		}
		
		if ( is_dir($skin_dir) )
		{
			if ( $handle = opendir($skin_dir) )
			{
			
				while (($filename = readdir($handle)) !== false)
				{
					if (($filename != ".") && ($filename != ".."))
					{
					
						if ( preg_match( "/\.php$/", $filename ) )
						{
							
							$name = preg_replace( "/^(\S+)\.(\S+)$/", "\\1", $filename );
							
							if ($FH = fopen($skin_dir."/".$filename, 'r') )
							{
								$fdata = fread( $FH, filesize($skin_dir."/".$filename) );
								fclose($FH);
							}
							else
							{
								$errors[] = "无法打开和读取 $filename ，跳过文件 ...";
								continue;
							}
							
							$fdata = str_replace( "\r", "\n", $fdata );
							$fdata = str_replace( "\n\n", "\n", $fdata );
							
							if ( ! preg_match( "/\n/", $fdata ) )
							{
								$errors[] = "无法找到任何行结束标签 $filename ，跳过文件 ...";
								continue;
							}
							
							$farray = explode( "\n", $fdata );
							
							//----------------------------------------------------
							
							$functions = array();
							
							foreach($farray as $f)
							{
								
								// Skip javascript functions...
								
								if ( preg_match( "/<script/i", $f ) )
								{
									$script_token = 1;
								}
								
								if ( preg_match( "/<\/script>/i", $f ) )
								{
									$script_token = 0;
								}
								
								//-------------------------------
								
								if ($script_token == 0)
								{
									if ( preg_match( "/^function\s*([\w\_]+)\s*\((.*)\)/i", $f, $matches ) )
									{
										$functions[$matches[1]] = '';
										$config[$matches[1]]    = $matches[2];
										$flag = $matches[1];
										continue;
									}
								}
									
								if ($flag)
								{
									$functions[$flag] .= $f."\n";
									continue;
								}
								 
							}
							
							//----------------------------------------------------
							// Remove current templates for this set...
							//----------------------------------------------------
							
							$DB->query("DELETE FROM ibf_skin_templates WHERE set_id='".$IN['id']."' AND group_name='$name'");
							
							$final = "";
							$flag  = 0;
							
							foreach($functions as $fname => $ftext)
							{
								preg_match( "/return <<<(EOF|HTML)(.+?)(EOF|HTML);/s", $ftext, $matches );
								
								$matches[2] = str_replace( '\\n' , '\\\\\\n', $matches[2] );
								
								
								$db_update = $DB->compile_db_update_string( array (
																				'set_id'          => $IN['id'],
																				'group_name'      => $name,
																				'section_content' => $matches[2],
																				'func_name'       => $fname,
																				'func_data'       => trim($config[$fname]),
																				'updated'         => time(),
																	  )       );
																	  
						
								$DB->query("INSERT INTO ibf_skin_templates SET $db_update");
							}
							
							$functions = array();
							
							//----------------------------------------------------
							
						} // if *.php
						
					} // if not dir
					
				} // while loop
				
				closedir($handle);
				
			}
			else
			{
				$ADMIN->error("无法打开和读取目录 $skin_dir");
			}
		}
		else
		{
			$ADMIN->error("$skin_dir 不是一个目录，请检查 admin.php 文件中 \$root_path 变量设置");
		}
		
		$ADMIN->done_screen("从主题界面文件中编辑模板文件完成", "论坛模板管理", "act=templ" );
		
		if (count($errors > 0))
		{
			$this->html .= $SKIN->start_table("错误和警告");
		
			$this->html .= $SKIN->add_td_basic( implode("<br>", $errors) );
											 
			$this->html .= $SKIN->end_table();
		}
		
		
	}
	
	
	//-------------------------------------------------------------
	// Add templates
	//-------------------------------------------------------------
	
	
	function add_templates()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//-------------------------------------
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
		
			if ( ! is_writeable(ROOT_PATH.'Skin') )
			{
				$ADMIN->error("无法写入目录 'Skin'，请检查目录属性（CHMOD 777）。");
			}
			
			//-------------------------------------
			
			if ( ! is_dir(ROOT_PATH.'Skin/s'.$IN['id']) )
			{
				$ADMIN->error("无法找到默认模板文件进行复制，请检查后重试。");
			}
		
		}
		
		//-------------------------------------
		
		$DB->query("SELECT * FROM ibf_tmpl_names WHERE skid='".$IN['id']."'");
		
		//-------------------------------------
		
		if ( ! $row = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		//-------------------------------------
		
		$row['skname'] = $row['skname'].".NEW";
		
		// Insert a new row into the DB...
		
		$final = array();
		
		foreach($row as $k => $v)
		{
			if ($k == 'skid')
			{
				continue;
			}
			else
			{
				$final[ $k ] = $v;
			}
		}
		
		$db_string = $DB->compile_db_insert_string( $final );
		
		$DB->query("INSERT INTO ibf_tmpl_names (".$db_string['FIELD_NAMES'].") VALUES(".$db_string['FIELD_VALUES'].")");
		
		$new_id = $DB->get_insert_id();
		
		//-------------------------------------
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
		
			//-------------------------------------
			
			if ( ! $ADMIN->copy_dir( $INFO['base_dir'].'Skin/s'.$IN['id'] , $INFO['base_dir'].'Skin/s'.$new_id ) )
			{
				$DB->query("DELETE FROM ibf_tmpl_names WHERE skid='$new_id'");
				
				$ADMIN->error( $ADMIN->errors );
			}
		
		}
		
		// Copy over the templates stored inthe database...
		
		$get = $DB->query("SELECT * FROM ibf_skin_templates WHERE set_id='".$IN['id']."'");
		
		while( $r = $DB->fetch_row($get) )
		{
			$r['section_content'] = str_replace( '\\n' , '\\\\\\n', $r['section_content'] );
			
			$row = $DB->compile_db_insert_string( array (
														'set_id'          =>  $new_id,
														'group_name'      =>  $r['group_name'],
														'section_content' =>  $r['section_content'],
														'func_name'       =>  $r['func_name'],
														'func_data'       =>  $r['func_data'],
														'updated'         => time(),
														'can_remove'      => $r['can_remove'],
											 )       );
											 
			$put = $DB->query("INSERT INTO ibf_skin_templates ({$row['FIELD_NAMES']}) VALUES({$row['FIELD_VALUES']})");
		}
		
		//-------------------------------------
		// All done, yay!
		//-------------------------------------
		
		$ADMIN->done_screen("添加论坛模板文件", "论坛模板管理", "act=templ" );
	
	}
	
	//-------------------------------------------------------------
	// REMOVE WRAPPERS
	//-------------------------------------------------------------
	
	function remove()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		//+-------------------------------
		
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
			
			if ( ! $ADMIN->rm_dir( $INFO['base_dir']."Skin/s".$IN['id'] ) )
			{
				$ADMIN->error("无法删除论坛模板文件，请检查目录属性（CHMOD 777）。");
			}
			
		}
		
		$DB->query("DELETE FROM ibf_tmpl_names WHERE skid='".$IN['id']."'");
		$DB->query("DELETE FROM ibf_skin_templates WHERE set_id='".$IN['id']."'");
		
		$std->boink_it($SKIN->base_url."&act=templ");
		exit();
		
		
	}
	
	//-------------------------------------------------------------
	// EDIT TEMPLATES, STEP TWO
	//-------------------------------------------------------------
	
	function edit_bit()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_COOKIE_VARS;
		
		//-----------------------------------
		// Check for valid input...
		//-----------------------------------
		
		if ($IN['suid'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		$DB->query("SELECT * FROM ibf_skin_templates WHERE suid='".$IN['suid']."'");
		
		//-----------------------------------
		
		if ( ! $template = $DB->fetch_row() )
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//-----------------------------------
		
		if ( $cookie = $HTTP_COOKIE_VARS['ad_tempform'] )
		{
			list($rows, $cols) = explode( '-', $cookie );
		}
		
		$cols = $cols ? $cols : 80;
		$rows = $rows ? $rows : 40;
		$wrap = 'soft';
		
		//+-------------------------------
		
		$DB->query("SELECT * from ibf_tmpl_names WHERE skid='".$template['set_id']."'");
		
		if ( ! $row = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		//+-------------------------------
		// Swop < and > into ascii entities
		// to prevent textarea breaking html
		//+-------------------------------
		
		$templ = $this->convert_tags($template['section_content']);
		
		$templ = preg_replace("/&/", "&#38;", $templ );
		$templ = preg_replace("/</", "&#60;", $templ );
		$templ = preg_replace("/>/", "&#62;", $templ );
		
		//+-------------------------------
	
		$ADMIN->page_detail = "你可以编辑这个模板文件的 HTML 标签。";
		$ADMIN->page_title  = "论坛模板文件编辑";
		
									     
		//+-------------------------------
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->js_template_tools();
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'doedit'    ),
												  2 => array( 'act'   , 'templ'     ),
												  3 => array( 'suid'  , $IN['suid'] ),
									     )  , "theform"    );
									     
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"   , "100%" );

		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "模板文件：".$template['func_name'] );
		
		$ADMIN->html .= $SKIN->add_td_basic( "<input type='button' value='模板变量搜索' id='editbutton' title='查看模板变量定义' onClick='pop_win(\"code=macro_one&suid={$template['suid']}\", \"模板变量\", 400, 200)'>".
											 "&nbsp;<input type='button' value='对照和比较' id='editbutton' title='与默认设置进行对照和比较' onClick='pop_win(\"act=rtempl&code=compare&suid={$template['suid']}\", \"对照和比较\", 500,400)'>".
											 "&nbsp;<input type='button' value='恢复默认设置' id='editbutton' title='Restore the original, unedited template bit' onClick='restore(\"{$template['suid']}\",\"{$IN['expand']}\")'>".
											 "&nbsp;<input type='button' value='查看默认设置' id='editbutton' title='以 HTML 方式查看' onClick='pop_win(\"act=rtempl&code=preview&suid={$template['suid']}&type=html\", \"查看默认设置\", 400,400)'>".
											 "&nbsp;<input type='button' value='搜索' id='editbutton' title='搜索模板中的变量' onClick='pop_win(\"act=rtempl&code=search&suid={$template['suid']}&type=html\", \"搜索\", 500,400)'>".
										     "&nbsp;<input type='button' value='编辑表框尺寸' id='editbutton' title='改变下面的表框尺寸' onClick='edit_box_size(\"$cols\", \"$rows\")'>",
											 "center", "catrow");
											 
		$ADMIN->html .= $SKIN->add_td_basic( "<b>显示 HTML 代码：&nbsp;".
											 "<select name='htmlcode' onChange=\"document.theform.res.value='&'+document.theform.htmlcode.options[document.theform.htmlcode.selectedIndex].value+';'\" id='multitext'><option value='copy'>&copy;</option>
											 <option value='raquo'>&raquo;</option>
											 <option value='laquo'>&laquo;</option>
											 <option value='#149'>&#149;</option>
											 <option value='reg'>&reg;</option>
											 </select>&nbsp;&nbsp;<input type='text' name='res' size=20 id='multitext'>&nbsp;&nbsp;<input type='button' value='select' id='editbutton' onClick='document.theform.res.focus();document.theform.res.select();'>"
			
											, "center", "tdrow1");
		
		$ADMIN->html .= $SKIN->add_td_row( array( 
													"<center>".$SKIN->form_textarea('template', $templ, $cols, $rows, $wrap)."</center>",
									     )      );
									     
		
									     
		$ADMIN->html .= $SKIN->end_form("更新文件");
									     
		$ADMIN->html .= $SKIN->end_table();
		
		$ADMIN->nav[] = array( 'act=templ' ,'论坛模板管理首页' );
		$ADMIN->nav[] = array( "act=templ&code=edit&id={$template['set_id']}" ,$row['skname'] );
		$ADMIN->nav[] = array( "act=templ&code=edit&id={$template['set_id']}&expand={$IN['expand']}", $template['group_name'] );
		$ADMIN->nav[] = array( "", $template['func_name'] );
		
		$ADMIN->output();
		
		
	}
	
	//-------------------------------------------------------------
	// EDIT TEMPLATES, STEP ONE
	//-------------------------------------------------------------
	
	function do_form()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("你必须指定一个存在的论坛模板文件ID，请返回后重试！");
		}
		
		//+-------------------------------
		
		$DB->query("SELECT * from ibf_tmpl_names WHERE skid='".$IN['id']."'");
		
		if ( ! $row = $DB->fetch_row() )
		{
			$ADMIN->error("无法在数据库中找到相关的数据信息");
		}
		
		
		$form_array = array();
	
		//+-------------------------------
	
		$ADMIN->page_detail = "请在下面选择需要编辑的选项。";
		$ADMIN->page_title  = "编辑论坛模板文件";
		
		//+-------------------------------
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->js_no_specialchars();
		
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'editinfo'    ),
												  2 => array( 'act'   , 'templ'       ),
												  3 => array( 'id'    , $IN['id']     ),
									     ), "theAdminForm", "onSubmit=\"return no_specialchars('templates')\""      );
									     
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"   , "60%" );
		$SKIN->td_header[] = array( "&nbsp;"   , "40%" );

		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "编辑论坛模板文件信息" );
		
									     
		$ADMIN->html .= $SKIN->add_td_row( array( 
													"<b>模板文件名称：</b>",
													$SKIN->form_input('skname', $row['skname']),
									     )      );
									     
		
									     
		$ADMIN->html .= $SKIN->add_td_row( array( 
													"<b>模板文件作者：</b>",
													$SKIN->form_input('author', $row['author']),
										 )      );
										 
		$ADMIN->html .= $SKIN->add_td_row( array( 
													"<b>模板文件作者信箱：</b>",
													$SKIN->form_input('email', $row['email']),
										 )      );
										 
		$ADMIN->html .= $SKIN->add_td_row( array( 
													"<b>模板文件作者网站：</b>",
													$SKIN->form_input('url', $row['url']),
										 )      );
									     
		
									     
		$ADMIN->html .= $SKIN->end_form("编辑模板文件信息");
									     
		$ADMIN->html .= $SKIN->end_table();
									     
		
		$ADMIN->nav[] = array( 'act=templ' ,'论坛模板管理首页' );
		
		$ADMIN->output();
		
		
	}
	
	//-------------------------------------------------------------
	// SHOW CURRENT TEMPLATE PACKS
	//-------------------------------------------------------------
	
	function list_current()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		$form_array = array();
	
		$ADMIN->page_detail = "论坛模板文件中所有的HTML代码都是在论坛中需要使用的<br>你可以在此建立新的模板文件或修改当前的模板文件。";
		$ADMIN->page_title  = "论坛模板管理";
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "模板文件名称"        , "35%" );
		$SKIN->td_header[] = array( "模板分配"   , "25%" );
		$SKIN->td_header[] = array( "编辑属性"    , "10%" );
		$SKIN->td_header[] = array( "管理HTML代码"  , "15%" );
		$SKIN->td_header[] = array( "删除"       , "15%" );
		
		//+-------------------------------
		
		$DB->query("SELECT DISTINCT(s.set_id), s.sname, t.skid, t.skname from ibf_tmpl_names t, ibf_skins s WHERE s.set_id=t.skid ORDER BY t.skname ASC");
		
		$used_ids = array();
		$show_array = array();
		
		if ( $DB->get_num_rows() )
		{
		
			$ADMIN->html .= $SKIN->start_table( "当前使用的论坛模板文件" );
			
			while ( $r = $DB->fetch_row() )
			{
			
				$show_array[ $r['skid'] ] .= stripslashes($r['sname'])."<br>";
			
				if ( in_array( $r['skid'], $used_ids ) )
				{
					continue;
				}
				
				$ADMIN->html .= $SKIN->add_td_row( array( "<b>".stripslashes($r['skname'])."</b><br>[ <a href='{$SKIN->base_url}&act=templ&code=export&id={$r['skid']}' title='下载这个论坛模板文件'>导出</a> ]",
														  "<#X-{$r['skid']}#>",
														  //"<center><a href='".$SKIN->base_url."&act=templ&code=export&id={$r['skid']}'>Download</a></center>",
														  "<center><a href='".$SKIN->base_url."&act=templ&code=dedit&id={$r['skid']}' title='编辑模板文件'>编辑属性</a></center>",
														  "<center><a href='".$SKIN->base_url."&act=templ&code=edit&id={$r['skid']}' title='编辑，上传和下载'>管理HTML代码</a></center>",
														  "删除前请重新匹配",
												 )      );
												   
				$used_ids[] = $r['skid'];
				
				$form_array[] = array( $r['skid'], $r['skname'] );
				
			}
			
			foreach( $show_array as $idx => $string )
			{
				$string = preg_replace( "/<br>$/", "", $string );
				
				$ADMIN->html = preg_replace( "/<#X-$idx#>/", "$string", $ADMIN->html );
			}
			
			$ADMIN->html .= $SKIN->end_table();
		}
		
		if ( count($used_ids) > 0 )
		{
		
			$DB->query("SELECT skid, skname FROM ibf_tmpl_names WHERE skid NOT IN(".implode(",",$used_ids).")");
		
			if ( $DB->get_num_rows() )
			{
			
				$SKIN->td_header[] = array( "模板文件名称"          , "55%" );
				$SKIN->td_header[] = array( "编辑属性"    , "10%" );
				$SKIN->td_header[] = array( "管理HTML代码"    , "20%" );
				$SKIN->td_header[] = array( "删除"         , "15%" );
			
				$ADMIN->html .= $SKIN->start_table( "当前可用的论坛模板文件" );
				
				$ADMIN->html .= $SKIN->js_checkdelete();
				
				while ( $r = $DB->fetch_row() )
				{
					
					$ADMIN->html .= $SKIN->add_td_row( array( "<b>".stripslashes($r['skname'])."</b>",
															  //"<center><a href='".$SKIN->base_url."&act=templ&code=export&id={$r['skid']}'>Download</a></center>",
															  "<center><a href='".$SKIN->base_url."&act=templ&code=dedit&id={$r['skid']}'>编辑属性</a></center>",
															  "<center><a href='".$SKIN->base_url."&act=templ&code=edit&id={$r['skid']}' title='编辑，上传，下载'>管理HTML代码</a></center>",
															  "<center><a href='javascript:checkdelete(\"act=templ&code=remove&id={$r['skid']}\")'>删除</a></center>",
													 )      );
													 
					$form_array[] = array( $r['skid'], $r['skname'] );
													   
				}
				
				$ADMIN->html .= $SKIN->end_table();
			}
		}
		
		//+-------------------------------
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'add'     ),
												  2 => array( 'act'   , 'templ'    ),
												  3 => array( 'MAX_FILE_SIZE', '10000000000' ),
									     ) , "uploadform", " enctype='multipart/form-data'"     );
												  
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		$ADMIN->html .= $SKIN->start_table( "添加新模板文件" );
			
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>新模板文件基于 ...</b>" ,
										  		  $SKIN->form_dropdown( "id", $form_array)
								 )      );
								 
		$ADMIN->html .= $SKIN->add_td_row( array( "<b><u>或者</u> 从你的电脑中选择执行导入的模板文件。</b><br>注意：模板文件必须有效。",
												  $SKIN->form_upload(),
										 )      );
		
		$ADMIN->html .= $SKIN->end_form("添加论坛模板文件");
										 
		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'tools'     ),
												  2 => array( 'act'   , 'templ'    ),
									     )      );
		
		$SKIN->td_header[] = array( "模板文件工具"  , "50%" );
		$SKIN->td_header[] = array( "运行模板文件"  , "50%" );
		
		$extra = "";
		
		if ( SAFE_MODE_ON == 1)
		{
			$extra = "<br><span id='detail'>警告：检查到论坛安全模式，某些工具可能不能工作。</span>";
		}
		
		$ADMIN->html .= $SKIN->start_table( "模板工具：".$extra );
			
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->add_td_row( array( $SKIN->form_dropdown( "tool",
																		array(
																				1 => array( 'tmpl', '在PHP主题界面中重新计算数据'   ),
																			 )
												                      ) ,
										  		  $SKIN->form_dropdown( "id", $form_array)
								 )      );
		
		$ADMIN->html .= $SKIN->end_form("运行工具");
										 
		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		//+-------------------------------
		
		$ADMIN->output();
	
	}
	
	function convert_tags($t="")
	{
		if ($t == "")
		{
			return "";
		}
		
		$t = preg_replace( "/{?\\\$ibforums->base_url}?/"            , "{ibf.script_url}"   , $t );
		$t = preg_replace( "/{?\\\$ibforums->session_id}?/"          , "{ibf.session_id}"   , $t );
		$t = preg_replace( "/{?\\\$ibforums->skin\['?(\w+)'?\]}?/"   , "{ibf.skin.\\1}"      , $t );
		$t = preg_replace( "/{?\\\$ibforums->lang\['?(\w+)'?\]}?/"   , "{ibf.lang.\\1}"      , $t );
		$t = preg_replace( "/{?\\\$ibforums->vars\['?(\w+)'?\]}?/"   , "{ibf.vars.\\1}"      , $t );
		$t = preg_replace( "/{?\\\$ibforums->member\['?(\w+)'?\]}?/" , "{ibf.member.\\1}"    , $t );
		
		// Make some tags safe..
		
		$t = preg_replace( "/\{ibf\.vars\.(sql_driver|sql_host|sql_database|sql_pass|sql_user|sql_port|sql_tbl_prefix|smtp_host|smtp_port|smtp_user|smtp_pass|html_dir|base_dir|upload_dir)\}/", "" , $t );
				
		return $t;
		
	}
	
	function unconvert_tags($t="")
	{
		if ($t == "")
		{
			return "";
		}
		
		// Make some tags safe..
		
		$t = preg_replace( "/\{ibf\.vars\.(sql_driver|sql_host|sql_database|sql_pass|sql_user|sql_port|sql_tbl_prefix|smtp_host|smtp_port|smtp_user|smtp_pass|html_dir|base_dir|upload_dir)\}/", "" , $t );
		
		$t = preg_replace( "/{ibf\.script_url}/i"   , '{$ibforums->base_url}'         , $t);
		$t = preg_replace( "/{ibf\.session_id}/i"   , '{$ibforums->session_id}'       , $t);
		$t = preg_replace( "/{ibf\.skin\.(\w+)}/"   , '{$ibforums->skin[\''."\\1".'\']}'   , $t);
		$t = preg_replace( "/{ibf\.lang\.(\w+)}/"   , '{$ibforums->lang[\''."\\1".'\']}'   , $t);
		$t = preg_replace( "/{ibf\.vars\.(\w+)}/"   , '{$ibforums->vars[\''."\\1".'\']}'   , $t);
		$t = preg_replace( "/{ibf\.member\.(\w+)}/" , '{$ibforums->member[\''."\\1".'\']}' , $t);
		
		return $t;
		
	}
	
	/*
	<!--IBF_START_FUNC|calendar_events|$events = ""-->
        <tr>
           <td id='category' colspan='2'>{ibf.lang.calender_f_title}</td>
    	</tr>
    	<tr>
          <td id='forum1' width='5%' valign='middle'>{ibf.skin.F_ACTIVE}</td>
          <td id='forum2' width='95%'>$events</td>
        </tr>
    <!--IBF_END_FUNC|calendar_events-->
*/
	
	
	
	function process_upload($raw, $setid, $group, $isnew=0)
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		$skin_dir     = ROOT_PATH."Skin/s".$setid;
		
		//-------------------------------------------
		// If we are not using safe mode skins, lets
		// test to make sure we can write to that dir
		//-------------------------------------------
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				if ($isnew == 1)
				{
					$DB->query("DELETE FROM ibf_tmpl_names WHERE skid='$setid'");
				}
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
			
			// Are we creating a new template set? 
			// if so, lets create the directory
			
			if ($isnew == 1)
			{
				if ( ! is_writeable(ROOT_PATH.'Skin') )
				{	
					$DB->query("DELETE FROM ibf_tmpl_names WHERE skid='$setid'");
					$ADMIN->error("无法写入目录 'Skin' ，请检查目录权限（CHMOD 777）。");
				}
				
				if ( ! file_exists($skin_dir) )
				{
					// Directory does not exist, lets create it
					
					if ( ! @mkdir($skin_dir, 0777) )
					{
						$DB->query("DELETE FROM ibf_tmpl_names WHERE skid='$setid'");
						$ADMIN->error("无法建立目录 '$skin_dir' ，请检查目录权限（CHMOD 777）。");
					}
					else
					{
						@chmod($skin_dir, 0777);
					}
				}
			}
			else
			{
				if ( ! is_writeable($skin_dir) )
				{
					$ADMIN->error("无法写入目录 '$skin_dir' ，请检查目录权限（CHMOD 777）。");
				}
			}
		
		}
		
		//--------------------------------
		// Remove everything up until the
		// first <!--START tag...
		//--------------------------------
		
		$raw = preg_replace( "/^.*?(<!--IBF_START_FUNC)/s", "\\1", trim($raw));
		
		$raw = str_replace( "\r\n", "\n", $raw);
		
		//+-------------------------------
		// Convert the tags back to php native
		//+-------------------------------
		
		$raw = $this->unconvert_tags($raw);
		
		//+-------------------------------
		// Grab our vars and stuff
		//+-------------------------------
		
		$DB->query("SELECT func_name, group_name FROM ibf_skin_templates WHERE set_id='$setid'");
		
		if ( $DB->get_num_rows() )
		{
			while ( $gname = $DB->fetch_row() )
			{
				$curr_group[ $gname['group_name'] ][ $gname['func_name'] ] = 1;
			}
		}
		
		$master = array();
		$flag   = 0;
		
		$eachline = explode( "\n", $raw );
		
		foreach ($eachline as $line)
		{
			if ($flag == 0)
			{
				// We're not gathering HTML, lets see if we have a new
				// function start..
				
				if ( preg_match( "/\s*<!--IBF_START_FUNC\|(\S+?)\|(.*?)-->\s*/", $line, $matches) )
				{
					$func = trim($matches[1]);
					$data = trim($matches[2]);
					
					if ($func != "")
					{
					
						$flag = $func;
						
						$master[$func] = array( 'func_name'  => $func,
												'func_data'  => $data,
												'content'    => ""
											  );
					}
					continue;
					
				}
				
			}
			
			if ( preg_match("/\s*?<!--IBF_END_FUNC\|$flag-->\s*?/", $line) )
			{
				 // We have found the end of the subbie..
				 // Reset the flag and feed the next line.
				 
				 $flag = 0;
				 continue;
			}
			else
			{
				// Carry on feeding the HTML...
				
				if ( isset($master[$flag]['content']) )
				{
					$master[$flag]['content'] .= $line."\n";
					continue;
				}
			}
			
		}
		
		//+-------------------------------
		// Start parsing the php skin file
		//+-------------------------------
		
		if ($INFO['safe_mode_skins'] != 1)
		{
		
			if (SAFE_MODE_ON == 1)
			{
				$ADMIN->error("监测到安全模式功能，你需要修改启用论坛设置[安全模式主题]，你可以在[论坛变量设置]里进行设置。");
			}
		
			$final = "<"."?php\n\n".
					 "class $group {\n\n";
			
			foreach( $master as $func_name => $data )
			{
			
				$final .= "\n\nfunction ".trim($data['func_name'])."(".trim($data['func_data']).") {\n".
					   	  "global \$ibforums;\n".
					   	  "return <<<EOF\n";
					   	  
			    $final .= trim($data['content']);
					   
				$final .= "\nEOF;\n}\n";
				
			}
			
			$final .= "\n\n}\n?".">";
			
			if ($fh = fopen( $skin_dir."/".$group.".php", 'w' ) )
			{
				fwrite($fh, $final, strlen($final) );
				fclose($fh);
			}
			else
			{
				if ($isnew == 1)
				{
					$DB->query("DELETE FROM ibf_tmpl_names WHERE skid='$setid'");
				}
				$errors[] = "无法保存信息到 $phpskin ，请检查目录权限设置。";
			}
		
		}
		
		//+-------------------------------
		// Update the DB
		//+-------------------------------
		
		
		foreach( $master as $func_name => $data )
		{
		
			if ($isnew == 0)
			{
				if ($curr_group[$group][$func_name] != 1)
				{
					// Not a current group/ func..
					
					$isnew = 1;
				}
			}
		
			if ($isnew == 0)
			{
				$data['content'] = str_replace( '\\n' , '\\\\\\n', $data['content'] );
				
				$str = $DB->compile_db_update_string( array(
															  'section_content' => trim($data['content']),
															  'func_data'       => trim($data['func_data'])
													)      );
													
				$DB->query("UPDATE ibf_skin_templates SET $str WHERE set_id='$setid' AND group_name='$group' AND func_name='".trim($data['func_name'])."'");
			}
			else
			{
				$data['content'] = str_replace( '\\n' , '\\\\\\n', $data['content'] );
				
				$str = $DB->compile_db_insert_string( array(
															  'section_content' => trim($data['content']),
															  'func_data'       => trim($data['func_data']),
															  'set_id'          => $setid,
															  'group_name'      => $group,
															  'func_name'       => trim($data['func_name']),
															  'can_remove'      => 0,
													)      );
													
				$DB->query("INSERT INTO ibf_skin_templates ({$str['FIELD_NAMES']}) VALUES({$str['FIELD_VALUES']})");
			}
		}
		
		
		return TRUE;
		
		
	}
	
	/*foreach($functions as $fname => $ftext)
	  {
		  preg_match( "/return <<<(EOF|HTML)(.+?)(EOF|HTML);/s", $ftext, $matches );
		  
		  // Are we updating a current set, but have a new group to add?
		  // Who knows, but it's bloody exciting
		  
		  if ($insert == 0)
		  {
			  if ($curr_group[$name][$fname] != 1)
			  {
				  // Not a current group..
				  
				  $insert = 1;
			  }
		  }
		  
		  // Swap fake newlines
		  
		  $matches[2] = str_replace( '\n', '\\\n', $matches[2] );
		  
		  // Swap real newlines
		  //$matches[2] = str_replace( "\r", '\\r', $matches[2] );
		  //$matches[2] = str_replace( "\n", '\\n', $matches[2] );
		  
		  if ($insert == 0)
		  {
		  
			  $db_update = $DB->compile_db_update_string( array (
															  'section_content' => str_replace( '\n', '\\\n', $matches[2] ),
															  'func_data'       => trim($config[$fname]),
															  'updated'         => time(),
													)       );
																						
			  $DB->query("UPDATE ibf_skin_templates SET $db_update WHERE func_name='$fname' AND set_id='".$IN['id']."' AND group_name='$name'");
		  }
		  else
		  {
		  
			  $db_update = $DB->compile_db_update_string( array (
															  'set_id'          => $IN['id'],
															  'group_name'      => $name,
															  'section_content' => str_replace( '\n', '\\\n', $matches[2] ),
															  'func_name'       => $fname,
															  'func_data'       => trim($config[$fname]),
															  'updated'         => time(),
													)       );
													
			  //----------------------------------------------------
			  // Remove current templates with this name
			  //----------------------------------------------------
	  
			  //$DB->query("DELETE FROM ibf_skin_templates WHERE func_name='$fname' AND set_id='".$IN['id']."' AND group_name='$name'");
	  
			  $DB->query("INSERT INTO ibf_skin_templates SET $db_update");
		  //}
		  
		  
	  }*/
	
	
}


?>