<?php
//  ------------------------------------------------------------------------ //
// 本模組由 tad 製作
// 製作日期：2007-11-04
// $Id: newspaper.php,v 1.3 2008/06/25 06:35:58 tad Exp $
// ------------------------------------------------------------------------- //

/*-----------引入檔案區--------------*/
include_once "admin_header.php";

/*-----------function區--------------*/


//找出現有電子報
function newspaper_set_table($sel_nps_sn=""){
        global $xoopsDB;

        //找出現有設定組
        $sql = "select nps_sn,title from ".$xoopsDB->prefix("tad_news_paper_setup")."";
        $result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
        while(list($nps_sn,$title)=$xoopsDB->fetchRow($result)){
          $selected=($sel_nps_sn==$nps_sn)?"selected":"";
                $option.="<option value='{$nps_sn}' $selected>$title</option>";
        }
        if(empty($option))return ;

        $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.nps_sn='{$sel_nps_sn}' order by a.np_date desc";
/*
        //PageBar(資料數, 每頁顯示幾筆資料, 最多顯示幾個頁數選項);
        $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, _MA_TADNEW_DB_SELECT_ERROR2);
        $total=$xoopsDB->getRowsNum($result);

        $navbar = new PageBar($total, 20, 10);
        $mybar = $navbar->makeBar();
        $bar= sprintf(_MD_TADNEW_TOOLBAR,$mybar['total'],$mybar['current'])."{$mybar['left']}{$mybar['center']}{$mybar['right']}";
        $sql.=$mybar['sql'];
*/
  $bar="";
        $result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());


        $main="
        <script>
        function delete_tad_newspaper_set(){
                var sure = window.confirm('"._MD_TADNEW_SURE_DEL."');
                if (!sure)        return;
                location.href=\"{$_SERVER['PHP_SELF']}?op=del_newspaper_set&nps_sn={$sel_nps_sn}\";
        }
        function delete_tad_newspaper(npsn){
                var sure = window.confirm('"._MD_TADNEW_SURE_DEL."');
                if (!sure)        return;
                location.href=\"{$_SERVER['PHP_SELF']}?op=del_newspaper&npsn=\" + npsn;
        }
        </script>
        <form action='{$_SERVER['PHP_SELF']}' id='newspaper_set' method='post'>



        <select name='nps_sn' id='nps_sn' onChange=\"window.location.href='{$_SERVER['PHP_SELF']}?nps_sn='+this.value \"><option value=''>"._MA_TADNEW_NP_OPTION."</option>$option</select>
        ";

        //修改按鈕
        if(!empty($sel_nps_sn)){
                $main.="
                <input type='hidden' name='mode' value='modify'>
                <input type='submit' value='"._MA_TADNEW_NP_MODIFY."'>
                ";
        }

        //刪除按鈕
        if(!empty($sel_nps_sn) and empty($total)){
                $main.="
                <input type='button' value='"._MA_TADNEW_NP_DEL."'  onClick='delete_tad_newspaper_set()'>";
        }elseif(!empty($sel_nps_sn)){
                $main.=sprintf(_MA_TADNEW_NP_DEL_DESC,$total);
        }else{
                $main.="";
        }

        $main.="</form>
        <table id='tbl'>
        <tr><td colspan=3>$bar</td></tr>
        <tr><th>"._MA_TADNEW_NP_TITLE."</th><th>"._MA_TADNEW_NP_DATE."</th><th>"._MA_TADNEW_FUNCTION."</th></tr>";


        while(list($allnpsn,$number,$title,$np_date)=$xoopsDB->fetchRow($result)){
                        $main.="<tr><td><a href='../newspaper.php?npsn={$allnpsn}'>{$title}".sprintf(_MA_TADNEW_NP_NUMBER_INPUT,$number)."</a></td><td>{$np_date}</td><td><a href='newspaper.php?op=edit_newspaper&npsn={$allnpsn}'>"._MA_TADNEW_EDIT."</a> | <a href=\"javascript:delete_tad_newspaper($allnpsn);\">"._MA_TADNEW_DEL."</a></td></tr>";
        }
        $main.="<!--tr><td colspan=3>$bar</td></tr--></table>";

        return $main;
}


