<?php
/*
+-----------------------------------------------------------------------------+
| $Id: sys.class.php 2010-05-24 01:19:04Z Bleakwind $
| System lib
| Copyright (c) 2003-2010 Bleakwind (www.weaverdream.com)
| http://www.weaverdream.com/
| Release under the GNU Lesser General Public License Version 3 (LGPLv3):
|   http://www.gnu.org/licenses/lgpl.html
+-----------------------------------------------------------------------------+
*/

class sys
{
    var $ip                     = "";

    var $get                    = array();
    var $post                   = array();

    var $magic_quotes_gpc       = 0;
    var $nowtime;

    var $channel_info           = array();
    var $channel_path           = array();
    var $channel_list           = array();

    var $channel_all            = array();
    var $channel_upper          = array();
    var $channel_tree           = array();

    var $setmodel_info          = array();
    var $table_list             = array();
    var $field_array            = array();
    var $model_array            = array();

    var $area_array             = array();
    var $area_select            = array();

    // Initialize
    function sys()
    {
        // Return System Configuration
        $this->magic_quotes_gpc = get_magic_quotes_gpc();
        $this->nowtime          = time();

        // Return $_GET and $_POST
        $this->return_get();
        $this->return_post();

        // Return My IP
        $this->return_ip();

        return;
    }

    /*
    +-----------------------------------------------------------------------------+
    | public
    +-----------------------------------------------------------------------------+
    */
    // Standardization url
    function stand_url()
    {
        global $PAGE_PATH;
        $page_http  = $_SERVER['HTTPS'] == "on" ? "https://" : "http://";
        $result     = parse_url(CONFIG_ROOTDIR);
        $account    = $result['user'] != "" ? $result['user'].":".$result['pass']."@" : "";
        $host       = $result['host'];
        $port       = $result['port'] != "" ? ":".$result['port'] : "";
        $url        = $result['scheme']."://".$account.$host.$port.$_SERVER['REQUEST_URI'];
        if ($host.$port != $_SERVER['HTTP_HOST'] || $result['scheme']."://" != $page_http) {
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: ".$url);
            exit;
        }
        return;
    }

    // Return get
    function return_get()
    {
        $return_get = array();
        if ( is_array($_GET) ) {
            foreach ($_GET as $k => $v) {
                if ( is_array($_GET[$k]) ) {
                    while( list($k2, $v2) = each($_GET[$k]) ) {
                        $return_get[$k][$k2] = $this->clean_value($v2,true);
                    }
                } else {
                    $return_get[$k] = $this->clean_value($v,true);
                }
            }
        }
        $this->get = $return_get;

        return $this->get;
    }

    // Return post
    function return_post()
    {
        $return_post = array();
        if ( is_array($_POST) ) {
            foreach ($_POST as $k => $v) {
                if ( is_array($_POST[$k]) ) {
                    while( list($k2, $v2) = each($_POST[$k]) ) {
                        $return_post[$k][ $k2] = $this->clean_value($v2);
                    }
                } else {
                    $return_post[$k] = $this->clean_value($v);
                }
            }
        }
        $this->post = $return_post;

        return $this->post;
    }

    // Clean value
    function clean_value($val, $strip=false)
    {
        if ( $this->magic_quotes_gpc ) {
            $val = stripslashes($val);
        }
        if ($strip === true) {
            $val = strip_tags($val);
            $val = strtolower($val);
            $val = trim($val);
        }

        return $val;
    }

    // Clean variable
    function clean_variable()
    {
        return;
    }

    // Check login
    function check_login($cookie, $message="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $db, $SYSCHECK, $LANGUAGE, $MEMBER;
        $returnurl      = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $login_warning  = $LANGUAGE['s']['_public']['source_lib_sys_class']['login_warning']."<!-- ".$this->get['act']." error for login -->";
        if (in_array($this->get['act'], $SYSCHECK['list_login_member'])) {
            if (!$cookie->iflogin()) {
                $this->prompt("jump", $CONFIGURE['common']['control_index']."?act=login&msg=".htmlentities(urlencode($login_warning))."&ret=".htmlentities(urlencode($returnurl)));
                exit;
            }
        }
        return;
    }

    // Check privilege
    function check_privilege($message="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $db, $SYSCHECK, $LANGUAGE, $MEMBER;
        $returnurl          = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $privileges_warning = $LANGUAGE['s']['_public']['source_lib_sys_class']['privileges_warning']."<!-- ".$this->get['act']." error for privilege -->";
        if (in_array($this->get['act'], $SYSCHECK['list_privilege_member'])) {
            if ($MEMBER['mg_privilege'][$this->get['act']] != "1") {
                $this->prompt("failed", $privileges_warning, $returnurl);
            }
        }
        return;
    }

    // Check fileallow
    function check_fileallow($message="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $db, $SYSCHECK, $LANGUAGE, $MEMBER;
        $returnurl          = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $fileallow_warning  = $LANGUAGE['s']['_public']['source_lib_sys_class']['fileallow_warning']."<!-- ".$this->get['act']." error for fileallow -->";
        if (array_key_exists($this->get['act'], $SYSCHECK['list_fileallow_member'])) {
            if ($MEMBER['mg_fileallow'][$this->get['act']] != "1") {
                $this->prompt("failed", $fileallow_warning, $returnurl);
            }
        }
        return;
    }

