<?php
/**
 * 支付接口
 *
 * @version        $Id: sys_info_mark.php 1 22:28 2010年7月20日Z tianya $
 * @package        DedeCMS.Administrator
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */
require_once(dirname(__FILE__)."/config.php");
require_once(DEDEINC.'/datalistcp.class.php');
CheckPurview('sys_Data');

$dopost = (empty($dopost))? '' : $dopost;
$pid = (empty($pid))? 0 : preg_replace('/[^0-9]/','',$pid);
/*
下面數數組格式的例子:
*/
//一個簡單的[數組<->表單]解析類
/*數組結構應該為:
  array(
    [name]=>array(
        [title]=>'當前表單項的名稱',
        [type]=>'text|select',
        [description]=>'表單內容的介紹說明'
        [iterm]=>'1:使用標準雙接口,使用擔保交易接口', //如果含有":",則前面為value值,後面為顯示內容
        [value]=>'使用擔保交易接口',
    ),
    ...
  )
  使用方法:
  將上述的格式傳入到數組中去,然後進行解析:
  1.聲明類,並創建數組
  $af = new Array2form($config);
  
  2.設置一個表單模板(可選,如果不設置載入默認)
  $af->SetDefaultTpl($templets); $templets:為一個底冊模板文件
  表單模板格式為:
  <p>~title~:~form~<small>~description~</small></p>
  
  3.獲取特定項目表單
  $af->GetIterm('alipay', 1) //1.表示獲取一個默認模板下的完整表單,2.僅獲取一個表單項
  
  4.獲取所有表單內容
  $af->GetAll() //獲取表單所有解析後的內容
  
*/
class Array2form
{
    var $FormArray = array();
    var $ArrFromTPL = '';
    
    function __construct($formarray = array())
    {
        if(count($formarray) > 1)
        {
            $this->FormArray = $formarray;
          //var_dump($this->FormArray);
            $this->SetDefaultTpl();
        }
    }
    
    //析構函數,兼容PHP4
    /*
    function Array2form($formarray = array())
    {
        $this->__construct($formarray);
    }
    */
    
    //獲取一個特定項目的表單
    function GetIterm($itermid = '', $itermtype = 1)
    {
        $reval = $reval_form =  $reval_title = $reval_des = $myformItem = '';
        if(is_array($this->FormArray))
        {
            foreach ($this->FormArray as $key => $val) {
                if($key == $itermid)
                {
                    $reval_title = $val['title'];
                    $reval_des = $val['description'];
                    $reval_form = $this->GetForm($key,$val, $val['type']);
                    //進行模板標籤替換
                    if($itermtype == 1)
                        $reval = preg_replace(array("/~title~/","/~form~/","/~description~/"), 
                                                                array($reval_title, $reval_form, $reval_des), $this->ArrFromTPL);
                    else return $reval_form;    
                }
            }
        } else {
            return FALSE;
        }
        return empty($reval)? '' : $reval;    
    }
    
    function GetForm($key, $formarry = array(), $formtype='text')
    {
        switch ($formtype) 
        {
            case 'text':
                //生成文本編輯框
                $valstr=(empty($formarry['value']))? "value=''" : "value='{$formarry['value']}'";
                $reval_form = "<input type='text' name='{$key}' id='{$key}' style='width:300px' class='text'{$valstr}>";
            break;
            case 'select':
                //生成選擇框
                $reval_title = $formarry['title'];
                $items = explode(',',$formarry['iterm']);
                $reval_form = "<select name='{$key}' class='text'>";
                if(is_array($items))
                {
                    foreach($items as $v)
                    {
                        $v = trim($v);
                        if($v=='') continue;
                        //統一將中文冒號轉為英文
                        $v = str_replace("：", ":", $v);
                        if( preg_match("/[\:]/",$v) )
                        { 
                            list($value, $name) = preg_split('#:#', $v);
                            $reval_form .= ($formarry['value'] == $value)? "<option value='$value' selected>$name</option>\r\n" : "<option value='$value'>$name</option>\r\n";
                        } else {
                            $reval_form .= ($formarry['value'] == $v)? "<option value='$v' selected>$v</option>\r\n" : "<option value='$v'>$v</option>\r\n";
                        }
                    }
                }
                $reval_form .= "</select>\r\n";
            break;
        }
        return $reval_form;
    }
    
    
    //獲取所有的表單內容
    function GetAll()
    {
        $reval=empty($reval)? '' : $reval;    
        if(is_array($this->FormArray))
        {
            foreach ($this->FormArray as $key => $val)
            {
                $reval .= $this->GetIterm($key);
            }
            return $reval;
        }else{
            return FALSE;    
        }
    }
    