//選擇佈景
function newspaper_themes($themes=""){

        if (is_dir(_TADNEWS_NSP_THEMES_PATH)) {
                if ($dh = opendir(_TADNEWS_NSP_THEMES_PATH)) {
                  $select="<select name='themes'>";
                        while (($file = readdir($dh)) !== false) {
                          if($file=="." or $file=="..")continue;
                          if(is_dir(_TADNEWS_NSP_THEMES_PATH."/".$file)){
                            $selected=($themes==$file)?"selected":"";
                                        $select.="<option value='$file' $selected>$file</option>";
                                }
                        }
                        $select.="</select>";
                        closedir($dh);
                }
        }
        return $select;
}

//建立電子報
function open_newspaper($mode="",$nps_sn=""){
        global $xoopsDB,$xoopsModule,$xoopsUser,$xoopsConfig;


        $newspaper_list=(empty($mode))?newspaper_set_table($_GET['nps_sn']):"";

        if(!empty($mode) or empty($newspaper_list)){

          $hidden=(empty($nps_sn))?"":"<input type='hidden' name='nps_sn' value='{$nps_sn}'>";
          $set=(empty($nps_sn))?array():get_newspaper_set($nps_sn);

                $nps_theme=newspaper_themes($set['themes']);


                $np_title=(empty($nps_sn))?"$xoopsConfig[sitename]"._MA_TADNEW_NP:$set['title'];

                $author=$xoopsUser->getVar('uname');

                $head=(empty($nps_sn) or empty($set['head']))?sprintf(_MA_TADNEW_NP_HEAD_CONTENT,$xoopsConfig['sitename'],XOOPS_URL):$set['head'];

                $foot=(empty($nps_sn) or empty($set['foot']))?sprintf(_MA_TADNEW_NP_FOOT_CONTENT,$author,XOOPS_URL,$xoopsConfig['sitename'],$xoopsConfig['sitename'],$xoopsConfig['adminmail'],$xoopsConfig['adminmail'],XOOPS_URL,XOOPS_URL):$set['foot'];

                include_once(XOOPS_ROOT_PATH."/class/xoopsformloader.php");
                include_once(XOOPS_ROOT_PATH."/class/xoopseditor/xoopseditor.php");

                // text render : use xoopseditor
                $editor_configs = array();
                $editor_configs["name"] ="head";
                $editor_configs["value"] = $head;
                $editor_configs["width"] = "100%";
                $editor_configs["height"] = "300px";
                $editor_configs["rows"] = 35;
                $editor_configs["cols"] = 200;
                $editor_configs['editor'] = $GLOBALS["xoopsModuleConfig"]['form_editor'];

                $editor = new XoopsFormEditor("", "head", $editor_configs);
                $head_editor = $editor->render();

                $editor_configs = array();
                $editor_configs["name"] ="foot";
                $editor_configs["value"] = $foot;
                $editor_configs["width"] = "100%";
                $editor_configs["height"] = "300px";
                $editor_configs["rows"] = 35;
                $editor_configs["cols"] = 200;
                $editor_configs['editor'] = $GLOBALS["xoopsModuleConfig"]['form_editor'];

                $editor = new XoopsFormEditor("", "foot", $editor_configs);
                $foot_editor = $editor->render();
                // text render : use xoopseditor
        }

        //找出現有設定組
        $sql = "select nps_sn,title from ".$xoopsDB->prefix("tad_news_paper_setup")." where status='1'";
        $result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

        while(list($nps_sn,$title)=$xoopsDB->fetchRow($result)){
                $option.="<option value='{$nps_sn}'>$title</option>";
        }

        //電子報設定選項
        if(empty($option) or !empty($mode)){
    $selector=="";
    $create="<form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm'>
                <tr><td class='title'>"._MA_TADNEW_NP_THEMES."</td><td>{$nps_theme}</td></tr>
          <tr><td class='title' style='width:150px'>"._MA_TADNEW_NP_TITLE."</td><td style='width:650px'>
                <input type='input' name='title' style='width:100%' value='{$np_title}'></td></tr>
                <tr><td class='title'>"._MA_TADNEW_NP_CONTENT_HEAD."</td><td>$head_editor</td></tr>
                <tr><td class='title'>"._MA_TADNEW_NP_CONTENT_FOOT."</td><td>$foot_editor</td></tr>
          <tr><td class='bar' colspan=2>
          $hidden
          <input type='hidden' name='op' value='save_newspaper_set'>
                <input type='submit' value='"._MA_TADNEW_NP_SUBMIT."'></td><td></tr>";
  }else{
                $selector="
                <tr><td class='title' style='width:150px'>"._MA_TADNEW_NP_SELECT."</td><td>
                <form action='{$_SERVER['PHP_SELF']}' method='post'>
                <select name='nps_sn'>$option</select>
          <input type='hidden' name='op' value='add_newspaper'>
                <input type='submit' value='"._MA_TADNEW_NP_SUBMIT."'></td></tr>
                </form>";
          $create="<tr><td class='title' >"._MA_TADNEW_NP_CREATE."</td><td><input type='button' value='"._MA_TADNEW_NP_SUBMIT."'  onClick=\"window.location.href='{$_SERVER['PHP_SELF']}?mode=create'\"></td></tr>";
        }

        $main="
  <table class='form_tbl'>
        $selector
        $create
  </table>

  </form>";


        $main=div_3d(_MA_TADNEW_NP_STEP1,$main,"corners");
        if(!empty($newspaper_list)){
                $main.=div_3d(_MA_TADNEW_NP_LIST,$newspaper_list,"corners");
        }

  return $main;
}