    // Set prompt
    function set_prompt($varname="")
    {
        global $db, $prompt_id;
        $str_query = "";
        if (is_array($varname)) {
            foreach ($varname as $k => $v) {
                $str_query .= $k."=".$v.",";
            }
            $str_query = substr($str_query, 0, -1);
        } else {
            $str_query = "prompt_type=null,prompt_if=0,prompt_message=null,prompt_returntext=null,prompt_returnurl=null,prompt_image=null,prompt_act=''";
        }
        $sql = "UPDATE ".DB_TABLE_PROMPT."
                SET ".$str_query."
                WHERE prompt_id='".$prompt_id."'";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
            $return = FALSE;
        } else {
            $return = TRUE;
        }
        return $return;
    }

    // Prompt message
    // jump : function prompt($status="", $url="",     $message="",   $returnurl="",  $image="")
    // other: function prompt($status="", $message="", $returnurl="", $returntext="", $image="")
    function prompt($status="", $message="", $returnurl="", $returntext="", $image="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $db, $LANGUAGE;
        if ($status == "jump") {
            $url       = $message;
            $message   = $returnurl;
            $returnurl = $returntext;
            $this->set_prompt(array(
                'prompt_type'       => "'jump'",
                'prompt_if'         => "1",
                'prompt_message'    => "'".$message."'",
                'prompt_returnurl'  => "'".$returnurl."'",
                'prompt_act'        => "'".$this->get['act']."'",
            ));
            header("location:".$url);
            exit;
            return;
        } elseif ($status == "succeed") {
            $message    = $message    ? $message    : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_succeed'];
            $returnurl  = $returnurl  ? $returnurl  : "javascript:history.back(1)";
            $returntext = $returntext ? $returntext : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_return'];
            $image      = $image      ? $image      : "succeed.gif";
        } elseif ($status == "failed") {
            $message    = $message    ? $message    : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_failed'];
            $returnurl  = $returnurl  ? $returnurl  : "javascript:history.back(1)";
            $returntext = $returntext ? $returntext : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_return'];
            $image      = $image      ? $image      : "failed.gif";
        } else {
            $message    = $message    ? $message    : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_unallowed'];
            $returnurl  = $returnurl  ? $returnurl  : "javascript:history.back(1)";
            $returntext = $returntext ? $returntext : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_return'];
            $image      = $image      ? $image      : "warning.gif";
        }
        $this->set_prompt(array(
            'prompt_type'       => "'prompt'",
            'prompt_if'         => "1",
            'prompt_message'    => "'".$message."'",
            'prompt_returnurl'  => "'".$returnurl."'",
            'prompt_returntext' => "'".$returntext."'",
            'prompt_image'      => "'".$image."'",
            'prompt_act'        => "'prompt'",
        ));
        @header("location:".$CONFIGURE['common']['control_index']."?act=prompt");
        exit;
        return;
    }

    // Prompt message for login member
    // jump : function prompt($status="", $url="",     $message="",   $returnurl="",  $image="")
    // other: function prompt($status="", $message="", $returnurl="", $returntext="", $image="")
    function cp_prompt($status="", $message="", $returnurl="", $returntext="", $image="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $db, $LANGUAGE;
        if ($status == "jump") {
            $url       = $message;
            $message   = $returnurl;
            $returnurl = $returntext;
            $this->set_prompt(array(
                'prompt_type'       => "'jump'",
                'prompt_if'         => "1",
                'prompt_message'    => "'".$message."'",
                'prompt_returnurl'  => "'".$returnurl."'",
                'prompt_act'        => "'".$this->get['act']."'",
            ));
            header("location:".$url);
            exit;
            return;
        } elseif ($status == "succeed") {
            $message    = $message    ? $message    : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_succeed'];
            $returnurl  = $returnurl  ? $returnurl  : "javascript:history.back(1)";
            $returntext = $returntext ? $returntext : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_return'];
            $image      = $image      ? $image      : "succeed.gif";
        } elseif ($status == "failed") {
            $message    = $message    ? $message    : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_failed'];
            $returnurl  = $returnurl  ? $returnurl  : "javascript:history.back(1)";
            $returntext = $returntext ? $returntext : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_return'];
            $image      = $image      ? $image      : "failed.gif";
        } else {
            $message    = $message    ? $message    : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_unallowed'];
            $returnurl  = $returnurl  ? $returnurl  : "javascript:history.back(1)";
            $returntext = $returntext ? $returntext : $LANGUAGE['s']['_public']['source_lib_sys_class']['prompt_return'];
            $image      = $image      ? $image      : "warning.gif";
        }
        $this->set_prompt(array(
            'prompt_type'       => "'cp_prompt'",
            'prompt_if'         => "1",
            'prompt_message'    => "'".$message."'",
            'prompt_returnurl'  => "'".$returnurl."'",
            'prompt_returntext' => "'".$returntext."'",
            'prompt_image'      => "'".$image."'",
            'prompt_act'        => "'cp_prompt'",
        ));
        @header("location:".$CONFIGURE['common']['control_index']."?act=cp_prompt");
        exit;
        return;
    }

    // Return visitor's IP
    function return_ip()
    {
        if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif ($_SERVER['HTTP_CLIENT_IP']) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif ($_SERVER['REMOTE_ADDR']) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = "Unknown";
        }
        $this->ip = trim($ip);

        return $this->ip;
    }

    // Filtrate the IP
    function forbid_ip()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $db, $LANGUAGE, $MEMBER, $t;
        $if_isset_ip = "2";
        if ($this->ip == "") { $this->return_ip(); }
        $ip_part = explode(".", $this->ip);
        $sql = "SELECT *
                FROM ".DB_TABLE_FORBID_IP."
                WHERE (ip1='".$ip_part[0]."' OR ip1='*')
                        AND (ip2='".$ip_part[1]."' OR ip2='*')
                        AND (ip3='".$ip_part[2]."' OR ip3='*')
                        AND (ip4='".$ip_part[3]."' OR ip4='*')
                        AND ((time_begin < ".$this->nowtime." OR time_begin = 0) AND (time_end > ".$this->nowtime." OR time_end = 0) )";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            if ($result->RecordCount() > 0) {
                /*echo "<div align='center'><div style='width:300px;padding: 3px;background-color:#D6DFF7;border:#1151BF 1px solid;font-family:sans-serif;font-size: 11px;'>\n";
                echo "<b>".$LANGUAGE['s']['_public']['source_lib_sys_class']['forbid_ip_message']."</b>\n";
                echo "</div></div>\n";*/
                //exit;
                $if_isset_ip = "1";
            }
        }
        return $if_isset_ip;
    }

    // Return select option
    function return_select($sort)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $select_option = array();
        if (is_array($sort)) {
            $array_select   = $sort;
            $list_select    = implode("','", $array_select);
        } else {
            $array_select   = explode(",", $sort);
            $list_select    = implode("','", $array_select);
        }
        if (!empty($array_select)) {
            $sql = "SELECT id,sort,name,value,if_default
                    FROM ".DB_TABLE_SELECT."
                    WHERE sort IN ('".$list_select."') ORDER BY rank,id";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                while (!$result->EOF) {
                    if (in_array($result->fields['sort'], $array_select)) {
                        $select_option{$result->fields['sort']}[$result->fields['id']] = array(
                            'id'         => $result->fields['id'],
                            'sort'       => $result->fields['sort'],
                            'name'       => $result->fields['name'],
                            'value'      => $result->fields['value'],
                            'if_default' => $result->fields['if_default'],
                        );
                    }
                    $result->MoveNext();
                }
            }
        }
        return $select_option;
    }

    // Return select option
    function return_select_value($id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $return = array();
        if (!empty($id)) {
            $sql = "SELECT name,value
                    FROM ".DB_TABLE_SELECT."
                    WHERE id=".$id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                if (!$result->EOF) {
                    $return['name']     = $result->fields['name'];
                    $return['value']    = $result->fields['value'];
                }
            }
        }
        return $return;
    }

    // search_select_key
    function search_select_key($key, $array)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (is_array($array) && count($array) > 0) {
            foreach($array as $k => $v){
                if ($v['name'] == $key) {
                    return $k;
                }
            }
        }
        return;
    }

    /*
    +-----------------------------------------------------------------------------+
    | private
    +-----------------------------------------------------------------------------+
    */

    // Auto Run
    function auto_run()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        // ...
    }

    // About Member
    // return member
    function return_member($id, $field, $cache="0")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $str_query = "";
        if (is_array($field)) {
            foreach ($field as $v) {
                if($v == "*"){
                    $str_query .= $v.",";
                } else {
                    $str_query .= $v." as m_".$v.",";
                }
            }
            $str_query = substr($str_query, 0, -1);
        } else {
            $str_query = $field;
        }
        if (is_array($id)) {
            foreach($id as $k => $v) {
                $where = $k."='".$v."'";
            }
        } else {
            $where = "id='".$id."'";
        }
        $passport_sql = "SELECT ".$str_query." FROM ".DB_TABLE_MEMBER." WHERE ".$where;
        if ( $cache > 0 ) {
            $db->cacheSecs = $cache;
            $passport_result = &$db->CacheExecute($passport_sql);
        } else {
            $passport_result = &$db->Execute($passport_sql);
        }
        if (!$passport_result) {
            echo $db->ErrorMsg();
            $fields = FALSE;
        } else {
            if (!$passport_result->EOF) {
                $fields = $passport_result->fields;
                $total_record = count($fields)/2;
                for ($i=0;$i<$total_record;$i++) {
                    unset($fields[$i]);
                }
            } else {
                $fields = FALSE;
            }
        }
        $passport_result->Close();
        return $fields;
    }

    // return member group
    function return_member_group($type, $point, $field, $cache="0")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (is_array($field)) {
            $str_query = implode(",", $field);
        } else {
            $str_query = $field;
        }
        $passport_sql = "SELECT ".$str_query." FROM ".DB_TABLE_MEMBER_GROUP."
                         WHERE mg_type='".$type."' AND (mg_point_begin<=".(int)$point." || mg_point_begin IS NULL) AND (mg_point_end>=".(int)$point." || mg_point_end IS NULL)
                         ORDER BY mg_point_begin
                         LIMIT 1";

        if( $cache > 0 ) {
            $db->cacheSecs = $cache;
            $passport_result = &$db->CacheExecute($passport_sql);
        } else {
            $passport_result = &$db->Execute($passport_sql);
        }
        if (!$passport_result) {
            echo $db->ErrorMsg();
            $fields = FALSE;
        } else {
            if (!$passport_result->EOF) {
                $fields = $passport_result->fields;
                $total_record = count($fields)/2;
                for ($i=0;$i<$total_record;$i++) {
                    unset($fields[$i]);
                }
            } else {
                $fields = FALSE;
            }
        }
        $passport_result->Close();
        return $fields;
    }

    // return member info
    function return_member_info($id, $field, $cache="0")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (is_array($field)) {
            $member_field   = explode(",", $field[0]);
            $member_group   = explode(",", $field[1]);
            foreach ($member_field as $v) {
                if($v == "*"){
                    $str_query_member .= "m.".$v.",";
                } else {
                    $str_query_member .= "m.".$v." as m_".$v.",";
                }
            }
            foreach ($member_group as $v) {
                $str_query_member_group .= "mg.".$v.",";
            }
            $str_query = substr($str_query_member.$str_query_member_group, 0, -1);
            if (is_array($id)){
                foreach($id as $k => $v) {
                    $where = $k."='".$v."'";
                }
            } else {
                $where = "id='".$id."'";
            }
            $passport_sql = "SELECT ".$str_query." FROM ".DB_TABLE_MEMBER." m
                             LEFT JOIN ".DB_TABLE_MEMBER_GROUP." mg ON mg.mg_type=m.mg_type AND mg.mg_point_begin<=m.point AND mg.mg_point_end>=m.point
                             WHERE m.".$where."
                             LIMIT 1";
            if( $cache > 0 ) {
                $db->cacheSecs = $cache;
                $passport_result = &$db->CacheExecute($passport_sql);
            } else {
                $passport_result = &$db->Execute($passport_sql);
            }
            if (!$passport_result) {
                echo $db->ErrorMsg();
                $fields = FALSE;
            } else {
                if (!$passport_result->EOF) {
                    $fields = $passport_result->fields;
                    $total_record = count($fields)/2;
                    for ($i=0;$i<$total_record;$i++) {
                        unset($fields[$i]);
                    }
                } else {
                    $fields = FALSE;
                }
            }
        } else {
            $fields = FALSE;
        }
        return $fields;
    }

    // select for database
    function return_member_list($field, $condition="", $orderby="", $limit="", $cache="0")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (is_array($field)) {
            $str_query = implode(",", $field);
        } else {
            $str_query = $field;
        }
        $member_list = array();
        $passport_sql = "SELECT ".$str_query." FROM ".DB_TABLE_MEMBER;
        if (!empty($condition)) {
            $passport_sql .= " WHERE ".$condition;
        }
        if (!empty($orderby)) {
            $passport_sql .= " ORDER BY ".$orderby;
        }
        if (!empty($limit)) {
            $passport_sql .= " LIMIT ".$limit;
        }
        if( $cache > 0 ) {
            $db->cacheSecs = $cache;
            $passport_result = &$db->CacheExecute($passport_sql);
        } else {
            $passport_result = &$db->Execute($passport_sql);
        }
        if (!$passport_result) {
            echo $db->ErrorMsg();
            $member_list = FALSE;
        } else {
            while (!$passport_result->EOF) {
                $fields = $passport_result->fields;
                $member_list[$passport_result->fields[0]] = $fields;
                $passport_result->MoveNext();
            }
        }
        $passport_result->Close();
        return $member_list;
    }

    // check_member_group
    function check_member_group($mid, $time)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $result = false;
        if ($time < $this->nowtime) {
            $update_sql = "UPDATE ".DB_TABLE_MEMBER." SET
                               mg_type                  = '".addslashes($CONFIG['default_group_member'])."',
                               mg_type_expired  = '0'
                           WHERE id=".$mid."";
            $update_result = $db->Execute($update_sql);
            if (!$update_result) {
                echo $db->ErrorMsg();
            } else {
                $result = true;
            }
        }
        return $result;
    }

    // Return sort array
    function return_avatar($avatar_type, $avatar_value)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if ($avatar_value != "") {
            if ($avatar_type == "1" ) {
                $avatar_path = $SETTING['dir_avatar_select']."/".$avatar_value;
            }elseif ($avatar_type == "2" ) {
                $avatar_path = $avatar_value;
            }elseif ($avatar_type == "3" ) {
                $avatar_path = $SETTING['dir_member_attach']."/".$avatar_value;
            }else{
                $avatar_path = "";
            }
        }else{
            $avatar_path = "";
        }
        return $avatar_path;
    }
    //////

    // About Article
    // return_article_info
    function return_article_info($article_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $sql = "SELECT article.*,
                    detail.detail as detail, detail.page_type as detail_page_type, detail.page_word as detail_page_word,
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                FROM ".DB_TABLE_ARTICLE." article
                    LEFT JOIN ".DB_TABLE_ARTICLE_DETAIL." detail ON detail.article_id=article.id
                    LEFT JOIN ".DB_TABLE_ARTICLE_COVER." cover ON cover.article_id=article.id
                WHERE article.id=".$article_id."";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            if (!$result->EOF) {
                $article_info = array(
                        'id'                        => $result->fields['id'],
                        'phrase'                    => $result->fields['phrase'],
                        'phrase_len'                => mb_strwidth($result->fields['phrase'],"UTF-8"),
                        'subject'                   => $result->fields['subject'],
                        'subject_len'               => mb_strwidth($result->fields['subject'],"UTF-8"),
                        'prefix'                    => $result->fields['prefix'],
                        'color'                     => $result->fields['color'],
                        'fontstyle'                 => $result->fields['fontstyle'],
                        'decoration'                => $result->fields['decoration'],
                        'keyword'                   => $result->fields['keyword'],
                        'brief'                     => $result->fields['brief'],
                        'post_id'                   => $result->fields['post_id'],
                        'post_username'             => $result->fields['post_username'],
                        'post_ip'                   => $result->fields['post_ip'],
                        'post_time'                 => $result->fields['post_time'],
                        'amend_id'                  => $result->fields['amend_id'],
                        'amend_username'            => $result->fields['amend_username'],
                        'amend_ip'                  => $result->fields['amend_ip'],
                        'amend_time'                => $result->fields['amend_time'],
                        'click'                     => $result->fields['click'],
                        'if_enable'                 => $result->fields['if_enable'],
                        'if_enable_begin'           => $result->fields['if_enable_begin'],
                        'if_enable_end'             => $result->fields['if_enable_end'],
                        'if_top'                    => $result->fields['if_top'],
                        'if_top_begin'              => $result->fields['if_top_begin'],
                        'if_top_end'                => $result->fields['if_top_end'],
                        'if_turn'                   => $result->fields['if_turn'],
                        'if_turn_type'              => $result->fields['if_turn_type'],
                        'if_turn_url'               => $result->fields['if_turn_url'],

                        'detail'                    => $result->fields['detail'],
                        'page_type'                 => $result->fields['page_type'],
                        'page_word'                 => $result->fields['page_word'],

                        'cover_id'                  => $result->fields['cover_id'],
                        'cover_dir'                 => $result->fields['cover_dir'],
                        'cover_filename'            => $result->fields['cover_filename'],
                );

                $article_info['detail_list']    = explode("[PAGESPLIT]", $article_info['detail']);
                $article_info['detail_num']     = count($article_info['detail_list']);

                $article_info['attach']         = func::db_select(DB_TABLE_ARTICLE_ATTACH, "*", "article_id=".$result->fields['id'], "", "id");
            }
        }
        return $article_info;
    }

    // return_article_list
    function return_article_list($limit="", $condition="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;

        $sql_where      = "";
        $sql_groupby    = "";
        $sql_orderby    = "";
        $sql_limit      = "";

        $article_list   = array();

        if (!empty($condition['article_id'])){
            if (!is_array($condition['article_id'])) {
                $condition['article_id'] = explode(",", $condition['article_id']);
            }
            $condition['article_id'] = func::array_clean($condition['article_id']);
            if (is_array($condition['article_id']) && count($condition['article_id']) > 0){
                if (count($condition['article_id']) > 1){
                    $sql_where .= " AND article.id IN (".implode(",", $condition['article_id']).")";
                } else {
                    $sql_where .= " AND article.id=".implode(",", $condition['article_id'])."";
                }
            }
        }

        if (!empty($condition['except_article_id'])){
            if (!is_array($condition['except_article_id'])) {
                $condition['except_article_id'] = explode(",", $condition['except_article_id']);
            }
            $condition['except_article_id'] = func::array_clean($condition['except_article_id']);
            if (is_array($condition['except_article_id']) && count($condition['except_article_id']) > 0){
                if (count($condition['except_article_id']) > 1){
                    $sql_where .= " AND article.id NOT IN (".implode(",", $condition['except_article_id']).")";
                } else {
                    $sql_where .= " AND article.id!=".implode(",", $condition['except_article_id'])."";
                }
            }
        }

        if ($condition['if_top'] == "1") {
            $sql_where .= " AND ((article.if_top=1) || (article.if_top=3 AND article.if_top_begin<".time()." AND article.if_top_begin>".time()."))";
        }

        if ($condition['cover'] == "1") {
            $sql_where .= " AND cover.filename!=''";
        }

        $sql_where = substr(trim($sql_where), 0, 3) == "AND" ? substr(trim($sql_where), 3) : trim($sql_where);
        $sql_where = $sql_where != "" ? "WHERE ".$sql_where : "";

        if ($condition['click'] == "1"){
            $sql_orderby .= " click DESC,";
        }

        if ($condition['rand'] == "1"){
            $sql_orderby .= " rand(),";
        }

        if ((int)$limit > 0){
            $sql_limit .= " LIMIT ".(int)$limit;
        } else {
            $sql_limit .= " LIMIT ".$CONFIG['page_record_article_list'];
        }

        $sql = "SELECT article.*,
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                FROM ".DB_TABLE_ARTICLE." article
                    LEFT JOIN ".DB_TABLE_ARTICLE_COVER." cover ON cover.article_id=article.id
                ".$sql_where."
                ORDER BY ".$sql_orderby." article.if_top, article.post_time DESC ".$sql_limit;
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $article_list[] = array(
                    'id'                        => $result->fields['id'],
                    'phrase'                    => $result->fields['phrase'],
                    'phrase_len'                => mb_strwidth($result->fields['phrase'],"UTF-8"),
                    'subject'                   => $result->fields['subject'],
                    'subject_len'               => mb_strwidth($result->fields['subject'],"UTF-8"),
                    'prefix'                    => $result->fields['prefix'],
                    'color'                     => $result->fields['color'],
                    'fontstyle'                 => $result->fields['fontstyle'],
                    'decoration'                => $result->fields['decoration'],
                    'keyword'                   => $result->fields['keyword'],
                    'brief'                     => $result->fields['brief'],
                    'post_id'                   => $result->fields['post_id'],
                    'post_username'             => $result->fields['post_username'],
                    'post_ip'                   => $result->fields['post_ip'],
                    'post_time'                 => $result->fields['post_time'],
                    'amend_id'                  => $result->fields['amend_id'],
                    'amend_username'            => $result->fields['amend_username'],
                    'amend_ip'                  => $result->fields['amend_ip'],
                    'amend_time'                => $result->fields['amend_time'],
                    'click'                     => $result->fields['click'],
                    'if_enable'                 => $result->fields['if_enable'],
                    'if_enable_begin'           => $result->fields['if_enable_begin'],
                    'if_enable_end'             => $result->fields['if_enable_end'],
                    'if_top'                    => $result->fields['if_top'],
                    'if_top_begin'              => $result->fields['if_top_begin'],
                    'if_top_end'                => $result->fields['if_top_end'],
                    'if_turn'                   => $result->fields['if_turn'],
                    'if_turn_type'              => $result->fields['if_turn_type'],
                    'if_turn_url'               => $result->fields['if_turn_url'],

                    'cover_id'                  => $result->fields['cover_id'],
                    'cover_dir'                 => $result->fields['cover_dir'],
                    'cover_filename'            => $result->fields['cover_filename'],
                );
                $result->MoveNext();
            }
        }
        return $article_list;
    }

    // return_article_attach_list
    function return_article_attach_list($attach_list, $attach_type, $attach_where, $attach_table, $attach_dir)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $str_js_han     = "";
        $result_str     = "";
        $result_js      = "";
        $filelist       = func::db_select($attach_table, "*", $attach_where, "", "id DESC");
        if (is_array($filelist) && count($filelist) > 0){
            $result_str = "";
            $result_str .= "<table width=\"100%\" cellpadding=\"3\" cellspacing=\"1\" border=\"0\">";
            foreach($filelist as $file){
                $path   = $attach_dir."/".$file['dir'];
                if (file_exists($path.$file['filename'])) {
                    list($width, $height, $type, $attr) = @getimagesize($path.$file['filename']);
                }
                if (preg_match("/^(\.gif|\.jpg|\.png)$/i", substr($file['filename'], -4))){
                    $file_icon = "<img src=\"".CONFIG_ROOTDIR.$path.$file['filename']."\" width=\"45\" height=\"45\" border=\"0\" align=\"absmiddle\">";
                } else {
                    $file_icon = "&nbsp;";
                }
                if ($attach_type == "add") { $file['article_id'] = $MEMBER['id']; }
                $result_str .= "
                  <tr align=\"center\" bgcolor=\"#DEDEDE\">
                    <td width=\"15%\">
                      <span title=\"删除附件\"><img src=\"".$SETTING['dir_images_admin']."/icon_delete.gif\" onclick=\"xajax_attach_del('".$attach_type."','".$file['article_id']."','".$file['id']."','".$attach_list."');\" style=\"cursor:pointer;\" alt=\"删\" /></span>
                      <span title=\"复制附件地址\" id=\"block_attach_".$attach_table."_".$file['id']."\"></span>
                    </td>
                    <td width=\"85%\" align=\"left\"><input type=\"text\" id=\"attach_".$attach_table."_".$file['id']."\" name=\"attach_".$attach_table."_".$file['id']."\" value=\"".$path.$file['filename']."\" onclick=\"this.select();\" class=\"input\" style=\"width:430px;\" /></td>
                  </tr>\n
                  <tr align=\"center\" bgcolor=\"#EEEEEE\">
                    <td width=\"15%\">".$file_icon."</td>
                    <td width=\"85%\" align=\"left\">".$file['brief']."</td>
                  </tr>\n";
                $str_js_han .= "$('#block_attach_".$attach_table."_".$file['id']."').bwcopyer({id: 'attach_".$attach_table."_".$file['id']."', get: 'attach_get', ret: 'attach_ret'});\n";
            }
            $result_str .= "</table>";
            $result_js = "\n$(document).ready(function() {\n".$str_js_han."});\n";
        }
        return array($result_str, $result_js);
    }
    //////

    // About datum
    // return_datum_info
    function return_datum_info($datum_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $sql = "SELECT datum.*,
                    detail.detail as detail, detail.page_type as detail_page_type, detail.page_word as detail_page_word,
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                FROM ".DB_TABLE_DATUM." datum
                    LEFT JOIN ".DB_TABLE_DATUM_DETAIL." detail ON detail.datum_id=datum.id
                    LEFT JOIN ".DB_TABLE_DATUM_COVER." cover ON cover.datum_id=datum.id
                WHERE datum.id=".$datum_id."";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            if (!$result->EOF) {
                $datum_info = array(
                        'id'                        => $result->fields['id'],
                        'phrase'                    => $result->fields['phrase'],
                        'phrase_len'                => mb_strwidth($result->fields['phrase'],"UTF-8"),
                        'subject'                   => $result->fields['subject'],
                        'subject_len'               => mb_strwidth($result->fields['subject'],"UTF-8"),
                        'prefix'                    => $result->fields['prefix'],
                        'color'                     => $result->fields['color'],
                        'fontstyle'                 => $result->fields['fontstyle'],
                        'decoration'                => $result->fields['decoration'],
                        'keyword'                   => $result->fields['keyword'],
                        'brief'                     => $result->fields['brief'],
                        'post_id'                   => $result->fields['post_id'],
                        'post_username'             => $result->fields['post_username'],
                        'post_ip'                   => $result->fields['post_ip'],
                        'post_time'                 => $result->fields['post_time'],
                        'amend_id'                  => $result->fields['amend_id'],
                        'amend_username'            => $result->fields['amend_username'],
                        'amend_ip'                  => $result->fields['amend_ip'],
                        'amend_time'                => $result->fields['amend_time'],
                        'click'                     => $result->fields['click'],
                        'if_enable'                 => $result->fields['if_enable'],
                        'if_enable_begin'           => $result->fields['if_enable_begin'],
                        'if_enable_end'             => $result->fields['if_enable_end'],
                        'if_top'                    => $result->fields['if_top'],
                        'if_top_begin'              => $result->fields['if_top_begin'],
                        'if_top_end'                => $result->fields['if_top_end'],
                        'if_turn'                   => $result->fields['if_turn'],
                        'if_turn_type'              => $result->fields['if_turn_type'],
                        'if_turn_url'               => $result->fields['if_turn_url'],
                        'rank'                      => $result->fields['rank'],

                        'detail'                    => $result->fields['detail'],
                        'page_type'                 => $result->fields['page_type'],
                        'page_word'                 => $result->fields['page_word'],

                        'cover_id'                  => $result->fields['cover_id'],
                        'cover_dir'                 => $result->fields['cover_dir'],
                        'cover_filename'            => $result->fields['cover_filename'],
                );

                $datum_info['detail_list']    = explode("[PAGESPLIT]", $datum_info['detail']);
                $datum_info['detail_num']     = count($datum_info['detail_list']);

                $datum_info['attach']         = func::db_select(DB_TABLE_DATUM_ATTACH, "*", "datum_id=".$result->fields['id'], "", "id");
            }
        }
        return $datum_info;
    }

    // return_datum_list
    function return_datum_list($limit="", $condition="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;

        $sql_where      = "";
        $sql_groupby    = "";
        $sql_orderby    = "";
        $sql_limit      = "";

        $datum_list   = array();

        if (!empty($condition['datum_id'])){
            if (!is_array($condition['datum_id'])) {
                $condition['datum_id'] = explode(",", $condition['datum_id']);
            }
            $condition['datum_id'] = func::array_clean($condition['datum_id']);
            if (is_array($condition['datum_id']) && count($condition['datum_id']) > 0){
                if (count($condition['datum_id']) > 1){
                    $sql_where .= " AND datum.id IN (".implode(",", $condition['datum_id']).")";
                } else {
                    $sql_where .= " AND datum.id=".implode(",", $condition['datum_id'])."";
                }
            }
        }

        if (!empty($condition['except_datum_id'])){
            if (!is_array($condition['except_datum_id'])) {
                $condition['except_datum_id'] = explode(",", $condition['except_datum_id']);
            }
            $condition['except_datum_id'] = func::array_clean($condition['except_datum_id']);
            if (is_array($condition['except_datum_id']) && count($condition['except_datum_id']) > 0){
                if (count($condition['except_datum_id']) > 1){
                    $sql_where .= " AND datum.id NOT IN (".implode(",", $condition['except_datum_id']).")";
                } else {
                    $sql_where .= " AND datum.id!=".implode(",", $condition['except_datum_id'])."";
                }
            }
        }

        if ($condition['if_top'] == "1") {
            $sql_where .= " AND ((datum.if_top=1) || (datum.if_top=3 AND datum.if_top_begin<".time()." AND datum.if_top_begin>".time()."))";
        }

        if ($condition['cover'] == "1") {
            $sql_where .= " AND cover.filename!=''";
        }

        $sql_where = substr(trim($sql_where), 0, 3) == "AND" ? substr(trim($sql_where), 3) : trim($sql_where);
        $sql_where = $sql_where != "" ? "WHERE ".$sql_where : "";

        if ($condition['click'] == "1"){
            $sql_orderby .= " click DESC,";
        }

        if ($condition['rand'] == "1"){
            $sql_orderby .= " rand(),";
        }

        if ((int)$limit > 0){
            $sql_limit .= " LIMIT ".(int)$limit;
        } else {
            $sql_limit .= "";
        }

        $sql = "SELECT datum.*,
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                FROM ".DB_TABLE_DATUM." datum
                    LEFT JOIN ".DB_TABLE_DATUM_COVER." cover ON cover.datum_id=datum.id
                ".$sql_where."
                ORDER BY ".$sql_orderby." datum.if_top, datum.rank, datum.post_time DESC ".$sql_limit;
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $datum_list[] = array(
                    'id'                        => $result->fields['id'],
                    'phrase'                    => $result->fields['phrase'],
                    'phrase_len'                => mb_strwidth($result->fields['phrase'],"UTF-8"),
                    'subject'                   => $result->fields['subject'],
                    'subject_len'               => mb_strwidth($result->fields['subject'],"UTF-8"),
                    'prefix'                    => $result->fields['prefix'],
                    'color'                     => $result->fields['color'],
                    'fontstyle'                 => $result->fields['fontstyle'],
                    'decoration'                => $result->fields['decoration'],
                    'keyword'                   => $result->fields['keyword'],
                    'brief'                     => $result->fields['brief'],
                    'post_id'                   => $result->fields['post_id'],
                    'post_username'             => $result->fields['post_username'],
                    'post_ip'                   => $result->fields['post_ip'],
                    'post_time'                 => $result->fields['post_time'],
                    'amend_id'                  => $result->fields['amend_id'],
                    'amend_username'            => $result->fields['amend_username'],
                    'amend_ip'                  => $result->fields['amend_ip'],
                    'amend_time'                => $result->fields['amend_time'],
                    'click'                     => $result->fields['click'],
                    'if_enable'                 => $result->fields['if_enable'],
                    'if_enable_begin'           => $result->fields['if_enable_begin'],
                    'if_enable_end'             => $result->fields['if_enable_end'],
                    'if_top'                    => $result->fields['if_top'],
                    'if_top_begin'              => $result->fields['if_top_begin'],
                    'if_top_end'                => $result->fields['if_top_end'],
                    'if_turn'                   => $result->fields['if_turn'],
                    'if_turn_type'              => $result->fields['if_turn_type'],
                    'if_turn_url'               => $result->fields['if_turn_url'],
                    'rank'                      => $result->fields['rank'],

                    'cover_id'                  => $result->fields['cover_id'],
                    'cover_dir'                 => $result->fields['cover_dir'],
                    'cover_filename'            => $result->fields['cover_filename'],
                );
                $result->MoveNext();
            }
        }
        return $datum_list;
    }

    // return_datum_attach_list
    function return_datum_attach_list($attach_list, $attach_type, $attach_where, $attach_table, $attach_dir)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $str_js_han     = "";
        $result_str     = "";
        $result_js      = "";
        $filelist       = func::db_select($attach_table, "*", $attach_where, "", "id DESC");
        if (is_array($filelist) && count($filelist) > 0){
            $result_str = "";
            $result_str .= "<table width=\"100%\" cellpadding=\"3\" cellspacing=\"1\" border=\"0\">";
            foreach($filelist as $file){
                $path   = $attach_dir."/".$file['dir'];
                if (file_exists($path.$file['filename'])) {
                    list($width, $height, $type, $attr) = @getimagesize($path.$file['filename']);
                }
                if (preg_match("/^(\.gif|\.jpg|\.png)$/i", substr($file['filename'], -4))){
                    $file_icon = "<img src=\"".CONFIG_ROOTDIR.$path.$file['filename']."\" width=\"45\" height=\"45\" border=\"0\" align=\"absmiddle\">";
                } else {
                    $file_icon = "&nbsp;";
                }
                if ($attach_type == "add") { $file['datum_id'] = $MEMBER['id']; }
                $result_str .= "
                  <tr align=\"center\" bgcolor=\"#DEDEDE\">
                    <td width=\"15%\">
                      <span title=\"删除附件\"><img src=\"".$SETTING['dir_images_admin']."/icon_delete.gif\" onclick=\"xajax_attach_del('".$attach_type."','".$file['datum_id']."','".$file['id']."','".$attach_list."');\" style=\"cursor:pointer;\" alt=\"删\" /></span>
                      <span title=\"复制附件地址\" id=\"block_attach_".$attach_table."_".$file['id']."\"></span>
                    </td>
                    <td width=\"85%\" align=\"left\"><input type=\"text\" id=\"attach_".$attach_table."_".$file['id']."\" name=\"attach_".$attach_table."_".$file['id']."\" value=\"".$path.$file['filename']."\" onclick=\"this.select();\" class=\"input\" style=\"width:430px;\" /></td>
                  </tr>\n
                  <tr align=\"center\" bgcolor=\"#EEEEEE\">
                    <td width=\"15%\">".$file_icon."</td>
                    <td width=\"85%\" align=\"left\">".$file['brief']."</td>
                  </tr>\n";
                $str_js_han .= "$('#block_attach_".$attach_table."_".$file['id']."').bwcopyer({id: 'attach_".$attach_table."_".$file['id']."', get: 'attach_get', ret: 'attach_ret'});\n";
            }
            $result_str .= "</table>";
            $result_js = "\n$(document).ready(function() {\n".$str_js_han."});\n";
        }
        return array($result_str, $result_js);
    }
    //////

    // About content
    // return_scheduler_info
    function return_scheduler_info($scheduler_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $scheduler_info = array();
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $scheduler_id)) {
            $sql = "SELECT *
                        FROM ".DB_TABLE_SCHEDULER."
                    WHERE id=".$scheduler_id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                if (!$result->EOF) {
                    $scheduler_info = array(
                        'scheduler_id'  => $result->fields['id'],
                        'content_id'    => $result->fields['content_id'],
                        'channel_id'    => $result->fields['channel_id'],
                    );
                }
            }
        }
        return $scheduler_info;
    }

    // return_content_info
    function return_content_info($scheduler_id, $reselect=true)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $content_info = array();

        $scheduler_info = $this->return_scheduler_info($scheduler_id);
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $scheduler_info['scheduler_id']) &&
            preg_match("/^[1-9][0-9]{0,10}$/i", $scheduler_info['content_id']) &&
            preg_match("/^[1-9][0-9]{0,10}$/i", $scheduler_info['channel_id']) ) {

            if ($reselect) {
                $this->return_channel_info($scheduler_info['channel_id']);

                $this->return_setmodel_info($this->channel_info['setmodel_id']);
                $this->return_table_list();
                $this->return_field_array();
                $this->return_model_array();
            }

            if (preg_match("/^[1-9][0-9]{0,10}$/i", $scheduler_info['content_id']) && is_array($this->model_array) && count($this->model_array) > 0) {
                if (is_array($this->model_array['tree']) && count($this->model_array['tree']) > 0) {
                    foreach($this->model_array['tree'] as $k => $v) {
                        if (is_array($v) && count($v) > 0) {
                            $sql_select = implode(",", $this->model_array['select'][$k]);
                            $sql_table  = implode("", $this->model_array['table'][$k]);
                            $sql_where  = "content.content_id=".$scheduler_info['content_id'];
                            $sql = "SELECT ".$sql_select." ".$sql_table."
                                    WHERE ".$sql_where."
                                    GROUP BY ".$k.".".$k."_id";
                            $result = &$db->Execute($sql);
                            if (!$result) {
                                echo $db->ErrorMsg();
                            } else {
                                while (!$result->EOF) {
                                    if ($k == "content"){
                                        $content_info[$k] = array(
                                            'content_id'                => $result->fields['content_id'],
                                            'phrase'                    => $result->fields['phrase'],
                                            'phrase_len'                => mb_strwidth($result->fields['phrase'],"UTF-8"),
                                            'subject'                   => $result->fields['subject'],
                                            'subject_len'               => mb_strwidth($result->fields['subject'],"UTF-8"),
                                            'color'                     => $result->fields['color'],
                                            'fontstyle'                 => $result->fields['fontstyle'],
                                            'decoration'                => $result->fields['decoration'],
                                            'prefix'                    => $result->fields['prefix'],
                                            'author'                    => $result->fields['author'],
                                            'excerpt'                   => $result->fields['excerpt'],
                                            'template_content'          => $result->fields['template_content'],
                                            'click'                     => $result->fields['click'],
                                            'keyword'                   => $result->fields['keyword'],
                                            'brief'                     => $result->fields['brief'],
                                            'post_id'                   => $result->fields['post_id'],
                                            'post_username'             => $result->fields['post_username'],
                                            'post_ip'                   => $result->fields['post_ip'],
                                            'post_time'                 => $result->fields['post_time'],
                                            'verify_id'                 => $result->fields['verify_id'],
                                            'verify_username'           => $result->fields['verify_username'],
                                            'verify_ip'                 => $result->fields['verify_ip'],
                                            'verify_time'               => $result->fields['verify_time'],
                                            'if_enable'                 => $result->fields['if_enable'],
                                            'if_enable_begin'           => $result->fields['if_enable_begin'],
                                            'if_enable_end'             => $result->fields['if_enable_end'],
                                            'if_top'                    => $result->fields['if_top'],
                                            'if_top_begin'              => $result->fields['if_top_begin'],
                                            'if_top_end'                => $result->fields['if_top_end'],
                                            'if_view'                   => $result->fields['if_view'],
                                            'if_view_privilege'         => $result->fields['if_view_privilege'],
                                            'if_inerface'               => $result->fields['if_inerface'],
                                            'if_inerface_privilege'     => $result->fields['if_inerface_privilege'],
                                            'if_inerface_identity'      => $result->fields['if_inerface_identity'],
                                            'if_inerface_check'         => $result->fields['if_inerface_check'],
                                            'if_turn'                   => $result->fields['if_turn'],
                                            'if_turn_type'              => $result->fields['if_turn_type'],
                                            'if_turn_url'               => $result->fields['if_turn_url'],
                                            'rank'                      => $result->fields['rank'],

                                            'scheduler_id'              => $scheduler_info['scheduler_id'],
                                            'channel_id'                => $scheduler_info['channel_id'],

                                            'cover_id'                  => $result->fields['cover_id'],
                                            'cover_dir'                 => $result->fields['cover_dir'],
                                            'cover_filename'            => $result->fields['cover_filename'],
                                            'cover_content_id'          => $result->fields['cover_content_id'],
                                            'cover_admin_id'            => $result->fields['cover_admin_id'],
                                        );
                                    } elseif ($this->model_array['level'][$k] == "content" && $this->model_array['recordtype'][$k] == "1") {
                                        if (is_array($this->model_array['field'][$k]) && count($this->model_array['field'][$k]) > 0) {
                                            foreach ($this->model_array['field'][$k] as $k_f => $v_f) {
                                                $content_info[$k][$result->fields[$this->model_array['level'][$k]."_id"]][$result->fields[$k."_id"]][$v_f] = $result->fields[$v_f];
                                                if ($this->model_array['attach'][$k][$v_f] == "1") {
                                                    $content_info['attach_mark'][] = $result->fields[$v_f];
                                                }
                                            }
                                        }
                                    } else {
                                        if (is_array($this->model_array['field'][$k]) && count($this->model_array['field'][$k]) > 0) {
                                            foreach ($this->model_array['field'][$k] as $k_f => $v_f) {
                                                $content_info[$k][$result->fields[$this->model_array['level'][$k]."_id"]][$result->fields[$k."_id"]][$v_f] = $result->fields[$v_f];
                                                if ($this->model_array['attach'][$k][$v_f] == "1") {
                                                    $content_info['attach_mark'][] = $result->fields[$v_f];
                                                }
                                            }
                                        }
                                    }
                                    $result->MoveNext();
                                }
                            }
                        }
                    }
                }
                if (is_array($content_info['attach_mark']) && count($content_info['attach_mark'])>0) {
                    $content_info['attach_mark'] = array_unique($content_info['attach_mark']);
                    if (is_array($this->model_array['attach']) && count($this->model_array['attach'])>0) {
                        $content_info['attach'] = $this->return_content_attach_value($content_info['attach_mark']);
                    }
                }
                $content_info['trans']  = $this->return_trans_content($this->setmodel_info['id'],$scheduler_info['content_id']);
            }
        }
        return $content_info;
    }

    // return_content_list
    function return_content_list($limit="", $condition="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db, $sys, $t, $bwpage;

        $sql_where      = "";
        $sql_groupby    = "";
        $sql_orderby    = "";
        $sql_limit      = "";

        $content_list   = array();

        if (!empty($condition['scheduler_id'])){
            if (!is_array($condition['scheduler_id'])) {
                $condition['scheduler_id'] = explode(",", $condition['scheduler_id']);
            }
            $condition['scheduler_id'] = func::array_clean($condition['scheduler_id']);
            if (is_array($condition['scheduler_id']) && count($condition['scheduler_id']) > 0){
                if (count($condition['scheduler_id']) > 1){
                    $sql_where .= " AND scheduler.id IN (".implode(",", $condition['scheduler_id']).")";
                } else {
                    $sql_where .= " AND scheduler.id=".implode(",", $condition['scheduler_id'])."";
                }
            }
        }

        if (!empty($condition['except_scheduler_id'])){
            if (!is_array($condition['except_scheduler_id'])) {
                $condition['except_scheduler_id'] = explode(",", $condition['except_scheduler_id']);
            }
            $condition['except_scheduler_id'] = func::array_clean($condition['except_scheduler_id']);
            if (is_array($condition['except_scheduler_id']) && count($condition['except_scheduler_id']) > 0){
                if (count($condition['except_scheduler_id']) > 1){
                    $sql_where .= " AND scheduler.id NOT IN (".implode(",", $condition['except_scheduler_id']).")";
                } else {
                    $sql_where .= " AND scheduler.id!=".implode(",", $condition['except_scheduler_id'])."";
                }
            }
        }

        if (!empty($condition['content_id'])){
            if (!is_array($condition['content_id'])) {
                $condition['content_id'] = explode(",", $condition['content_id']);
            }
            $condition['content_id'] = func::array_clean($condition['content_id']);
            if (is_array($condition['content_id']) && count($condition['content_id']) > 0){
                if (count($condition['content_id']) > 1){
                    $sql_where .= " AND scheduler.content_id IN (".implode(",", $condition['content_id']).")";
                } else {
                    $sql_where .= " AND scheduler.content_id=".implode(",", $condition['content_id'])."";
                }
            }
        }

        if (!empty($condition['except_content_id'])){
            if (!is_array($condition['except_content_id'])) {
                $condition['except_content_id'] = explode(",", $condition['except_content_id']);
            }
            $condition['except_content_id'] = func::array_clean($condition['except_content_id']);
            if (is_array($condition['except_content_id']) && count($condition['except_content_id']) > 0){
                if (count($condition['except_content_id']) > 1){
                    $sql_where .= " AND scheduler.content_id NOT IN (".implode(",", $condition['except_content_id']).")";
                } else {
                    $sql_where .= " AND scheduler.content_id!=".implode(",", $condition['except_content_id'])."";
                }
            }
        }

        if (!empty($condition['channel_id'])){
            if (!is_array($condition['channel_id'])) {
                $condition['channel_id'] = explode(",", $condition['channel_id']);
            }
            $condition['channel_id'] = func::array_clean($condition['channel_id']);
            if (is_array($condition['channel_id']) && count($condition['channel_id']) > 0){
                if (count($condition['channel_id']) > 1){
                    $sql_where .= " AND scheduler.channel_id IN (".implode(",", $condition['channel_id']).")";
                } else {
                    $sql_where .= " AND scheduler.channel_id=".implode(",", $condition['channel_id'])."";
                }
            }
        }

        if (preg_match("/^[1-9][0-9]{0,10}$/i", $condition['prefix'])){
            $sql_where .= " AND FIND_IN_SET(".$condition['prefix'].", content.prefix) > 0";
        }
        if (preg_match("/^[12]$/i", $condition['if_enable'])) {
            $sql_where .= " AND ((content.if_enable=1) || (content.if_enable=3 AND content.if_enable_begin<".time()." AND content.if_enable_end>".time()."))";
        }
        if (preg_match("/^[12]$/i", $condition['if_top'])) {
            $sql_where .= " AND ((content.if_top=1) || (content.if_top=3 AND content.if_top_begin<".time()." AND content.if_top_end>".time()."))";
        }
        if (preg_match("/^[12]$/i", $condition['if_view'])) {
            $sql_where .= " AND content.if_view=".$condition['if_view'];
        }
        if (preg_match("/^[12]$/i", $condition['if_inerface'])) {
            $sql_where .= " AND content.if_inerface=".$condition['if_inerface'];
        }
        if (preg_match("/^[12]$/i", $condition['if_turn'])) {
            $sql_where .= " AND content.if_turn=".$condition['if_turn'];
        }
        if (preg_match("/^[12]$/i", $condition['if_turn_type'])) {
            $sql_where .= " AND content.if_turn_type=".$condition['if_turn_type'];
        }

        if ($condition['cover'] == "1") {
            $sql_where .= " AND cover.filename!=''";
        }

        if ($condition['rank'] != "2"){
            $sql_orderby .= " content.rank,";
        }

        if ($condition['click'] == "1"){
            $sql_orderby .= " content.click DESC,";
        }

        if ($condition['rand'] == "1"){
            $sql_orderby .= " rand(),";
        }

        $sql_where = substr(trim($sql_where), 0, 3) == "AND" ? substr(trim($sql_where), 3) : trim($sql_where);
        $sql_where = $sql_where != "" ? "WHERE ".$sql_where : "";

        if (preg_match("/^[a-z0-9_]+$/i", $condition['page_item']) &&
            preg_match("/^[1-9][0-9]{0,10}$/i", $condition['page_current']) &&
            preg_match("/^[1-9][0-9]{0,10}$/i", $condition['page_listnum']) &&
            !empty($condition['page_url'])){
            $total_record = 0;
            $sql = "SELECT count(*) as total_record
                    FROM ".DB_TABLE_SCHEDULER." scheduler
                        LEFT JOIN ".DB_TABLE_CONTENT." content ON content.content_id=scheduler.content_id
                        LEFT JOIN ".DB_TABLE_CHANNEL." channel ON channel.id=scheduler.channel_id
                        LEFT JOIN ".DB_TABLE_CONTENT_COVER." cover ON cover.content_id=content.content_id
                    ".$sql_where."";
            $result = &$db->Execute($sql);
            if ($result) {
                $total_record = (int)$result->fields['total_record'];
            }
            $bwpage->set_record($total_record);
            $bwpage->set_page_current($condition['page_current']);
            $bwpage->set_record_listnum($condition['page_listnum']);
            $bwpage->page($condition['page_url']);
            if (preg_match("/^[0-9]{1,11}$/i", $bwpage->record_listfirst) &&
                preg_match("/^[1-9][0-9]{0,10}$/i", $bwpage->record_listnum)){
                $sql_limit .= " LIMIT ".$bwpage->record_listfirst.",".$bwpage->record_listnum;
                $t->assign(array(
                    $condition['page_item']    => $bwpage->pagination,
                ));
            }
        } elseif (preg_match("/^[1-9][0-9]{0,10}$/i", $limit)) {
            $sql_limit .= " LIMIT ".$limit;
        } else {
            $sql_limit .= "";
        }

        $sql = "SELECT scheduler.id as scheduler_id,
                    content.*,
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename,
                    channel.id as channel_id, channel.name as channel_name
                FROM ".DB_TABLE_SCHEDULER." scheduler
                    LEFT JOIN ".DB_TABLE_CONTENT." content ON content.content_id=scheduler.content_id
                    LEFT JOIN ".DB_TABLE_CHANNEL." channel ON channel.id=scheduler.channel_id
                    LEFT JOIN ".DB_TABLE_CONTENT_COVER." cover ON cover.content_id=content.content_id
                ".$sql_where."
                GROUP BY scheduler.id
                ORDER BY ".$sql_orderby." content.if_top, content.post_time DESC
                ".$sql_limit;
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $content_list[] = array(
                    'scheduler_id'              => $result->fields['scheduler_id'],

                    'content_id'                => $result->fields['content_id'],
                    'phrase'                    => $result->fields['phrase'],
                    'phrase_len'                => mb_strwidth($result->fields['phrase'],"UTF-8"),
                    'subject'                   => $result->fields['subject'],
                    'subject_len'               => mb_strwidth($result->fields['subject'],"UTF-8"),
                    'color'                     => $result->fields['color'],
                    'fontstyle'                 => $result->fields['fontstyle'],
                    'decoration'                => $result->fields['decoration'],
                    'prefix'                    => $result->fields['prefix'],
                    'author'                    => $result->fields['author'],
                    'excerpt'                   => $result->fields['excerpt'],
                    'template_content'          => $result->fields['template_content'],
                    'click'                     => $result->fields['click'],
                    'keyword'                   => $result->fields['keyword'],
                    'brief'                     => $result->fields['brief'],
                    'post_id'                   => $result->fields['post_id'],
                    'post_username'             => $result->fields['post_username'],
                    'post_ip'                   => $result->fields['post_ip'],
                    'post_time'                 => $result->fields['post_time'],
                    'verify_id'                 => $result->fields['verify_id'],
                    'verify_username'           => $result->fields['verify_username'],
                    'verify_ip'                 => $result->fields['verify_ip'],
                    'verify_time'               => $result->fields['verify_time'],
                    'if_enable'                 => $result->fields['if_enable'],
                    'if_enable_begin'           => $result->fields['if_enable_begin'],
                    'if_enable_end'             => $result->fields['if_enable_end'],
                    'if_top'                    => $result->fields['if_top'],
                    'if_top_begin'              => $result->fields['if_top_begin'],
                    'if_top_end'                => $result->fields['if_top_end'],
                    'if_view'                   => $result->fields['if_view'],
                    'if_view_privilege'         => $result->fields['if_view_privilege'],
                    'if_inerface'               => $result->fields['if_inerface'],
                    'if_inerface_privilege'     => $result->fields['if_inerface_privilege'],
                    'if_inerface_identity'      => $result->fields['if_inerface_identity'],
                    'if_inerface_check'         => $result->fields['if_inerface_check'],
                    'if_turn'                   => $result->fields['if_turn'],
                    'if_turn_type'              => $result->fields['if_turn_type'],
                    'if_turn_url'               => $result->fields['if_turn_url'],
                    'rank'                      => $result->fields['rank'],

                    'cover_id'                  => $result->fields['cover_id'],
                    'cover_dir'                 => $result->fields['cover_dir'],
                    'cover_filename'            => $result->fields['cover_filename'],

                    'channel_id'                => $result->fields['channel_id'],
                    'channel_name'              => $result->fields['channel_name'],
                    'channel_name_len'          => mb_strwidth($result->fields['channel_name'],"UTF-8"),
                );
                $result->MoveNext();
            }
        }
        return $content_list;
    }

    // return_content_attach_list
    function return_content_attach_value($attach_mark)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $attach_list = array();
        if (!is_array($attach_mark) || count($attach_mark)<=0) {
            $attach_mark = preg_split("/[\s,|]+/i", $attach_mark);
        }
        if (is_array($attach_mark) && count($attach_mark)>0) {
            $sql = "SELECT *
                    FROM ".DB_TABLE_CONTENT_ATTACH."
                    WHERE key_id IN ('".implode("','",$attach_mark)."')";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                while (!$result->EOF) {
                    $attach_list[$result->fields['key_id']][$result->fields['id']] = array(
                            'id'            => $result->fields['id'],
                            'dir'           => $result->fields['dir'],
                            'filename'      => $result->fields['filename'],
                            'brief'         => $result->fields['brief'],
                            'watermark'     => $result->fields['watermark'],
                            'key_id'        => $result->fields['key_id'],
                            'admin_id'      => $result->fields['admin_id'],
                            'time'          => $result->fields['time'],
                            'down'          => $result->fields['down'],
                        );
                    $result->MoveNext();
                }
            }
        }
        return $attach_list;
    }

    // return_content_attach_list
    function return_content_attach_list($area_id, $attach_list, $attach_where, $attach_table, $attach_dir, $attach_mark)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $str_js_han     = "";
        $result_str     = "";
        $result_js      = "";
        $filelist       = func::db_select($attach_table, "*", $attach_where, "", "id DESC");
        if (is_array($filelist) && count($filelist) > 0){
            $result_str = "";
            $result_str .= "<table width=\"100%\" cellpadding=\"1\" cellspacing=\"1\" border=\"0\">";
            foreach($filelist as $file){
                $path   = $attach_dir."/".$file['dir'];
                if (file_exists($path.$file['filename'])) {
                    list($width, $height, $type, $attr) = @getimagesize($path.$file['filename']);
                }
                if (preg_match("/^(\.gif|\.jpg|\.png)$/i", substr($file['filename'], -4))){
                    $file_icon = "<img src=\"".CONFIG_ROOTDIR.$path.$file['filename']."\" width=\"45\" height=\"45\" border=\"0\" align=\"absmiddle\">";
                } else {
                    $file_icon = "&nbsp;";
                }
                $result_str .= "
                  <tr align=\"center\">
                    <td width=\"10%\" bgcolor=\"#EEEEEE\">
                      <span title=\"删除附件\"><img src=\"".$SETTING['dir_images_admin']."/icon_delete.gif\" onclick=\"xajax_attach_del('".$area_id."','".$file['key_id']."','".$file['id']."','".$attach_list."');\" style=\"cursor:pointer;\" alt=\"删\" /></span>
                      <span title=\"复制附件地址\" id=\"block_attach_".$attach_table."_".$file['id']."\"></span>
                    </td>
                    <td width=\"60%\" align=\"left\" bgcolor=\"#EEEEEE\"><input type=\"hidden\" id=\"content_attach[".$file['id']."][key_id]\" name=\"content_attach[".$file['id']."][key_id]\" value=\"".$attach_mark."\"  /><input type=\"text\" id=\"content_attach[".$file['id']."][filename]\" name=\"content_attach[".$file['id']."][filename]\" value=\"".$path.$file['filename']."\" onclick=\"this.select();\" readonly class=\"input\" style=\"width:400px;\" /></td>
                    <td width=\"30%\" align=\"left\">&nbsp;</td>
                  </tr>\n
                  <tr align=\"center\">
                    <td width=\"10%\" bgcolor=\"#EEEEEE\">".$file_icon."</td>
                    <td width=\"60%\" align=\"left\" bgcolor=\"#EEEEEE\"><textarea id=\"content_attach[".$file['id']."][brief]\" name=\"content_attach[".$file['id']."][brief]\" rows=\"3\" cols=\"75\" style=\"width:400px;height:40px;\" class=\"textarea\">".$file['brief']."</textarea></td>
                    <td width=\"30%\" align=\"left\">&nbsp;</td>
                  </tr>\n";
                $str_js_han .= "$('#block_attach_".$attach_table."_".$file['id']."').bwcopyer({id: 'attach_".$attach_table."_".$file['id']."', get: 'attach_get', ret: 'attach_ret'});\n";
            }
            $result_str .= "</table>";
            $result_js = "\n$(document).ready(function() {\n".$str_js_han."});\n";
        }
        return array($result_str, $result_js);
    }
    //////

    // About channel
    // return_channel_info
    function return_channel_info($channel_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (preg_match("/^[1-9][0-9]*$/", $channel_id)) {
            $sql_select     = "";
            $sql_leftjoin   = "";
            if ($ADMIN['iflogin'] == "1") {
                $sql_select     .= "channel_manage.admin_id as channel_manage_admin_id,";
                $sql_leftjoin   .= "LEFT JOIN ".DB_TABLE_CHANNEL_MANAGE." channel_manage ON channel_manage.channel_id=channel.id AND channel_manage.admin_id=".$ADMIN['mid'];
            }
            $sql = "SELECT channel.*,
                        ".$sql_select."
                        cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                    FROM ".DB_TABLE_CHANNEL." channel
                        LEFT JOIN ".DB_TABLE_CHANNEL_COVER." cover ON cover.channel_id=channel.id
                        ".$sql_leftjoin."
                    WHERE channel.id=".$channel_id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                if (!$result->EOF) {
                    $this->channel_info = array(
                        'id'                        => $result->fields['id'],
                        'channel_id'                => $result->fields['id'],
                        'upper_id'                  => $result->fields['upper_id'],
                        'path'                      => $result->fields['path'],
                        'name'                      => $result->fields['name'],
                        'password'                  => $result->fields['password'],
                        'brief'                     => $result->fields['brief'],
                        'remark'                    => $result->fields['remark'],
                        'keyword'                   => $result->fields['keyword'],
                        'setmodel_id'               => $result->fields['setmodel_id'],
                        'template_channel'          => $result->fields['template_channel'],
                        'template_content'          => $result->fields['template_content'],
                        'page_record'               => $result->fields['page_record'],
                        'number_total_content'      => $result->fields['number_total_content'],
                        'number_today_content'      => $result->fields['number_today_content'],
                        'if_enable'                 => $result->fields['if_enable'],
                        'if_show'                   => $result->fields['if_show'],
                        'if_add'                    => $result->fields['if_add'],
                        'if_splitword'              => $result->fields['if_splitword'],
                        'if_recommend'              => $result->fields['if_recommend'],
                        'if_view'                   => $result->fields['if_view'],
                        'if_view_privilege'         => $result->fields['if_view_privilege'],
                        'if_inerface'               => $result->fields['if_inerface'],
                        'if_inerface_privilege'     => $result->fields['if_inerface_privilege'],
                        'if_inerface_identity'      => $result->fields['if_inerface_identity'],
                        'if_inerface_check'         => $result->fields['if_inerface_check'],
                        'if_turn'                   => $result->fields['if_turn'],
                        'if_turn_type'              => $result->fields['if_turn_type'],
                        'if_turn_url'               => $result->fields['if_turn_url'],
                        'rank'                      => $result->fields['rank'],

                        'cover_id'                  => $result->fields['cover_id'],
                        'cover_dir'                 => $result->fields['cover_dir'],
                        'cover_filename'            => $result->fields['cover_filename'],

                        'channel_manage_admin_id'   => $result->fields['channel_manage_admin_id'],
                    );
                }
            }
        } else {
            $this->channel_info = array();
        }
        return $this->channel_info;
    }

    // return_channel_path
    function return_channel_path($channel_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->channel_path  = array();

        $channel_id = (int)$channel_id;

        if ($channel_id != "0") {
            $sql = "SELECT path FROM ".DB_TABLE_CHANNEL." WHERE id=".$channel_id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                if (!$result->EOF) {
                    $path = $result->fields['path'];
                }
            }
            $array_path = explode(",", $path);
            $sql = "SELECT id, upper_id, name, if_recommend
                    FROM ".DB_TABLE_CHANNEL."
                    WHERE id IN (".$path.")";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                while (!$result->EOF) {
                    $current[$result->fields['id']] = array(
                            'id'            => $result->fields['id'],
                            'upper_id'      => $result->fields['upper_id'],
                            'name'          => $result->fields['name'],
                            'keyword'       => $result->fields['keyword'],
                            'if_recommend'  => $result->fields['if_recommend'],
                        );
                    $result->MoveNext();
                }
            }
            foreach ($array_path as $v) {
                $this->channel_path[] = $current[$v];
            }
        }
        return $this->channel_path;
    }

    // Get sort
    function return_channel_all()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->channel_all      = array();
        $this->channel_upper    = array();
        $sql_select     = "";
        $sql_leftjoin   = "";
        if ($ADMIN['iflogin'] == "1") {
            $sql_select     .= "channel_manage.admin_id as channel_manage_admin_id,";
            $sql_leftjoin   .= "LEFT JOIN ".DB_TABLE_CHANNEL_MANAGE." channel_manage ON channel_manage.channel_id=channel.id AND channel_manage.admin_id=".$ADMIN['mid'];
        }
        $sql = "SELECT channel.*,
                    ".$sql_select."
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                FROM ".DB_TABLE_CHANNEL." channel
                    LEFT JOIN ".DB_TABLE_CHANNEL_COVER." cover ON cover.channel_id=channel.id
                    ".$sql_leftjoin."
                WHERE channel.if_enable=1
                ORDER BY channel.rank, channel.id";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $this->channel_all[$result->fields['id']] = array(
                    'id'                        => $result->fields['id'],
                    'upper_id'                  => $result->fields['upper_id'],
                    'path'                      => $result->fields['path'],
                    'name'                      => $result->fields['name'],
                    'password'                  => $result->fields['password'],
                    'brief'                     => $result->fields['brief'],
                    'remark'                    => $result->fields['remark'],
                    'keyword'                   => $result->fields['keyword'],
                    'setmodel_id'               => $result->fields['setmodel_id'],
                    'template_channel'          => $result->fields['template_channel'],
                    'template_content'          => $result->fields['template_content'],
                    'page_record'               => $result->fields['page_record'],
                    'number_total_content'      => $result->fields['number_total_content'],
                    'number_today_content'      => $result->fields['number_today_content'],
                    'if_enable'                 => $result->fields['if_enable'],
                    'if_show'                   => $result->fields['if_show'],
                    'if_add'                    => $result->fields['if_add'],
                    'if_splitword'              => $result->fields['if_splitword'],
                    'if_recommend'              => $result->fields['if_recommend'],
                    'if_view'                   => $result->fields['if_view'],
                    'if_view_privilege'         => $result->fields['if_view_privilege'],
                    'if_inerface'               => $result->fields['if_inerface'],
                    'if_inerface_privilege'     => $result->fields['if_inerface_privilege'],
                    'if_inerface_identity'      => $result->fields['if_inerface_identity'],
                    'if_inerface_check'         => $result->fields['if_inerface_check'],
                    'if_turn'                   => $result->fields['if_turn'],
                    'if_turn_type'              => $result->fields['if_turn_type'],
                    'if_turn_url'               => $result->fields['if_turn_url'],
                    'rank'                      => $result->fields['rank'],

                    'cover_id'                  => $result->fields['cover_id'],
                    'cover_dir'                 => $result->fields['cover_dir'],
                    'cover_filename'            => $result->fields['cover_filename'],

                    'channel_manage_admin_id'   => $result->fields['channel_manage_admin_id'],
                );
                $this->channel_upper[$result->fields['upper_id']][] = array(
                    'id'                        => $result->fields['id'],
                    'upper_id'                  => $result->fields['upper_id'],
                    'path'                      => $result->fields['path'],
                    'name'                      => $result->fields['name'],
                    'password'                  => $result->fields['password'],
                    'brief'                     => $result->fields['brief'],
                    'remark'                    => $result->fields['remark'],
                    'keyword'                   => $result->fields['keyword'],
                    'setmodel_id'               => $result->fields['setmodel_id'],
                    'template_channel'          => $result->fields['template_channel'],
                    'template_content'          => $result->fields['template_content'],
                    'page_record'               => $result->fields['page_record'],
                    'number_total_content'      => $result->fields['number_total_content'],
                    'number_today_content'      => $result->fields['number_today_content'],
                    'if_enable'                 => $result->fields['if_enable'],
                    'if_show'                   => $result->fields['if_show'],
                    'if_add'                    => $result->fields['if_add'],
                    'if_splitword'              => $result->fields['if_splitword'],
                    'if_recommend'              => $result->fields['if_recommend'],
                    'if_view'                   => $result->fields['if_view'],
                    'if_view_privilege'         => $result->fields['if_view_privilege'],
                    'if_inerface'               => $result->fields['if_inerface'],
                    'if_inerface_privilege'     => $result->fields['if_inerface_privilege'],
                    'if_inerface_identity'      => $result->fields['if_inerface_identity'],
                    'if_inerface_check'         => $result->fields['if_inerface_check'],
                    'if_turn'                   => $result->fields['if_turn'],
                    'if_turn_type'              => $result->fields['if_turn_type'],
                    'if_turn_url'               => $result->fields['if_turn_url'],
                    'rank'                      => $result->fields['rank'],

                    'cover_id'                  => $result->fields['cover_id'],
                    'cover_dir'                 => $result->fields['cover_dir'],
                    'cover_filename'            => $result->fields['cover_filename'],

                    'channel_manage_admin_id'   => $result->fields['channel_manage_admin_id'],
                );
                $result->MoveNext();
            }
        }
        return true;
    }

    // Return return_channel_list
    function return_channel_list($upper_id, $limit="", $condition=null)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->channel_list  = array();

        $sql_select         = "";
        $sql_leftjoin       = "";
        $sql_where          = "";
        $sql_orderby        = "";
        $sql_limit          = "";

        if ($ADMIN['iflogin'] == "1") {
            $sql_select     .= "channel_manage.admin_id as channel_manage_admin_id,";
            $sql_leftjoin   .= "LEFT JOIN ".DB_TABLE_CHANNEL_MANAGE." channel_manage ON channel_manage.channel_id=channel.id AND channel_manage.admin_id=".$ADMIN['mid'];
        }

        if (preg_match("/^[1]$/i", $condition['allsub'])) {
            $sql_where .= " FIND_IN_SET(".$upper_id.", channel.path) > 0";
        }elseif (preg_match("/^[0-9]{0,11}$/i", $upper_id)) {
            $sql_where .= " AND channel.upper_id=".$upper_id;
        }

        if (preg_match("/^[12]$/i", $condition['if_enable'])) {
            $sql_where .= " AND channel.if_enable=".$condition['if_enable'];
        }
        if (preg_match("/^[12]$/i", $condition['if_show'])) {
            $sql_where .= " AND channel.if_show=".$condition['if_show'];
        }
        if (preg_match("/^[12]$/i", $condition['if_add'])) {
            $sql_where .= " AND channel.if_add=".$condition['if_add'];
        }
        if (preg_match("/^[12]$/i", $condition['if_splitword'])) {
            $sql_where .= " AND channel.if_splitword=".$condition['if_splitword'];
        }
        if (preg_match("/^[12]$/i", $condition['if_recommend'])) {
            $sql_where .= " AND channel.if_recommend=".$condition['if_recommend'];
        }
        if (preg_match("/^[12]$/i", $condition['if_view'])) {
            $sql_where .= " AND channel.if_view=".$condition['if_view'];
        }
        if (preg_match("/^[12]$/i", $condition['if_inerface'])) {
            $sql_where .= " AND channel.if_inerface=".$condition['if_inerface'];
        }
        if (preg_match("/^[12]$/i", $condition['if_turn'])) {
            $sql_where .= " AND channel.if_turn=".$condition['if_turn'];
        }
        if (preg_match("/^[12]$/i", $condition['if_turn_type'])) {
            $sql_where .= " AND channel.if_turn_type=".$condition['if_turn_type'];
        }

        if ($condition['rank'] != "2"){
            $sql_orderby .= " channel.rank,";
        }

        if (preg_match("/^[1-9][0-9]{0,10}$/i", $limit)) {
            $sql_limit = " LIMIT ".$limit;
        }

        $sql_where = substr(trim($sql_where), 0, 3) == "AND" ? substr(trim($sql_where), 3) : trim($sql_where);
        $sql_where = $sql_where != "" ? "WHERE ".$sql_where : "";

        $sql = "SELECT channel.*,
                    ".$sql_select."
                    cover.id as cover_id, cover.dir as cover_dir, cover.filename as cover_filename
                FROM ".DB_TABLE_CHANNEL." channel
                    LEFT JOIN ".DB_TABLE_CHANNEL_COVER." cover ON cover.channel_id=channel.id
                    ".$sql_leftjoin."
                ".$sql_where." ORDER BY ".$sql_orderby." channel.id ".$sql_limit;
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $this->channel_list[$result->fields['id']] = array(
                    'id'                        => $result->fields['id'],
                    'upper_id'                  => $result->fields['upper_id'],
                    'path'                      => $result->fields['path'],
                    'name'                      => $result->fields['name'],
                    'password'                  => $result->fields['password'],
                    'brief'                     => $result->fields['brief'],
                    'remark'                    => $result->fields['remark'],
                    'keyword'                   => $result->fields['keyword'],
                    'setmodel_id'               => $result->fields['setmodel_id'],
                    'template_channel'          => $result->fields['template_channel'],
                    'template_content'          => $result->fields['template_content'],
                    'page_record'               => $result->fields['page_record'],
                    'number_total_content'      => $result->fields['number_total_content'],
                    'number_today_content'      => $result->fields['number_today_content'],
                    'if_enable'                 => $result->fields['if_enable'],
                    'if_show'                   => $result->fields['if_show'],
                    'if_add'                    => $result->fields['if_add'],
                    'if_splitword'              => $result->fields['if_splitword'],
                    'if_recommend'              => $result->fields['if_recommend'],
                    'if_view'                   => $result->fields['if_view'],
                    'if_view_privilege'         => $result->fields['if_view_privilege'],
                    'if_inerface'               => $result->fields['if_inerface'],
                    'if_inerface_privilege'     => $result->fields['if_inerface_privilege'],
                    'if_inerface_identity'      => $result->fields['if_inerface_identity'],
                    'if_inerface_check'         => $result->fields['if_inerface_check'],
                    'if_turn'                   => $result->fields['if_turn'],
                    'if_turn_type'              => $result->fields['if_turn_type'],
                    'if_turn_url'               => $result->fields['if_turn_url'],
                    'rank'                      => $result->fields['rank'],

                    'cover_id'                  => $result->fields['cover_id'],
                    'cover_dir'                 => $result->fields['cover_dir'],
                    'cover_filename'            => $result->fields['cover_filename'],

                    'channel_manage_admin_id'   => $result->fields['channel_manage_admin_id'],
                );
                $sub_record_sql     = "SELECT count(*) as sub_record FROM ".DB_TABLE_CHANNEL." WHERE upper_id=".$result->fields['id']."";
                $sub_record_result  = &$db->Execute($sub_record_sql);
                if (!$sub_record_result) {
                    echo $db->ErrorMsg();
                    $sub_record = 0;
                } else {
                    $sub_record = $sub_record_result->fields['sub_record'];
                }
                $this->channel_list[$result->fields['id']]['sub_record'] = (int)$sub_record;
                $result->MoveNext();
            }
        }
        return $this->channel_list;
    }

    // Return sort
    function return_channel_tree($default = "", $upper_id = 0, $depth = 0)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if ( empty($this->channel_all) ) { $this->return_channel_all(); }
        if ( is_array($this->channel_all) ) {
            foreach ($this->channel_all as $key => $list) {
                if ($list['upper_id'] == $upper_id) {
                    if ($default != "" && $default == $list['id']) {
                        $list['depth']       = $depth;
                        $list['selected']    = "1";
                        $this->channel_tree[$list['id']] = $list;
                        $depth++;
                        $this->return_channel_tree($default, $list['id'], $depth);
                        $depth--;
                    }else{
                        $list['depth']       = $depth;
                        $this->channel_tree[$list['id']] = $list;
                        $depth++;
                        $this->return_channel_tree($default, $list['id'], $depth);
                        $depth--;
                    }
                }
            }
        }
        return $this->channel_tree;
    }

    // Return sort
    function update_channel_path($channel_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->channel_tree = array();

        $channel_id = (int)$channel_id;

        $this->return_channel_tree("", $channel_id);
        $allsub = array_merge((array)$channel_id, array_keys($this->channel_tree));

        foreach ($allsub as $v) {
            $upper_id = $v;
            $path     = array();
            $if_end   = false;
            while($if_end === false) {
                $sql = "SELECT id,upper_id FROM ".DB_TABLE_CHANNEL." WHERE id=".$upper_id."";
                $result = &$db->Execute($sql);
                if (!$result) {
                    echo $db->ErrorMsg();
                    $if_end = true;
                } else {
                    if (!$result->EOF) {
                        $path[]   = $result->fields['id'];
                        $upper_id = $result->fields['upper_id'];
                    }else{
                        $if_end = true;
                    }
                }
            }
            krsort($path);
            $update_sql = "UPDATE ".DB_TABLE_CHANNEL." SET
                               path = '".addslashes(implode(",", $path))."'
                           WHERE id=".$v."";
            $update_result = $db->Execute($update_sql);
            if (!$update_result) {
                echo $db->ErrorMsg();
            }
        }
        return $allsub;
    }

    // Return channel manage
    function return_channel_manage($channel_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $sql = "SELECT channel_manage.*,
                    member.username as username,
                    s.value as color_value,s.name as color_name
                FROM ".DB_TABLE_CHANNEL_MANAGE." channel_manage
                    LEFT JOIN ".DB_TABLE_MEMBER." member ON member.id=channel_manage.admin_id
                    LEFT JOIN ".DB_TABLE_SELECT." s ON s.id=channel_manage.color
                WHERE channel_id=".$channel_id."
                ORDER BY channel_manage.rank, channel_manage.admin_id";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        }else {
            while(!$result->EOF){
                $channel_manage_list[] = array(
                    'channel_id'    => $result->fields['channel_id'],
                    'admin_id'      => $result->fields['admin_id'],
                    'color'         => $result->fields['color'],
                    'bold'          => $result->fields['bold'],
                    'rank'          => $result->fields['rank'],
                    'time_created'  => $result->fields['time_created'],

                    'username'      => $result->fields['username'],

                    'color_value'   => $result->fields['color_value'],
                    'color_name'    => $result->fields['color_name'],
                );
                $result->MoveNext();
            }
        }
        return $channel_manage_list;
    }
    //////

    // return_trans_group_all
    function return_trans_group_all()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $trans_group_all    = array();
        $sql = "SELECT trans.id as trans_id,
                    trans.name as trans_name,
                    trans_group.id as trans_group_id,
                    trans_group.name as trans_group_name
                FROM ".DB_TABLE_TRANS_GROUP." trans_group
                    LEFT JOIN ".DB_TABLE_TRANS." trans ON FIND_IN_SET(trans.id, trans_group.trans_id) > 0
                ORDER BY trans_group.rank, trans.rank";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $trans_group_all[$result->fields['trans_group_id']][] = array(
                    'trans_id'          => $result->fields['trans_id'],
                    'trans_name'        => $result->fields['trans_name'],
                    'trans_group_id'    => $result->fields['trans_group_id'],
                    'trans_group_name'  => $result->fields['trans_group_name'],
                );
                $result->MoveNext();
            }
        }
        return true;
    }

    //
    function return_trans_group()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $trans_group_all    = array();
        $sql = "SELECT * FROM ".DB_TABLE_TRANS_GROUP." ORDER BY rank";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $trans_group[] = array(
                    'id'        => $result->fields['id'],
                    'name'      => $result->fields['name'],
                );
                $result->MoveNext();
            }
        }
        return $trans_group;
    }

    //
    function return_trans_list($setmodel_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $setmodel_id = (int)$setmodel_id;

        $sql = "SELECT trans.id as trans_id,
                    trans.name as trans_name,
                    trans_group.id as trans_group_id,
                    trans_group.name as trans_group_name,
                    setmodel_trans_group.if_must as setmodel_trans_group_if_must,
                    setmodel_trans_group.rank as setmodel_trans_group_rank
                FROM ".DB_TABLE_SETMODEL_TRANS_GROUP." setmodel_trans_group
                    LEFT JOIN ".DB_TABLE_TRANS_GROUP." trans_group ON trans_group.id=setmodel_trans_group.trans_group_id
                    LEFT JOIN ".DB_TABLE_TRANS." trans ON FIND_IN_SET(trans.id, trans_group.trans_id) > 0
                WHERE setmodel_trans_group.setmodel_id=".$setmodel_id."
                ORDER BY setmodel_trans_group.rank, trans.rank, trans.id";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $trans_list[$result->fields['trans_group_id']]['id']        = $result->fields['trans_group_id'];
                $trans_list[$result->fields['trans_group_id']]['name']      = $result->fields['trans_group_name'];
                $trans_list[$result->fields['trans_group_id']]['if_must']   = $result->fields['setmodel_trans_group_if_must'];
                $trans_list[$result->fields['trans_group_id']]['rank']      = $result->fields['setmodel_trans_group_rank'];
                $trans_list[$result->fields['trans_group_id']]['trans'][$result->fields['trans_id']]  = array(
                        'id'    => $result->fields['trans_id'],
                        'name'  => $result->fields['trans_name'],
                );
                $result->MoveNext();
            }
            /*
            if (!empty($trans_list)) {
                foreach ($trans_list as $key => $row) {
                    $rank[$key] = $row['rank'];
                }
                array_multisort($rank, SORT_NUMERIC, SORT_ASC, $trans_list);
            }
            */
        }
        return $trans_list;
    }

    // return_trans_content
    function return_trans_content($setmodel_id, $content_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $setmodel_id    = (int)$setmodel_id;
        $content_id     = (int)$content_id;

        $sql = "SELECT trans.id as trans_id,
                    trans.name as trans_name,
                    trans_group.id as trans_group_id,
                    trans_group.name as trans_group_name,
                    setmodel_trans_group.if_must as setmodel_trans_group_if_must,
                    setmodel_trans_group.rank as setmodel_trans_group_rank
                FROM ".DB_TABLE_SETMODEL_TRANS_GROUP." setmodel_trans_group
                    LEFT JOIN ".DB_TABLE_TRANS_GROUP." trans_group ON trans_group.id=setmodel_trans_group.trans_group_id
                    LEFT JOIN ".DB_TABLE_TRANS_CONTENT." trans_content ON trans_content.trans_group_id=setmodel_trans_group.trans_group_id AND trans_content.content_id=".$content_id."
                    LEFT JOIN ".DB_TABLE_TRANS." trans ON trans.id=trans_content.trans_id
                WHERE setmodel_trans_group.setmodel_id=".$setmodel_id."
                ORDER BY setmodel_trans_group.rank";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $trans_content[$result->fields['trans_group_id']] = array(
                    'id'            => $result->fields['trans_group_id'],
                    'name'          => $result->fields['trans_group_name'],
                    'if_must'       => $result->fields['setmodel_trans_group_if_must'],
                    'rank'          => $result->fields['setmodel_trans_group_rank'],
                    'trans_id'      => $result->fields['trans_id'],
                    'trans_name'    => $result->fields['trans_name'],
                );
                $result->MoveNext();
            }
        }
        return $trans_content;
    }
    //////

    // return_setmodel_info
    function return_setmodel_info($setmodel_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->setmodel_info = array();
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $setmodel_id)) {
            $sql = "SELECT *
                    FROM ".DB_TABLE_SETMODEL."
                    WHERE id=".$setmodel_id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            }else {
                if (!$result->EOF){
                    $this->setmodel_info = array(
                        'id'                => $result->fields['id'],
                        'name'              => $result->fields['name'],
                        'code'              => $result->fields['code'],
                        'brief'             => $result->fields['brief'],
                        'template_channel'  => $result->fields['template_channel'],
                        'template_content'   => $result->fields['template_content'],
                        'if_enable'         => $result->fields['if_enable'],
                        'rank'              => $result->fields['rank'],
                    );
                }
            }
        }
        return $this->setmodel_info;
    }

    // return_setmodel_list
    function return_setmodel_list()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $sql = "SELECT *
                FROM ".DB_TABLE_SETMODEL."
                ORDER BY rank";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        }else {
            while(!$result->EOF){
                $setmodel_list[$result->fields['code']] = array(
                    'id'                => $result->fields['id'],
                    'name'              => $result->fields['name'],
                    'code'              => $result->fields['code'],
                    'brief'             => $result->fields['brief'],
                    'template_channel'  => $result->fields['template_channel'],
                    'template_content'   => $result->fields['template_content'],
                    'if_enable'         => $result->fields['if_enable'],
                    'rank'              => $result->fields['rank'],
                );
                $result->MoveNext();
            }
        }
        return $setmodel_list;
    }

    // return_table_info
    function return_table_info($table_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $table_id)) {
            $sql = "SELECT setmodel_table.*,
                        setmodel.name as setmodel_name,
                        setmodel.code as setmodel_code,
                        setmodel.template_channel as setmodel_template_channel,
                        setmodel.template_content as setmodel_template_content,
                        setmodel.if_enable as setmodel_if_enable,
                        setmodel.rank as setmodel_rank
                    FROM ".DB_TABLE_SETMODEL_TABLE." setmodel_table
                        LEFT JOIN ".DB_TABLE_SETMODEL." setmodel ON setmodel.id=setmodel_table.setmodel_id
                    WHERE setmodel_table.id=".$table_id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            }else {
                if (!$result->EOF){
                    $table_info = array(
                        'id'                        => $result->fields['id'],
                        'setmodel_id'               => $result->fields['setmodel_id'],
                        'name'                      => $result->fields['name'],
                        'code'                      => $result->fields['code'],
                        'rowformat'                 => $result->fields['rowformat'],
                        'recordtype'                => $result->fields['recordtype'],
                        'if_preload'                => $result->fields['if_preload'],
                        'rank'                      => $result->fields['rank'],
                        'table_fullcode'            => $SETTING['config_db_prefix']."content".$result->fields['setmodel_code'].$result->fields['code'],

                        'setmodel_name'             => $result->fields['setmodel_name'],
                        'setmodel_code'             => $result->fields['setmodel_code'],
                        'setmodel_template_channel' => $result->fields['setmodel_template_channel'],
                        'setmodel_template_content'  => $result->fields['setmodel_template_content'],
                        'setmodel_if_enable'        => $result->fields['setmodel_if_enable'],
                        'setmodel_rank'             => $result->fields['setmodel_rank'],
                    );
                }
            }
        }
        return $table_info;
    }

    // return_table_list
    function return_table_list()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->table_list = array();
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $this->setmodel_info['id'])) {
            $sql = "SELECT setmodel_table.*,
                        setmodel.name as setmodel_name,
                        setmodel.code as setmodel_code,
                        setmodel.template_channel as setmodel_template_channel,
                        setmodel.template_content as setmodel_template_content,
                        setmodel.if_enable as setmodel_if_enable,
                        setmodel.rank as setmodel_rank
                    FROM ".DB_TABLE_SETMODEL_TABLE." setmodel_table
                        LEFT JOIN ".DB_TABLE_SETMODEL." setmodel ON setmodel.id=setmodel_table.setmodel_id
                    WHERE setmodel_table.setmodel_id=".$this->setmodel_info['id']."
                    ORDER BY setmodel_table.rank, setmodel_table.id";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            }else {
                while(!$result->EOF){
                    $this->table_list["content".$result->fields['setmodel_code'].$result->fields['code']] = array(
                        'id'                        => $result->fields['id'],
                        'setmodel_id'               => $result->fields['setmodel_id'],
                        'name'                      => $result->fields['name'],
                        'code'                      => $result->fields['code'],
                        'rowformat'                 => $result->fields['rowformat'],
                        'recordtype'                => $result->fields['recordtype'],
                        'if_preload'                => $result->fields['if_preload'],
                        'rank'                      => $result->fields['rank'],
                        'table_fullcode'            => $SETTING['config_db_prefix']."content".$result->fields['setmodel_code'].$result->fields['code'],

                        'setmodel_name'             => $result->fields['setmodel_name'],
                        'setmodel_code'             => $result->fields['setmodel_code'],
                        'setmodel_template_channel' => $result->fields['setmodel_template_channel'],
                        'setmodel_template_content'  => $result->fields['setmodel_template_content'],
                        'setmodel_if_enable'        => $result->fields['setmodel_if_enable'],
                        'setmodel_rank'             => $result->fields['setmodel_rank'],
                    );
                    $result->MoveNext();
                }
            }
        }
        return $this->table_list;
    }

    // return_field_info
    function return_field_info($field_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $field_id)) {
            $sql = "SELECT setmodel_field.*,

                        setmodel_table.setmodel_id as setmodel_id,
                        setmodel_table.name as table_name,
                        setmodel_table.code as table_code,
                        setmodel_table.rowformat as table_rowformat,
                        setmodel_table.recordtype as table_recordtype,
                        setmodel_table.if_preload as table_if_preload,
                        setmodel_table.rank as table_rank,

                        setmodel.name as setmodel_name,
                        setmodel.code as setmodel_code,
                        setmodel.template_channel as setmodel_template_channel,
                        setmodel.template_content as setmodel_template_content,
                        setmodel.if_enable as setmodel_if_enable,
                        setmodel.rank as setmodel_rank
                    FROM ".DB_TABLE_SETMODEL_FIELD." setmodel_field
                        LEFT JOIN ".DB_TABLE_SETMODEL_TABLE." setmodel_table ON setmodel_table.id=setmodel_field.table_id
                        LEFT JOIN ".DB_TABLE_SETMODEL." setmodel ON setmodel.id=setmodel_table.setmodel_id
                    WHERE setmodel_field.id=".$field_id."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            }else {
                if (!$result->EOF){
                    $value_array    = array();
                    if (preg_match("/^option|radio|checkbox$/i", $result->fields['type']) && !empty($result->fields['value'])) {
                        $value_tmp      = explode("|", $result->fields['value']);
                        if (is_array($value_tmp) && count($value_tmp)>0){
                            foreach($value_tmp as $k => $v) {
                                preg_match("/([0-9]+)\,([^,]+)\,([a-z0-9_]+)\:?([1]?)/i", $v, $v_tmp);
                                $value_array[$v_tmp[1]] = array('name' => $v_tmp[2], 'code' => $v_tmp[3], 'default' => $v_tmp[4] );
                            }
                        }
                    }
                    $field_info = array(
                        'id'                        => $result->fields['id'],
                        'table_id'                  => $result->fields['table_id'],
                        'name'                      => $result->fields['name'],
                        'code'                      => $result->fields['code'],
                        'type'                      => $result->fields['type'],
                        'team'                      => $result->fields['team'],
                        'length'                    => $result->fields['length'],
                        'prompt'                    => $result->fields['prompt'],
                        'handle_before'             => $result->fields['handle_before'],
                        'handle_alfter'             => $result->fields['handle_alfter'],
                        'value'                     => $result->fields['value'],
                        'value_array'               => $value_array,
                        'html'                      => $result->fields['html'],
                        'if_preload'                => $result->fields['if_preload'],
                        'if_enable'                 => $result->fields['if_enable'],
                        'rank'                      => $result->fields['rank'],

                        'setmodel_id'               => $result->fields['setmodel_id'],
                        'table_name'                => $result->fields['table_name'],
                        'table_code'                => $result->fields['table_code'],
                        'table_rowformat'           => $result->fields['table_rowformat'],
                        'table_recordtype'          => $result->fields['table_recordtype'],
                        'table_if_preload'          => $result->fields['table_if_preload'],
                        'table_rank'                => $result->fields['table_rank'],
                        'table_fullcode'            => $SETTING['config_db_prefix']."content".$result->fields['setmodel_code'].$result->fields['table_code'],

                        'setmodel_name'             => $result->fields['setmodel_name'],
                        'setmodel_code'             => $result->fields['setmodel_code'],
                        'setmodel_template_channel' => $result->fields['setmodel_template_channel'],
                        'setmodel_template_content'  => $result->fields['setmodel_template_content'],
                        'setmodel_if_enable'        => $result->fields['setmodel_if_enable'],
                        'setmodel_rank'             => $result->fields['setmodel_rank'],
                    );
                }
            }
        }
        return $field_info;
    }

    // return_field_list
    function return_field_list($table_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $table_id)) {
            $sql = "SELECT setmodel_field.*,

                        setmodel_table.setmodel_id as setmodel_id,
                        setmodel_table.name as table_name,
                        setmodel_table.code as table_code,
                        setmodel_table.rowformat as table_rowformat,
                        setmodel_table.recordtype as table_recordtype,
                        setmodel_table.if_preload as table_if_preload,
                        setmodel_table.rank as table_rank,

                        setmodel.name as setmodel_name,
                        setmodel.code as setmodel_code,
                        setmodel.template_channel as setmodel_template_channel,
                        setmodel.template_content as setmodel_template_content,
                        setmodel.if_enable as setmodel_if_enable,
                        setmodel.rank as setmodel_rank
                    FROM ".DB_TABLE_SETMODEL_FIELD." setmodel_field
                        LEFT JOIN ".DB_TABLE_SETMODEL_TABLE." setmodel_table ON setmodel_table.id=setmodel_field.table_id
                        LEFT JOIN ".DB_TABLE_SETMODEL." setmodel ON setmodel.id=setmodel_table.setmodel_id
                    WHERE setmodel_field.table_id=".$table_id." AND type!='index'
                    ORDER BY setmodel_field.team, setmodel_field.rank";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            }else {
                while(!$result->EOF){
                    $value_array    = array();
                    if (preg_match("/^option|radio|checkbox$/i", $result->fields['type']) && !empty($result->fields['value'])) {
                        $value_tmp      = explode("|", $result->fields['value']);
                        if (is_array($value_tmp) && count($value_tmp)>0){
                            foreach($value_tmp as $k => $v) {
                                preg_match("/([0-9]+)\,([^,]+)\,([a-z0-9_]+)\:?([1]?)/i", $v, $v_tmp);
                                $value_array[$v_tmp[1]] = array('name' => $v_tmp[2], 'code' => $v_tmp[3], 'default' => $v_tmp[4] );
                            }
                        }
                    }
                    $field_list[$result->fields['code']] = array(
                        'id'                        => $result->fields['id'],
                        'table_id'                  => $result->fields['table_id'],
                        'name'                      => $result->fields['name'],
                        'code'                      => $result->fields['code'],
                        'type'                      => $result->fields['type'],
                        'team'                      => $result->fields['team'],
                        'length'                    => $result->fields['length'],
                        'prompt'                    => $result->fields['prompt'],
                        'handle_before'             => $result->fields['handle_before'],
                        'handle_alfter'             => $result->fields['handle_alfter'],
                        'value'                     => $result->fields['value'],
                        'value_array'               => $value_array,
                        'html'                      => $result->fields['html'],
                        'if_preload'                => $result->fields['if_preload'],
                        'if_enable'                 => $result->fields['if_enable'],
                        'rank'                      => $result->fields['rank'],

                        'setmodel_id'               => $result->fields['setmodel_id'],
                        'table_name'                => $result->fields['table_name'],
                        'table_code'                => $result->fields['table_code'],
                        'table_rowformat'           => $result->fields['table_rowformat'],
                        'table_recordtype'          => $result->fields['table_recordtype'],
                        'table_if_preload'          => $result->fields['table_if_preload'],
                        'table_rank'                => $result->fields['table_rank'],
                        'table_fullcode'            => $SETTING['config_db_prefix']."content".$result->fields['setmodel_code'].$result->fields['table_code'],

                        'setmodel_name'             => $result->fields['setmodel_name'],
                        'setmodel_code'             => $result->fields['setmodel_code'],
                        'setmodel_template_channel' => $result->fields['setmodel_template_channel'],
                        'setmodel_template_content'  => $result->fields['setmodel_template_content'],
                        'setmodel_if_enable'        => $result->fields['setmodel_if_enable'],
                        'setmodel_rank'             => $result->fields['setmodel_rank'],
                    );
                    if ($result->fields['team'] == "2" && $result->fields['code'] != "content_id") {
                        $this_code              = $result->fields['code'];
                        $this_table_fullcode    = $field_list[$result->fields['code']]['table_fullcode'];
                        $field_list[$this_code]['link_table_info'] = func::db_select(DB_TABLE_SETMODEL_TABLE, "id,rowformat,recordtype",
                            "setmodel_id=".(int)$result->fields['setmodel_id']." AND
                             code='".substr($this_code,strlen("content".$result->fields['setmodel_code']),-3)."'");
                        $field_list[$this_code]['link_table_info'] = $field_list[$this_code]['link_table_info'][0];
                        $field_list[$this_code]['link_field_info'] = func::db_select(DB_TABLE_SETMODEL_FIELD, "id,if_enable",
                            "table_id=".(int)$field_list[$this_code]['link_table_info']['id']." AND
                             code='".substr($this_table_fullcode,3)."_id'");
                        $field_list[$this_code]['link_field_info'] = $field_list[$this_code]['link_field_info'][0];
                    }
                    $result->MoveNext();
                }
            }
        }
        return $field_list;
    }

    // return_field_array
    function return_field_array()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->field_array = array();
        if (is_array($this->table_list) && count($this->table_list) > 0) {
            foreach($this->table_list as $k => $v) {
                $this->field_array[$k] = $this->return_field_list($v['id']);
            }
        }
        return $this->field_array;
    }

    // return_model_array
    function return_model_array()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;

        $this->model_array = array();
        $this->model_array = array("level" => array(),"tree" => array(),"recordtype" => array(),"table" => array(),"select" => array(),"field" => array(),"attach" => array());
        $this->model_array['tree']['content']['base']               = "content";
        $this->model_array['tree']['content']['content_cover']      = "content";
        $this->model_array['recordtype']['content']                 = "1";
        $this->model_array['select']['content']['content']          = "content.*";
        $this->model_array['select']['content']['cover_id']         = "content_cover.id as cover_id";
        $this->model_array['select']['content']['cover_dir']        = "content_cover.dir as cover_dir";
        $this->model_array['select']['content']['cover_filename']   = "content_cover.filename as cover_filename";
        $this->model_array['select']['content']['cover_content_id'] = "content_cover.content_id as cover_content_id";
        $this->model_array['select']['content']['cover_admin_id']   = "content_cover.admin_id as cover_admin_id";
        $this->model_array['field']['content'][]                    = "content";
        $this->model_array['field']['content'][]                    = "cover_id";
        $this->model_array['field']['content'][]                    = "cover_dir";
        $this->model_array['field']['content'][]                    = "cover_filename";
        $this->model_array['field']['content'][]                    = "cover_content_id";
        $this->model_array['field']['content'][]                    = "cover_admin_id";
        if (is_array($this->field_array) && count($this->field_array) > 0) {
            foreach($this->field_array as $k_t => $v_t) {
                if (is_array($v_t) && count($v_t) > 0) {
                    foreach($v_t as $k_f => $v_f) {
                        if ($v_f['if_enable'] == "1"){
                            if (preg_match("/^1|2|3|4$/i", $v_f['team'])) {
                                $this->model_array['field'][$k_t][]               = $v_f['code'];
                                $this->model_array['select'][$k_t][$v_f['code']]  = $k_t.".".$v_f['code'];
                            }
                            if (preg_match("/^2$/i", $v_f['team'])) {
                                $this->model_array['level'][$k_t]                 = substr($v_f['code'],0,-3);
                            }
                            if (preg_match("/^attach$/i", $v_f['type'])) {
                                $this->model_array['attach'][$k_t][$v_f['code']]  = "1";
                            }
                        }
                    }
                }
            }
        }
        if (is_array($this->model_array['level']) && count($this->model_array['level']) > 0) {
            foreach($this->model_array['level'] as $k => $v){
                    $this->model_array['tree'][$k]['base']    = $k;
                    $this->model_array['tree'][$k][$k]        = $v;
                    $this->model_array['recordtype'][$k]      = $this->field_array[$k][$k.'_id']['table_recordtype'];
                    $k_tmp = $k;
                    $v_tmp = $v;
                    while ($v_tmp != "content") {
                        $k_tmp  = $v_tmp;
                        $v_tmp  = $this->model_array['level'][$k_tmp];
                        $this->model_array['tree'][$k][$k_tmp] = $v_tmp;
                    }
            }
        }
        if (is_array($this->model_array['tree']) && count($this->model_array['tree']) > 0) {
            foreach($this->model_array['tree'] as $k_t => $v_t){
                if (is_array($v_t) && count($v_t) > 0) {
                    foreach($v_t as $k_f => $v_f){
                        if ($k_f == "base") {
                            $this->model_array['table'][$k_t][$k_f]   = " FROM ".$SETTING['config_db_prefix'].$v_f." ".$v_f;
                        } else {
                            if ($k_t == "content") {
                                $this->model_array['table'][$k_t][$k_f]   = " LEFT JOIN ".$SETTING['config_db_prefix'].$k_f." ".$k_f." ON ".$k_f.".".$v_f."_id=".$v_f.".".$v_f."_id";
                            } else {
                                $this->model_array['table'][$k_t][$k_f]   = " LEFT JOIN ".$SETTING['config_db_prefix'].$v_f." ".$v_f." ON ".$v_f.".".$v_f."_id=".$k_f.".".$v_f."_id";
                            }
                        }
                    }
                }
            }
        }
        return $this->model_array;
    }

    // return_model_array
    function clean_model_info()
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $this->setmodel_info    = array();
        $this->table_list       = array();
        $this->field_array      = array();
        $this->model_array      = array();
        return;
    }

    // return_index_list
    function return_index_list($table_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (preg_match("/^[1-9][0-9]{0,10}$/i", $table_id)) {
            $sql = "SELECT setmodel_field.*,

                        setmodel_table.setmodel_id as setmodel_id,
                        setmodel_table.name as table_name,
                        setmodel_table.code as table_code,
                        setmodel_table.rowformat as table_rowformat,
                        setmodel_table.recordtype as table_recordtype,
                        setmodel_table.if_preload as table_if_preload,
                        setmodel_table.rank as table_rank,

                        setmodel.name as setmodel_name,
                        setmodel.code as setmodel_code,
                        setmodel.template_channel as setmodel_template_channel,
                        setmodel.template_content as setmodel_template_content,
                        setmodel.if_enable as setmodel_if_enable,
                        setmodel.rank as setmodel_rank
                    FROM ".DB_TABLE_SETMODEL_FIELD." setmodel_field
                        LEFT JOIN ".DB_TABLE_SETMODEL_TABLE." setmodel_table ON setmodel_table.id=setmodel_field.table_id
                        LEFT JOIN ".DB_TABLE_SETMODEL." setmodel ON setmodel.id=setmodel_table.setmodel_id
                    WHERE setmodel_field.table_id=".$table_id." AND type='index'
                    ORDER BY setmodel_field.team, setmodel_field.rank";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            }else {
                while(!$result->EOF){
                    $index_list[$result->fields['code']] = array(
                        'id'                        => $result->fields['id'],
                        'table_id'                  => $result->fields['table_id'],
                        'name'                      => $result->fields['name'],
                        'code'                      => $result->fields['code'],
                        'type'                      => $result->fields['type'],
                        'team'                      => $result->fields['team'],
                        'length'                    => $result->fields['length'],
                        'prompt'                    => $result->fields['prompt'],
                        'handle_before'             => $result->fields['handle_before'],
                        'handle_alfter'             => $result->fields['handle_alfter'],
                        'value'                     => $result->fields['value'],
                        'html'                      => $result->fields['html'],
                        'if_preload'                => $result->fields['if_preload'],
                        'if_enable'                 => $result->fields['if_enable'],
                        'rank'                      => $result->fields['rank'],

                        'setmodel_id'               => $result->fields['setmodel_id'],
                        'table_name'                => $result->fields['table_name'],
                        'table_code'                => $result->fields['table_code'],
                        'table_rowformat'           => $result->fields['table_rowformat'],
                        'table_recordtype'          => $result->fields['table_recordtype'],
                        'table_if_preload'          => $result->fields['table_if_preload'],
                        'table_rank'                => $result->fields['table_rank'],
                        'table_fullcode'            => $SETTING['config_db_prefix']."content".$result->fields['setmodel_code'].$result->fields['table_code'],

                        'setmodel_name'             => $result->fields['setmodel_name'],
                        'setmodel_code'             => $result->fields['setmodel_code'],
                        'setmodel_template_channel' => $result->fields['setmodel_template_channel'],
                        'setmodel_template_content'  => $result->fields['setmodel_template_content'],
                        'setmodel_if_enable'        => $result->fields['setmodel_if_enable'],
                        'setmodel_rank'             => $result->fields['setmodel_rank'],
                    );
                    $result->MoveNext();
                }
            }
        }
        return $index_list;
    }

    // init_table
    function init_table($table_id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $result = true;

        if ($result) {
            $table_info   = $this->return_table_info($table_id);
            if ( !preg_match("/^[1-9][0-9]*$/",$table_info['id'])
                || !preg_match("/^[1-9][0-9]*$/",$table_info['setmodel_id'])
                || !preg_match("/^[a-z_][0-9a-z_]{0,23}$/i", $table_info['code'])
                || !preg_match("/^[a-z_][0-9a-z_]{0,23}$/i", $table_info['setmodel_code']) ) {
                $result = false;
            }
        }

        if ($result) {
            $field_list[] = array(
                'name'              => "主键",
                'code'              => "content".$table_info['setmodel_code'].$table_info['code']."_id",
                'type'              => "int",
                'team'              => "1",
                'prompt'            => "",
                'value'             => "",
                'if_enable'         => "1",
            );
            $index_list[] = array(
                'name'              => "索引-主键",
                'code'              => "content".$table_info['setmodel_code'].$table_info['code']."_id",
                'type'              => "index",
                'team'              => "1",
                'prompt'            => "",
                'value'             => "",
                'if_enable'         => "1",
            );
            $field_list[] = array(
                'name'              => "链接到基本表",
                'code'              => "content_id",
                'type'              => "int",
                'team'              => "2",
                'prompt'            => "链接到基本表",
                'value'             => "",
                'if_enable'         => "1",
            );
            $index_list[] = array(
                'name'              => "索引-链接到基本表",
                'code'              => "content_id",
                'type'              => "index",
                'team'              => "2",
                'prompt'            => "",
                'value'             => "",
                'if_enable'         => "1",
            );
        }

        if ($result) {
            $sql = "SELECT *
                    FROM ".DB_TABLE_SETMODEL_TABLE."
                    WHERE setmodel_id=".$table_info['setmodel_id']."
                    ORDER BY rank, id";
            $result = &$db->Execute($sql);
            if (!$result) {
                $result = false;
            }else {
                while(!$result->EOF){
                    if ($result->fields['code'] != $table_info['code']) {
                        $field_list[] = array(
                            'name'              => "链接到".$result->fields['name'],
                            'code'              => "content".$table_info['setmodel_code'].$result->fields['code']."_id",
                            'type'              => "int",
                            'team'              => "2",
                            'prompt'            => "链接到".$result->fields['name'],
                            'value'             => "",
                            'if_enable'         => "2",
                        );
                        $index_list[] = array(
                            'name'              => "索引-链接到".$result->fields['name'],
                            'code'              => "content".$table_info['setmodel_code'].$result->fields['code']."_id",
                            'type'              => "index",
                            'team'              => "2",
                            'prompt'            => "",
                            'value'             => "",
                            'if_enable'         => "2",
                        );
                    }
                    $result->MoveNext();
                }
            }
        }

        if ($result) {
            $field_list[] = array(
                'name'              => "添加人",
                'code'              => "member_id",
                'type'              => "int",
                'team'              => "3",
                'prompt'            => "添加人将自动获取",
                'value'             => "\$MEMBER[\'id\']",
                'if_enable'         => "1",
            );
            $index_list[] = array(
                'name'              => "索引-添加人",
                'code'              => "member_id",
                'type'              => "index",
                'team'              => "3",
                'prompt'            => "",
                'value'             => "",
                'if_enable'         => "1",
            );
        }

        if ($result) {
            if (is_array($field_list) && count($field_list) > 0) {
                $i = "1";
                foreach ($field_list as $v) {
                    $field_info = func::db_select(DB_TABLE_SETMODEL_FIELD, "id,if_enable", "table_id=".$table_info['id']." AND code='".$v['code']."'AND type!='index'");
                    $field_info = $field_info[0];
                    if (preg_match("/[1-9][0-9]{0,10}/", $field_info['id'])) {
                        $sql_data = array(
                            'name'              => "'".$v['name']."'",
                            'type'              => "'".$v['type']."'",
                            'team'              => "'".$v['team']."'",
                            'length'            => "11",
                            'prompt'            => "'".$v['prompt']."'",
                            'handle_before'     => "''",
                            'handle_alfter'     => "''",
                            'value'             => "'".$v['value']."'",
                            'html'              => "''",
                            'if_preload'        => "1",
                            'rank'              => (int)$i,
                        );
                        $field_enable[$v['code']] = $field_info['if_enable'];
                        $result = func::db_update(DB_TABLE_SETMODEL_FIELD, $sql_data, "table_id=".$table_info['id']." AND code='".$v['code']."'AND type!='index'");
                        if (!$result) {
                            $result = false;
                        }
                    } else {
                        $sql_data = array(
                            'table_id'          => (int)$table_info['id'],
                            'name'              => "'".$v['name']."'",
                            'code'              => "'".$v['code']."'",
                            'type'              => "'".$v['type']."'",
                            'team'              => "'".$v['team']."'",
                            'length'            => "11",
                            'prompt'            => "'".$v['prompt']."'",
                            'handle_before'     => "''",
                            'handle_alfter'     => "''",
                            'value'             => "'".$v['value']."'",
                            'html'              => "''",
                            'if_preload'        => "1",
                            'if_enable'         => "'".$v['if_enable']."'",
                            'rank'              => (int)$i,
                        );
                        $field_enable[$v['code']] = $v['if_enable'];
                        $result = func::db_insert(DB_TABLE_SETMODEL_FIELD, $sql_data);
                        if (!$result) {
                            $result = false;
                        }
                    }
                    $i++;
                }
            }
            if (is_array($index_list) && count($index_list) > 0) {
                $i = "1";
                foreach ($index_list as $v) {
                    if ($field_enable[$v['code']] == "1") {
                        $v['if_enable'] = "1";
                    } else {
                        $v['if_enable'] = "2";
                    }
                    $total_record = func::db_count_record(DB_TABLE_SETMODEL_FIELD, "table_id=".$table_info['id']." AND code='".$v['code']."' AND type='index'");
                    if ($total_record > 0) {
                        if ($v['if_enable'] == "1") {
                            $sql_data = array(
                                'name'              => "'".$v['name']."'",
                                'type'              => "'".$v['type']."'",
                                'team'              => "'".$v['team']."'",
                                'length'            => "0",
                                'prompt'            => "''",
                                'handle_before'     => "''",
                                'handle_alfter'     => "''",
                                'value'             => "''",
                                'html'              => "''",
                                'if_preload'        => "1",
                                'if_enable'         => "'".$v['if_enable']."'",
                                'rank'              => (int)$i,
                            );
                            $result = func::db_update(DB_TABLE_SETMODEL_FIELD, $sql_data, "table_id=".$table_info['id']." AND code='".$v['code']."' AND type='index'");
                            if (!$result) {
                                $result = false;
                            }
                        } else {
                            $result = func::db_delete(DB_TABLE_SETMODEL_FIELD, "table_id=".$table_info['id']." AND code='".$v['code']."' AND type='index'");
                            if (!$result) {
                                $result = false;
                            }
                        }
                    } else {
                        if ($v['if_enable'] == "1") {
                            $sql_data = array(
                                'table_id'          => (int)$table_info['id'],
                                'name'              => "'".$v['name']."'",
                                'code'              => "'".$v['code']."'",
                                'type'              => "'".$v['type']."'",
                                'team'              => "'".$v['team']."'",
                                'length'            => "0",
                                'prompt'            => "''",
                                'handle_before'     => "''",
                                'handle_alfter'     => "''",
                                'value'             => "''",
                                'html'              => "''",
                                'if_preload'        => "1",
                                'if_enable'         => "'".$v['if_enable']."'",
                                'rank'              => (int)$i,
                            );
                            $result = func::db_insert(DB_TABLE_SETMODEL_FIELD, $sql_data);
                            if (!$result) {
                                $result = false;
                            }
                        }
                    }
                    $i++;
                }
            }
            $sql_data = array(
                'team'  => "'4'",
            );
            $result = func::db_update(DB_TABLE_SETMODEL_FIELD, $sql_data, "team=0");
            if (!$result) {
                $result = false;
            }
            $sql_data = array(
                'rank'  => "'".$i."'",
            );
            $result = func::db_update(DB_TABLE_SETMODEL_FIELD, $sql_data, "table_id=".$table_info['id']." AND team=4 AND rank<".$i."");
            if (!$result) {
                $result = false;
            }

        }
        return $result;
    }

    // build_table
    function build_table($table_info)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $db_table_fullcode          = $table_info['table_fullcode'];
        $db_table_rowformat        = $table_info['rowformat'] == "1" ? "FIXED" : "DYNAMIC";
        $db_field_name['id']    = "content".$table_info['setmodel_code'].$table_info['code']."_id";
        $sql = "CREATE TABLE IF NOT EXISTS ".$db_table_fullcode." (
                  ".$db_field_name['id']." int(11) unsigned NOT NULL auto_increment,
                  PRIMARY KEY  (".$db_field_name['id'].")
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=".$db_table_rowformat."";
        $result = $db->Execute($sql);
        return $result;
    }

    // return_index_sql
    function return_index_sql($table_fullcode)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $return         = "";
        $sql = "SHOW CREATE TABLE ".$table_fullcode."";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            if (!$result->EOF) {
                preg_match_all("/KEY\s\`([^\`]+)\`\s/i", $result->fields['Create Table'], $matchs);
                if (is_array($matchs[1]) && count($matchs[1])>0) {
                    foreach($matchs[1] as $v) {
                        $return .= "DROP INDEX `".$v."`,";
                    }
                }
            }
        }
        return $return;
    }

    // build_index_sql
    function build_index_sql($index_list)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $sql_primary    = "";
        $sql_index      = "";
        $return         = "";
        if (is_array($index_list) && count($index_list) > 0) {
            foreach ($index_list as $v) {
                if ($v['type'] == "index" && $v['if_enable'] == "1") {
                    if ($v['team'] == "1") {
                        $sql_primary    = "ADD PRIMARY KEY (`model_vote_item_id`),";
                    } else {
                        $sql_index     .= "ADD INDEX `".$v['code']."` (".$v['code']."),";
                    }
                }
            }
            $return = $sql_index;
        }
        return $return;
    }

    // build_field_sql
    function build_field_sql($rowformat,$field_info)
    {
        global $field_type_list;
        if (!is_array($field_type_list) || count($field_type_list) <= 0) {
            $field_type_list    = $this->return_field_type_list($rowformat);
        }
        if ( ($field_info['length'] > $field_type_list[$field_info['type']]['field_length']) && ($field_type_list[$field_info['type']]['field_length'] > 0) ) {
            $field_info['length'] = $field_type_list[$field_info['type']]['field_length'];
        }
        if ($field_info['team'] == "1") {
                $field_info['field_creat']          = $field_type_list[$field_info['type']]['field_creat'];
                $field_info['field_sql']            = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL auto_increment";
                $field_info['field_place']          = " FIRST";

        } elseif ($field_info['team'] == "2") {
                $field_info['field_creat']          = $field_type_list[$field_info['type']]['field_creat'];
                $field_info['field_sql']            = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL default '0'";
                $field_info['field_place']          = preg_match("/[a-z_][0-9a-z_]{1,29}/i", $field_info['field_before']) ? " AFTER ".$field_info['field_before'] : "";

        } elseif ($field_info['team'] == "3") {
                $field_info['field_creat']          = $field_type_list[$field_info['type']]['field_creat'];
                $field_info['field_sql']            = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL default '0'";
                $field_info['field_place']          = preg_match("/[a-z_][0-9a-z_]{1,29}/i", $field_info['field_before']) ? " AFTER ".$field_info['field_before'] : "";

        } else {
            if ($rowformat == "1") {
                if ($field_info['type'] == "singletext") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "multitext") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "htmlfile") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "int") {
                    if ($field_info['length'] > 0 && $field_info['length'] <= 2) {
                        $field_info['field_creat']   = "tinyint";
                    } elseif ($field_info['length'] > 2 && $field_info['length'] <= 4) {
                        $field_info['field_creat']   = "smallint";
                    } elseif ($field_info['length'] > 4 && $field_info['length'] <= 7) {
                        $field_info['field_creat']   = "mediumint";
                    } else {
                        $field_info['field_creat']   = "int";
                    }
                    $field_info['field_sql']    = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "decimal") {
                    preg_match("/^([0-9]{2})\,([0-9]{1})$/", $field_info['length'], $length_decimal);
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default '".sprintf ("%01.".$length_decimal[2]."f", "0")."'";
                } elseif ($field_info['type'] == "time") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "option") {
                    $v_option_max = 0;
                    $field_info['field_value']      = explode("|", $field_info['value']);
                    if (is_array($field_info['field_value']) && count($field_info['field_value']) > 0) {
                        foreach($field_info['field_value'] as $v_option){
                            preg_match("/([0-9]+)\,([^,]+)\,([a-z0-9_]+)\:?([1]?)/i", $v_option, $this_option);
                            if (strlen($this_option[1]) > $v_option_max) {
                                $v_option_max = strlen($this_option[1]);
                            }
                        }
                    }
                    if ($v_option_max > 0 && $v_option_max <= 2) {
                        $field_info['field_creat']   = "tinyint";
                    } elseif ($v_option_max > 2 && $v_option_max <= 4) {
                        $field_info['field_creat']   = "smallint";
                    } elseif ($v_option_max > 4 && $v_option_max <= 7) {
                        $field_info['field_creat']   = "mediumint";
                    } else {
                        $field_info['field_creat']   = "int";
                    }
                    $field_info['field_sql']        = $field_info['field_creat']."(".$v_option_max.") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "radio") {
                    $v_option_max = 0;
                    $field_info['field_value']      = explode("|", $field_info['value']);
                    if (is_array($field_info['field_value']) && count($field_info['field_value']) > 0) {
                        foreach($field_info['field_value'] as $v_option){
                            preg_match("/([0-9]+)\,([^,]+)\,([a-z0-9_]+)\:?([1]?)/i", $v_option, $this_option);
                            if (strlen($this_option[1]) > $v_option_max) {
                                $v_option_max = strlen($this_option[1]);
                            }
                        }
                    }
                    if ($v_option_max > 0 && $v_option_max <= 2) {
                        $field_info['field_creat']   = "tinyint";
                    } elseif ($v_option_max > 2 && $v_option_max <= 4) {
                        $field_info['field_creat']   = "smallint";
                    } elseif ($v_option_max > 4 && $v_option_max <= 7) {
                        $field_info['field_creat']   = "mediumint";
                    } else {
                        $field_info['field_creat']   = "int";
                    }
                    $field_info['field_sql']        = $field_info['field_creat']."(".$v_option_max.") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "checkbox") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "attach") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                }
            } else {
                if ($field_info['type'] == "singletext") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "multitext") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "htmlfile") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                } elseif ($field_info['type'] == "html") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat'];
                } elseif ($field_info['type'] == "int") {
                    if ($field_info['length'] > 0 && $field_info['length'] <= 2) {
                        $field_info['field_creat']   = "tinyint";
                    } elseif ($field_info['length'] > 2 && $field_info['length'] <= 4) {
                        $field_info['field_creat']   = "smallint";
                    } elseif ($field_info['length'] > 4 && $field_info['length'] <= 7) {
                        $field_info['field_creat']   = "mediumint";
                    } else {
                        $field_info['field_creat']   = "int";
                    }
                    $field_info['field_sql']    = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "decimal") {
                    preg_match("/^([0-9]{2})\,([0-9]{1})$/", $field_info['length'], $length_decimal);
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default '".sprintf ("%01.".$length_decimal[2]."f", "0")."'";
                } elseif ($field_info['type'] == "time") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "option") {
                    $v_option_max = 0;
                    $field_info['field_value']      = explode("|", $field_info['value']);
                    if (is_array($field_info['field_value']) && count($field_info['field_value']) > 0) {
                        foreach($field_info['field_value'] as $v_option){
                            preg_match("/([0-9]+)\,([^,]+)\,([a-z0-9_]+)\:?([1]?)/i", $v_option, $this_option);
                            if (strlen($this_option[1]) > $v_option_max) {
                                $v_option_max = strlen($this_option[1]);
                            }
                        }
                    }
                    if ($v_option_max > 0 && $v_option_max <= 2) {
                        $field_info['field_creat']   = "tinyint";
                    } elseif ($v_option_max > 2 && $v_option_max <= 4) {
                        $field_info['field_creat']   = "smallint";
                    } elseif ($v_option_max > 4 && $v_option_max <= 7) {
                        $field_info['field_creat']   = "mediumint";
                    } else {
                        $field_info['field_creat']   = "int";
                    }
                    $field_info['field_sql']        = $field_info['field_creat']."(".$v_option_max.") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "radio") {
                    $v_option_max = 0;
                    $field_info['field_value']      = explode("|", $field_info['value']);
                    if (is_array($field_info['field_value']) && count($field_info['field_value']) > 0) {
                        foreach($field_info['field_value'] as $v_option){
                            preg_match("/([0-9]+)\,([^,]+)\,([a-z0-9_]+)\:?([1]?)/i", $v_option, $this_option);
                            if (strlen($this_option[1]) > $v_option_max) {
                                $v_option_max = strlen($this_option[1]);
                            }
                        }
                    }
                    if ($v_option_max > 0 && $v_option_max <= 2) {
                        $field_info['field_creat']   = "tinyint";
                    } elseif ($v_option_max > 2 && $v_option_max <= 4) {
                        $field_info['field_creat']   = "smallint";
                    } elseif ($v_option_max > 4 && $v_option_max <= 7) {
                        $field_info['field_creat']   = "mediumint";
                    } else {
                        $field_info['field_creat']   = "int";
                    }
                    $field_info['field_sql']        = $field_info['field_creat']."(".$v_option_max.") unsigned NOT NULL default '0'";
                } elseif ($field_info['type'] == "checkbox") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat'];
                } elseif ($field_info['type'] == "attach") {
                    $field_info['field_creat']      = $field_type_list[$field_info['type']]['field_creat'];
                    $field_info['field_sql']        = $field_info['field_creat']."(".$field_info['length'].") NOT NULL default ''";
                }
            }
            $field_info['field_place']              = preg_match("/[a-z_][0-9a-z_]{1,29}/i", $field_info['field_before']) ? " AFTER ".$field_info['field_before'] : "";
        }
        $field_info['field_before']                 = $field_info['code'];
        return $field_info;
    }

    // build_field
    function build_field($table_info,$field_list)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;

        $this->build_table($table_info);

        if (is_array($field_list) && count($field_list) > 0) {

            $sql            = "Describe ".$table_info['table_fullcode']."";
            $result         = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                while (!$result->EOF) {
                    if (!array_key_exists($result->fields['Field'], $field_list)) {
                        $sql = "ALTER TABLE ".$table_info['table_fullcode']."
                                DROP COLUMN ".$result->fields['Field']."";
                        $result_drop = &$db->Execute($sql);
                    }
                    $result->MoveNext();
                }
            }

            $field_befor = "";
            foreach ($field_list as $v) {
                $result_field   = "";
                $sql            = "Describe ".$table_info['table_fullcode']." ".$v['code']."";
                $result         = &$db->Execute($sql);
                if (!$result) {
                    echo $db->ErrorMsg();
                } else {
                    if (!$result->EOF) {
                        $result_field = $result->fields['Field'];
                    }
                }

                if ($v['if_enable'] == "1") {
                    $v['field_before']  = $field_befor;
                    $v                  = $this->build_field_sql($table_info['rowformat'], $v);
                    $field_befor        = $v['field_before'];

                    if (preg_match("/[a-z_][0-9a-z_]{1,29}/i", $result_field)) {
                        $sql = "ALTER TABLE ".$table_info['table_fullcode']."
                                CHANGE COLUMN ".$v['code']." ".$v['code']." ".$v['field_sql'].$v['field_place']."";
                        $result = &$db->Execute($sql);
                    } else {
                        $sql = "ALTER TABLE ".$table_info['table_fullcode']."
                                ADD COLUMN ".$v['code']." ".$v['field_sql'].$v['field_place']."";
                        $result = &$db->Execute($sql);
                    }
                } else {
                    $v['field_sql']     = " DROP COLUMN ".$v['code']."";

                    if (preg_match("/[a-z_][0-9a-z_]{1,29}/i", $result_field)) {
                        $sql = "ALTER TABLE ".$table_info['table_fullcode']."
                                ".$v['field_sql']."";
                        $result = &$db->Execute($sql);
                    }
                }
            }

            $index_sql_return   = $this->return_index_sql($table_info['table_fullcode']);
            $index_list         = $this->return_index_list($table_info['id']);
            $index_sql_build    = $this->build_index_sql($index_list);
            $index_sql          = $index_sql_return.$index_sql_build;
            if (substr($index_sql, -1) == ",") { $index_sql = substr($index_sql, 0, -1);}
            if (!empty($index_sql)) {
                $sql = "ALTER TABLE ".$table_info['table_fullcode']."
                        ".$index_sql."";
                $result = &$db->Execute($sql);
            }

        }
        return $result;
    }

    // set_field_type
    function set_field_type($table,$field_cover,$field_where,$type)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if (preg_match("/^int|float|bool|string$/i", $type)) {
            $sql = "SELECT ".$field_where.",".$field_cover." FROM ".$table."";
            $result = &$db->Execute($sql);
            if (!$result) {
                echo $db->ErrorMsg();
            } else {
                while (!$result->EOF) {
                    settype($result->fields[$field_cover],$type);
                    $sql_update = "UPDATE ".$table."
                                        SET ".$field_cover."=".$result->fields[$field_cover]."
                                   WHERE ".$field_where."=".$result->fields[$field_where];
                    $result_update = &$db->Execute($sql_update);
                    if (!$result_update) {
                        echo $db->ErrorMsg();
                    }
                    $result->MoveNext();
                }
            }
            $return = true;
        } else {
            $return = false;
        }
        return $return;
    }

    // return_field_type_list
    function return_field_type_list($field_rowformat="")
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        if ($field_rowformat != "1") {
            $field_rowformat = "2";
        }
        $sql = "SELECT *
                FROM ".DB_TABLE_FIELD_TYPE."
                WHERE field_rowformat=".$field_rowformat."
                ORDER BY field_rank";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $field_list[$result->fields['field_type']] = array(
                    'field_type'            => $result->fields['field_type'],
                    'field_rowformat'       => $result->fields['field_rowformat'],
                    'field_name'            => $result->fields['field_name'],
                    'field_creat'           => $result->fields['field_creat'],
                    'field_length'          => $result->fields['field_length'],
                    'field_ifsys'           => $result->fields['field_ifsys'],
                    'field_rank'            => $result->fields['field_rank'],
                );
                $result->MoveNext();
            }
        }
        return $field_list;
    }
    //////
    // update_area_path
    function update_area_path($id)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $sql = "SELECT id FROM ".DB_TABLE_AREA." ORDER BY id";
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $allsub[]   = $result->fields['id'];
                $result->MoveNext();
            }
        }
        foreach ($allsub as $v) {
            $upper_id = $v;
            $path     = array();
            $if_end   = false;
            while($if_end === false) {
                $sql = "SELECT id,upper_id FROM ".DB_TABLE_AREA." WHERE id=".$upper_id."";
                $result = &$db->Execute($sql);
                if (!$result) {
                    echo $db->ErrorMsg();
                    $if_end = true;
                } else {
                    if (!$result->EOF) {
                        $path[]   = $result->fields['id'];
                        $upper_id = $result->fields['upper_id'];
                    }else{
                        $if_end = true;
                    }
                }
            }
            krsort($path);
            $update_sql = "UPDATE ".DB_TABLE_AREA." SET
                               path      = '".addslashes(implode(",", $path))."'
                           WHERE id=".$v."";
            $update_result = $db->Execute($update_sql);
            if (!$update_result) {
                echo $db->ErrorMsg();
            }
        }
        return $allsub;
    }
    //////

}
?>