<?php
//  ------------------------------------------------------------------------ //
// 本模組由 tad 製作
// 製作日期：2008-02-28
// $Id: function.php,v 1.2 2008/05/14 01:22:58 tad Exp $
// ------------------------------------------------------------------------- //

define("_TAD_PLAYER_UPLOAD_DIR",XOOPS_ROOT_PATH."/uploads/tad_player/");
define("_TAD_PLAYER_UPLOAD_URL",XOOPS_URL."/uploads/tad_player/");


define("_TAD_PLAYER_FLV_DIR",XOOPS_ROOT_PATH."/uploads/tad_player/flv/");
define("_TAD_PLAYER_FLV_URL",XOOPS_URL."/uploads/tad_player/flv/");

define("_TAD_PLAYER_IMG_DIR",XOOPS_ROOT_PATH."/uploads/tad_player/img/");
define("_TAD_PLAYER_IMG_URL",XOOPS_URL."/uploads/tad_player/img/");

define("_TAD_PLAYER_BATCH_UPLOAD_DIR",XOOPS_ROOT_PATH."/uploads/tad_player_batch_uploads/");
define("_TAD_PLAYER_BATCH_UPLOAD_URL",XOOPS_URL."/uploads/tad_player_batch_uploads/");

if(!file_exists(_TAD_PLAYER_UPLOAD_DIR."mediaplayer.swf")){
	copy(XOOPS_ROOT_PATH."/modules/tad_player/class/jw_player/mediaplayer.swf",_TAD_PLAYER_UPLOAD_DIR."mediaplayer.swf");
}

//播放語法($mode=single or playlist)
function play_code($file="",$sn="",$mode="",$width="",$height="",$autostart=true,$skin=""){
	global $xoopsModuleConfig;
	if($mode=="playlist"){
	  if(empty($width)) $width=$xoopsModuleConfig['width'];
	  if(empty($width)) $height=$xoopsModuleConfig['height'];

	  $width=(empty($file['width']))?$width:$file['width'];
		$height=(empty($file['height']))?$height:$file['height'];

	  if($xoopsModuleConfig['display']=="right"){
			$all_width=$width+$xoopsModuleConfig['display_max'];
	    $all_height=$height+20;
	    $pic="playlist:'right',";

		  $width_js="width:'{$width}',playlistsize:'{$xoopsModuleConfig['display_max']}',";
		  $height_js="height:'{$height}',";
		}else{
		  $all_width=$width;
			$all_height=$height+$xoopsModuleConfig['display_max'];
	    $pic="playlist:'bottom',";
	    
		  $width_js="width:'{$width}',playlistsize:'{$xoopsModuleConfig['display_max']}',";
		  $height_js="height:'{$height}',";
		}
		$media=_TAD_PLAYER_UPLOAD_URL."{$sn}_list.xml";
	  

	}else{
		if(empty($width))  $width=(empty($file['width']))?$xoopsModuleConfig['width']:$file['width'];
		if(empty($height))  $height=(empty($file['height']))?$xoopsModuleConfig['height']:$file['height'];
		$all_width=$width;
		$all_height=$height+40;
		if(empty($file['location']) and !empty($file['youtube'])){
	    $media= $file['youtube'];
	    $media=str_replace("?","%3F",$media);
	    $media=str_replace("=","%3D",$media);
	    $media=str_replace("&","%26",$media);
		}elseif(substr($file['location'],0,4)=='http'){
	    $media=$file['location'];
		}else{
	    $media=_TAD_PLAYER_FLV_URL."{$sn}_{$file['location']}";
		}
	  $pic=(empty($image))?"":"image:'{$image}',";
	  $width_js="width:'{$width}',";
	  $height_js="height:'{$height}',";
	}
	
	$type=strtolower(substr($file['location'],-3));
  if($type=="mp3" and empty($file['image'])){
    $height=20;
	}
	

	
  $dl=($xoopsModuleConfig['download']=='1')?"showdownload:'true',
	link:'{$media}',":"";
	
	
  if(substr($file['image'],0,4)=="http"){
    $image=$file['image'];
	}else{
    $image=_TAD_PLAYER_IMG_URL.$file['image'];
	}
	
  $play_list="";

  $backcolor=str_replace("#","0x",$xoopsModuleConfig['backcolor']);
  $frontcolor=str_replace("#","0x",$xoopsModuleConfig['frontcolor']);
  $lightcolor=str_replace("#","0x",$xoopsModuleConfig['lightcolor']);
  $screencolor=str_replace("#","0x",$xoopsModuleConfig['screencolor']);
  $skin=empty($skin)?"":"skin:'".XOOPS_URL."/modules/tad_player/class/jw_player/skin/{$skin}/{$skin}.swf',";
  
  
	$main="
	<script type='text/javascript' src='".XOOPS_URL."/modules/tad_player/class/jquery.js'></script>
	<script type='text/javascript' src='".XOOPS_URL."/modules/tad_player/class/jw_player/swfobject.js'></script>
	<script type='text/javascript'>
	var player{$sn} = null;
	$(document).ready(function(){
	    createPlayer{$sn}();
	});

	function addlog(title,log_time) {
	 $.ajax({
	   type: 'POST',
	   url: 'addlog.php',
	   data: 'title='+title+'&log_time='+log_time
	 });
	}

	function playerReadyCallback{$sn}(obj) {
		player{$sn} = document.getElementById(obj['id']);
		player{$sn}.addModelListener( 'STATE', 'stateMonitor' );
	};

	function showtime(){
	  now = new Date();
		setTimeout('showtime()',1000);
		return now.getTime();
	}

	function stateMonitor( obj ){
		if(obj.newstate == 'COMPLETED'){
		  addlog('stop',showtime());
		}else if(obj.newstate == 'PLAYING'){
		  addlog('start',showtime());
		}else if(obj.newstate == 'PAUSED'){
		  addlog('paus',showtime());
		}
	}


	function createPlayer{$sn}() {
		var flashvars = {
			file:'{$media}',
			$pic
			$width_js
			$height_js
			$dl
			$skin
			autostart:'{$autostart}',
			playerready:'playerReadyCallback{$sn}',
			backcolor:'{$backcolor}',
			frontcolor:'{$frontcolor}',
			lightcolor:'{$lightcolor}',
			screencolor:'{$screencolor}'
		}

		var params = {
			allowfullscreen:'true',
			allowscriptaccess:'always'
		}

		var attributes = {
			id:'player{$sn}',
			name:'player{$sn}'
		}


		swfobject.embedSWF('"._TAD_PLAYER_UPLOAD_URL."mediaplayer.swf', 'placeholder{$sn}', '{$all_width}', '{$all_height}', '9', false, flashvars, params, attributes);
	}

	</script>
	<div id='placeholder{$sn}'><a href='http://www.adobe.com/go/getflashplayer'>Get flash</a></div>";
	return $main;
}