//儲存電子報設定
function save_newspaper_set(){
        global $xoopsDB,$xoopsUser;

        if(empty($_POST['nps_sn'])){
                $sql = "insert into ".$xoopsDB->prefix("tad_news_paper_setup")." (title,head,foot,themes,status) values('{$_POST['title']}','{$_POST['head']}','{$_POST['foot']}','{$_POST['themes']}','1')";
        }else{
                $sql = "update ".$xoopsDB->prefix("tad_news_paper_setup")." set title='{$_POST['title']}',head='{$_POST['head']}',foot='{$_POST['foot']}',themes='{$_POST['themes']}' where nps_sn='{$_POST['nps_sn']}'";
        }
        $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

        //取得最後新增資料的流水編號
        $nps_sn=(empty($_POST['nps_sn']))?$xoopsDB->getInsertId():$_POST['nps_sn'];

        return $nps_sn;
}


//自動抓數字
function get_max_number($nps_sn=""){
        global $xoopsDB;
        $sql = "select max(`number`) from ".$xoopsDB->prefix("tad_news_paper")." where nps_sn='{$nps_sn}'";
        $result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
        list($number)=$xoopsDB->fetchRow($result);
        $max_number=(empty($number))?1:$number+1;
        return $max_number;
}

//選擇電子報內容
function add_newspaper($nps_sn=""){
        global $xoopsDB,$xoopsModule,$xoopsUser;

        $cates=get_all_news_cate();

        $sql = "select * from ".$xoopsDB->prefix("tad_news")." where enable='1' order by start_day desc";
        $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

        $news="
        <select multiple id='select1' style='width:300px;height: 180px;'>";
        while(list($nsn,$ncsn,$news_title,$news_content,$start_day,$end_day,$enable,$uid,$passwd,$enable_group)=$xoopsDB->fetchRow($result)){

                $news.="<option value='{$nsn}'>[{$nsn}][ {$cates[$ncsn]} ] {$news_title}</option>";
        }
        $news.="
        </select>";

        $newspaper_set=get_newspaper_set($nps_sn);

        //自動抓數字
        $number=get_max_number($nps_sn);

  $main="
        <script type='text/javascript' src='".XOOPS_URL."/modules/tadnews/class/jquery.js'>
  </script>
         <script type=\"text/javascript\">
          $().ready(function() {
           $('#add').click(function() {
            return !$('#select1 option:selected').remove().appendTo('#select2');
           });
           $('#remove').click(function() {
            return !$('#select2 option:selected').remove().appendTo('#select1');
           });
          });
         </script>

        <form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm'>
  <table class='form_tbl' style='width:800px'>
  <tr><td class='title' style='width:100px'>"._MA_TADNEW_NP_NUMBER."</td><td>
  {$newspaper_set['title']}".sprintf(_MA_TADNEW_NP_NUMBER_INPUT,"<input type='input' name='number' value='{$number}' size=2>")."
        </td></tr>
        <tr><td class='title'>"._MA_TADNEW_NP_CONTENT."</td><td>
        <div style='float:left;text-align: center;margin: 10px;'>
        $news
        <a href='#' id='add' style='display: block;border: 1px solid #aaa;text-decoration: none;background-color: #fafafa;color: #123456; margin: 12px 2px 12px 2px;clear:both;'>"._MA_TADNEW_NP_ADD." &gt;&gt;</a></div>
        <div style='float:left;text-align: center;margin: 10px;'>
        <select multiple name='toBox[]' id='select2' style='width:300px;height: 180px;'>
        </select> <a href='#' id='remove' style='display: block;border: 1px solid #aaa;text-decoration: none;background-color: #fafafa;color: #123456; margin:  12px 2px 12px 2px;clear:both;'>&lt;&lt; "._MA_TADNEW_NP_REMOVE."</a>
        </div>
        </td></tr>
  <tr><td class='bar' colspan=2>
  <input type='hidden' name='op' value='save_newspaper'>
  <input type='hidden' name='nps_sn' value='{$_REQUEST['nps_sn']}'>
        <input type='submit' value='"._MA_TADNEW_NP_SUBMIT."'></td><td>
  </table>

  </form>
";

        $main=div_3d(_MA_TADNEW_NP_STEP2,$main);
        return $main;
}

