<?php
//  ------------------------------------------------------------------------ //
// 本模組由 tad 製作
// 製作日期：2007-11-04
// $Id: function.php,v 1.5 2008/07/03 07:15:41 tad Exp $
// ------------------------------------------------------------------------- //

define("_SEPARTE","<div style=\"page-break-after: always;\"><span style=\"display: none;\">&nbsp;</span></div>");
define("_SEPARTE2","--summary--");
define("_TADNEWS_FILE_DIR",XOOPS_ROOT_PATH."/uploads/tadnews");
define("_TADNEWS_UP_FILE_PATH",XOOPS_ROOT_PATH."/uploads/tadnews/file");
define("_TADNEWS_UP_FILE_URL",XOOPS_URL."/uploads/tadnews/file");
define("_TADNEWS_NSP_THEMES_PATH",XOOPS_ROOT_PATH."/uploads/tadnews/themes");
define("_TADNEWS_NSP_THEMES_URL",XOOPS_URL."/uploads/tadnews/themes");
define("_TADNEWS_CATE_DIR",XOOPS_ROOT_PATH."/uploads/tadnews/cate");
define("_TADNEWS_CATE_URL",XOOPS_URL."/uploads/tadnews/cate");

//檢查置頂時間
function chk_always_top(){
	global $xoopsDB,$xoopsUser;
  $now=date("Y-m-d H:i:s" , xoops_getUserTimestamp(time()));
	$sql="update ".$xoopsDB->prefix("tad_news")." set always_top='0' WHERE always_top_date <='{$now}' and always_top_date!='0000-00-00 00:00:00'";
	$xoopsDB->queryF($sql);
}

//TadNews物件
class tadnews{
	var $kind="news";
	var $now;
	var $today;
	var $view_ncsn;
	var $show_mode="summary"; //summary,list,cate
	var $show_num="10";
	var $admin_tool=false;
	var $show_enable=1;
	
	//建構函數
	function tadnews(){
		$this->now=date("Y-m-d",xoops_getUserTimestamp(time()));
		$this->today=date("Y-m-d H:i:s",xoops_getUserTimestamp(time()));
	}
	
	//設定種類
	function set_news_kind($new_kind="news"){
		$this->kind=$new_kind;
	}

	//設定是否秀出草稿
	function set_show_enable($enable="1"){
		$this->show_enable=$enable;
	}

	//設定欲觀看分類
	function set_view_ncsn($ncsn=""){
	  global $xoopsDB;
		$this->view_ncsn=$ncsn;
		$sql="select not_news from ".$xoopsDB->prefix("tad_news_cate")." where ncsn='{$ncsn}'";
		$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
		list($not_news)=$xoopsDB->fetchRow($result);
		if($not_news==1){
			$this->set_news_kind("page");
		}
	}

	//設定顯示方式，summary,list,cate
	function set_show_mode($show_mode="summary"){
		$this->show_mode=$show_mode;
	}

	//設定顯示資料數
	function set_show_num($show_num="10"){
	  if($this->show_mode=="list"){
      $show_num*=2;
		}elseif($this->show_mode=="cate"){
      $show_num=round($show_num/2,0);
		}
		$this->show_num=$show_num;
	}

	//設定管理工具
	function set_admin_tool($admin_tool=false){
		$this->admin_tool=$admin_tool;
	}
	
	//置頂圖示
	function get_news_pic($always_top="",$post_date=""){
		$always_top_pic=($always_top=='1')?"<img src='".XOOPS_URL."/modules/tadnews/images/top.gif' alt='"._MB_TADNEW_ALWAYS_TOP."' title='"._MB_TADNEW_ALWAYS_TOP."' hspace=3 align='absmiddle'>":$this->get_today_pic($post_date);
		return $always_top_pic;
	}


	//今日文章
	function get_today_pic($post_date=""){
		$today_pic=($this->now==$post_date)?"<img src='".XOOPS_URL."/modules/tadnews/images/today.gif' alt='"._MB_TADNEW_TODAY_NEWS."' title='"._MB_TADNEW_TODAY_NEWS."' hspace=3 align='absmiddle'>":"";
		return $today_pic;
	}
	