//製作防盜連檔案
if($xoopsModuleConfig['prevent_hotlinking']=='1'){
	mk_htaccess();
}elseif($xoopsModuleConfig['prevent_hotlinking']=='0' and file_exists(_TAD_PLAYER_UPLOAD_DIR.".htaccess")){
	unlink(_TAD_PLAYER_UPLOAD_DIR.".htaccess");
}

//取得路徑
function get_pcsn_path($pcsn=""){
	global $xoopsDB;

	$sql = "select title,of_csn from ".$xoopsDB->prefix("tad_player_cate")." where pcsn='{$pcsn}'";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error()."<br>".$sql);
	list($title,$of_csn)=$xoopsDB->fetchRow($result);

	$pre_title=(!empty($of_csn))?get_pcsn_path($of_csn):"";

	$path=$pre_title." / ".$title;
	
	return $path;
}

//熱門影片
function hot_media(){
	global $xoopsDB,$xoopsModule,$xoopsModuleConfig;

	$sql = "select a.psn,a.pcsn,a.title,a.counter,b.title from ".$xoopsDB->prefix("tad_player")." as a left join ".$xoopsDB->prefix("tad_player_cate")." as b on a.pcsn=b.pcsn order by a.counter desc limit 0,10";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	$i=0;
	while(list($psn,$pcsn,$title,$counter,$cate_title)=$xoopsDB->fetchRow($result)){
    $hot_media[$i]['psn']=$psn;
    $hot_media[$i]['title']=$title;
    $hot_media[$i]['counter']=$counter;
    $i++;
	}
	return $hot_media;
}