//儲存電子報內容
function save_newspaper(){
        global $xoopsDB,$xoopsUser;
  $nsn_array=implode(",",$_POST['toBox']);

        $sql = "insert into ".$xoopsDB->prefix("tad_news_paper")." (`nps_sn`, `number`, `nsn_array`, `np_date`) values('{$_POST['nps_sn']}','{$_POST['number']}','{$nsn_array}',now())";
        $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

        //取得最後新增資料的流水編號
        $npsn=$xoopsDB->getInsertId();

        return $npsn;
}



//【步驟三】編輯電子報
function edit_newspaper($npsn=""){
        global $xoopsDB,$xoopsModule,$xoopsUser;
        $cates=get_all_news_cate();
        $newspaper=get_newspaper($npsn);
        $newspaper_set=get_newspaper_set($newspaper['nps_sn']);



/*
        $head=str_replace('{N}',$newspaper['number'],$newspaper_set['head']);
        $head=str_replace('{D}',date("Y-m-d"),$head);

        $html="
        <link rel='stylesheet' type='text/css' media='screen' href='".XOOPS_URL."/modules/tadnews/module.css' />
  {$head}
        ";
*/
  $html="";

        $sql = "select * from ".$xoopsDB->prefix("tad_news")." where nsn in({$newspaper['nsn_array']})";
        $result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3,  mysql_error());
        while(list($nsn,$ncsn,$news_title,$news_content,$start_day,$end_day,$enable,$uid,$passwd,$enable_group)=$xoopsDB->fetchRow($result)){


                        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;
                        $html.="<h3 class='TadNewsPaper_title'>"._MA_TADNEW_NP_TITLE_L."{$cates[$ncsn]}"._MA_TADNEW_NP_TITLE_R."<a href='".XOOPS_URL."/modules/tadnews/index.php?nsn={$nsn}' target='_blank'>{$news_title}</a></h3>
                        <div class='TadNewsPaper_content'>$news_content</div>
                        <hr class='TadNewsPaper_hr'>";
        }
        //$html.="{$newspaper_set['foot']}";

        include_once(XOOPS_ROOT_PATH."/class/xoopsformloader.php");
        include_once(XOOPS_ROOT_PATH."/class/xoopseditor/xoopseditor.php");
        include_once(XOOPS_ROOT_PATH."/modules/tadnews/class/fckeditor/fckeditor.php") ;
        $oFCKeditor = new FCKeditor('np_content') ;
        $oFCKeditor->BasePath        = XOOPS_URL."/modules/tadnews/class/fckeditor/" ;
        $oFCKeditor->Config['AutoDetectLanguage']=false;
        $oFCKeditor->Config['DefaultLanguage']                = 'zh' ;
        $oFCKeditor->ToolbarSet ='my';
        $oFCKeditor->Width = '100%' ;
        $oFCKeditor->Height = '600' ;
        $oFCKeditor->Value =$html;
        $editor=$oFCKeditor->CreateHtml() ;

        $main="
        <form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm'>
  <table class='form_tbl' style='width:800px'>
  <tr><td colspan=2>$editor</td></tr>
  <tr><td class='bar' colspan=2>
  <input type='hidden' name='npsn' value='{$npsn}'>
  <input type='hidden' name='op' value='save_all'>
        <input type='submit' value='"._MA_TADNEW_NP_SUBMIT."'></td><td>
  </table>

  </form>";

        $main=div_3d(_MA_TADNEW_NP_STEP3,$main);
        return $main;
}

//儲存所有內容
function save_all($npsn=""){
        global $xoopsDB,$xoopsUser;

        $sql = "update ".$xoopsDB->prefix("tad_news_paper")." set np_content='{$_POST['np_content']}' where npsn='{$npsn}'";
        $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());

        return $npsn;
}

