<?php
//  ------------------------------------------------------------------------ //
// 本模組由 tad 製作
// 製作日期：2008-03-23
// $Id: function.php,v 1.7 2008/05/10 11:46:50 tad Exp $
// ------------------------------------------------------------------------- //
//引入TadTools的函式庫
if(!file_exists(XOOPS_ROOT_PATH."/Frameworks/tadtools/tad_function.php")){
 redirect_header("index.php",3, _TAD_NEED_TADTOOLS);
}
include_once XOOPS_ROOT_PATH."/Frameworks/tadtools/tad_function.php";

define("_TADGAL_UP_FILE_DIR",XOOPS_ROOT_PATH."/uploads/tadgallery/");
define("_TADGAL_UP_FILE_URL",XOOPS_URL."/uploads/tadgallery/");
define("_TADGAL_UP_IMPORT_DIR",_TADGAL_UP_FILE_DIR."upload_pics/");
define("_TADGAL_UP_MP3_DIR",_TADGAL_UP_FILE_DIR."mp3/");
define("_TADGAL_UP_MP3_URL",_TADGAL_UP_FILE_URL."mp3/");


$photo_border=array("none"=>_MA_TADGAL_SHOW_MODE_1,"shadow"=>_MA_TADGAL_SHOW_MODE_2,"curved"=>_MA_TADGAL_SHOW_MODE_3,"instant"=>_MA_TADGAL_SHOW_MODE_4,"edge"=>_MA_TADGAL_SHOW_MODE_5,"slided"=>_MA_TADGAL_SHOW_MODE_6);

$cate_show_mode_array=array("thubm"=>_MA_TADGAL_CATE_SHOW_MODE_1,"3d"=>_MA_TADGAL_CATE_SHOW_MODE_2,"slideshow"=>_MA_TADGAL_CATE_SHOW_MODE_3);

if($xoopsModuleConfig['prevent_hotlinking']=='1'){
  mk_htaccess();
}elseif($xoopsModuleConfig['prevent_hotlinking']=='0' and file_exists(_TADGAL_UP_FILE_DIR.".htaccess")){
  unlink(_TADGAL_UP_FILE_DIR.".htaccess");
}

//製作相簿或相片的外框
function mk_gallery_border($rel="",$url="",$cover_pic="",$title="",$pass=false,$fcsn=""){

  $pass_col=($pass)?"
  <div style='width:100%;text-align:center;position:absolute;bottom:2px;'>
  <form action='{$_SERVER['PHP_SELF']}' method='post'>
  <img src='images/view_lock.gif' alt='view_lock.gif, 1.4kB' title='View lock' border='0' align='absmiddle'>
  <input type='hidden' name='csn' value='{$fcsn}'>
  <input type='password' name='passwd' size=10 style='border:1px solid #000;font-size:10px;'>
  </form>
   </div>":"";

  $data="
  <a $rel href='{$url}'>
    <div style='background-image:url({$cover_pic});border:0px solid transparent;' class='GalleryCate'>
      <div class='GalleryCate_txt'>
  <div style='vertical-align: middle;	text-align:center;border:0px;width:100px;margin:0px auto;padding-top:105px;color:#606060;font-size:11px;'>$title</div>
      </div>
      $pass_col
    </div>
  </a>";
  return $data;
}

//製作防盜連設定
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 \".(png|gif|jpg|PNG|GIF|JPG)\">　
 Order Allow,Deny
 Allow from env=allowed
</FilesMatch>";


  $filename =_TADGAL_UP_FILE_DIR.".htaccess";

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

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

}


//把 bytes 轉換成其他單位
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1024, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
}

function getGps($exifCoord, $hemi) {

    $degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
    $minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
    $seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;

    $flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;

    return $flip * ($degrees + $minutes / 60 + $seconds / 3600 );

}

function gps2Num($coordPart) {

    $parts = explode('/', $coordPart);

    if (count($parts) <= 0)
  return 0;

    if (count($parts) == 1)
  return $parts[0];

    return floatval($parts[0]) / floatval($parts[1]);
}