//製作防盜連設定
function mk_htaccess(){
  global $xoopsDB,$xoopsModule,$xoopsConfig,$xoopsModuleConfig;


	$allow_hotlinking=explode(";",$xoopsModuleConfig['allow_hotlinking']);

  $main="SetEnvIfNoCase Referer \"^".XOOPS_URL."(/|$)\" allowed=1
";

  foreach($allow_hotlinking as $url){
    $main.="SetEnvIfNoCase Referer \"^{$url}(/|$)\" allowed=1
";
	}

  $main.="SetEnvIfNoCase Referer \"^$\" allowed=1

<FilesMatch \".(xml|XML|flv|FLV|mp3|MP3|mp4|MP4|m4v|M4V|swf|SWF)\">　
 Order Allow,Deny
 Allow from env=allowed
</FilesMatch>";


  $filename =_TAD_PLAYER_UPLOAD_DIR.".htaccess";

  if (!$handle = fopen($filename, 'w')) {
    redirect_header($_SERVER['PHP_SELF'],3, sprintf(_MA_TADPLAYER_CANT_OPEN,$filename));
  }

  if (fwrite($handle, $main) === FALSE) {
    redirect_header($_SERVER['PHP_SELF'],3, sprintf(_MA_TADPLAYER_CANT_WRITE,$filename));
  }
  fclose($handle);

}

//新增資料到tad_player_cate中
function add_tad_player_cate(){
	global $xoopsDB,$xoopsModuleConfig;
	if(empty($_POST['new_pcsn']))return;
  $width=$xoopsModuleConfig['width'];
  $height=$xoopsModuleConfig['height'];
	$enable_group=implode(",",$_POST['enable_group']);
	$sql = "insert into ".$xoopsDB->prefix("tad_player_cate")." (of_csn,title,enable_group,sort,width,height) values('{$_POST['pcsn']}','{$_POST['new_pcsn']}','','0','{$width}','{$height}')";
	$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	//取得最後新增資料的流水編號
	$pcsn=$xoopsDB->getInsertId();
	return $pcsn;
}

//分類選單
function cate_select($pcsn=0,$size=20){
	$cate_select=get_tad_player_cate_option(0,0,$pcsn);

	$select="<select name='pcsn' size='{$size}' onChange=\"window.location.href='{$_SERVER['PHP_SELF']}?pcsn=' + this.value\">
	$cate_select
	</select>";

	return $select;
}



//取得所有類別標題
function tad_player_get_all_news_cate($of_csn=0,$code="big5"){
	global $xoopsDB;
	$sql = "select pcsn,title,enable_group from ".$xoopsDB->prefix("tad_player_cate")." where of_csn='{$of_csn}' order by sort";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());


	$option="";
	while(list($pcsn,$title,$enable_group)=$xoopsDB->fetchRow($result)){
		$have_sub=tad_player_chk_cate_have_sub($pcsn);
		if($code=="utf8")$title=to_utf8($title);
		$option.="<li><a href='index.php?pcsn=$pcsn'>$title</a>";
		if($have_sub){
				$option.="\n<ul>\n";
				$option.="<li parentId='$pcsn'><a href='#'>Loading</a></li>";
				$option.="\n</ul>\n";
			}
		$option.="</li>";

	}
	return $option;
}


//檢查有無子選項
function tad_player_chk_cate_have_sub($pcsn=0){
	global $xoopsDB;
	$sql = "select pcsn from ".$xoopsDB->prefix("tad_player_cate")." where of_csn='{$pcsn}'";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, _MA_TADNEW_DB_SELECT_ERROR1);
	while(list($sub_pcsn)=$xoopsDB->fetchRow($result)){
		if(!empty($sub_pcsn))return true;
	}
	return false;
}


//做縮圖
function thumbnail($filename="",$thumb_name="",$type="image/jpeg",$width="100"){

	ini_set('memory_limit', '50M');
	// Get new sizes
	list($old_width, $old_height) = getimagesize($filename);

	$percent=($old_width>$old_height)?round($width/$old_width,2):round($width/$old_height,2);

	$newwidth = ($old_width>$old_height)?$width:$old_width * $percent;
	$newheight = ($old_width>$old_height)?$old_height * $percent:$width;

	// Load
	$thumb = imagecreatetruecolor($newwidth, $newheight);
	if($type=="image/jpeg" or $type=="image/jpg" or $type=="image/pjpg" or $type=="image/pjpeg"){
		$source = imagecreatefromjpeg($filename);
		$type="image/jpeg";
	}elseif($type=="image/png"){
		$source = imagecreatefrompng($filename);
		$type="image/png";
	}elseif($type=="image/gif"){
		$source = imagecreatefromgif($filename);
		$type="image/gif";
	}

	// Resize
	imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $old_width, $old_height);

  header("Content-type: image/png");
	imagepng($thumb,$thumb_name);