	//取得新聞
	function get_news(){
	  global $xoopsDB,$xoopsUser;

	  //取得目前使用者的所屬群組
		if($xoopsUser){
			$User_Groups=$xoopsUser->getGroups();
		}else{
			$User_Groups=array();
		}
		
		//分析目前觀看得是新聞還是自訂頁面
	  $kind_chk=($this->kind=="news")?"not_news!='1'":"not_news='1'";
	  
	  //是否秀出草稿
	  $show_enable=($this->show_enable==1)?"and enable='1'":"";
	  
	  //找出所有分類
    $sql="select ncsn,nc_title,enable_group,enable_post_group,cate_pic from ".$xoopsDB->prefix("tad_news_cate")." where $kind_chk";
    
		$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],10, mysql_error()."<br>$sql");
		
		$cates_enable_post_group[]="";
		
		//假如是要秀出類別新聞
		if($this->show_mode=="cate"){
		  $all_news="<table id='tbl' style='width:100%'>";
			while(list($ncsn,$nc_title,$enable_group,$enable_post_group,$cate_pic)=$xoopsDB->fetchRow($result)){
				//判斷本文及所屬分類是否允許該用戶之所屬群組觀看
				$cate_read_poewr=$this->chk_cate_power($ncsn,$User_Groups,$cates_enable_post_group[$ncsn],"read");
				$news_read_poewr=$this->chk_news_power($enable_group,$User_Groups);
				if(!$cate_read_poewr or !$news_read_poewr){
					continue;
				}
				
				$pic=(empty($cate_pic))?XOOPS_URL."/modules/tadnews/images/no_cover.png":XOOPS_URL."/uploads/tadnews/cate/{$cate_pic}";

		    $all_news.="<tr><td style='vertical-align:top;width:130px;'><img src='{$pic}' align=left hspace=4 alt='{$nc_title}' title='{$nc_title}' class='cate_thumb' onClick='window.location.href=\"".XOOPS_URL."/modules/tadnews/index.php?ncsn={$ncsn}\"'></td>
				<td colspan=2 style='vertical-align:top;'><a href='".XOOPS_URL."/modules/tadnews/index.php?ncsn=$ncsn'><img src='".XOOPS_URL."/modules/tadnews/images/icon_more.gif' alt='more' title='more' align=right></a><div class='cate_title'><a href='".XOOPS_URL."/modules/tadnews/index.php?ncsn=$ncsn'>{$nc_title}</a></div>
				<table style='width:100%'>";

				$sql2 = "select nsn,news_title,news_content,start_day,end_day,enable,uid,passwd,enable_group,counter,prefix_tag,always_top from ".$xoopsDB->prefix("tad_news")." where ncsn='{$ncsn}' $show_enable and start_day < '{$this->today}' and (end_day > '{$this->today}' or end_day='0000-00-00 00:00:00') order by always_top desc , start_day desc limit 0,{$this->show_num}";
				$result2 = $xoopsDB->query($sql2) or redirect_header($_SERVER['PHP_SELF'],3, $sql2);
				while(list($nsn,$news_title,$news_content,$start_day,$end_day,$enable,$uid,$passwd,$enable_group,$counter,$prefix_tag,$always_top)=$xoopsDB->fetchRow($result2)){
				    $enable_txt=($enable==1)?"":"["._MA_TADNEW_NEWS_UNABLE."]";
						$end_day=($end_day=="0000-00-00 00:00:00")?"":"~ ".$end_day;
						$uid_name=XoopsUser::getUnameFromId($uid,0);
						$news_title=(empty($news_title))?_MD_TADNEWS_NO_TITLE:$news_title;
						$post_date=substr($start_day,0,10);
						$today_pic=($now==$post_date)?"<img src='".XOOPS_URL."/modules/tadnews/images/today.gif' alt='"._MB_TADNEW_TODAY_NEWS."' title='"._MB_TADNEW_TODAY_NEWS."' hspace=3 align='absmiddle'>":"";
						$always_top_pic=($always_top=='1')?"<img src='".XOOPS_URL."/modules/tadnews/images/top.gif' alt='"._MB_TADNEW_ALWAYS_TOP."' title='"._MB_TADNEW_ALWAYS_TOP."' hspace=3 align='absmiddle'>":$today_pic;

				  	$all_news.="<tr><td style='width:80px;' class='noline'>$post_date</td><td class='noline'>{$enable_txt}{$always_top_pic}{$prefix_tag} <a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}'>{$news_title}</a></td></tr>";

				}
				$all_news.="</table>
				</td></tr>";
			}
    	$all_news.="</table>";
			$data=$all_news;
		}else{
			while(list($ncsn,$nc_title,$enable_group,$enable_post_group,$cate_pic)=$xoopsDB->fetchRow($result)){
			  //只有可讀的分類才納入
				$cate_read_poewr=$this->chk_cate_power($ncsn,$User_Groups,$enable_group,"read");
				if($cate_read_poewr){
					$ncsn_ok[]=$ncsn; //權限內可觀看群組
					$cates[$ncsn]=$nc_title;
					$cates_enable_post_group[$ncsn]=$enable_post_group;
					$cates_enable_group[$ncsn]=$enable_group;
					$cates_pic[$ncsn]=$cate_pic;
				}
			  
			}


			$ok_cate=implode(",",$ncsn_ok);

			//假如沒有指定觀看分類
			if(is_null($this->view_ncsn)){
			  if($this->kind=="page"){
					$where_cate=(empty($ok_cate))?"and 0":"and ncsn in($ok_cate)";
				}else{
          $where_cate=(empty($ok_cate))?"and ncsn='0'":"and (ncsn in($ok_cate) or ncsn='0')";
				}
	      
			}else{
	      $where_cate="and ncsn='".$this->view_ncsn."'";
			}

			$desc=($this->kind=="page")?"":"desc";
			
			//判斷是否要檢查日期
			$date_chk=($this->admin_tool)?"":"and start_day < '".$this->today."' and (end_day > '".$this->today."' or end_day='0000-00-00 00:00:00') ";
			
			
			$sql = "select * from ".$xoopsDB->prefix("tad_news")." where 1 $show_enable $where_cate $date_chk order by always_top desc , start_day $desc";
		//	die($sql);
//die($sql);

			//PageBar(資料數, 每頁顯示幾筆資料, 最多顯示幾個頁數選項);
			$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],10, mysql_error()."<br>$sql");
			$total=$xoopsDB->getRowsNum($result);

			$navbar = new PageBar($total, $this->show_num, 10);
			$mybar = $navbar->makeBar();
			$bar= sprintf(_MD_TADNEW_TOOLBAR,$mybar['total'],$mybar['current'])."{$mybar['left']}{$mybar['center']}{$mybar['right']}";
			$sql.=$mybar['sql'];

			$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

			$all_news="";
			while($news=$xoopsDB->fetchArray($result)){

				foreach($news as $k=>$v){
					$$k=$v;
				}

				//判斷本文及所屬分類是否允許該用戶之所屬群組觀看
				$news_read_poewr=$this->chk_news_power($enable_group,$User_Groups);
				if(!$news_read_poewr){
					continue;
				}

				//新聞資訊列
				$fun=$this->admin_tool($uid,$nsn,$counter);
				$end_day=($end_day=="0000-00-00 00:00:00")?"":"~ ".$end_day;
				$enable_txt=($enable==1)?"":"["._MA_TADNEW_NEWS_UNABLE."]";

				//製作新聞標題內容，及密碼判斷
				$have_pass=(isset($_SESSION['have_pass']))?$_SESSION['have_pass']:array();
				if(!empty($passwd) and !in_array($nsn,$have_pass)){
					$news_content="<form action='{$_SERVER['PHP_SELF']}' method='post'><img src='images/lock.png' align='absmiddle' hspace=4 alt='lock.png'>"._MD_TADNEW_NEWS_NEED_PASSWD."
					<input type='hidden' name='nsn' value='{$nsn}'>
					<input type='password' name='tadnews_passwd'>
					<input type='submit'>
					</form>";
				}else{
					//$files=$this->get_news_files($nsn,0);
					$files=show_files("nsn",$nsn,true);
					$news_content.=$files;

					if(eregi(_SEPARTE2,$news_content)){
					  $news_content=str_replace("<p>"._SEPARTE2."</p>",_SEPARTE2,$news_content);
			      $content=explode(_SEPARTE2,$news_content);
					}else{
						$content=explode(_SEPARTE,$news_content);
					}

					$more=(empty($content[1]))?"":"<p><a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}'>"._MD_TADNEW_MORE."...</a></p>";
					$news_content=$content[0].$more;
				}

				$uid_name=XoopsUser::getUnameFromId($uid,0);

				$news_title=(empty($news_title))?_MD_TADNEWS_NO_TITLE:$news_title;
				$cate_name=(empty($cates[$ncsn]))?_MD_TADNEWS_NO_CATE:$cates[$ncsn];

				$post_date=substr($start_day,0,10);
				$today_pic=$this->get_news_pic($always_top,$start_day);

				if($this->show_mode=="list"){
				  $g_txt=$this->txt_to_group_name($enable_group,_MA_TADNEW_ALL_OK);
				  $show_admin_tool=($this->admin_tool)?"<td nowrap>$passwd</td><td nowrap>$g_txt</td><td nowrap><a href='post.php?op=tad_news_form&nsn=$nsn'>"._MA_TADNEW_EDIT."</a>
			<a href=\"javascript:delete_tad_news_func($nsn);\">"._MA_TADNEW_DEL."</a></td>":"";

		      $all_news.="<tr><td nowrap><a href='".XOOPS_URL."/modules/tadnews/index.php?ncsn={$ncsn}'>{$cate_name}</a></td><td width=70%>{$enable_txt}{$today_pic}{$prefix_tag} <a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}'>{$news_title}</a></td><td nowrap><a href='".XOOPS_URL."/userinfo.php?uid={$uid}'>$uid_name</a></td><td nowrap>$post_date</td><td nowrap>$counter</td>$show_admin_tool</tr>";

				}else{
				  $all_news.="
     <div class=\"tadnews_inset\" style=\"clear: both;\">
					<b class=\"b1\"></b><b class=\"b2\"></b><b class=\"b3\"></b><b class=\"b4\"></b>
					<div class=\"boxcontent\">
						<h1>{$always_top_pic}{$prefix_tag} <a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}'>{$news_title}</a></h1>
						<div id='news_toolbar'>$fun</div>
						<div id='news_info'><a href='".XOOPS_URL."/userinfo.php?uid={$uid}'>$uid_name</a> - <a href='".XOOPS_URL."/modules/tadnews/index.php?ncsn={$ncsn}'>{$cate_name}</a> | $start_day $end_day
						</div>
						<div id='news_content'>$news_content</div>
					</div>
     <b class=\"b4b\"></b><b class=\"b3b\"></b><b class=\"b2b\"></b><b class=\"b1b\"></b>
					</div>
					";
				}
			}

			if(empty($all_news)){
			  $cate_post_power=$this->chk_cate_power($ncsn,$User_Groups,"post");
			  $no_news=(empty($cate_post_power))?_MD_TADNEW_NO_NEWS:"<input type=\"button\" value=\""._MD_TADNEW_ADD_FIRST."\" onClick=\"window.location.href='post.php'\">";

			$all_news="
				<div class=\"tadnews_inset\">
				<b class=\"b1\"></b><b class=\"b2\"></b><b class=\"b3\"></b><b class=\"b4\"></b>
				<div class=\"boxcontent\">
					<div style=\"text-align:center\">$no_news</div>
				</div>
				<b class=\"b4b\"></b><b class=\"b3b\"></b><b class=\"b2b\"></b><b class=\"b1b\"></b>
				</div>"
				;
			}elseif($this->show_mode=="list"){
			  $show_admin_tool_title=($this->admin_tool)?"<th nowrap>"._MA_TADNEW_NEWS_PASSWD."</th><th nowrap>"._MA_TADNEW_CAN_READ_NEWS_GROUP."</th><th nowrap>"._MA_TADNEW_FUNCTION."</th>":"";
		    $all_news=div_3d("","<table id='tbl' style='width:100%' class='dot'><tr><th nowrap>"._MA_TADNEW_NEWS_CATE."</th><th nowrap>"._MA_TADNEW_NEWS_TITLE."</th><th nowrap>"._MD_TADNEW_POSTER."</th><th nowrap>"._MA_TADNEW_START_DATE."</th><th nowrap>"._MD_TADNEW_HOT."</th>$show_admin_tool_title</tr>$all_news</table>","corners","width:100%");
			}

			$del_js=del_js();

			$data="
			$del_js
			$all_news
			<div class='bar' align='center'>{$bar}</div>";
		}
		return $data;
		
	}

	

	
	//取得分類新聞
	function get_cate_news($show_ncsn=0,$the_level=0){
	  global $xoopsDB;

	  //取得目前使用者的所屬群組
		if($xoopsUser){
			$User_Groups=$xoopsUser->getGroups();
		}else{
			$User_Groups=array();
		}

    $sql="select ncsn,nc_title,enable_group,enable_post_group,cate_pic from ".$xoopsDB->prefix("tad_news_cate")." where not_news!='1' and of_ncsn='{$show_ncsn}' order by sort";
		$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
		
		$all_news=($level > 0)?"":"
		<!--TadNews Start-->
		<table id='tbl' style='width:96%'>";

		$pic_w=$xoopsModuleConfig['cate_pic_width']+10;
	
	
		while(list($ncsn,$nc_title,$enable_group,$enable_post_group,$cate_pic)=$xoopsDB->fetchRow($result)){
			//判斷所屬分類是否允許該用戶之所屬群組觀看
			$cate_read_poewr=$this->chk_cate_power($ncsn,$User_Groups,$cates_enable_post_group[$ncsn],"read");
			if(!$cate_read_poewr){
				continue;
			}
			$pic=(empty($cate_pic))?"images/no_cover.png":_TADNEWS_CATE_URL."/{$cate_pic}";
			$all_news.="<tr><td style='vertical-align:top;width:{$pic_w}px;'><img src='{$pic}' align=left hspace=4 alt='{$nc_title}' title='{$nc_title}' class='cate_thumb'></td><td colspan=2><a href='index.php?ncsn=$ncsn'><img src='images/icon_more.gif' alt='more' title='more' align=right></a><div class='cate_title'><a href='index.php?ncsn=$ncsn'>{$nc_title}</a></div>
		<table style='width:100%'>";
		
			
			$sql2 = "select * from ".$xoopsDB->prefix("tad_news")." where ncsn='{$ncsn}' $show_enable and start_day < '".$this->today."' and (end_day > '".$this->today."' or end_day='0000-00-00 00:00:00') order by always_top desc , start_day desc limit 0,".$this->show_num;
			$result2 = $xoopsDB->query($sql2) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
			while($news=$xoopsDB->fetchArray($result2)){

				foreach($news as $k=>$v){
					$$k=$v;
				}
				$news_read_poewr=$this->chk_news_power($enable_group,$User_Groups);
				if(!$news_read_poewr){
					continue;
				}

				$news_title=(empty($news_title))?_MD_TADNEWS_NO_TITLE:$news_title;
				$post_date=substr($start_day,0,10);
				$today_pic=$this->get_news_pic($always_top,$post_date);

		  	$all_news.="<tr><td style='width:80px;' class='noline'>$post_date</td><td class='noline'>{$always_top_pic}{$prefix_tag} <a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}'>{$news_title}</a></td></tr>";

			}
			$all_news.="</table>
			</td></tr>";

			$level++;
			$all_news.=$this->get_cate_news($ncsn,$level);
		}
		$all_news.=($the_level > 0)?"":"</table>
		<!--TadNews End-->";

		return $all_news;
	}

	//判斷本文之所屬分類是否允許該用戶之所屬群組觀看或發佈
	function chk_cate_power($ncsn="",$User_Groups="",$enable_group="",$kind="read"){
		global $xoopsDB,$xoopsUser;

		if(!empty($enable_group)){
			$ok=false;
			$cate_enable_group=explode(",",$enable_group);
			if(in_array("",$cate_enable_group)){
	      return true;
			}

			foreach($User_Groups as $gid){
				if(in_array($gid,$cate_enable_group)){
					return true;
				}
			}
		}else{
			return true;
		}
		return false;
	}

	//判斷本文是否允許該用戶之所屬群組觀看或發佈
	function chk_news_power($enable_group="",$User_Groups=""){
		global $xoopsDB,$xoopsUser;

		if(empty($enable_group))return true;

		$news_enable_group=explode(",",$enable_group);
		foreach($User_Groups as $gid){
			if(in_array($gid,$news_enable_group)){
				return true;
			}
		}

		return false;
	}
	
	
	//新聞編輯工具
	function admin_tool($uid,$nsn,$counter=""){
		global $xoopsUser,$xoopsModuleConfig,$xoopsModule;
		if($xoopsUser){
			$uuid=$xoopsUser->getVar('uid');
			$module_id = $xoopsModule->getVar('mid');
      $isAdmin=$xoopsUser->isAdmin($module_id);
		}else{
			$uuid=$isAdmin="";
		}


		$admin_fun=($uid==$uuid or $isAdmin)?"
		<a href='post.php'>"._MD_TADNEW_ADD."</a> |
		<a href='post.php?op=tad_news_form&nsn=$nsn'>"._MD_TADNEW_EDIT."</a> |
		<a href=\"javascript:delete_tad_news_func($nsn);\">"._MD_TADNEW_DEL."</a> |":"";



		$bbcode=($xoopsModuleConfig['show_bbcode']=='1')?"<a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}&bb=1'>BBCode</a> |":"";

		$fun="<div>
		$admin_fun
		$bbcode
		"._MD_TADNEW_HOT."{$counter}
		</div>";

		return $fun;
	}


	
	//刪除的js
	function del_js(){
		$js="<script>
		function delete_tad_news_func(nsn){
			var sure = window.confirm('"._MD_TADNEW_SURE_DEL."');
			if (!sure)	return;
			location.href=\"{$_SERVER['PHP_SELF']}?op=delete_tad_news&nsn=\" + nsn;
		}
		</script>";
		return $js;
	}

  //把字串換成群組
	function txt_to_group_name($enable_group="",$default_txt="",$syb="<br />"){
		$groups_array=$this->get_all_groups();
		if(empty($enable_group)){
	    $g_txt=$default_txt;
		}else{
		  $gs=explode(",",$enable_group);
		  $g_txt="";
		  foreach($gs as $gid){
	    	$g_txt.=$groups_array[$gid]."{$syb}";
			}
		}
		return $g_txt;
	}

  //取得所有群組
	function get_all_groups(){
		global $xoopsDB;
		$sql = "select groupid,name from ".$xoopsDB->prefix("groups")."";
		$result = $xoopsDB->query($sql);
		while(list($groupid,$name)=$xoopsDB->fetchRow($result)){
			$data[$groupid]=$name;
		}
		return $data;
	}

}
































	//判斷本文及所屬分類是否允許該用戶之所屬群組觀看
	function read_power_chk($ncsn="",$enable_group=""){
		global $xoopsDB,$xoopsUser;

		//取得目前使用者的所屬群組
		if($xoopsUser){
			$User_Groups=$xoopsUser->getGroups();
		}else{
			$User_Groups=array();
		}

		//判斷本文之所屬分類是否允許該用戶之所屬群組觀看
		if(!chk_cate_power($ncsn,$User_Groups)){
			return false;
		}

		//判斷本文是否允許該用戶之所屬群組觀看
		if(!chk_news_power($enable_group,$User_Groups)){
			return false;
		}

		return true;
	}


	//判斷本文之所屬分類是否允許該用戶之所屬群組觀看或發佈
	function chk_cate_power($ncsn="",$User_Groups="",$kind="read"){
		global $xoopsDB,$xoopsUser;

		$cate=get_tad_news_cate($ncsn);
		$enable_group=($kind=="post")?$cate['enable_post_group']:$cate['enable_group'];


		if(!empty($enable_group)){
			$ok=false;
			$cate_enable_group=explode(",",$enable_group);
			if(in_array("",$cate_enable_group)){
	      return true;
			}

			foreach($User_Groups as $gid){
				if(in_array($gid,$cate_enable_group)){
					return true;
				}
			}
		}else{
			return true;
		}
		return false;
	}

	//判斷本文是否允許該用戶之所屬群組觀看或發佈
	function chk_news_power($enable_group="",$User_Groups=""){
		global $xoopsDB,$xoopsUser;

		if(empty($enable_group))return true;

		$news_enable_group=explode(",",$enable_group);
		foreach($User_Groups as $gid){
			if(in_array($gid,$news_enable_group)){
				return true;
			}
		}

		return false;
	}