//上傳者選單
function get_all_author($now_uid=""){
  global $xoopsDB;
  $sql = "select distinct uid from ".$xoopsDB->prefix("tad_gallery")."";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error()."<br>$sql");
  $option="<option value=''>"._MD_TADGAL_ALL_AUTHOR."</option>";
  while(list($uid)=$xoopsDB->fetchRow($result)){

    $uid_name=XoopsUser::getUnameFromId($uid,1);
    if(empty($uid_name)){
      $uid_name=XoopsUser::getUnameFromId($uid,0);
    }

    $selected=($now_uid==$uid)?"selected":"";
    $option.="<option value='{$uid}' $selected>{$uid_name}</option>";
  }
  return $option;
}

//封面圖選單
function get_cover($csn="",$cover=""){
  global $xoopsDB;
  if(empty($csn))return "<option value=''>"._MD_TADGAL_COVER."</option>";

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

  $csn_arr_str=implode(",",$csn_arr);

  $sql = "select sn,dir,filename from ".$xoopsDB->prefix("tad_gallery")." where csn in($csn_arr_str)  order by filename";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error()."<br>$sql");
  //$option="<option value=''>"._MD_TADGAL_COVER."</option>";
  $option="";
  while(list($sn,$dir,$filename)=$xoopsDB->fetchRow($result)){
    $selected=($cover=="small/{$dir}/{$sn}_s_{$filename}")?"selected":"";
    $option.="<option value='small/{$dir}/{$sn}_s_{$filename}' $selected>{$filename}</option>";
  }
  return $option;
}


//取出所有標籤(傳回陣列)
function get_all_tag(){
    $tag_all = array();
  global $xoopsDB;
  $sql = "select tag from ".$xoopsDB->prefix("tad_gallery")." where tag!=''";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error()."<br>$sql");
  while(list($tag)=$xoopsDB->fetchRow($result)){

    $tag_arr=explode(",",$tag);

    foreach($tag_arr as $val){
      $val=trim($val);
      $tag_all[$val]++;
    }
  }
  return $tag_all;
}

//製作標籤勾選單
function tag_select($tag=""){

  $tag_arr=explode(",",$tag);

  $tag_all=get_all_tag();
  $menu="";
  foreach($tag_all as $tag=>$n){
    if(empty($tag))continue;
    $checked=(in_array($tag,$tag_arr))?"checked":"";
    $menu.="<input type='checkbox' name='tag[]' value='{$tag}' $checked>{$tag}
    ";
  }
  return $menu;
}


//變更精選相片狀態
function update_tad_gallery_good($sn="",$v='0'){
  global $xoopsDB;
   $sql = "update ".$xoopsDB->prefix("tad_gallery")." set `good`='{$v}' where sn='{$sn}'";
  $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],10, mysql_error());
}



//找出上一張或下一張
function get_pre_next($csn="",$sn=""){
  global $xoopsDB;
  $sql = "select sn from ".$xoopsDB->prefix("tad_gallery")." where csn='{$csn}' order by photo_sort , post_date";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  $stop=false;
  $pre=0;
  while(list($psn)=$xoopsDB->fetchRow($result)){
    if($stop){
      $next=$psn;
      break;
    }
    if($psn==$sn){
      $now=$psn;
      $stop=true;
    }else{
      $pre=$psn;
     }
  }
  $main['pre']=$pre;
  $main['next']=$next;
  return $main;
}
//取得圖片網址
function get_pic_url($dir="",$sn="",$filename="",$kind="",$path_kind=""){

  $show_path=($path_kind=="dir")?_TADGAL_UP_FILE_DIR:_TADGAL_UP_FILE_URL;

  if($kind=="m"){
    if(is_file(_TADGAL_UP_FILE_DIR."medium/{$dir}/{$sn}_m_{$filename}")){
      return "{$show_path}medium/{$dir}/{$sn}_m_{$filename}";
    }
  }elseif($kind=="s"){
    if(is_file(_TADGAL_UP_FILE_DIR."small/{$dir}/{$sn}_s_{$filename}")){
      return "{$show_path}small/{$dir}/{$sn}_s_{$filename}";
    }elseif(is_file(_TADGAL_UP_FILE_DIR."medium/{$dir}/{$sn}_m_{$filename}")){
      return "{$show_path}medium/{$dir}/{$sn}_m_{$filename}";
    }
  }
  return "{$show_path}{$dir}/{$sn}_{$filename}";
}