/*
	// Content type
 	header("Content-type: ".$type);
	// Output
	if($type=="image/jpeg" or $type=="image/jpg" or $type=="image/pjpg" or $type=="image/pjpeg"){
		imagejpeg($thumb,$thumb_name,90);
	}elseif($type=="image/png"){
		imagepng($thumb,$thumb_name);
	}elseif($type=="image/gif"){
		imagegif($thumb,$thumb_name);
	}
*/
	return;
	exit;
}

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


//判斷某人在哪些類別中有觀看的權利
function chk_cate_power(){
	global $xoopsDB,$xoopsUser,$xoopsModule;
	if(!empty($xoopsUser)){
	  $module_id = $xoopsModule->getVar('mid');
	  $isAdmin=$xoopsUser->isAdmin($module_id);
		if($isAdmin){
	    $ok_cat[]="";
		}
		$user_array=$xoopsUser->getGroups();
	}else{
    $user_array=array(3);
    $isAdmin=0;
	}


	$sql = "select pcsn,enable_group from ".$xoopsDB->prefix("tad_player_cate")."";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

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

	return $ok_cat;
}


//取得分類下拉選單
function get_tad_player_cate_option($of_csn=0,$level=0,$v="",$show_dot='1',$optgroup=true,$chk_view='1'){
	global $xoopsDB;
	$dot=($show_dot=='1')?str_repeat(_MD_TADPLAYER_BLANK,$level):"";
	$level+=1;
	
	$sql = "select count(*),pcsn from ".$xoopsDB->prefix("tad_player")." group by pcsn";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	while(list($count,$pcsn)=$xoopsDB->fetchRow($result)){
	  $cate_count[$pcsn]=$count;
	}
	
	$option=($of_csn)?"":"<option value='0'>"._MA_TADPLAYER_CATE_SELECT."</option>";
	$sql = "select pcsn,title from ".$xoopsDB->prefix("tad_player_cate")." where of_csn='{$of_csn}' order by sort";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());


  if($chk_view)$ok_cat=chk_cate_power();
	while(list($pcsn,$title)=$xoopsDB->fetchRow($result)){
	
	  if($chk_view){
			if(!in_array($pcsn,$ok_cat)){
			  continue;
			}
		}
	
		$selected=($v==$pcsn)?"selected":"";
	  if(empty($cate_count[$pcsn]) and $optgroup){
			$option.="<optgroup label='{$title}' style='font-style: normal;color:black;'>".get_tad_player_cate_option($pcsn,$level,$v,"0")."</optgroup>";
		}else{
		  $counter=(empty($cate_count[$pcsn]))?0:$cate_count[$pcsn];
      $option.="<option value='{$pcsn}' $selected >{$dot}{$title} ($counter)</option>";
      $option.=get_tad_player_cate_option($pcsn,$level,$v,$show_dot,$optgroup,$chk_view);
		}
	  
		
		
	}
	return $option;
}

//取得tad_player_cate所有資料陣列
function get_tad_player_cate_all(){
	global $xoopsDB;
	$sql = "select pcsn,title from ".$xoopsDB->prefix("tad_player_cate");
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
	while(list($pcsn,$title)=$xoopsDB->fetchRow($result)){
    $data[$pcsn]=$title;
	}
	return $data;
}

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

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



//計數器
function add_counter($psn=""){
	global $xoopsDB;
	$sql = "update ".$xoopsDB->prefix("tad_player")." set `counter` = `counter` + 1 where psn='{$psn}'";
	$xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
}