//解析分類的設定檔
function get_setup($setup=""){
	if(empty($setup))return "";
	$set=explode(";",$setup);
	foreach($set as $s){
		$ss=explode("=",$s);
		$key=$ss[0];
		$val=$ss[1];
		$all[$key]=$val;
	}
	return $all;
}

//圓角文字框
function div_3d($title="",$main="",$kind="raised",$style=""){
	$main="<table style='width:auto;{$style}'><tr><td>
	<div class='{$kind}'>
	<h1>$title</h1>
	<b class='b1'></b><b class='b2'></b><b class='b3'></b><b class='b4'></b>
	<div class='boxcontent'>
 	$main
	</div>
	<b class='b4b'></b><b class='b3b'></b><b class='b2b'></b><b class='b1b'></b>
	</div>
	</td></tr></table>";
	return $main;
}


//身份查核
function chk_who($author_id=""){
	global $xoopsDB,$xoopsUser,$xoopsModule;
	if(empty($xoopsUser))return false;

  $module_id = $xoopsModule->getVar('mid');
  $isAdmin=$xoopsUser->isAdmin($module_id);
  if($isAdmin)return true;

	$uid=$xoopsUser->getVar('uid');
  if($uid==$author_id) return true;

  return false;
}


//找出現有電子報（若是 $mode=css 則用圖形顯示）
function newspaper_set_select($mode=""){
	global $xoopsDB;
	$sql = "select a.npsn,a.number,b.title,a.np_date from ".$xoopsDB->prefix("tad_news_paper")." as a ,".$xoopsDB->prefix("tad_news_paper_setup")." as b where a.nps_sn=b.nps_sn and b.status='1' order by a.np_date desc";
	

	$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

	$main=($mode=="css")?"<div id='middlebar'><ul class='menu'><li><a href='#' onclick=\"javascript:showlayer('sm_1')\">"._MD_TADNEW_NEWSPAPER_LIST."</a></li><ul class='submenu' id='sm_1'>":"<select onChange=\"window.location.href='".XOOPS_URL."/modules/tadnews/newspaper.php?npsn='+this.value \"><option value=''>"._MD_TADNEW_NEWSPAPER_LIST."</option>";
	
	while(list($allnpsn,$number,$title,$np_date)=$xoopsDB->fetchRow($result)){
			$main.=($mode=="css")?"<li><a href='".XOOPS_URL."/modules/tadnews/newspaper.php?npsn={$allnpsn}'>{$title}".sprintf(_MA_TADNEW_NP_TITLE,$number)."</a></li>":"<option value='{$allnpsn}'>{$title}".sprintf(_MA_TADNEW_NP_TITLE,$number)."</option>";
	}
	$main.=($mode=="css")?"</ul></ul></div>":"</select>";

	return $main;
}