//刪除tad_gallery某筆資料資料
function delete_tad_gallery($sn=""){
  global $xoopsDB;

  $pic=get_tad_gallery($sn);

  $sql = "delete from ".$xoopsDB->prefix("tad_gallery")." where sn='$sn'";
  $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());


  if(is_file(_TADGAL_UP_FILE_DIR."small/{$pic['dir']}/{$sn}_s_{$pic['filename']}")){
    unlink(_TADGAL_UP_FILE_DIR."small/{$pic['dir']}/{$sn}_s_{$pic['filename']}");
  }

  if(is_file(_TADGAL_UP_FILE_DIR."medium/{$pic['dir']}/{$sn}_m_{$pic['filename']}")){
    unlink(_TADGAL_UP_FILE_DIR."medium/{$pic['dir']}/{$sn}_m_{$pic['filename']}");
  }

  unlink(_TADGAL_UP_FILE_DIR."{$pic['dir']}/{$sn}_{$pic['filename']}");
  return $pic['csn'];
}


//把檔案大小轉為文字型態
function sizef($size="",$html=true){
  if($size > 1048576){
    $size_txt=($html)?round($size/1048576,1)." <font color=red>MB</font>":round($size/1048576,1)." MB";
  }elseif($size > 1024){
    $size_txt=($html)?round($size/1024,1)." <font color=blue>KB</font>":round($size/1024,1)." KB";
  }else{
    $size_txt=($html)?$size." <font color=gray>Bytes</font>":$size." Bytes";
  }
  return $size_txt;
}

//把字串換成群組
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_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;
}

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

  $col=($kind=="upload")?"enable_upload_group":"enable_group";


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

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

  return $ok_cat;
}