    //獲取一個特定項目的表單
    function SetDefaultTpl($tplname = '')
    {
        if(empty($tplname)) 
        {
            $this->ArrFromTPL = '<p>~title~：~form~<small>~description~</small></p>';
        } else {
            if(file_exists($tplname)) $this->ArrFromTPL = file_get_contents($tplname);
          else $this->ArrFromTPL = $tplname;
        }
    }
}
$tplstring = "
            <tr>
              <td height='25' align='center'>~title~：</td>
              <td>~form~ <small>~description~</small></td>
            </tr>
";

//安裝支付接口
if($dopost=='install')
{
    $row = $dsql->GetOne("SELECT * FROM `#@__payment` WHERE id='$pid'");
    if(is_array($row))
    {
        if($cfg_soft_lang == 'utf-8')
        {
            $config_row = AutoCharset(unserialize(utf82gb($row['config'])));
        }else if($cfg_soft_lang == 'gb2312'){
            $config_row = unserialize($row['config']);
        }
        //print_r($config_row);exit;
        $af = new Array2form($config_row);
        $af->SetDefaultTpl($tplstring);
        $reval = $af->GetAll();
    }
    include DedeInclude('templets/sys_payment_install.htm');
    exit;
} 
//配置支付接口
else if($dopost=='config')
{
    if($pay_name=="" || $pay_desc=="" || $pay_fee=="")
    {
        ShowMsg("您有未填寫的項目！","-1");
        exit();
    }
    $row = $dsql->GetOne("SELECT * FROM `#@__payment` WHERE id='$pid'");
    if($cfg_soft_lang == 'utf-8')
    {
        $config = AutoCharset(unserialize(utf82gb($row['config'])));
    }else if($cfg_soft_lang == 'gb2312'){
        $config = unserialize($row['config']);
    }
    $payments = "'code' => '".$row['code']."',";
    foreach ($config as $key => $v)
    {
        $config[$key]['value'] = ${$key};
        $payments .= "'".$key."' => '".$config[$key]['value']."',";
    }
    $payments = substr($payments, 0, -1);
    $payment = "\$payment=array(".$payments.")";
    $configstr = "<"."?php\r\n".$payment."\r\n?".">\r\n";
    if(!empty($payment))
    {
        $m_file = DEDEDATA."/payment/".$row['code'].".php";
        $fp = fopen($m_file,"w") or die("寫入文件 $safeconfigfile 失敗，請檢查權限！");
        fwrite($fp,$configstr);
        fclose($fp);
    }
    if($cfg_soft_lang == 'utf-8')
    {
        $config = AutoCharset($config,'utf-8','gb2312');
        $config = serialize($config);
        $config = gb2utf8($config);
    }else{
        $config = serialize($config);
    }
    
    $query = "UPDATE `#@__payment` SET name = '$pay_name',fee='$pay_fee',description='$pay_desc',config='$config',enabled='1' WHERE id='$pid'";
    $dsql->ExecuteNoneQuery($query);
    if($pm=='edit') $msg="保存修改成功";
    else $msg="安裝成功！";
    ShowMsg($msg, "sys_payment.php");
    exit();
}

//刪除支付接口
else if($dopost=='uninstall')
{
    $row = $dsql->GetOne("SELECT * FROM `#@__payment` WHERE id='$pid'");
    if($cfg_soft_lang == 'utf-8')
    {
        $config = AutoCharset(unserialize(utf82gb($row['config'])));
    }else if($cfg_soft_lang == 'gb2312'){
        $config = unserialize($row['config']);
    }
    foreach ($config as $key => $v) $config[$key]['value']="";
    if($cfg_soft_lang == 'utf-8')
    {
        $config = AutoCharset($config,'utf-8','gb2312');
        $config = serialize($config);
        $config = gb2utf8($config);
    }else{
        $config = serialize($config);
    }
    $query = "UPDATE `#@__payment` SET fee='',config='$config',enabled='0' WHERE id='$pid'";
    $dsql->ExecuteNoneQuery($query);
    //同時需要刪除對應的緩存
    $m_file = DEDEDATA."/payment/".$row['code'].".php";
    @unlink($m_file);
    ShowMsg("刪除成功！", "sys_payment.php");
    exit();
}
$sql = "SELECT * FROM `#@__payment` ORDER BY rank ASC";
$dlist = new DataListCP();
$dlist->SetTemplet(DEDEADMIN."/templets/sys_payment.htm");
$dlist->SetSource($sql);
$dlist->display();