//判斷目前登入者在哪些類別中有發表的權利
function chk_cate_post_power($kind="post"){
	global $xoopsDB,$xoopsUser,$xoopsModule;
	if(empty($xoopsUser))return false;

  $module_id = $xoopsModule->getVar('mid');
  $isAdmin=$xoopsUser->isAdmin($module_id);
	if($isAdmin){
    $ok_cat[]="";
	}
	$user_array=$xoopsUser->getGroups();

	$col=($kind=="post")?"enable_post_group":"enable_group";

	//非管理員才要檢查
	$where=($isAdmin)?"":"where $col!=''";

	$sql = "select ncsn,{$col} from ".$xoopsDB->prefix("tad_news_cate")." $where";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

	while(list($ncsn,$power)=$xoopsDB->fetchRow($result)){
	  if($isAdmin){
      $ok_cat[]=$ncsn;
		}else{
			$power_array=explode(",",$power);
			foreach($power_array as $gid){
				if(in_array($gid,$user_array)){
					$ok_cat[]=$ncsn;
					break;
				}
			}
		}
	}
	return $ok_cat;
}




//取得電子報設定資料
function get_newspaper_set($nps_sn=""){
	global $xoopsDB,$xoopsModule,$xoopsUser,$xoopsConfig;
	$sql = "select * from ".$xoopsDB->prefix("tad_news_paper_setup")." where nps_sn='{$nps_sn}'";
	$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	$data=$xoopsDB->fetchArray($result);
	return $data;
}