//取得分類下拉選單
function get_tad_gallery_cate_option($of_csn=0,$level=0,$v="",$chk_view=1,$chk_up=0,$this_csn="",$no_self="0"){
  global $xoopsDB,$xoopsUser,$xoopsModule;

  if ($xoopsUser) {
    $module_id = $xoopsModule->getVar('mid');
    $isAdmin=$xoopsUser->isAdmin($module_id);
  }else{
    $isAdmin=false;
  }

  $sql = "select count(*),csn from ".$xoopsDB->prefix("tad_gallery")." group by csn";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  while(list($count,$csn)=$xoopsDB->fetchRow($result)){
    $cate_count[$csn]=$count;
  }

  //$left=$level*10;
  $level+=1;

  $syb=str_repeat("-", $level)." ";

  $option=($of_csn)?"":"<option value='0'>"._MA_TADGAL_CATE_SELECT."</option>";
  $sql = "select csn,title from ".$xoopsDB->prefix("tad_gallery_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();
  if($chk_up)$ok_up_cat=chk_cate_power("upload");

  while(list($csn,$title)=$xoopsDB->fetchRow($result)){
    if($chk_view){
      if(!in_array($csn,$ok_cat)){
  continue;
      }
    }
    if($chk_up){
      if(!in_array($csn,$ok_up_cat)){
  continue;
      }
    }
    if($no_self=='1' and $this_csn==$csn)continue;
    $selected=($v==$csn)?"selected":"";
    $count=(empty($cate_count[$csn]))?0:$cate_count[$csn];
    $option.="<option value='{$csn}' $selected>{$syb}{$title}({$count})</option>";
    $option.=get_tad_gallery_cate_option($csn,$level,$v,$chk_view,$chk_up,$this_csn,$no_self);
  }
  return $option;
}



//把多重陣列變成字串
function implodeArray2D ($sep="", $array="",$pre=""){
  $myts =& MyTextSanitizer::getInstance();
  $array1=array("FILE","COMPUTED","IFD0","EXIF","GPS","SubIFD","IFD1","GPSLongitude","GPSLatitude");
  $str = "";
  foreach ($array as $k=>$v){
      if(is_array($v)){
  if(!in_array($k,$array1))continue;
  $str.=implodeArray2D ($sep, $v ,"[$k]");
      }else{
  $k=$myts->addSlashes ($k);
  $v=$myts->addSlashes ($v);
  if(substr($k,0,12)=="UndefinedTag")continue;
  if(strlen($v) > 200)continue;
  $str.= "{$pre}[$k]={$v}{$sep}";
      }
  }
  return $str;
}







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


//自動取得某分類下最大的排序
function auto_get_csn_sort($csn=""){
  global $xoopsDB;
  $sql = "select max(`sort`) from ".$xoopsDB->prefix("tad_gallery_cate")." where of_csn='{$csn}' group by of_csn";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  list($max_sort)=$xoopsDB->fetchRow($result);

  return ++$max_sort;
}


//新增資料到tad_gallery_cate中
function add_tad_gallery_cate($csn="",$new_csn=""){
  global $xoopsDB,$xoopsUser;
  if(empty($new_csn))return;
  $upload_powers=chk_cate_power("upload");
  //身份篩選
  if(!in_array($csn,$upload_powers)){
    redirect_header($_SERVER['PHP_SELF'],3, _TADGAL_NO_UPLOAD_POWER);
  }

  if(empty($_POST['enable_group'])){
    $enable_group="";
  }else{
    $enable_group=implode(",",$_POST['enable_group']);
  }

  if(empty($_POST['enable_upload_group'])){
    $enable_upload_group="1";
  }else{
    $enable_upload_group=implode(",",$_POST['enable_upload_group']);
  }

  $sort=(empty($_POST['sort']))?auto_get_csn_sort():$_POST['sort'];
  $uid=$xoopsUser->getVar('uid');

  $sql = "insert into ".$xoopsDB->prefix("tad_gallery_cate")." (of_csn,title,enable_group,enable_upload_group,mode,sort,uid) values('{$csn}','{$new_csn}','{$enable_group}','{$enable_upload_group}','{$_POST['mode']}','$sort','{$uid}')";
  $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  //取得最後新增資料的流水編號
  $csn=$xoopsDB->getInsertId();
  return $csn;
}


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

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



//輸出為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 photo_name($sn="",$kind="",$local="1"){
  global $xoopsDB;

  $sql = "select filename,dir from ".$xoopsDB->prefix("tad_gallery")." where sn='{$sn}'";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  list($filename,$dir)=$xoopsDB->fetchRow($result);

  $place=($local)?_TADGAL_UP_FILE_DIR:_TADGAL_UP_FILE_URL;

  if($kind=="m"){
    $k="m_";
    $place.="medium/";
  }elseif($kind=="s"){
    $k="s_";
    $place.="small/";
  }else{
    $k="";
  }
  $photo_name="{$place}{$dir}/{$sn}_{$k}{$filename}";
  return $photo_name;
}


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

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

  //檢查是否是180度的相片
  $pic180=(($old_width/$old_height) > 2 and ($old_width/$width) > 2 )?true:false;

  if($pic180){
  $height=$width * 0.75;
  $percent = round($height/$old_height,2);

  $newwidth = round($old_width * $percent,0);
  $newheight = round($old_height * $percent,0);
  }else{
    $percent=($old_width>$old_height)?round($width/$old_width,2):round($width/$old_height,2);

    $newwidth = ($old_width>$old_height)?$width:round($old_width * $percent,0);
    $newheight = ($old_width>$old_height)?round($old_height * $percent,0):$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";
  }else{
    die($type);
  }

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


  // Output
  if($type=="image/jpeg"){
    imagejpeg($thumb,$thumb_name,90);
  }elseif($type=="image/png"){
    imagepng($thumb,$thumb_name);
  }elseif($type=="image/gif"){
    imagegif($thumb,$thumb_name);
  }
  imagedestroy($source);
  imagedestroy($thumb);
}