//製作播放清單
function mk_list_xml($pcsn=""){
  global $xoopsDB,$xoopsModule,$upload_dir;

  
	$cate=get_tad_player_cate($pcsn);

	$sql = "SELECT * FROM ".$xoopsDB->prefix("tad_player")." WHERE `pcsn`='{$pcsn}' order by sort";
	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());


  $main="<playlist version=\"1\" xmlns=\"http://xspf.org/ns/0/\">
	<title>{$cate['title']}</title>
	<info>http:/xspf.org/xspf-v1.html</info>
	<trackList>\n";

  while($midia=$xoopsDB->fetchArray($result)){
    foreach($midia as $k=>$v){
			$$k=$v;
		}

    $title=htmlspecialchars($title);
    $creator=htmlspecialchars($creator);
    
    //$location=urlencode($location);
    if(substr($image,0,4)=="http"){
	    $image=$image;
		}else{
	    $image=_TAD_PLAYER_IMG_URL.$image;
		}
	
    $image=(empty($image))?"":"\n<image>$image</image>";

    
    if(empty($location) and !empty($youtube)){
	    $media=$youtube;
		}elseif(substr($location,0,4)=='http'){
	    $media=$location;
		}else{
	    $media=_TAD_PLAYER_FLV_URL."{$psn}_{$location}";
		}
		


    if(substr($post_date,0,2)=='20')$post_date=strtotime($post_date);
    $post_date=date("Y-m-d H:i:s",xoops_getUserTimestamp($post_date));
    $main.="	<track>
			<title>{$title}</title>
      <creator>{$creator}".sprintf(_MA_TADPLAYER_SHOW_DATE,$post_date)."</creator>
			<location>$media</location>
			$image
			<info>".XOOPS_URL."/modules/tad_player/play.php?psn=$psn</info>
		</track>\n";

  }
  $main.="</trackList>
</playlist>\n";

	$main=to_utf8($main);

  $filename =_TAD_PLAYER_UPLOAD_DIR."{$pcsn}_list.xml";

  if (!$handle = fopen($filename, 'w')) {
    redirect_header($_SERVER['PHP_SELF'],3, sprintf(_MA_TADPLAYER_CANT_OPEN,$filename));
  }

  if (fwrite($handle, $main) === FALSE) {
    redirect_header($_SERVER['PHP_SELF'],3, sprintf(_MA_TADPLAYER_CANT_WRITE,$filename));
  }
  fclose($handle);
}

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

if(!function_exists("is_utf8")){
	//判斷字串是否為utf8
	function  is_utf8($str)  {
	    $i=0;
	    $len  =  strlen($str);

	    for($i=0;$i<$len;$i++)  {
	        $sbit  =  ord(substr($str,$i,1));
	        if($sbit  <  128)  {
	            //本字節為英文字符，不與理會
	        }elseif($sbit  >  191  &&  $sbit  <  224)  {
	            //第一字節為落於192~223的utf8的中文字(表示該中文為由2個字節所組成utf8中文字)，找下一個中文字
	            $i++;
	        }elseif($sbit  >  223  &&  $sbit  <  240)  {
	            //第一字節為落於223~239的utf8的中文字(表示該中文為由3個字節所組成的utf8中文字)，找下一個中文字
	            $i+=2;
	        }elseif($sbit  >  239  &&  $sbit  <  248)  {
	            //第一字節為落於240~247的utf8的中文字(表示該中文為由4個字節所組成的utf8中文字)，找下一個中文字
	            $i+=3;
	        }else{
	            //第一字節為非的utf8的中文字
	            return  0;
	        }
	    }
	    //檢查完整個字串都沒問體，代表這個字串是utf8中文字
	    return  1;
	}
}
/********************* 預設函數 *********************/
//圓角文字框
function div_3d($title="",$main="",$kind="raised",$style="",$bgcolor="white"){

	$h1=(empty($title))?"":"<h1>$title</h1>";

	$main="<table style='width:auto;{$style}'><tr><td>
	<div class='{$kind}'>
	$h1
	<b class='b1'></b><b class='b2' style='background-color:$bgcolor'></b><b class='b3' style='background-color:$bgcolor'></b><b class='b4' style='background-color:$bgcolor'></b>
	<div class='boxcontent' style='background-color:$bgcolor'>
 	$main
	</div>
	<b class='b4b' style='background-color:$bgcolor'></b><b class='b3b' style='background-color:$bgcolor'></b><b class='b2b' style='background-color:$bgcolor'></b><b class='b1b'></b>
	</div>
	</td></tr></table>";
	return $main;
}