//取得電子報資料
function get_newspaper($npsn=""){
	global $xoopsDB,$xoopsModule,$xoopsUser,$xoopsConfig;
	$sql = "select * from ".$xoopsDB->prefix("tad_news_paper")." where npsn='{$npsn}'";
	$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	$data=$xoopsDB->fetchArray($result);
	return $data;
}


//預覽電子報
function preview_newspaper($npsn=""){
	global $xoopsDB;
	$np=get_newspaper($npsn);
	$sql = "select title,head,foot,themes from ".$xoopsDB->prefix("tad_news_paper_setup")." where nps_sn='{$np['nps_sn']}'";
	$result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	list($title,$head,$foot,$themes)=$xoopsDB->fetchRow($result);

	$head=str_replace('{N}',$np['number'],$head);
	$head=str_replace('{D}',substr($np['np_date'],0,10),$head);

	$filename = _TADNEWS_NSP_THEMES_PATH."/{$themes}/index.html";
	$handle = fopen($filename, "rb");
	$contents = '';
	while (!feof($handle)) {
	  $contents .= fread($handle, 8192);
	}
	fclose($handle);
	$main=str_replace("{TNP_THEME}",_TADNEWS_NSP_THEMES_URL."/{$themes}/",$contents);
	$main=str_replace("{TNP_CSS}","<link rel='stylesheet' type='text/css' media='screen' href='".XOOPS_URL."/modules/tadnews/module.css' />",$main);
	$main=str_replace("{TNP_TITLE}",$title,$main);
	$char=_CHARSET;
	$main=str_replace("{TNP_CODE}",$char,$main);
	$main=str_replace("{TNP_HEAD}",$head,$main);
	$main=str_replace("{TNP_FOOT}",$foot,$main);
	$main=str_replace("{TNP_URL}",XOOPS_URL."/modules/tadnews/newspaper.php?npsn={$npsn}",$main);
	$main=str_replace("{TNP_CONTENT}",$np['np_content'],$main);
	return $main;
}

//以流水號取得某筆tad_news資料
function get_tad_news($nsn="",$uid_chk=false){
	global $xoopsDB,$xoopsUser,$xoopsModule;
	if(empty($nsn))return;

	$sql = "select * from ".$xoopsDB->prefix("tad_news")." where nsn='$nsn'";
	$result = $xoopsDB->query($sql) or redirect_header("index.php",3,mysql_error());
	$data=$xoopsDB->fetchArray($result);
	

	if($uid_chk){
	  if(empty($xoopsUser)) redirect_header("index.php",3,_MA_TADNEW_NO_ADMIN_POWER);
		$module_id = $xoopsModule->getVar('mid');
	  $isAdmin=$xoopsUser->isAdmin($module_id);
		$uid=$xoopsUser->getVar('uid');
	  if(!$isAdmin and $uid!=$data['uid']){
       redirect_header("index.php",3,_MA_TADNEW_NO_ADMIN_POWER);
		}
  }
	
	return $data;
}