//圓角文字框
function pic_3d($width=150,$height=150,$main=""){
  $width+=22;
  $height+=22;
  $main="
  <div class='pic_corners' style='width:{$width}px;height:{$height}px;display:inline;float:left'>
  <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>";
  return $main;
}


//取得路徑
function get_cate_path($csn="",$sub=false){
   global $xoopsDB;

 if(!$sub){
    $home[_MD_HOMEPAGE]=XOOPS_URL."/modules/tadgallery/index.php";
 }else{
    $home=array();
 }

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

   $opt_sub=(!empty($of_csn))?get_cate_path($of_csn,true):"";

   if(!empty($title)){
    $opt[$title]=XOOPS_URL."/modules/tadgallery/index.php?csn=$csn";
 }
 if(is_array($opt_sub)){
    $path=array_merge($home,$opt_sub,$opt);
 }elseif(is_array($opt)){
    $path=array_merge($home,$opt);
 }else{
    $path=$home;
 }
   return $path;
}

/********************* 預設函數 *********************/
//圓角文字框
function div_3d($title="",$main="",$kind="raised",$style="",$txt=""){
  $main="<table style='width:auto;{$style}'><tr><td>
  <div class='{$kind}'>
  <h1>$title</h1>$txt
  <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;
}


//製作Media RSS
function mk_rss_xml(){
  global $xoopsDB,$xoopsModule,$xoopsConfig;
  $ok_cat=chk_cate_power();
  $ok=implode("','",$ok_cat);

  $sql = "select a.sn,a.csn,a.title,a.description,a.filename,a.size,a.dir from ".$xoopsDB->prefix("tad_gallery")." as a , ".$xoopsDB->prefix("tad_gallery_cate")." as b where a.csn=b.csn and a.csn in('{$ok}') and b.passwd='' and b.enable_group='' order by a.post_date desc";
  $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error()."<br>$sql");

  $main="<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>
<rss version=\"2.0\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:atom=\"http://www.w3.org/2005/Atom\">
  <channel>
  <atom:icon>".XOOPS_URL."/modules/tadgallery/images/piclen_logo.png</atom:icon>
  <generator>Tad Gallery</generator>
  <title>{$xoopsConfig['sitename']}</title>
  <link>".XOOPS_URL."/modules/tadgallery</link>
  <description></description>\n";

  while(list($sn,$csn,$title,$description,$filename,$size,$dir)=$xoopsDB->fetchRow($result)){

    $title=(empty($title))?$filename:$title;
    $title=htmlspecialchars($title);
    $description=htmlspecialchars($description);
    $filename=htmlspecialchars($filename);
    $pic_url=get_pic_url($dir,$sn,$filename);
    $mpic_url=get_pic_url($dir,$sn,$filename,"m");
    $spic_url=get_pic_url($dir,$sn,$filename,"s");
    $main.="    <item>
      <title>{$title}</title>
      <link>".XOOPS_URL."/modules/tadgallery/view.php?sn={$sn}</link>
      <guid>{$sn}-{$csn}</guid>
      <media:thumbnail url=\"{$spic_url}\"/>
      <media:content url=\"{$pic_url}\" fileSize=\"{$size}\" />
      <media:title type=\"plain\">{$title}</media:title>
      <media:description type=\"plain\">{$description}</media:description>
    </item>\n";

  }
  $main.="      </channel>
</rss>\n";

  $main=to_utf8($main);

  $filename =_TADGAL_UP_FILE_DIR."photos.rss";

  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);

}
?>