//寄信表單
function sendmail_form($npsn=""){
        global $xoopsDB,$xoopsModule,$xoopsUser,$xoopsConfig;
  $newspaper=get_newspaper($npsn);

        //取得郵寄名單
        $sql = "select email from ".$xoopsDB->prefix("tad_news_paper_email")." where nps_sn='{$newspaper['nps_sn']}'";
        $result=$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
        while(list($email)=$xoopsDB->fetchRow($result)){
    $email_array[]=$email;
        }
        $email=implode(" , ",$email_array);

  $main="
          "._MD_TADNEW_MAIL_LIST."<br>
                <form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm'>
                <textarea name='mail_list' style='width:760px;height:150px'>$email</textarea>
                <input type='hidden' name='npsn' value='{$npsn}'>
                <input type='hidden' name='op' value='send_now'>
                <p></p>
                <p align='center'><input type='submit' value='"._MD_TADNEW_SEND_NOW."'></p>
          </form>";
         $main=div_3d(_MA_TADNEW_NP_STEP4,$main);

  $main.="
                <iframe src='{$_SERVER['PHP_SELF']}?op=preview&npsn={$npsn}' style='width:800px;height:480px;border:1px solid gray;clear:both'>
                {$newspaper['np_content']}
                </iframe>
        ";
  return $main;
}


//立即寄出
function send_now($npsn=""){
        global $xoopsConfig;
        $xoopsMailer =& getMailer();
        $xoopsMailer->multimailer->ContentType="text/html";

  $newspaper=get_newspaper($npsn);
        $newspaper_set=get_newspaper_set($newspaper['nps_sn']);
        $subject=$newspaper_set['title'] . sprintf(_MA_TADNEW_NP_NUMBER_INPUT,$newspaper['number']);

        $mail_array=explode(",",$_POST['mail_list']);

        $content=preview_newspaper($npsn);
        $content=str_replace("src=\"/","src=\"".XOOPS_URL."/",$content);

        $headers="";
        $xoopsMailer->addHeaders("MIME-Version: 1.0");


        set_time_limit(0);
        $log="";
        foreach($mail_array as $mail){
          $mail=trim($mail);
                if(empty($mail))continue;

                //mail($mail, $subject, $content, $headers);
    if($xoopsMailer->sendMail($mail, $subject, $content,$headers)){
      $log.="{$mail} "._MD_TADNEW_SEND_OK."<br>";
                }else{
      $log.="{$mail} "._MD_TADNEW_SEND_ERROR."<br>";
                }
        }
        return $log;
}

//刪除電子報
function del_newspaper($npsn=""){
        global $xoopsDB;

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

}

//刪除電子報設定組
function del_newspaper_set($nps_sn=""){
        global $xoopsDB;

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

}


/*-----------執行動作判斷區----------*/
$op = (!isset($_REQUEST['op']))? "main":$_REQUEST['op'];

switch($op){

        case "save_newspaper_set";
        $nps_sn=save_newspaper_set();
        header("location: {$_SERVER['PHP_SELF']}?op=add_newspaper&nps_sn={$nps_sn}");

        //刪除電子報設定組
        case "del_newspaper_set";
        del_newspaper_set($_GET['nps_sn']);
        header("location: {$_SERVER['PHP_SELF']}");

        //編輯資料
        case "add_newspaper";
        $main=add_newspaper($_REQUEST['nps_sn']);
        break;

        case "save_newspaper";
        $npsn=save_newspaper();
        header("location: {$_SERVER['PHP_SELF']}?op=edit_newspaper&npsn={$npsn}");

        //編輯電子報資料
        case "edit_newspaper";
        $main=edit_newspaper($_GET['npsn']);
        break;


        case "save_all";
        save_all($_POST['npsn']);
        header("location: {$_SERVER['PHP_SELF']}?op=sendmail&npsn={$_POST['npsn']}");
        break;

        //刪除電子報
        case "del_newspaper";
        del_newspaper($_GET['npsn']);
        header("location: {$_SERVER['PHP_SELF']}");
        break;

        case "sendmail";
        $main=sendmail_form($_GET['npsn']);
        break;

        case "send_now";
        $main=send_now($_POST['npsn']);
        break;

        case "preview":
        $main=preview_newspaper($_GET['npsn']);
        break;

        default:
        $main=open_newspaper($_REQUEST['mode'],$_REQUEST['nps_sn']);
        break;
}

/*-----------秀出結果區--------------*/
if($op=="preview"){
  echo $main;
}else{
xoops_cp_header();
loadModuleAdminMenu(4);
echo "<link rel='stylesheet' type='text/css' media='screen' href='../module.css' />";
echo $main;
xoops_cp_footer();
}
?>