//取得所有類別標題
function get_all_news_cate(){
	global $xoopsDB;
	$sql = "select ncsn,nc_title from ".$xoopsDB->prefix("tad_news_cate")." order by sort";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

	while(list($ncsn,$nc_title)=$xoopsDB->fetchRow($result)){
		$data[$ncsn]=$nc_title;
	}
	return $data;
}

//取得所有群組
function get_all_groups(){
	global $xoopsDB;
	$sql = "select groupid,name from ".$xoopsDB->prefix("groups")."";
	$result = $xoopsDB->query($sql);
	while(list($groupid,$name)=$xoopsDB->fetchRow($result)){
		$data[$groupid]=$name;
	}
	return $data;
}


//把字串換成群組
function txt_to_group_name($enable_group="",$default_txt="",$syb="<br />"){
	$groups_array=get_all_groups();
	if(empty($enable_group)){
    $g_txt=$default_txt;
	}else{
	  $gs=explode(",",$enable_group);
	  $g_txt="";
	  foreach($gs as $gid){
    	$g_txt.=$groups_array[$gid]."{$syb}";
		}
	}
	return $g_txt;
}



//取得分類下拉選單
function get_tad_news_cate_option($of_ncsn=0,$level=0,$v="",$this_ncsn="",$no_self="0",$not_news="null"){
	global $xoopsDB,$xoopsUser,$xoopsModule;

	if ($xoopsUser) {
    $module_id = $xoopsModule->getVar('mid');
    $isAdmin=$xoopsUser->isAdmin($module_id);
  }else{
    $isAdmin=false;
	}
  
	$ok_cat=chk_cate_post_power();
	
	$left=$level*10;
	$level+=1;
	
	$and_not_news=($not_news!="null")?"and not_news='{$not_news}'":"";

    
	$option=($of_ncsn or !$isAdmin)?"":"<option value='0'></option>";
	$option=="";
	$sql = "select ncsn,nc_title,not_news from ".$xoopsDB->prefix("tad_news_cate")." where of_ncsn='{$of_ncsn}' $and_not_news order by sort";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	
	while(list($ncsn,$nc_title,$not_news)=$xoopsDB->fetchRow($result)){
	  if(!in_array($ncsn,$ok_cat))continue;
	  if($no_self=='1' and $this_ncsn==$ncsn)continue;
		$selected=($v==$ncsn)?"selected":"";
		$color=($not_news=='1')?"red":"black";
		$option.="<option value='{$ncsn}' style='padding-left: {$left}px;color:{$color};' $selected>{$nc_title}</option>";
		$option.=get_tad_news_cate_option($ncsn,$level,$v,$this_ncsn,$no_self,$not_news);
	}
	return $option;
}

//刪除tad_news某筆資料資料
function delete_tad_news($nsn=""){
	global $xoopsDB,$xoopsUser,$xoopsModule;

	//確認有管理員或本人才能管理
	$news=get_tad_news($nsn);
	if(!chk_who($news['uid'])){
		redirect_header($_SERVER['PHP_SELF'],3, _MA_TADNEW_NO_ADMIN_POWER);
	}
	
	$sql = "delete from ".$xoopsDB->prefix("tad_news")." where nsn='$nsn'";
	$xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	
	//刪除檔案
	del_files("","nsn",$nsn);
}


//刪除的js
function del_js(){
	$js="<script>
	function delete_tad_news_func(nsn){
		var sure = window.confirm('"._MD_TADNEW_SURE_DEL."');
		if (!sure)	return;
		location.href=\"{$_SERVER['PHP_SELF']}?op=delete_tad_news&nsn=\" + nsn;
	}
	</script>";
	return $js;
}


//以流水號取得某筆tad_news_cate資料
function get_tad_news_cate($ncsn=""){
	global $xoopsDB;
	if(empty($ncsn))return;
	$sql = "select * from ".$xoopsDB->prefix("tad_news_cate")." where ncsn='$ncsn'";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	$data=$xoopsDB->fetchArray($result);
	return $data;
}



/********************* 預設函數 *********************/

//管理介面的選單
function menu_interface($show=1){
global $xoopsModule,$xoopsModuleConfig;
	if(empty($show))return;
	$dirname=$xoopsModule->getVar('dirname');
	include_once("../language/tchinese/modinfo.php");
	include("menu.php");
	//$page=explode("/",$_SERVER['PHP_SELF']);
	//$n=sizeof($page)-1;
	
	if(is_array($adminmenu)){
		foreach($adminmenu as $m){
		  $menu_parts = pathinfo($m['link']);
		  $SCRIPT_NAME_parts = pathinfo($_SERVER['SCRIPT_NAME']);
		  $current=($menu_parts['basename']==$SCRIPT_NAME_parts['basename'])?"class='current'":"";
		  //$current=("/modules/{$dirname}/{$m['link']}"==$_SERVER['SCRIPT_NAME'])?"class='current'":"";
			$td.="<li $current><a href='".XOOPS_URL."/modules/{$dirname}/{$m['link']}'><b>{$m['title']}</b></a></li>";
		}
	}else{
		$td="";
	}
	
	$main="
	<style type='text/css'>
	#admin_menu {
		width:96%;
		padding: 0 0 0 32px;
		margin: 0;
		list-style: none;
		height: 35px;
		background: #fff url(".XOOPS_URL."/modules/{$dirname}/images/button1.gif);
		position: relative;
		border: 1px solid #000;
		border-width: 0 1px;
		border-bottom: 1px solid #444;
	}
	#admin_menu li {
		float: left;
		list-style: none;
	}
	#admin_menu li a {
		display: block;
		float: left;
		height: 35px;
		line-height: 35px;
		color: #aaa;
		text-decoration: none;
		font-size: 12px;
		font-family: arial, verdana, sans-serif;
		font-weight: bold;
		text-align: center;
		padding: 0 0 0 8px;
		cursor: pointer;
	}
	#admin_menu li a b {
		float: left;
		display: block;
		padding: 0 16px 0 8px;
	}
	#admin_menu li.current a {
		color: #fff;
		background: url(".XOOPS_URL."/modules/{$dirname}/images/button3.gif);
	}
	#admin_menu li.current a b {
		background: url(".XOOPS_URL."/modules/{$dirname}/images/button3.gif) no-repeat right top;
	}
	#admin_menu li a:hover {
		color: #fff;
		background: #000 url(".XOOPS_URL."/modules/{$dirname}/images/button4.gif);
	}
	#admin_menu li a:hover b {
		background: url(".XOOPS_URL."/modules/{$dirname}/images/button4.gif) no-repeat right top;
	}
	#admin_menu li.current a:hover {
		color: #fff;
		background: #000 url(".XOOPS_URL."/modules/{$dirname}/images/button3.gif);
		cursor: default;
	}
	#admin_menu li.current a:hover b {
		background: url(".XOOPS_URL."/modules/{$dirname}/images/button3.gif) no-repeat right top;
	}
	</style>
	<ul id='admin_menu'>{$td}
	<li><a href='".XOOPS_URL."/modules/{$dirname}/'><b>"._MD_TADNEW_TO_MOD."</b></a></li>
	</ul>";
	return $main;
}