//管理介面的選單
function menu_interface($show=1){
global $xoopsModule,$xoopsModuleConfig;
	if(empty($show))return;
	$dirname=$xoopsModule->getVar('dirname');
	include_once("".XOOPS_ROOT_PATH."/modules/{$dirname}/language/tchinese/modinfo.php");
	include("menu.php");
	$page=explode("/",$_SERVER['PHP_SELF']);
	$n=sizeof($page)-1;
	if(is_array($adminmenu)){
		foreach($adminmenu as $m){
			$td.="<a href='".XOOPS_URL."/modules/{$dirname}/{$m['link']}'>{$m['title']}</a>";
		}
	}else{
		$td="<td></td>";
	}
	$main="
	<style type='text/css'>
	#admtool{
		margin-bottom:10px;
	}
	#admtool a:link, #admtool a:visited {
		font-size: 12px;
		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;
	}
	#admtool 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='admtool'>{$td}<a href='".XOOPS_URL."/modules/{$dirname}/'>"._BACK_MODULES_PAGE."</a>
	</div>";
	return $main;
}

//首頁的連結工具
function toolbar($interface_menu=array(),$bgcolor="#F0F0F0"){
	global $xoopsModule,$xoopsModuleConfig,$xoopsUser,$interface_menu_pic;
	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_link="index.php";

			
			$admin_tools="<a href='".XOOPS_URL."/modules/{$dirname}/admin/{$admin_link}' style='text-decoration: none;'><img src='images/admin.png' alt='"._TO_ADMIN_PAGE."' title='"._TO_ADMIN_PAGE."' hspace=2 onMouseOut='this.src=\"images/admin.png\"' onMouseOver='this.src=\"images/admin2.png\"'></a>";
		}
	}
	if(is_array($interface_menu)){
		foreach($interface_menu as $title => $url){
			$td.="<a href='".XOOPS_URL."/modules/{$dirname}/{$url}' style='text-decoration: none;'><img src='images/{$interface_menu_pic[$title]}.png' alt='{$title}' title='{$title}'  hspace=2  style='text-decoration: none;' onMouseOut=\"this.src='images/{$interface_menu_pic[$title]}.png'\" onMouseOver=\"this.src='images/{$interface_menu_pic[$title]}2.png'\"></a>";
		}
	}else{
		return;
	}

	$main="
	<table style='width:auto;padding:0px;border:0px;border-collapse: collapse;margin-bottom:3px;'>
	<tr><td style='width:5px;height:38px;padding:0px;'><img src='".XOOPS_URL."/modules/{$dirname}/images/3d_div_left.gif' alt='3d_div_left.gif, 99B' title='3d div left' border='0' height='38' width='5'></td>
	<td background='".XOOPS_URL."/modules/{$dirname}/images/3d_div_body.gif' style='vertical-align:middle;'>
	{$td}{$admin_tools}
	</td><td style='width:5px;height:38px;padding:0px;'><img src='".XOOPS_URL."/modules/{$dirname}/images/3d_div_right.gif' alt='3d_div_right.gif, 82B' title='3d div right' border='0' height='38' width='5'></td>
	</tr></table>";
	
	
	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='"._BP_BACK_PAGE."' align='absmiddle' hspace=3>"._BP_BACK_PAGE;
		$this->next = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/1rightarrow.gif' alt='"._BP_NEXT_PAGE."' align='absmiddle' hspace=3>"._BP_NEXT_PAGE;
		$this->first = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/2leftarrow.gif' alt='"._BP_FIRST_PAGE."' align='absmiddle' hspace=3>"._BP_FIRST_PAGE;
		$this->last = "<img src='".XOOPS_URL."/modules/{$mydirname}/images/2rightarrow.gif' alt='"._BP_LAST_PAGE."' align='absmiddle' hspace=3>"._BP_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='"._BP_BACK_PAGE."'>{$this->prev}</a> ";
			$bar_first = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}=1{$loadtime}' title='"._BP_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='"._BP_NEXT_PAGE."'>{$this->next}</a> ";
			$bar_last = " <a href='{$_SERVER['PHP_SELF']}{$this->query_str}{$this->glue}{$this->url_page}={$this->pTotal}{$loadtime}' title='"._BP_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,_BP_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,_BP_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;
	}

}

?>