//首頁的連結工具
function toolbar($interface_menu=array()){
	global $xoopsModule,$xoopsModuleConfig,$xoopsUser;
	if(empty($interface_menu))return;
	$dirname=$xoopsModule->getVar('dirname');
	$moduleperm_handler = & xoops_gethandler( 'groupperm' );
	//判斷是否有管理權限
	if ( $xoopsUser) {
		if ($moduleperm_handler->checkRight( 'module_admin', $xoopsModule->getVar( 'mid' ), $xoopsUser->getGroups() ) ) {
			$admin_tools="<a href='".XOOPS_URL."/modules/{$dirname}/admin/index.php'>"._MD_TADNEW_TO_ADMIN."</a>";
		}
	}
	$td="";
	if(is_array($interface_menu)){
		foreach($interface_menu as $title => $url){
			$td.="<a href='".XOOPS_URL."/modules/{$dirname}/{$url}'>{$title}</a>";
		}
	}else{
		return;
	}
	$main="
	<style type='text/css'>
	#toolbar{
		margin-bottom:10px;
	}
	#toolbar a:link, #toolbar a:visited {
		font-size: 11px;
		background-image: url(".XOOPS_URL."/modules/{$dirname}/images/bbg.jpg);
		margin-right: 0px;
		padding: 3px 10px 2px 10px;
		color: rgb(80,80,80);
		background-color: #FCE6EA;
		text-decoration: none;
		border-top: 1px solid #FFFFFF;
		border-left: 1px solid #FFFFFF;
		border-bottom: 1px solid #717171;
		border-right: 1px solid #717171;
	}
	#toolbar a:hover {
		background-image: url(".XOOPS_URL."/modules/{$dirname}/images/bbg2.jpg);
		color: rgb(255,0,128);
		border-top: 1px solid #717171;
		border-left: 1px solid #717171;
		border-bottom: 1px solid #FFFFFF;
		border-right: 1px solid #FFFFFF;
	}
	</style>
	<div id='toolbar'>{$td}{$admin_tools}</div>";
	return $main;
}

//單選回復原始資料函數
function chk($DBV="",$NEED_V="",$defaul="",$return="checked"){
	if($DBV==$NEED_V){
		return $return;
	}elseif(empty($DBV) && $defaul=='1'){
		return $return;
	}
	return "";
}

//複選回復原始資料函數
function chk2($defaul_array="",$NEED_V="",$defaul=1){
	if(in_array($NEED_V,$the_array)){
		return "checked";
	}elseif($defaul){
		return "checked";
	}

	return "";
}


//細部權限判斷
function power_chk($perm_name="",$psn=""){
	global $xoopsUser,$xoopsModule;

	//取得目前使用者的群組編號
	if($xoopsUser) {
		$groups = $xoopsUser->getGroups();
	}else{
		$groups = XOOPS_GROUP_ANONYMOUS;
	}

	//取得模組編號
	$module_id = $xoopsModule->getVar('mid');
	//取得群組權限功能
	$gperm_handler =& xoops_gethandler('groupperm');

	//權限項目編號
	$perm_itemid = intval($psn);
	//依據該群組是否對該權限項目有使用權之判斷 ，做不同之處理
	if($gperm_handler->checkRight($perm_name, $perm_itemid, $groups, $module_id)) {
		return true;
	}
	return false;
}

//單選判斷
function is_checked($v1="",$v2="",$default=""){
	if(isset($v1) and $v1==$v2){
		return "checked";
	}elseif($default=="default"){
		return "checked";
	}
}


//分頁物件
class PageBar{
	// 目前所在頁碼
	var $current;
	// 所有的資料數量 (rows)
	var $total;
	// 每頁顯示幾筆資料
	var $limit;
	// 目前在第幾層的頁數選項？
	var $pCurrent;
	// 總共分成幾頁？
	var $pTotal;
	// 每一層最多有幾個頁數選項可供選擇，如：3 = {[1][2][3]}
	var $pLimit;
	var $prev;
	var $next;
	var $prev_layer = ' ';
	var $next_layer = ' ';
	var $first;
	var $last;
	var $bottons = array();
	// 要使用的 URL 頁數參數名？
	var $url_page = "g2p";
	// 要使用的 URL 讀取時間參數名？
	var $url_loadtime = "loadtime";
	// 會使用到的 URL 變數名，給 process_query() 過濾用的。
	var $used_query = array();
	// 目前頁數顏色
	var $act_color = "#990000";
	var $query_str; // 存放 URL 參數列

	function PageBar($total, $limit, $page_limit){
		$mydirname = basename( dirname( __FILE__ ) ) ;
		$this->prev = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/1leftarrow.gif' alt='"._MD_TADNEW_BACK_PAGE."' align='absmiddle' hspace=3>"._MD_TADNEW_BACK_PAGE;
		$this->next = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/1rightarrow.gif' alt='"._MD_TADNEW_NEXT_PAGE."' align='absmiddle' hspace=3>"._MD_TADNEW_NEXT_PAGE;
		$this->first = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/2leftarrow.gif' alt='"._MD_TADNEW_FIRST_PAGE."' align='absmiddle' hspace=3>"._MD_TADNEW_FIRST_PAGE;
		$this->last = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/2rightarrow.gif' alt='"._MD_TADNEW_LAST_PAGE."' align='absmiddle' hspace=3>"._MD_TADNEW_LAST_PAGE;

		$this->limit = $limit;
		$this->total = $total;
		$this->pLimit = $page_limit;
	}

	function init(){
		$this->used_query = array($this->url_page, $this->url_loadtime);
		$this->query_str = $this->processQuery($this->used_query);
		$this->glue = ($this->query_str == "")?'?':
		'&';
		$this->current = (isset($_GET["$this->url_page"]))? $_GET["$this->url_page"]:
		1;
		$this->pTotal = ceil($this->total / $this->limit);
		$this->pCurrent = ceil($this->current / $this->pLimit);
	}

	//初始設定
	function set($active_color = "none", $buttons = "none"){
		if ($active_color != "none"){
			$this->act_color = $active_color;
		}

		if ($buttons != "none"){
			$this->buttons = $buttons;
			$this->prev = $this->buttons['prev'];
			$this->next = $this->buttons['next'];
			$this->prev_layer = $this->buttons['prev_layer'];
			$this->next_layer = $this->buttons['next_layer'];
			$this->first = $this->buttons['first'];
			$this->last = $this->buttons['last'];
		}
	}

	// 處理 URL 的參數，過濾會使用到的變數名稱
	function processQuery($used_query){
		// 將 URL 字串分離成二維陣列
		$vars = explode("&", $_SERVER['QUERY_STRING']);
		for($i = 0; $i < count($vars); $i++){
			$var[$i] = explode("=", $vars[$i]);
		}

		// 過濾要使用的 URL 變數名稱
		for($i = 0; $i < count($var); $i++){
			for($j = 0; $j < count($used_query); $j++){
				if (isset($var[$i][0]) && $var[$i][0] == $used_query[$j]) $var[$i] = array();
			}
		}

		// 合併變數名與變數值
		for($i = 0; $i < count($var); $i++){
			$vars[$i] = implode("=", $var[$i]);
		}

		// 合併為一完整的 URL 字串
		$processed_query = "";
		for($i = 0; $i < count($vars); $i++){
			$glue = ($processed_query == "")?'?':
			'&';
			// 開頭第一個是 '?' 其餘的才是 '&'
			if ($vars[$i] != "") $processed_query .= $glue.$vars[$i];
		}
		return $processed_query;
	}

	// 製作 sql 的 query 字串 (LIMIT)
	function sqlQuery(){
		$row_start = ($this->current * $this->limit) - $this->limit;
		$sql_query = " LIMIT {$row_start}, {$this->limit}";
		return $sql_query;
	}


	// 製作 bar
	function makeBar($url_page = "none"){
		if ($url_page != "none"){
			$this->url_page = $url_page;
		}
		$this->init();

		// 取得目前時間
		$loadtime = '&loadtime='.time();

		// 取得目前頁框(層)的第一個頁數啟始值，如 6 7 8 9 10 = 6
		$i = ($this->pCurrent * $this->pLimit) - ($this->pLimit - 1);

		$bar_center = "";
		while ($i <= $this->pTotal && $i <= ($this->pCurrent * $this->pLimit)){
			if ($i == $this->current){
				$bar_center = "{$bar_center}<font color='{$this->act_color}'>[{$i}]</font>";
			}else{
				$bar_center .= " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}'' title='{$i}'>{$i}</a> ";
			}
			$i++;
		}
		$bar_center = $bar_center . "";

		// 往前跳一頁
		if ($this->current <= 1){
			$bar_left = " {$this->prev} ";
			$bar_first = " {$this->first} ";
		}	else{
			$i = $this->current-1;
			$bar_left = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='"._MD_TADNEW_BACK_PAGE."'>{$this->prev}</a> ";
			$bar_first = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}=1{$loadtime}' title='"._MD_TADNEW_FIRST_PAGE."'>{$this->first}</a> ";
		}

		// 往後跳一頁
		if ($this->current >= $this->pTotal){
			$bar_right = " {$this->next} ";
			$bar_last = " {$this->last} ";
		}	else{
			$i = $this->current + 1;
			$bar_right = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='"._MD_TADNEW_NEXT_PAGE."'>{$this->next}</a> ";
			$bar_last = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$this->pTotal}{$loadtime}' title='"._MD_TADNEW_LAST_PAGE."'>{$this->last}</a> ";
		}

		// 往前跳一整個頁框(層)
		if (($this->current - $this->pLimit) < 1){
			$bar_l = " {$this->prev_layer} ";
		}	else{
			$i = $this->current - $this->pLimit;
			$bar_l = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='".sprintf($this->pLimit,_MD_TADNEW_GO_BACK_PAGE)."'>{$this->prev_layer}</a> ";
		}

		//往後跳一整個頁框(層)
		if (($this->current + $this->pLimit) > $this->pTotal){
			$bar_r = " {$this->next_layer} ";
		}	else{
			$i = $this->current + $this->pLimit;
			$bar_r = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='".sprintf($this->pLimit,_MD_TADNEW_GO_NEXT_PAGE)."'>{$this->next_layer}</a> ";
		}

		$page_bar['center'] = $bar_center;
		$page_bar['left'] = $bar_first . $bar_l . $bar_left;
		$page_bar['right'] = $bar_right . $bar_r . $bar_last;
		$page_bar['current'] = $this->current;
		$page_bar['total'] = $this->pTotal;
		$page_bar['sql'] = $this->sqlQuery();
		return $page_bar;
	}

}

//建立目錄
function mk_dir($dir=""){
    //若無目錄名稱秀出警告訊息
    if(empty($dir))redirect_header("index.php", 3,_MA_TADNEW_NO_DIRNAME);
    //若目錄不存在的話建立目錄
    if (!is_dir($dir)) {
        umask(000);
        //若建立失敗秀出警告訊息
        if(!mkdir($dir, 0777)){
            redirect_header("index.php", 3,sprintf(_MA_TADNEW_MKDIR_ERROR,$dir));
        }
    }
}

//輸出為UTF8
function to_utf8($buffer=""){
	if(_CHARSET=="UTF-8"){
		return $buffer;
	}else{
  	//$buffer=(!function_exists("mb_convert_encoding"))?iconv(_CHARSET,"UTF-8",$buffer):mb_convert_encoding($buffer,"UTF-8",_CHARSET);
  	$buffer=iconv(_CHARSET,"UTF-8",$buffer);
  	//$buffer=(!function_exists("mb_convert_encoding"))?die("iconv("._CHARSET.",\"UTF-8\",$buffer)"):die("mb_convert_encoding($buffer,\"UTF-8\","._CHARSET.")");
  	return $buffer;
	}
}


//避免截掉半個中文字
function cuttingstr($str,$ct,$mark="...") {
    if(strlen($str) > $ct) {
        for($i=0;$i<$ct;$i++) {
            $ch=substr($str,$i,1);
            if(ord($ch)>127) $i++;
        }
        $str= substr($str,0,$i).$mark;
    }
    return $str;
}
?>
