<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\DedeToEyou\logic;

use think\Db;
use think\Model;
use app\admin\logic\FieldLogic;

load_trait('controller/Jump');
class DedeToEyouLogic extends Model
{
    use \traits\controller\Jump;
    public $fieldLogic;
    public $admin_lang = 'cn';
    public $times;
    public $admin_id;

    /**
     * 初始化操作
     */
    public function initialize() {
        parent::initialize();
        $this->fieldLogic         = new FieldLogic;
        $this->admin_lang = get_admin_lang();
        $this->times = getTime();
        $this->admin_id = session('admin_info.admin_id');
        $this->admin_id = !empty($this->admin_id) ? intval($this->admin_id) : 0;
    }

    // 织梦频道ID对应易优频道ID
    public function DedeChannel($channel = 0, $type = '')
    {
        if ($channel == -1) { /*专题*/
            $channel = 7;
        } else if ($channel == 1) { /*文章*/
            $channel = 1;
        } else if ($channel == 2) { /*图集*/
            $channel = 3;
        } else if ($channel == 3) { /*下载*/
            $channel = 4;
        } else if ($channel == 6) { /*产品*/
            $channel = 2;
        } else if ($channel > 0 && $type == 'add') { /*自定义模型*/
            $channel = $channel + 100;
        }

        return $channel;
    }

    public function DeDb($name = '', $prefix = '')
    {
        if(!empty($name))
        {
            static $dede_prefix = null;
            if (null === $dede_prefix) {
                $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
                $weappData = json_decode($weappData['data'], true);
                $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
            }
            $prefix = !empty($prefix) ? $prefix : $dede_prefix;
            $table = $prefix . $name;
            return Db::table($table);
        }
    }

    /**
     * 获取栏目的目录名称，确保唯一性
     */
    public function get_dirname($typename = '', $dirname = '', $newDirnameArr = [])
    {
        if (!trim($dirname) || empty($dirname) || is_numeric($dirname)) {
            $dirname = get_pinyin($typename);
        }
        if (strval(intval($dirname)) == strval($dirname)) {
            $dirname .= get_rand_str(3,0,2);
        }
        $dirname = preg_replace('/(\s)+/', '_', $dirname);
        if (!$this->dirname_unique($dirname, $newDirnameArr)) {
            $nowDirname = $dirname.get_rand_str(3,0,2);
            return $this->get_dirname($typename, $nowDirname, $newDirnameArr);
        }

        return $dirname;
    }

    /**
     * 判断栏目目录名称的唯一性
     */
    public function dirname_unique($dirname = '', $newDirnameArr = [])
    {
        static $langMarks = null;
        $langMarks === null && $langMarks = M('language_mark')->column('mark'); // 多语言标识
        static $disableDirname = null;
        $disableDirname === null && $disableDirname = config('global.disable_dirname');
        $disableDirname = array_merge($disableDirname, $langMarks);
        !empty($newDirnameArr) && $disableDirname = array_merge($disableDirname, $newDirnameArr);
        foreach ($disableDirname as $key => $val) {
            if (strtolower($dirname) == strtolower($val)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 处理转换文档页
     * $typeid      栏目id
     * $fid         下一次执行栏目id
     * $achievepage 已完成文档数
     * $batch       是否分批次执行，true：分批，false：不分批
     * limit        每次执行多少条数据
     */
    public function handelBuildArticle($typeid, $channel = '', $achievepage = 0, $batch = true, $limit = '')
    {
        $channels = $dede_channels = [];
        if (!empty($channel)) {
            $dede_channels = explode(',', $channel);
            foreach ($dede_channels as $key => $value) {
                $channels[$key] = $this->DedeChannel($value);
            }
        }

        if (empty($achievepage)) {
            if (!empty($channels)) {
                $channels_str = implode(',', $channels);
                $where = "channel in ($channels_str)";
                if (in_array('-2', $channels)) {
                    $where .= " OR channel > 100";
                }
                M('archives')->where($where)->delete();
            } else {
                M('archives')->where("channel <> 6")->delete();
            }

            if (in_array('1', $channels)) { /*文章模型*/
                M('article_content')->where(['id'=>['gt', 0]])->delete();
            }
            if (in_array('2', $channels)) { /*产品模型*/
                M('product_content')->where(['id'=>['gt', 0]])->delete();
                M('product_img')->where(['img_id'=>['gt', 0]])->delete();
            }
            if (in_array('3', $channels)) { /*图集模型*/
                M('images_content')->where(['id'=>['gt', 0]])->delete();
                M('images_upload')->where(['img_id'=>['gt', 0]])->delete();
            }
            if (in_array('4', $channels)) { /*下载模型*/
                M('download_content')->where(['id'=>['gt', 0]])->delete();
                M('download_file')->where(['file_id'=>['gt', 0]])->delete();
            }
            if (in_array('7', $channels)) { /*专题模型*/
                M('special_content')->where(['id'=>['gt', 0]])->delete();
                M('special_node')->where(['node_id'=>['gt', 0]])->delete();
            }
            if (in_array('-2', $channels)) { /*自定义模型*/
                $channeltypeRow = Db::name('channeltype')->field('table')->where(['ifsystem'=>0])->select();
                foreach ($channeltypeRow as $key => $val) {
                    !empty($val['table']) && M($val['table'].'_content')->where(['id'=>['gt', 0]])->delete();
                }
            }
        }

        $msg                  = "";
        $result               = $this->getArticleData($typeid, $dede_channels, $achievepage, $limit);
        $info                 = $result['info'];
        $data['allpagetotal'] = $pagetotal = $result['pagetotal'];
        $data['achievepage']  = $achievepage;
        $data['pagetotal']    = 0;

        if ($batch && $pagetotal > $achievepage) {
            $msg .= $msg_temp = $this->createArticle($info);
            $data['achievepage'] += count($info);
        }

        return [$msg, $data];
    }

    /**
     * 获取详情页数据
     * $typeid      栏目id
     */
    public function getArticleData($typeid = 0, $channels = [], $offset = 0, $limit = 0)
    {
        empty($limit) && $limit = 500;
        $map = [];
        if (!empty($typeid)) {
            $id_arr = [$typeid];
            $this->getAllChild($id_arr, $typeid);
            $map['typeid'] = ['in',$id_arr];
        }
        if (!empty($channels)) {
            $channels_str = implode(',', $channels);
            $where_str = "channel in ($channels_str)";
            if (in_array('-2', $channels)) {
                $where_str .= " OR channel > 6";
            }
            $map[] = Db::raw("({$where_str})");
        } else {
            $where_str = "channel in (1,2,3,6,-1) OR channel > 6";
            $map[] = Db::raw("({$where_str})");
        }
        $map['arcrank'] = ['>=', -1];
        $map['id'] = ['>', 0];
//        $field = "id as aid,typeid,typeid2 as stypeid,100 as sort_order,flag,channel,arcrank,click,title,writer as author,litpic,senddate as add_time,pubdate as update_time,mid as users_id,description as seo_description,keywords as seo_keywords,filename as htmlfilename,'{$this->admin_id}' as admin_id";
//        if(getVersion() > "v1.5.5"){
//            $field = "id as aid,typeid,typeid2 as stypeid,shorttitle as subtitle,100 as sort_order,flag,channel,arcrank,click,title,writer as author,litpic,senddate as add_time
//            ,pubdate as update_time,mid as users_id,description as seo_description,keywords as seo_keywords,filename as htmlfilename,'{$this->admin_id}' as admin_id";
//        }
        $info = [];
        $list = $this->DeDb('archives')->field("*")
            ->where($map)
            ->order('id asc')
            ->limit($offset, $limit)
            ->select();
        foreach ($list as $key=>$val){
            $info_value = [];
            $info_value['aid'] = $val['id'];
            $info_value['typeid'] = $val['typeid'];
            $info_value['sort_order'] = 100;
            $info_value['flag'] = $val['flag'];
            $info_value['channel'] = $val['channel'];
            $info_value['arcrank'] = $val['arcrank'];
            $info_value['click'] = $val['click'];
            $info_value['title'] = $val['title'];
            $info_value['author'] = $val['writer'];
            $info_value['litpic'] = $val['litpic'];
            $info_value['add_time'] = $val['senddate'];
            $info_value['update_time'] = $val['pubdate'];
            $info_value['users_id'] = $val['mid'];
            $info_value['seo_description'] = $val['description'];
            $info_value['seo_keywords'] = $val['keywords'];
            $info_value['htmlfilename'] = $val['filename'];
            $info_value['admin_id'] = $this->admin_id;
            if (getVersion() > "v1.5.5" && isset($val['typeid2'])){
                $info_value['stypeid'] = $val['typeid2'];
            }
            if (getVersion() > "v1.5.5" && isset($val['shorttitle'])){
                $info_value['subtitle'] = $val['shorttitle'];
            }
            $info[] = $info_value;
        }

        // 总文档数
        $pagetotal = $this->DeDb('archives')->field('id')->where($map)->count();

        return ['info' => $info, 'pagetotal' => $pagetotal];
    }

    //文章的tag标签
    private function getAllTags($aid_arr, $archivesRow = []){
        $map = [];
        $map['aid'] = ['in',$aid_arr];
        $result = $this->DeDb('taglist')->field("tid,aid,tag,arcrank,typeid")->where($map)->select();
        $taglist = $tagindexs = $tids = array();
        foreach ($result as $k => $v) {
            array_push($tids, $v['tid']);
            $v['tag'] = htmlspecialchars($v['tag']);
            $v['arcrank'] = $archivesRow[$v['aid']]['arcrank'];
            $v['lang']  = $this->admin_lang;
            $v['add_time'] = $archivesRow[$v['aid']]['add_time'];
            $v['update_time'] = $archivesRow[$v['aid']]['update_time'];
            $taglist[$k] = $v;
        }

        if (!empty($tids)) {
            $tagindexs = $this->DeDb('tagindex')->field("id,tag,typeid,count,total,weekcc,monthcc,weekup,monthup,addtime as add_time")->where(['id'=>['IN', $tids]])->select();
            foreach ($tagindexs as $key => $value) {
                $value['tag'] = htmlspecialchars($value['tag']);
                $value['seo_description'] = '';
                $value['lang'] = $this->admin_lang;
                $tagindexs[$key] = $value;
            }
        }

        $info = [
            'taglist'   => $taglist,
            'tagindex'  => $tagindexs,
            'tids'      => $tids,
        ];
        return $info;
    }

    /**
     * 递归查询所有的子类
     * @param array $arctype_child_all 存放所有的子栏目
     * @param int $id 栏目ID 或 父栏目ID
     */ 
    private function getAllChild(&$arctype_child_all, $id){
        $where['reid'] = $id;
        $where['channeltype'] = ['gt', 0];
        $arctype_child = $this->DeDb('arctype')->where($where)->getfield('id',true); 
        
        if(!empty($arctype_child)){
            $arctype_child_all = array_merge($arctype_child_all,$arctype_child);
            for($i=0;$i<count($arctype_child);$i++){
                $this->getAllChild($arctype_child_all,$arctype_child[$i]);
            }
        }
    }

    /*
     * 转换详情页数据
     */
    private function createArticle($result)
    {
        $msg = "";
        $aid_arr = [];
        $archivesRow = [];

        $specialCount = $this->DeDb('archives')->where(['channel'=>['eq', -1]])->count();
        if (!empty($specialCount)) {
            $typeid_zt = M('arctype')->where('current_channel', 7)->value('id');
            if (empty($typeid_zt)) {
                $dirname_zt = 'zhuanti_'.date('md');
                $arctypeZtRow = [
                    'channeltype'   => 7,
                    'current_channel'   => 7,
                    'typename' => '默认专题',
                    'dirname'   => $dirname_zt,
                    'dirpath'   => "/{$dirname_zt}",
                    'diy_dirpath'   => "/{$dirname_zt}",
                    'templist'  => 'lists_special.htm',
                    'tempview' => 'view_special.htm',
                    'seo_description'   => '',
                    'is_hidden' => 0,
                    'sort_order'    => 100,
                    'admin_id'  => $this->admin_id,
                    'lang'  => $this->admin_lang,
                    'add_time'  => $this->times,
                    'update_time'  => $this->times,
                ];
                $typeid_zt = M('arctype')->insertGetId($arctypeZtRow);
            }
        }

        foreach ($result as $key => $val) {
            $val['channel'] = $this->DedeChannel($val['channel'], 'add');

            if (7 == $val['channel'] && !empty($typeid_zt)) {
                $val['typeid'] = $typeid_zt;
            }

            $val['is_head'] = $val['is_recom'] = $val['is_slide'] = $val['is_special'] = $val['is_roll'] = $val['is_b'] = $val['is_litpic'] = $val['is_jump'] = 0;
            $flagArr = explode(',', $val['flag']);
            if (in_array('h', $flagArr)) $val['is_head'] = 1;
            if (in_array('c', $flagArr)) $val['is_recom'] = 1;
            if (in_array('f', $flagArr)) $val['is_slide'] = 1;
            if (in_array('a', $flagArr)) $val['is_special'] = 1;
            if (in_array('s', $flagArr)) $val['is_roll'] = 1;
            if (in_array('b', $flagArr)) $val['is_b'] = 1;
            if (in_array('p', $flagArr)) $val['is_litpic'] = 1;
            if (in_array('j', $flagArr)) $val['is_jump'] = 1;
            unset($val['flag']);

            empty($val['add_time']) && $val['add_time'] = $val['update_time'];
            empty($val['update_time']) && $val['update_time'] = $val['add_time'];

            if ($val['arcrank'] < -1) {
                $val['arcrank'] = -1;
            }

            $val['title'] = htmlspecialchars($val['title']);
            $val['seo_title'] = htmlspecialchars($val['seo_title']);
            $val['seo_description'] = htmlspecialchars($val['seo_description']);
            $val['lang'] = $this->admin_lang;
            //副标题
            if (isset($val['stypeid'])){
                if (!empty($val['stypeid'])){
                    $val['stypeid'] = ",".trim($val['stypeid'],',').",";
                } else {
                    $val['stypeid'] = '';
                }
            }
            array_push($aid_arr, $val['aid']);
            $result[$key] = $archivesRow[$val['aid']] = $val;
        }

        $singleList_1 = M('archives')->field('aid', true)->where('channel', 6)->select();

        $r = M('archives')->where(['aid'=>['IN', $aid_arr]])->whereOr('channel', 6)->delete();
        if ($r !== false) {
            $r2 = M('archives')->insertAll($result);
            if ($r2 !== false) {
                try {
                    /*频道封面转为单页模型*/
                    if (!empty($singleList_1)) {
                        $archivesModel = new \app\admin\model\Archives;
                        $rdata = $archivesModel->saveAll($singleList_1);
                        if ($rdata) {
                            $typeidArr = get_arr_column($singleList_1, 'typeid');
                            $singleList_2 = M('single_content')->field('id, aid, typeid')->where(['typeid'=>['IN', $typeidArr]])->select();
                            if (!empty($singleList_2)) {
                                foreach ($rdata as $k1 => $v1) {
                                    $aid_new = $v1->getData('aid');
                                    $typeid = $v1->getData('typeid');
                                    foreach ($singleList_2 as $_k2 => $_v2) {
                                        $singleList_2[$_k2]['update_time'] = $this->times;
                                        if ($_v2['typeid'] == $typeid) {
                                            $singleList_2[$_k2]['aid'] = $aid_new;
                                            break;
                                        }
                                    }
                                }
                                if (!empty($singleList_2)) {
                                    $singleContentModel = new \weapp\DedeToEyou\model\SingleContentModel;
                                    $singleContentModel->saveAll($singleList_2);
                                }
                            }
                        }
                    }
                    /*end*/
                } catch (\Exception $e) {}

                $this->createArticleContent($archivesRow);
                $this->createTags($aid_arr, $archivesRow);

                delFile(rtrim(RUNTIME_PATH, '/'), true);
            } else {
                $msg .= '<span>' . '转换失败！' . $e->getMessage() . '</span><br>';
            }
        } else {
            $msg .= '<span>' . '转换失败！' . $e->getMessage() . '</span><br>';
        }

        return $msg;
    }

    /*
     * 转换详情页tag
     */
    private function createTags($aid_arr = [], $archivesRow = [])
    {
        $allTags     = $this->getAllTags($aid_arr, $archivesRow);
        if (!empty($allTags['tids'])) {
            $r = M('taglist')->where(['tid'=>['IN', $allTags['tids']]])->delete();
            if ($r !== false) {
                try {
                    Db::query('alter table '.PREFIX.'taglist AUTO_INCREMENT 1');
                } catch (\Exception $e) {}
                $taglistModel = new \app\common\model\Taglist;
                $taglistModel->saveAll($allTags['taglist'], false);
            }

            $r = M('tagindex')->where(['id'=>['IN', $allTags['tids']]])->delete();
            if ($r !== false) {
                try {
                    Db::query('alter table '.PREFIX.'tagindex AUTO_INCREMENT 1');
                } catch (\Exception $e) {}
                $tagindexModel = new \weapp\DedeToEyou\model\TagindexModel;
                $tagindexModel->saveAll($allTags['tagindex'], false);
            }
        }
    }

    /*
     * 转换详情页内容
     */
    private function createArticleContent($archivesList = [])
    {
        // 织梦数据表前缀
        static $dede_prefix = null;
        if (null === $dede_prefix) {
            $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
            $weappData = json_decode($weappData['data'], true);
            $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
        }
        $result = group_same_key($archivesList, 'channel');
        foreach ($result as $channel => $info) {
            $channelfieldRow = Db::name('channelfield')->field('name,dtype,dfvalue')->where(['channel_id'=>$channel])->getAllWithIndex('name');
            if ($channel == 1) {
                $aids = $info_new = array();
                foreach ($info as $_ik => $_iv) {
                    array_push($aids, $_iv['aid']);
                    $info_new[$_iv['aid']] = $_iv;
                }
                $archivesRow = [];
                $contentRow = $this->DeDb('addonarticle')->field("*")->where(['aid'=>['IN', $aids]])->select();
                foreach ($contentRow as $key => $val) {
                    $val['content'] = $val['body'];
                    unset($val['body']);
                    $val['add_time'] = $val['update_time'] = $this->times;
                    foreach ($val as $_k2 => $_v2) {
                        if ('img' == $channelfieldRow[$_k2]['dtype']) {
                            preg_match_all('/\{dede\:img(\s+)([^\}]*)\}(.*)\{\/dede\:img\}/iUs', $val[$_k2], $imginfo);
                            if (!empty($imginfo[3][0])) {
                                $val[$_k2] = str_replace(' ', '', $imginfo[3][0]);
                            }
                        } else if ('htmltext' == $channelfieldRow[$_k2]['dtype']) {
                            if (preg_match('/^\/(.*)\.txt$/i', $val[$_k2])) {
                                $htmldata = @file_get_contents(dirname(ROOT_PATH).$val[$_k2]);
                                $val[$_k2] = $htmldata;
                            }
                            $val[$_k2] = str_replace(['&times;'], ['×'], $val[$_k2]);
                            $val[$_k2] = htmlspecialchars($val[$_k2]);
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['radio','select'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            if (!in_array($val[$_k2], $dfvalue_arr)) {
                                $val[$_k2] = current($dfvalue_arr);
                            }
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['checkbox'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            $val_tmp = explode(',', $val[$_k2]);
                            foreach ($val_tmp as $_k3 => $_v3) {
                                if (!in_array($_v3, $dfvalue_arr)) {
                                    unset($val_tmp[$_k3]);
                                }
                            }
                            $val[$_k2] = implode(',', $val_tmp);
                        }
                    }
                    $contentRow[$key] = $val;

                    $jumplinks = '';
                    if (!empty($info_new[$val['aid']]['is_jump'])) {
                        $jumplinks = !empty($val['redirecturl']) ? trim($val['redirecturl']) : '';
                    }
                    $archivesRow[] = [
                        'aid'   => $val['aid'],
                        'jumplinks' => $jumplinks,
                    ];
                }
                if (!empty($contentRow)) {
                    $articleContentModel = new \weapp\DedeToEyou\model\ArticleContentModel;
                    $articleContentModel->saveAll($contentRow);
                }
                if (!empty($archivesRow)) {
                    $archivesModel = new \app\admin\model\Archives;
                    $archivesModel->saveAll($archivesRow);
                }
            }
            else if ($channel == 2) {
                $aids = $info_new = array();
                foreach ($info as $_ik => $_iv) {
                    array_push($aids, $_iv['aid']);
                    $info_new[$_iv['aid']] = $_iv;
                }
                $archivesRow = [];
                $contentRow = [];
                $contentList = $this->DeDb('addonshop')->field("*")->where(['aid'=>['IN', $aids]])->select();
                foreach ($contentList as $key => $val) {
                    $val['content'] = $val['body'];
                    unset($val['body']);
                    $val['add_time'] = $val['update_time'] = $this->times;
                    $val['old_price'] = $val['price'];
                    unset($val['price']);
                    $val['users_price'] = $val['trueprice'];
                    unset($val['trueprice']);
                    foreach ($val as $_k2 => $_v2) {
                        if ('img' == $channelfieldRow[$_k2]['dtype']) {
                            preg_match_all('/\{dede\:img(\s+)([^\}]*)\}(.*)\{\/dede\:img\}/iUs', $val[$_k2], $imginfo);
                            if (!empty($imginfo[3][0])) {
                                $val[$_k2] = str_replace(' ', '', $imginfo[3][0]);
                            }
                        } else if ('htmltext' == $channelfieldRow[$_k2]['dtype']) {
                            if (preg_match('/^\/(.*)\.txt$/i', $val[$_k2])) {
                                $htmldata = @file_get_contents(dirname(ROOT_PATH).$val[$_k2]);
                                $val[$_k2] = $htmldata;
                            }
                            $val[$_k2] = str_replace(['&times;'], ['×'], $val[$_k2]);
                            $val[$_k2] = htmlspecialchars($val[$_k2]);
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['radio','select'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            if (!in_array($val[$_k2], $dfvalue_arr)) {
                                $val[$_k2] = current($dfvalue_arr);
                            }
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['checkbox'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            $val_tmp = explode(',', $val[$_k2]);
                            foreach ($val_tmp as $_k3 => $_v3) {
                                if (!in_array($_v3, $dfvalue_arr)) {
                                    unset($val_tmp[$_k3]);
                                }
                            }
                            $val[$_k2] = implode(',', $val_tmp);
                        }
                    }
                    $contentRow[] = $val;

                    $jumplinks = '';
                    if (!empty($info_new[$val['aid']]['is_jump'])) {
                        $jumplinks = !empty($val['redirecturl']) ? trim($val['redirecturl']) : '';
                    }
                    $archivesRow[] = [
                        'aid'   => $val['aid'],
                        'jumplinks' => $jumplinks,
                        'old_price' => !empty($val['old_price']) ? $val['old_price'] : 0,
                        'users_price' => !empty($val['users_price']) ? $val['users_price'] : 0,
                    ];
                }
                if (!empty($contentRow)) {
                    $productContentModel = new \weapp\DedeToEyou\model\ProductContentModel;
                    $productContentModel->saveAll($contentRow);
                }
                if (!empty($archivesRow)) {
                    $archivesModel = new \app\admin\model\Archives;
                    $archivesModel->saveAll($archivesRow);
                }

                $productImgRow = [];
                foreach ($info as $key => $val) {
                    if (2 == $val['channel'] && !empty($val['litpic'])) {
                        $productImgRow[] = [
                            'aid'   => $val['aid'],
                            'title' => $val['title'],
                            'image_url' => $val['litpic'],
                            'intro' => '',
                            'sort_order'    => 100,
                            'add_time'  => $this->times,
                            'update_time'  => $this->times,
                        ];
                    }
                }
                if (!empty($productImgRow)) {
                    $productImgModel = new \weapp\DedeToEyou\model\ProductImgModel;
                    $productImgModel->saveAll($productImgRow);
                }
            }
            else if ($channel == 3) {
                $aids = $info_new = array();
                foreach ($info as $_ik => $_iv) {
                    array_push($aids, $_iv['aid']);
                    $info_new[$_iv['aid']] = $_iv;
                }
                $imagesUploadRow = [];
                $contentRow = $this->DeDb('addonimages')->field("*")->where(['aid'=>['IN', $aids]])->select();
                foreach ($contentRow as $key => $val) {
                    preg_match_all('/\{dede\:img(\s+)ddimg=[\'|\"]([^\'\"]*)[\'|\"](\s+)text=[\'|\"]([^\'\"]*)[\'|\"](.*)\}(.*)\{\/dede\:img\}/iUs', $val['imgurls'], $imginfo);
                    if (!empty($imginfo[6]) && is_array($imginfo[6])) {
                        foreach ($imginfo[6] as $_kimg => $_vimg) {
                            $_vimg = str_replace(' ', '', $_vimg);
                            if (!empty($_vimg)) {
                                $imagesUploadRow[] = [
                                    'aid'   => $val['aid'],
                                    'title' => !empty($archivesList[$val['aid']]) ? $archivesList[$val['aid']]['title'] : '',
                                    'image_url' => trim($_vimg),
                                    'intro' => !empty($imginfo[4][$_kimg]) ? trim($imginfo[4][$_kimg]) : '',
                                    'sort_order'    => 100,
                                    'add_time'  => $this->times,
                                    'update_time'  => $this->times,
                                ];
                            }
                        }
                    }
                    $val['content'] = $val['body'];
                    unset($val['body']);
                    $val['add_time'] = $val['update_time'] = $this->times;
                    foreach ($val as $_k2 => $_v2) {
                        if ('img' == $channelfieldRow[$_k2]['dtype']) {
                            preg_match_all('/\{dede\:img(\s+)([^\}]*)\}(.*)\{\/dede\:img\}/iUs', $val[$_k2], $imginfo);
                            if (!empty($imginfo[3][0])) {
                                $val[$_k2] = str_replace(' ', '', $imginfo[3][0]);
                            }
                        } else if ('htmltext' == $channelfieldRow[$_k2]['dtype']) {
                            if (preg_match('/^\/(.*)\.txt$/i', $val[$_k2])) {
                                $htmldata = @file_get_contents(dirname(ROOT_PATH).$val[$_k2]);
                                $val[$_k2] = $htmldata;
                            }
                            $val[$_k2] = str_replace(['&times;'], ['×'], $val[$_k2]);
                            $val[$_k2] = htmlspecialchars($val[$_k2]);
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['radio','select'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            if (!in_array($val[$_k2], $dfvalue_arr)) {
                                $val[$_k2] = current($dfvalue_arr);
                            }
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['checkbox'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            $val_tmp = explode(',', $val[$_k2]);
                            foreach ($val_tmp as $_k3 => $_v3) {
                                if (!in_array($_v3, $dfvalue_arr)) {
                                    unset($val_tmp[$_k3]);
                                }
                            }
                            $val[$_k2] = implode(',', $val_tmp);
                        }
                    }
                    $contentRow[$key] = $val;

                    $jumplinks = '';
                    if (!empty($info_new[$val['aid']]['is_jump'])) {
                        $jumplinks = !empty($val['redirecturl']) ? trim($val['redirecturl']) : '';
                    }
                    $archivesRow[] = [
                        'aid'   => $val['aid'],
                        'jumplinks' => $jumplinks,
                    ];
                }
                if (!empty($contentRow)) {
                    $imagesContentModel = new \weapp\DedeToEyou\model\ImagesContentModel;
                    $imagesContentModel->saveAll($contentRow);
                }
                if (!empty($archivesRow)) {
                    $archivesModel = new \app\admin\model\Archives;
                    $archivesModel->saveAll($archivesRow);
                }
                if (!empty($imagesUploadRow)) {
                    $imagesUploadModel = new \weapp\DedeToEyou\model\ImagesUploadModel;
                    $imagesUploadModel->saveAll($imagesUploadRow);
                }
            }
            else if ($channel == 4) {
                $aids = $info_new = array();
                foreach ($info as $_ik => $_iv) {
                    array_push($aids, $_iv['aid']);
                    $info_new[$_iv['aid']] = $_iv;
                }
                $archivesRow = [];
                $downloadFileRow = [];
                $contentRow = $this->DeDb('addonsoft')->field("*")->where(['aid'=>['IN', $aids]])->select();
                $LevelData = M('users_level')->field('level_id,level_value')->getAllWithIndex('level_value');
                foreach ($contentRow as $key => $val) {
                    $jumplinks = '';
                    if (!empty($info_new[$val['aid']]['is_jump'])) {
                        $jumplinks = !empty($val['redirecturl']) ? trim($val['redirecturl']) : '';
                    }
                    $archivesRow[] = [
                        'aid'   => $val['aid'],
                        'jumplinks' => $jumplinks,
                        'arc_level_id' => !empty($LevelData[$val['daccess']]['level_id']) ? $LevelData[$val['daccess']]['level_id'] : 0,
                    ];

                    if (!empty($val['softlinks'])) {
                        preg_match_all('/\{dede\:link(\s+)(.*)\'(\s?)\}([^\'\"\}\{]*)\{\/dede\:link\}/iUs', $val['softlinks'], $imginfo);
                        if (!empty($imginfo[4]) && is_array($imginfo[4])) {
                            foreach ($imginfo[4] as $_k2 => $_v2) {
                                $_v2 = str_replace(' ', '', $_v2);
                                if (!empty($_v2) && trim($_v2)) {
                                    $file_tmp2 = explode('/', $_v2);
                                    $file_name = end($file_tmp2);
                                    $server_name = '立即下载';
                                    if (!empty($imginfo[2][$_k2])) {
                                        $server_name = preg_replace('/^(.*)text\=(\'|\")([^\'\"]*)/i', '${3}', $imginfo[2][$_k2]);
                                    }
                                    $downloadFileRow[] = [
                                        'aid'   => $val['aid'],
                                        'title' => !empty($archivesList[$val['aid']]) ? $archivesList[$val['aid']]['title'] : '',
                                        'file_url'  => $_v2,
                                        'file_ext'  => '',
                                        'file_name' => $file_name,
                                        'server_name'   => $server_name,
                                        'file_mime' => '',
                                        'uhash' => md5($_v2),
                                        'md5file' => md5($_v2),
                                        'is_remote' => 1,
                                        'sort_order'    => 100,
                                        'add_time'  => $this->times,
                                        'update_time'  => $this->times,
                                    ];
                                }
                            }
                        }
                    }

                    $val['content'] = $val['introduce'];
                    unset($val['introduce']);
                    $val['add_time'] = $val['update_time'] = $this->times;
                    $val['level_value'] = $val['daccess'];
                    unset($val['daccess']);
                    foreach ($val as $_k2 => $_v2) {
                        if ('img' == $channelfieldRow[$_k2]['dtype']) {
                            preg_match_all('/\{dede\:img(\s+)([^\}]*)\}(.*)\{\/dede\:img\}/iUs', $val[$_k2], $imginfo);
                            if (!empty($imginfo[3][0])) {
                                $val[$_k2] = str_replace(' ', '', $imginfo[3][0]);
                            }
                        } else if ('htmltext' == $channelfieldRow[$_k2]['dtype']) {
                            if (preg_match('/^\/(.*)\.txt$/i', $val[$_k2])) {
                                $htmldata = @file_get_contents(dirname(ROOT_PATH).$val[$_k2]);
                                $val[$_k2] = $htmldata;
                            }
                            $val[$_k2] = str_replace(['&times;'], ['×'], $val[$_k2]);
                            $val[$_k2] = htmlspecialchars($val[$_k2]);
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['radio','select'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            if (!in_array($val[$_k2], $dfvalue_arr)) {
                                $val[$_k2] = current($dfvalue_arr);
                            }
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['checkbox'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            $val_tmp = explode(',', $val[$_k2]);
                            foreach ($val_tmp as $_k3 => $_v3) {
                                if (!in_array($_v3, $dfvalue_arr)) {
                                    unset($val_tmp[$_k3]);
                                }
                            }
                            $val[$_k2] = implode(',', $val_tmp);
                        }
                    }
                    $contentRow[$key] = $val;
                }
                if (!empty($contentRow)) {
                    $downloadContentModel = new \weapp\DedeToEyou\model\DownloadContentModel;
                    $downloadContentModel->saveAll($contentRow);
                }
                if (!empty($archivesRow)) {
                    $archivesModel = new \app\admin\model\Archives;
                    $archivesModel->saveAll($archivesRow);
                }
                if (!empty($downloadFileRow)) {
                    $downloadFileModel = new \weapp\DedeToEyou\model\DownloadFileModel;
                    $downloadFileModel->saveAll($downloadFileRow);
                }
            }
            else if ($channel == 7) {
                $aids = $info_new = array();
                foreach ($info as $_ik => $_iv) {
                    array_push($aids, $_iv['aid']);
                    $info_new[$_iv['aid']] = $_iv;
                }
                $specialNodeRow = [];
                $contentRow = $this->DeDb('addonspec')->field("*")->where(['aid'=>['IN', $aids]])->select();
                foreach ($contentRow as $key => $val) {
                    if (!empty($val['note'])) {
                        preg_match_all('/\{dede\:specnote(\s+)(.*)idlist=[\'|\"]([\,0-9]*)[\'|\"](.*)name=[\'|\"]([^\'\"]*)[\'|\"](.*)noteid=[\'|\"]([^\'\"]*)[\'|\"](.*)isauto=[\'|\"]([0-9]*)[\'|\"](.*)rownum=[\'|\"]([0-9]*)[\'|\"](.*)keywords=[\'|\"]([^\'\"]*)[\'|\"](.*)typeid=[\'|\"]([0-9]*)[\'|\"](.*)\{\/dede\:specnote}/iUs', $val['note'], $matches);
                        if (!empty($matches[5]) && is_array($matches[5])) {
                            foreach ($matches[5] as $_knote => $_vnote) {
                                $_vnote = trim($_vnote);
                                if (!empty($_vnote)) {
                                    $specialNodeRow[] = [
                                        'aid'   => $val['aid'],
                                        'title' => ('默认节点' == $_vnote) ? '节点1' : $_vnote,
                                        'code' => !empty($matches[7][$_knote]) ? ('default' == $matches[7][$_knote] ? 'default1' : $matches[7][$_knote]) : "default{$_knote}",
                                        'isauto' => !empty($matches[9][$_knote]) ? intval($matches[9][$_knote]) : 0,
                                        'keywords' => !empty($matches[13][$_knote]) ? trim($matches[13][$_knote]) : '',
                                        'typeid' => !empty($matches[15][$_knote]) ? intval($matches[15][$_knote]) : 0,
                                        'aidlist' => !empty($matches[3][$_knote]) ? $matches[3][$_knote] : '',
                                        'row' => !empty($matches[11][$_knote]) ? $matches[11][$_knote] : 0,
                                        'sort_order'    => 100,
                                        'lang'  => $this->admin_lang,
                                        'add_time'  => $this->times,
                                        'update_time'  => $this->times,
                                    ];
                                }
                            }
                        }
                    }

                    unset($val['note']);
                    $val['content'] = !empty($archivesList[$val['aid']]['seo_description']) ? htmlspecialchars($archivesList[$val['aid']]['seo_description']) : '';
                    $val['add_time'] = $val['update_time'] = $this->times;
                    foreach ($val as $_k2 => $_v2) {
                        if ('img' == $channelfieldRow[$_k2]['dtype']) {
                            preg_match_all('/\{dede\:img(\s+)([^\}]*)\}(.*)\{\/dede\:img\}/iUs', $val[$_k2], $imginfo);
                            if (!empty($imginfo[3][0])) {
                                $val[$_k2] = str_replace(' ', '', $imginfo[3][0]);
                            }
                        } else if ('htmltext' == $channelfieldRow[$_k2]['dtype']) {
                            if (preg_match('/^\/(.*)\.txt$/i', $val[$_k2])) {
                                $htmldata = @file_get_contents(dirname(ROOT_PATH).$val[$_k2]);
                                $val[$_k2] = $htmldata;
                            }
                            $val[$_k2] = str_replace(['&times;'], ['×'], $val[$_k2]);
                            $val[$_k2] = htmlspecialchars($val[$_k2]);
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['radio','select'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            if (!in_array($val[$_k2], $dfvalue_arr)) {
                                $val[$_k2] = current($dfvalue_arr);
                            }
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['checkbox'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            $val_tmp = explode(',', $val[$_k2]);
                            foreach ($val_tmp as $_k3 => $_v3) {
                                if (!in_array($_v3, $dfvalue_arr)) {
                                    unset($val_tmp[$_k3]);
                                }
                            }
                            $val[$_k2] = implode(',', $val_tmp);
                        }
                    }
                    $contentRow[$key] = $val;

                    $jumplinks = '';
                    if (!empty($info_new[$val['aid']]['is_jump'])) {
                        $jumplinks = !empty($val['redirecturl']) ? trim($val['redirecturl']) : '';
                    }
                    $archivesRow[] = [
                        'aid'   => $val['aid'],
                        'jumplinks' => $jumplinks,
                    ];
                }
                if (!empty($contentRow)) {
                    $specialContentModel = new \weapp\DedeToEyou\model\SpecialContentModel;
                    $specialContentModel->saveAll($contentRow);
                }
                if (!empty($specialNodeRow)) {
                    $specialNodeModel = new \weapp\DedeToEyou\model\SpecialNodeModel;
                    $specialNodeModel->saveAll($specialNodeRow);
                }
                if (!empty($archivesRow)) {
                    $archivesModel = new \app\admin\model\Archives;
                    $archivesModel->saveAll($archivesRow);
                }
            }
            else if ($channel > 100) {
                $channeltypeInfo = $this->DeDb('channeltype')->field('id,nid,addtable')->where(['id'=>($channel - 100)])->find();
                $addtable = $channeltypeInfo['addtable'];
                if (!empty($dede_prefix)) {
                    $addtable = preg_replace('/^'.$dede_prefix.'/i', '', $addtable);
                }

                $aids = $info_new = array();
                foreach ($info as $_ik => $_iv) {
                    array_push($aids, $_iv['aid']);
                    $info_new[$_iv['aid']] = $_iv;
                }
                $contentRow = $this->DeDb($addtable)->field("*")->where(['aid'=>['IN', $aids]])->select();
                foreach ($contentRow as $key => $val) {
                    if (!empty($val['imgurls']) && stristr($val['imgurls'], 'dede:img')) {
                        preg_match_all('/\{dede\:img(\s+)ddimg=[\'|\"]([^\'\"]*)[\'|\"](\s+)text=[\'|\"]([^\'\"]*)[\'|\"](.*)\}(.*)\{\/dede\:img\}/iUs', $val['imgurls'], $imginfo);
                        if (!empty($imginfo[6]) && is_array($imginfo[6])) {
                            $imgurls = [];
                            foreach ($imginfo[6] as $_kimg => $_vimg) {
                                $_vimg = str_replace(' ', '', $_vimg);
                                if (!empty($_vimg)) {
                                    $imgurls[] = [
                                        'image_url' => trim($_vimg),
                                        'intro' => !empty($imginfo[4][$_kimg]) ? trim($imginfo[4][$_kimg]) : '',
                                    ];
                                }
                            }
                            $val['imgurls'] = !empty($imgurls) ? serialize($imgurls) : '';
                        }
                    }
                    if (!isset($val['content'])) {
                        $val['content'] = '';
                        if (isset($val['body'])) {
                            $val['content'] = !empty($val['body']) ? $val['body'] : '';
                            unset($val['body']);
                        }
                    }
                    $val['add_time'] = $val['update_time'] = $this->times;
                    foreach ($val as $_k2 => $_v2) {
                        if ('img' == $channelfieldRow[$_k2]['dtype']) {
                            preg_match_all('/\{dede\:img(\s+)([^\}]*)\}(.*)\{\/dede\:img\}/iUs', $val[$_k2], $imginfo);
                            if (!empty($imginfo[3][0])) {
                                $val[$_k2] = str_replace(' ', '', $imginfo[3][0]);
                            }
                        } else if ('htmltext' == $channelfieldRow[$_k2]['dtype']) {
                            if (preg_match('/^\/(.*)\.txt$/i', $val[$_k2])) {
                                $htmldata = @file_get_contents(dirname(ROOT_PATH).$val[$_k2]);
                                $val[$_k2] = $htmldata;
                            }
                            $val[$_k2] = str_replace(['&times;'], ['×'], $val[$_k2]);
                            $val[$_k2] = htmlspecialchars($val[$_k2]);
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['radio','select'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            if (!in_array($val[$_k2], $dfvalue_arr)) {
                                $val[$_k2] = current($dfvalue_arr);
                            }
                        } else if (in_array($channelfieldRow[$_k2]['dtype'], ['checkbox'])) {
                            $dfvalue = $channelfieldRow[$_k2]['dfvalue'];
                            $dfvalue_arr = explode(',', $dfvalue);
                            $val_tmp = explode(',', $val[$_k2]);
                            foreach ($val_tmp as $_k3 => $_v3) {
                                if (!in_array($_v3, $dfvalue_arr)) {
                                    unset($val_tmp[$_k3]);
                                }
                            }
                            $val[$_k2] = implode(',', $val_tmp);
                        }
                    }
                    $contentRow[$key] = $val;

                    $jumplinks = '';
                    if (!empty($info_new[$val['aid']]['is_jump'])) {
                        $jumplinks = !empty($val['redirecturl']) ? trim($val['redirecturl']) : '';
                    }
                    $archivesRow[] = [
                        'aid'   => $val['aid'],
                        'jumplinks' => $jumplinks,
                    ];
                }
                if (!empty($contentRow)) {
                    $ey_addtable = preg_replace('/^addon/i', '', $addtable);
                    $ey_addtable = is_numeric($ey_addtable) ? 'addon'.intval($ey_addtable) : strtolower($ey_addtable);
                    if (empty($ey_addtable)) {
                        $this->error('自定义频道模型的内容转换失败，数据表名是空的', null, [], 8);
                    }
                    $class = '\weapp\DedeToEyou\model\\'.ucfirst($ey_addtable).'ContentModel';
                    $model = new $class;
                    $model->saveAll($contentRow);
                }
                if (!empty($archivesRow)) {
                    $archivesModel = new \app\admin\model\Archives;
                    $archivesModel->saveAll($archivesRow);
                }
            }
        }
    }

    /**
     * 转换频道模型的自定义字段
     */
    public function DedeDiyChannelfields()
    {
        // 织梦数据表前缀
        static $dede_prefix = null;
        if (null === $dede_prefix) {
            $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
            $weappData = json_decode($weappData['data'], true);
            $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
        }
        // 栏目与自定义字段绑定表
        $channelfield_bind_count = Db::name('channelfield_bind')->count('id');
        if ($channelfield_bind_count < 20) {
            Db::name('channelfield_bind')->where(['id'=>['gt', 0]])->delete();
            $channelfield_bind_count = 0;
        }
        // 织梦的模型列表，排除分类信息模型
        $is_system_channel = 1; // 是否系统模型
        $channeltypeRow = $this->DeDb('channeltype')->field('id,nid,fieldset,addtable')->where([
            'nid'=>['NOT IN', ['infos']]
        ])->order('nid asc')->select();
        $customFieldsArr = [];
        foreach ($channeltypeRow as $key => $val) {
            if ('image' == $val['nid']) {
                $table = PREFIX . 'images_content';
            } else if ('shop' == $val['nid']) {
                $table = PREFIX . 'product_content';
            } else if ('soft' == $val['nid']) {
                $table = PREFIX . 'download_content';
            } else if ('spec' == $val['nid']) {
                $table = PREFIX . 'special_content';
            } else if ('article' == $val['nid']) {
                $table = PREFIX . 'article_content';
            } else {
                $is_system_channel = 0;
                $addtable = $val['addtable'];
                if (!empty($dede_prefix)) {
                    $addtable = preg_replace('/^'.$dede_prefix.'/i', '', $addtable);
                }
                $addtable = preg_replace('/^addon/i', '', $addtable);
                $addtable = is_numeric($addtable) ? 'addon'.intval($addtable) : strtolower($addtable);
                if (empty($addtable)) {
                    $this->error('自定义字段转换失败，数据表名是空的', null, [], 8);
                    // continue;
                }
                $table = PREFIX . $addtable . '_content';
            }
            preg_match_all("/<field:([A-Za-z0-9_-]+)(\s+)([^>]*)itemname=[\'|\"]([^\'\"]*)[\'|\"](\s+)([^>]*)type=[\'|\"]([a-z]+)[\'|\"]([^>]*)>/", $val['fieldset'], $matches);
            if (!empty($matches[1])) {
                if ($val['nid'] == 'article') {
                    $nofields = ['body'];
                } 
                else if ($val['nid'] == 'image') {
                    $nofields = ['pagestyle','imgurls','body'];
                } 
                else if ($val['nid'] == 'soft') {
                    $nofields = ['filetype','language','softtype','accredit','os','softrank','officialUrl','officialDemo','softsize','softlinks','introduce','daccess','needmoney'];
                } 
                else if ($val['nid'] == 'shop') {
                    $nofields = ['body','price','trueprice','brand','units','vocation','infotype','uptime'];
                } 
                else if ($val['nid'] == 'spec') {
                    $nofields = ['note'];
                }
                else {
                    $nofields = ['pagestyle'];
                }
                foreach ($matches[1] as $_k => $_v) {
                    if (!empty($_v) && !in_array($_v, $nofields)) {
                        if (empty($is_system_channel)) {
                            if ('body' == $_v) {
                                $_v = 'content';
                            }
                        }
                        $fieldTitle = !empty($matches[4][$_k]) ? $matches[4][$_k] : '默认字段名';
                        if ('imgurls' == $_v) {
                            $fieldType = 'imgurls';
                        } else {
                            $fieldType = !empty($matches[7][$_k]) ? $matches[7][$_k] : 'text';
                        }
                        $customFieldsArr[$val['nid']][$_v] = [
                            'field' => $_v,
                            'title' => $fieldTitle,
                            'fieldset'  => $matches[0][$_k],
                            'typeDe'  => $fieldType,
                            'typeEy'  => $this->toDedeFieldtype($fieldType),
                        ];
                    }
                }
            }

            /*重新生成数据表字段缓存文件*/
            try {
                schemaTable($table);
            } catch (\Exception $e) {}
            /*--end*/
            $fieldlist = Db::table($table)->getFieldsType();
            foreach ($customFieldsArr[$val['nid']] as $_k => $_v) {
                try {
                    if (!empty($fieldlist[$_v['field']])) {
                        $this->channel_field_del($this->DedeChannel($val['id'], 'add'), $_v['field']); // 删除要新增的自定义字段
                    }
                } catch (\Exception $e) {
                    if (!empty($fieldlist[$_v['field']])) continue; // 忽略已经新增过的字段
                }

                $fieldset = $_v['fieldset'];
                preg_match_all("/<field:([A-Za-z0-9_-]+)(\s+)([^>]*)default=[\'|\"]([^\'\"]*)[\'|\"]([^>]*)>/", $fieldset, $matches);
                $dfvalue = !empty($matches[4][0]) ? trim($matches[4][0]) : '';
                /*去除中文逗号，过滤左右空格与空值、以及单双引号*/
                if (!empty($dfvalue)) {
                    $dfvalue    = str_replace('，', ',', $dfvalue);
                    if (in_array($_v['typeEy'], ['radio','checkbox','select','region'])) {
                        $pattern    = ['"', '\'', ';', '&', '?', '='];
                        $dfvalue    = func_preg_replace($pattern, '', $dfvalue);
                    }
                    $dfvalueArr = explode(',', $dfvalue);
                    foreach ($dfvalueArr as $_k2 => $_v2) {
                        $tmp_val = trim($_v2);
                        if (empty($tmp_val)) {
                            unset($dfvalueArr[$_k2]);
                            continue;
                        }
                        $dfvalueArr[$_k2] = $tmp_val;
                    }
                    $dfvalueArr = array_unique($dfvalueArr);
                    $dfvalue = implode(',', $dfvalueArr);
                }
                /*--end*/

                $saveData = [
                    'title' => $_v['title'],
                    'name'  => $_v['field'],
                    'dtype' => $_v['typeEy'],
                    'dfvalue'   => $dfvalue,
                    'dfvalue_unit' => '',
                    'IsScreening_status' => 0,
                    'remark' => '',
                    'typeids' => [0],
                    'channel_id'    => $this->DedeChannel($val['id'], 'add'),
                    'is_screening' => 0,
                ];
                /*组装完整的SQL语句，并执行新增字段*/
                $fieldinfos = $this->fieldLogic->GetFieldMake($saveData['dtype'], $saveData['name'], $dfvalue, $saveData['title']);
                $ntabsql    = $fieldinfos[0];
                $buideType  = $fieldinfos[1];
                $maxlength  = $fieldinfos[2];
                $ntabsql    = str_replace("varchar({$maxlength})", 'varchar(251)', $ntabsql);
                $sql        = " ALTER TABLE `$table` ADD $ntabsql ";
                if (false !== Db::execute($sql)) {
                    /*保存新增字段的记录*/
                    $newData = array(
                        'dfvalue'     => $dfvalue,
                        'maxlength'   => $maxlength,
                        'define'      => $buideType,
                        'ifcontrol'   => 0,
                        'sort_order'  => 100,
                        'add_time'    => getTime(),
                        'update_time' => getTime(),
                    );
                    $saveData    = array_merge($saveData, $newData);
                    Db::name('channelfield')->save($saveData);
                    $field_id = Db::name('channelfield')->getLastInsID();
                    /*--end*/

                    /*保存栏目与字段绑定的记录*/
                    $typeids = $saveData['typeids'];
                    if (!empty($typeids) && !empty($channelfield_bind_count)) {
                        /*多语言*/
                        if (is_language()) {
                            $attr_name_arr = [];
                            foreach ($typeids as $_k2 => $_v2) {
                                $attr_name_arr[] = 'tid' . $_v2;
                            }
                            $new_typeid_arr = Db::name('language_attr')->where([
                                'attr_name'  => ['IN', $attr_name_arr],
                                'attr_group' => 'arctype',
                            ])->column('attr_value');
                            !empty($new_typeid_arr) && $typeids = $new_typeid_arr;
                        }
                        /*--end*/
                        $addData = [];
                        foreach ($typeids as $_k2 => $_v2) {
                            if (1 < count($typeids) && empty($_v2)) {
                                continue;
                            }
                            $addData[] = [
                                'typeid'      => $_v2,
                                'field_id'    => $field_id,
                                'add_time'    => getTime(),
                                'update_time' => getTime(),
                            ];
                        }
                        !empty($addData) && model('ChannelfieldBind')->saveAll($addData);
                    }
                    /*--end*/

                    /*重新生成数据表字段缓存文件*/
                    try {
                        schemaTable($table);
                    } catch (\Exception $e) {}
                    /*--end*/
                }
            }
        }
    }

    /**
     * 织梦自定义字段类型，转为易优类型
     * @param  string $fieldType [description]
     * @return [type]            [description]
     */
    private function toDedeFieldtype($fieldType = '')
    {
        switch ($fieldType) {
            case 'textchar':
                $fieldType = 'text';
                break;
            case 'multitext':
                $fieldType = 'multitext';
                break;
            case 'htmltext':
            case 'textdata':
                $fieldType = 'htmltext';
                break;
            case 'imgfile':
                $fieldType = 'img';
                break;
            case 'imgurls':
                $fieldType = 'imgs';
                break;
            case 'addon':
            case 'softlinks':
                $fieldType = 'file';
                break;
        }

        return $fieldType;
    }

    /**
     * 转换自定义模型
     */
    public function DedeDiyChannelType()
    {
        // 织梦数据表前缀
        static $dede_prefix = null;
        if (null === $dede_prefix) {
            $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
            $weappData = json_decode($weappData['data'], true);
            $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
        }
        // 易优官方内置的模型标识
        $ey_channel_nid = ['article','product','images','download','media','single','special','guestbook','ask'];
        // 织梦的自定义模型列表
        $channeltypeRow = $this->DeDb('channeltype')->field('id,nid,typename as ntitle,fieldset,addtable')->where([
            'nid'=>['NOT IN', ['article','image','soft','spec','shop','infos']]
        ])->order('id asc')->select();
        foreach ($channeltypeRow as $key => $val) {
            $addtable = $val['addtable'];
            if (!empty($dede_prefix)) {
                $addtable = preg_replace('/^'.$dede_prefix.'/i', '', $addtable);
            }
            $addtable = preg_replace('/^addon/i', '', $addtable);
            $addtable = is_numeric($addtable) ? 'addon'.intval($addtable) : strtolower($addtable);
            if (empty($addtable)) {
                $this->error('频道模型转换失败，数据表名是空的', null, [], 8);
                // continue;
            }
            $nid = $addtable;
            if (in_array($nid, $ey_channel_nid)) {
                $nid = $nid.$val['id'];
            }
            $new_id = $val['id'] + 100;
            $saveData = [
                'id'    => $new_id,
                'nid'   => $nid,
                'title' => $val['ntitle'].'模型',
                'ntitle'=> $val['ntitle'],
                'table' => $addtable,
                'ctl_name' => ucfirst($nid),
                'data'  => '',
                'ifsystem' => 0,
                'is_release'    => 1,
                'sort_order'    => $new_id,
                'add_time'  => getTime(),
                'update_time'  => getTime(),
            ];

            // 删除已存在的模型
            $this->channeltype_del($new_id);
            // 创建文件以及数据表
            $this->create_sql_file($saveData);

            $insertId = Db::name('channeltype')->insertGetId($saveData);
            if (!empty($insertId)) {
                // 复制模型字段基础数据
                $this->fieldLogic->synArchivesTableColumns($insertId);

                try {
                    /*追加到快速入口列表*/
                    $this->syn_custom_quickmenu($saveData, $insertId);
                    /*end*/

                    schemaTable($saveData['table'].'_content');
                } catch (\Exception $e) {}

                delFile(CACHE_PATH, true);
                extra_cache('admin_channeltype_list_logic', NULL);
            }
        }
    }

    // 创建文件以及数据表
    private function create_sql_file($post) {
        $web_tpl_theme = tpCache('web.web_tpl_theme');
        $web_tpl_theme = !empty($web_tpl_theme) ? $web_tpl_theme : 'eyou';
        $view_suffix = config('template.view_suffix');
        $demopath = 'data/model/';
        $fileArr = []; // 生成的相关文件记录
        $filelist = getDirFile($demopath);
        foreach ($filelist as $key => $file) {
            if (stristr($file, 'custom_model_path')) {
                unset($filelist[$key]);
                continue;
            }
            $src = $demopath.$file;
            $dst = $file;
            $dst = str_replace('CustomModel', $post['ctl_name'], $dst);
            $dst = str_replace('custommodel', $post['nid'], $dst);
            $dst = str_replace('template/pc/', 'template/'.$web_tpl_theme.'/pc/', $dst);
            /*记录相关文件*/
            if (!stristr($dst, 'custom_model_path')) {
                array_push($fileArr, $dst);
            }
            /*--end*/
            $is_create_tpl = stristr($dst, '.'.$view_suffix); // 是否要生成前台模板文件
            if(!$is_create_tpl && tp_mkdir(dirname($dst))) {
                $fileContent = @file_get_contents($src);
                $fileContent = str_replace('CustomModel', $post['ctl_name'], $fileContent);
                $fileContent = str_replace('custommodel', strtolower($post['nid']), $fileContent);
                $fileContent = str_replace('CUSTOMMODEL', strtoupper($post['nid']), $fileContent);
                if (stristr($file, 'lists_custommodel.'.$view_suffix)) {
                    $replace = <<<EOF
<section class="article-list">
                    {eyou:list pagesize="10" titlelen="38"}
                    <article>
                        {eyou:notempty name="\$field.is_litpic"}
                        <a href="{\$field.arcurl}" title="{\$field.title}" style="float: left; margin-right: 10px"> <img src="{\$field.litpic}" alt="{\$field.title}" height="100" /> </a>
                        {/eyou:notempty} 
                        <h2><a href="{\$field.arcurl}" class="">{\$field.title}</a><span>{\$field.click}°C</span></h2>
                        <div class="excerpt">
                            <p>{\$field.seo_description}</p>
                        </div>
                        <div class="meta">
                            <span class="item"><time>{\$field.add_time|MyDate='Y-m-d',###}</time></span>
                            <span class="item">{\$field.typename}</span>
                        </div>
                    </article>
                    {/eyou:list}
                </section>
                <section class="list-pager">
                    {eyou:pagelist listitem='index,pre,pageno,next,end' listsize='2' /}
                    <div class="clear"></div>
                </section>
EOF;
                    $fileContent = str_replace("<!-- #list# -->", $replace, $fileContent);
                }

                $puts = @file_put_contents($dst, $fileContent);
                if (!$puts) {
                    $this->error('创建自定义模型生成相关文件失败，请检查站点目录权限！');
                } else {
                    // 判断是否存在手机端目录，同时生成一份
                    $tplplan = "template/".$web_tpl_theme."/mobile";
                    $planPath = realpath($tplplan);
                    if (file_exists($planPath)) {
                        $dst_m = str_replace('template/'.$web_tpl_theme.'/pc/', 'template/'.$web_tpl_theme.'/mobile/', $dst);
                        @file_put_contents($dst_m, $fileContent);
                    }
                }
            }
        }
        @file_put_contents($demopath.'custom_model_path/'.$post['nid'].'.filelist.txt', implode("\n\r", $fileArr));

        // 自定义模型附表的模型文件
        $src = 'weapp/DedeToEyou/model/ArticleContentModel.php';
        $dst = 'weapp/DedeToEyou/model/'.$post['ctl_name'].'ContentModel.php';
        $fileContent = @file_get_contents($src);
        $fileContent = str_replace('Article', $post['ctl_name'], $fileContent);
        $fileContent = str_replace('article', strtolower($post['nid']), $fileContent);
        @file_put_contents($dst, $fileContent);

        // 创建自定义模型附加表
        if (empty($post['ifsystem'])) {
            $table = 'ey_'.$post['table'].'_content';
            $tableSql = <<<EOF
DROP TABLE IF EXISTS `{$table}`;
CREATE TABLE `{$table}` (
  `id`          int(10) NOT NULL    AUTO_INCREMENT,
  `aid`         int(10) DEFAULT '0' COMMENT         '文档ID',
  `add_time`    int(11) DEFAULT '0' COMMENT         '新增时间',
  `update_time` int(11) DEFAULT '0' COMMENT         '更新时间',
  PRIMARY KEY (`id`),
  KEY `aid` (`aid`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='附加表';
EOF;
            $sqlFormat  = $this->sql_split($tableSql, PREFIX);

            // 执行SQL语句
            try {
                $counts = count($sqlFormat);
                for ($i = 0; $i < $counts; $i++) {
                    $sql = trim($sqlFormat[$i]);
                    if (stristr($sql, 'CREATE TABLE')) {
                        Db::execute($sql);
                    } else {
                        if(trim($sql) == '')
                           continue;
                        Db::execute($sql);
                    }
                }
            } catch (\Exception $e) {
                $this->error('数据库表创建失败，请检查'.$table.'表是否存在并删除，不行就请求技术支持！');
            }
        }
    }

    // 解析sql语句
    private function sql_split($sql, $tablepre) {
        if ($tablepre != "ey_")
            $sql = str_replace("`ey_", '`'.$tablepre, $sql);
              
        $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);
        
        $sql = str_replace("\r", "\n", $sql);
        $ret = array();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-')
                    $ret[$num] .= $query;
            }
            $num++;
        }
        return $ret;
    }

    /**
     * 同步自定义模型的快捷导航
     */
    private function syn_custom_quickmenu($data = [], $insertId)
    {
        $saveData = [
            [
                'title' => $data['title'],
                'laytext'   => $data['title'].'列表',
                'type' => 1,
                'controller' => 'Custom',
                'action' => 'index',
                'vars' => 'channel='.$insertId,
                'sort_order' => 100,
                'groups'    => 1,
                'add_time' => getTime(),
                'update_time' => getTime(),
            ],
            [
                'title' => $data['title'],
                'laytext'   => $data['title'].'列表',
                'type' => 2,
                'controller' => 'Custom',
                'action' => 'index',
                'vars' => 'channel='.$insertId,
                'sort_order' => 100,
                'groups'    => 1,
                'add_time' => getTime(),
                'update_time' => getTime(),
            ],
        ];
        model('Quickentry')->saveAll($saveData);
    }

    /**
     * 删除-模型字段
     */
    private function channel_field_del($channel_id, $field_name = '')
    {
        $id = Db::name('channelfield')->where(['channel_id'=>$channel_id, 'name'=>$field_name])->value('id');
        if (!empty($id)) {
            /*删除表字段*/
            $row = $this->fieldLogic->delChannelField($id);
            /*--end*/
            if (0 < $row['code']) {
                $map       = array(
                    'id'         => array('eq', $id),
                    'channel_id' => $channel_id,
                );
                /*删除字段的记录*/
                Db::name('channelfield')->where($map)->delete();
                /*--end*/
                /*删除栏目与字段绑定的记录*/
                model('ChannelfieldBind')->where(['field_id' => $id])->delete();
                /*--end*/
            }
            \think\Cache::clear('channelfield');
        }
    }

    /**
     * 删除自定义模型
     */
    private function channeltype_del($channel_id = '')
    {
        if (!empty($channel_id)) {
            $result = Db::name('channeltype')->field('id,title,nid')->where(['id'=>$channel_id])->select();
            $r = Db::name('channeltype')->where(['id'=>$channel_id])->delete();
            if (false !== $r) {
                // 删除栏目
                $arctype = Db::name('arctype')->where(['channeltype|current_channel'=>$channel_id])->delete();
                // 删除文章
                $archives = Db::name('archives')->where(['channel'=>$channel_id])->delete();
                // 删除自定义字段
                $channelfield = Db::name('channelfield')->where(['channel_id'=>$channel_id])->delete();

                // 删除文件
                foreach ($result as $key => $value) {
                    $nid = $value['nid'];

                    try {
                        /*删除快速入口的相关数据*/
                        Db::name('quickentry')->where([
                                'groups'    => 1,
                                'controller'    => 'Custom',
                                'action'    => 'index',
                                'vars'  => 'channel='.$value['id'],
                            ])->delete();
                        /*end*/

                        // 删除相关数据表
                        Db::execute('DROP TABLE '.PREFIX.$nid.'_content');
                    } catch (\Exception $e) {}

                    $filelist_path = 'data/model/custom_model_path/'.$nid.'.filelist.txt';
                    $fileStr = file_get_contents($filelist_path);
                    $filelist = explode("\n\r", $fileStr);
                    foreach ($filelist as $k1 => $v1) {
                        $v1 = trim($v1);
                        if (!empty($v1)) {
                            @unlink($v1);
                        }
                    }
                    @unlink($filelist_path);
                    !empty($nid) && delFile('application/admin/template/'.$nid, true);
                }
                
                delFile(CACHE_PATH, true);
                extra_cache('admin_channeltype_list_logic', NULL);
            }
        }
    }

    //模板标签转换
    public function DedeToEyouTemplate()
    {
        // 清空易优模板目录
        delFile('template/eyou', true);

        $root_dir = ROOT_DIR;

        // 织梦默认风格目录
        $cfg_df_style = $this->DeDb('sysconfig')->where(['varname'=>'cfg_df_style'])->value('value');
        $cfg_df_style = !empty($cfg_df_style) ? $cfg_df_style : 'default';

        $weappData = Db::name('weapp')->where(['code'=>'DedeToEyou'])->value('data');
        $weappData = json_decode($weappData, true);
        $is_relation = !empty($weappData['is_relation']) ? $weappData['is_relation'] : 0;
        $templets_path = !empty($weappData['templets_path']) ? $weappData['templets_path'] : 'templets/'.$cfg_df_style;
        $templets_path = '/'.$templets_path.'/';
        if (file_exists(trim($templets_path, '/'))) {
            $templets_path = $root_dir.$templets_path;
        }

        // 织梦模板与易优模板对应
        $tpl_relation_data = [];
        if (empty($is_relation)) {
            $tpl_relation_data = $this->tplDedeToEyou($templets_path);
        }
        
        // 易优默认风格
        $web_tpl_theme = tpCache('web.web_tpl_theme');
        $web_tpl_theme = 'eyou'; // !empty($web_tpl_theme) ? $web_tpl_theme : 'eyou';
        if(tp_mkdir('template/'.$web_tpl_theme.'/pc')) {
            $errfile = [];
            if (!empty($root_dir)) {
                $file_name = dirname(ROOT_PATH).$templets_path;
            } else {
                $file_name = ROOT_PATH.$templets_path;
            }
            $file_list = getDirFile($file_name);
            foreach ($file_list as $key=>$val){
                if (!preg_match('/(.*)\.htm$/i', $val)) {
                    $source = $file_name.$val;
                    $dst = 'template/'.$web_tpl_theme.'/pc/'.$val;
                    tp_mkdir(dirname($dst));
                    $is_copy = @copy($source, $dst);
                    if (empty($is_copy)) {
                        array_push($errfile, $templets_path.$val);
                    }
                }

                $tmp_filename = $file_name.$val;
                $myfile = fopen($tmp_filename, "r") or die("无法打开文件，请检查目录权限!");
                $file_value = fread($myfile,filesize($tmp_filename));
                /*--------------------------模板标签替换 start -----------------------------*/

                // $file_value = $this->tagDedeToEyou($file_value);
                $file_value = $this->tagDedeToEyou_new($file_value);

                // 公共底部文件追加插件标签
                if (preg_match('/(footer|foot)(_m)?\.htm$/i', $val)) {
                    if (stristr($file_value, '</body>')) {
                        $replace =<<<EOF

    <!-- 应用插件标签 start --> 
    {eyou:weapp type='default' /}
    <!-- 应用插件标签 end -->
</body>
EOF;
                        $file_value = str_ireplace('</body>', $replace, $file_value);
                    } else {
                        $weapptag_tmp =<<<EOF

<!-- 应用插件标签 start --> 
{eyou:weapp type='default' /}
<!-- 应用插件标签 end -->
EOF;
                        $file_value .= $weapptag_tmp;
                    }
                }

                /*--------------------------模板标签替换 end -----------------------------*/

                tp_mkdir('template/'.$web_tpl_theme.'/mobile');
                if (preg_match('/(.*)_m\.htm$/i', $val)) { // 如果是手机模板文件，将创建在手机目录里
                    $val_m = str_replace('_m.htm', '.htm', $val);
                    $file_value = str_ireplace('{eyou:global name=\'web_cmspath\' /}/m/skin', '{eyou:global name=\'web_templets_m\' /}/skin', $file_value);
                    $file_value = str_ireplace('{eyou:global name=\'web_cmspath\' /}/skin', '{eyou:global name=\'web_templets_m\' /}/skin', $file_value);
                    @file_put_contents('template/'.$web_tpl_theme.'/mobile/'.$val_m, $file_value);
                }
                else {
                    $puts = true;
                    // 模板创建并与栏目关联
                    $relationData = $this->tplRelationEyou($tpl_relation_data, $val, $is_relation);
                    foreach ($relationData['ey_tpllist'] as $_k2 => $_v2) {
                        $ey_val = $_v2;
                        // 创建PC模板
                        $file_value = str_ireplace('{eyou:global name=\'web_cmspath\' /}/skin', '{eyou:global name=\'web_templets_pc\' /}/skin', $file_value);
                        $puts = @file_put_contents('template/'.$web_tpl_theme.'/pc/'.$ey_val, $file_value);

                        // 如果PC模板文件没有独立的手机模板文件，就将PC模板文件也创建一份到手机目录
    //                    $tmp_filename_m = str_replace('.htm', '_m.htm', $file_name.$val);
    //                    if (!is_file($tmp_filename_m)) {
    //                        tp_mkdir('template/'.$web_tpl_theme.'/mobile');
    //                        @file_put_contents('template/'.$web_tpl_theme.'/mobile/'.$ey_val, $file_value);
    //                    }
                    }
                }

                //手机端模板创建与栏目关联
                $relationData = $this->tplRelationEyouMobile($tpl_relation_data, $val, $is_relation);
                foreach ($relationData['ey_tpllist'] as $_k2 => $_v2) {
                    $ey_val = $_v2;
                    // 创建mobile模板
                    $file_value = str_ireplace('{eyou:global name=\'web_cmspath\' /}/m/skin', '{eyou:global name=\'web_templets_m\' /}/skin', $file_value);
                    $file_value = str_ireplace('{eyou:global name=\'web_cmspath\' /}/skin', '{eyou:global name=\'web_templets_m\' /}/skin', $file_value);
                    $puts = @file_put_contents('template/'.$web_tpl_theme.'/mobile/'.$ey_val, $file_value);
                }

                if (empty($puts)) {
                    array_push($errfile, '/templets/'.$cfg_df_style.'/'.$val);
                }
            }
            // 栏目与模板关联
            if (empty($is_relation) && !empty($tpl_relation_data['tempall_data'])) {
                $saveData = [];
                foreach ($tpl_relation_data['tempall_data'] as $key=>$val){
                    foreach ($val as $_k2=>$_v2){
                        if (!empty($_v2['dd_typeid'])) {
                            $tmp_data = [
                                'id'    => $_v2['dd_typeid'],
                                'update_time' => getTime(),
                            ];
                            if (preg_match('/^lists_/i', $_v2['ey_tplfile'])) {
                                $tmp_data['templist'] = $_v2['ey_tplfile'];
                            } else if (preg_match('/^view_/i', $_v2['ey_tplfile'])) {
                                $tmp_data['tempview'] = $_v2['ey_tplfile'];
                            }
                            $saveData[] = $tmp_data;
                        }
                    }
                }
                !empty($saveData) && model('Arctype')->saveAll($saveData);
            }

            // 检查所有开启的频道模型，如果没有模板文件，就进行补充
            // $this->supplyChanneltypeTpl();

            // 同步模板文件以外的静态资源文件到手机端目录
            if (is_dir('template/'.$web_tpl_theme.'/mobile')) {
                foreach ($file_list as $key=>$val){
                    if (!preg_match('/(.*)\.htm$/i', $val)) {
                        $source = $file_name.$val;
                        $dst = 'template/'.$web_tpl_theme.'/mobile/'.$val;
                        tp_mkdir(dirname($dst));
                        $is_copy = @copy($source, $dst);
                        if (empty($is_copy)) {
                            array_push($errfile, $templets_path.$val);
                        }
                    }
                }
            }
            // 设置前台模板风格
            tpCache('web', ['web_tpl_theme'=>$web_tpl_theme]);
            // 写入全局内置参数
            write_global_params($this->admin_lang);
            return ['errfile'=>$errfile];
        }
    }

    /**
     * 织梦模板标签转易优
     * @param  string $file_value [description]
     * @return [type]          [description]
     */
    /*private function tagDedeToEyou($file_value = '')
    {
        //最早修改(特殊)
        $file_value = $this->tans_one("dede:field.title(.*?)}","\$eyou.field.seo_title}",$file_value);
        $file_value = str_replace("{dede:global name='keyword' function='RemoveXSS(@me)'/}","{\$eyou.field.seo_keywords}",$file_value);
        $file_value = str_replace("<script src=\"{dede:field name='phpurl'/}/count.php?view=yes&aid={dede:field name='id'/}&mid={dede:field name='mid'/}\"type='text/javascript' language=\"javascript\"></script>","{eyou:arcclick /}",$file_value);

        //基础前后包围标签替换
        $file_value = str_replace('{dede:','{eyou:',$file_value);
        $file_value = str_replace('{/dede:','{/eyou:',$file_value);

        //详细信息字段显示
        $file_value = $this->tans_one("[field:(.*?)/]","{\$field.(.*?)}",$file_value);
        //include包含  include filename
        $file_value = $this->tans_one(":include(.*?)filename",":include(.*?)file",$file_value);
        //正则修改arclist标签问题
        $file_value = $this->tans_one(":arclist(.*?)orderby='sortrank'",":arclist(.*?)orderby='add_time'",$file_value);
        $file_value = $this->tans_one(":arclist(.*?)orderby='pubdate'",":arclist(.*?)orderby='add_time'",$file_value);
        $file_value = $this->tans_one(":arclist(.*?)orderby='near'",":arclist(.*?)orderby='sort_order'",$file_value);
        $file_value = $this->tans_one(":arclist(.*?)orderby='id'",":arclist(.*?)orderby='aid'",$file_value);
        //正则修改list标签问题
        $file_value = $this->tans_one(":list(.*?)orderby='sortrank'",":arclist(.*?)orderby='add_time'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='default'",":arclist(.*?)orderby='add_time'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='pubdate'",":arclist(.*?)orderby='add_time'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='senddate'",":arclist(.*?)orderby='add_time'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='click'",":arclist(.*?)orderby='click'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='postnum '",":arclist(.*?)orderby='click'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='lastpost'",":arclist(.*?)orderby='now'",$file_value);
        $file_value = $this->tans_one(":list(.*?)orderby='id'",":arclist(.*?)orderby='aid'",$file_value);

        //arclistsg替换标签名称，等同于arclist
        $file_value = str_replace(':arclistsg',':arclist',$file_value);
        //autochannel替换标签名称，等同于type
        $file_value = str_replace(':autochannel',':type',$file_value);
        $file_value = $this->tans_one("[field:typelink(.*?)/]","{\$field.typeurl}",$file_value);
        //:field.标签的第二种形式
        $file_value = $this->tans_one("eyou:field.(.*?)/}","\$eyou.field.(.*?)}",$file_value);

        $file_value = $this->tans("eyou:field name='(.*?)'(.*?)}","eyou:field name='{1}'{2}}","\$eyou.field.{1}}",$file_value,2);
//            $file_value = $this->tans_one("eyou:field name='(.*?)'/}","\$eyou.field.(.*?)}",$file_value);
        //:global.标签的第二种形式 {dede:global.cfg_webname/}  {eyou:global name='web_copyright' /}
        $file_value = $this->tans_one(":global.(.*?)/}",":global name='(.*?)'/}",$file_value);
        //{dede:flink/} 链接替换
        $file_value = str_replace("{eyou:flink/}","{eyou:flink type='text' row='30' titlelen='15'}<a href='{\$field.url}'>{\$field.title}</a>{/eyou:flink}",$file_value);
        //prenext
        $file_value = $this->tans_one("{eyou:prenext get='pre'(.*?)/}","{eyou:prenext get='pre'}<span class=\"text-gray\">上一篇：</span><a href=\"{\$field.arcurl}\" class=\"text-main\" title=\"{\$field.title}\">{\$field.title}</a>{eyou:else /}<a class=\"text-gray\" >上一篇：到头啦！</a>{/eyou:prenext}",$file_value);
        $file_value = $this->tans_one("{eyou:prenext get='next'(.*?)/}","{eyou:prenext get='next'}<span class=\"text-gray\">下一篇：</span><a href=\"{\$field.arcurl}\" class=\"text-main\" title=\"{\$field.title}\">{\$field.title}</a>{eyou:else /}<a class=\"text-gray\" >上一篇：真没啦！</a>{/eyou:prenext}",$file_value);
        //字段名称替换
        $file_value = str_replace('.picname','.litpic',$file_value);
        $file_value = str_replace('.pubdate','.add_time',$file_value);
        $file_value = str_replace('.body','.content',$file_value);
        $file_value = str_replace('field.writer','field.author',$file_value);
        $file_value = str_replace('.description','.seo_description',$file_value);
        $file_value = str_replace('.keywords','.seo_keywords',$file_value);
        $file_value = str_replace('cn_substr','msubstr',$file_value);
        $file_value = str_ireplace('Html2Text','html_msubstr',$file_value);

        //global字段名称替换
        $file_value = str_replace("name='cfg_webname'","name='web_name'",$file_value);
        $file_value = str_replace("name='cfg_basehost'","name='web_basehost'",$file_value);
        $file_value = str_replace("name='cfg_indexurl'","name='web_cmsurl'",$file_value);
        $file_value = str_replace("name='cfg_indexname'","name='web_title'",$file_value);
        $file_value = str_replace("name='cfg_powerby'","name='web_copyright'",$file_value);
        $file_value = str_replace("name='cfg_keywords'","name='web_keywords'",$file_value);
        $file_value = str_replace("name='cfg_description'","name='web_description'",$file_value);
        $file_value = str_replace("name='cfg_beian'","name='web_recordnum'",$file_value);
        $file_value = str_replace("name='cfg_cmsurl'","name='web_cmsurl'",$file_value);

        //function方法切换
        $file_value = $this->tans(" function=\"(.*?)\('@me'\)\""," function=\"{1}('@me')\"","|{1}",$file_value,1);
        $file_value = $this->tans(" function=\"(.*?)\(@me\)\""," function=\"{1}(@me)\"","|{1}",$file_value,1);
        $file_value = $this->tans(" function=\"(.*?)\((.*?),@me\)\""," function=\"{1}({2},@me)\"","|{1}={2},###",$file_value,2);
        $file_value = $this->tans(" function=\"(.*?)\(@me,(.*?)\)\""," function=\"{1}(@me,{2})\"","|{1}=###,{2}",$file_value,2);

        $file_value = $this->tans(" function='(.*?)\(\"@me\"\)'"," function='{1}(\"@me\")'","|{1}",$file_value,1);
        $file_value = $this->tans(" function='(.*?)\(@me\)'"," function='{1}(@me)'","|{1}",$file_value,1);
        $file_value = $this->tans(" function='(.*?)\((.*?),@me\)'"," function='{1}({2},@me)'","|{1}={2},###",$file_value,2);
        $file_value = $this->tans(" function='(.*?)\(@me,(.*?)\)'"," function='{1}(@me,{2})'","|{1}=###,{2}",$file_value,2);

        $file_value = $this->tans(" function='(.*?)\(\"@me\"\)\""," function='{1}(\"@me\")\"","|{1}",$file_value,1);
        $file_value = $this->tans(" function='(.*?)\(@me\)\""," function='{1}(@me)\"","|{1}",$file_value,1);
        $file_value = $this->tans(" function='(.*?)\((.*?),@me\)\""," function='{1}({2},@me)\"","|{1}={2},###",$file_value,2);
        $file_value = $this->tans(" function='(.*?)\(@me,(.*?)\)\"'"," function='{1}(@me,{2})\"","|{1}=###,{2}",$file_value,2);

        $file_value = $this->tans(" function=\"(.*?)\('@me'\)'"," function=\"{1}('@me')'","|{1}",$file_value,1);
        $file_value = $this->tans(" function=\"(.*?)\(@me\)'"," function=\"{1}(@me)'","|{1}",$file_value,1);
        $file_value = $this->tans(" function=\"(.*?)\((.*?),@me\)'"," function=\"{1}({2},@me)'","|{1}={2},###",$file_value,2);
        $file_value = $this->tans(" function=\"(.*?)\(@me,(.*?)\)'"," function=\"{1}(@me,{2})'","|{1}=###,{2}",$file_value,2);

        //最后特殊
        $file_value = str_replace('{$eyou.field.position}','{eyou:position style=\' \' /}',$file_value);
        $file_value = str_replace('list.php?tid={$field.id}','{$field.typeurl}',$file_value);
        $file_value = str_replace('view.php?aid={$field.id}','{$field.arcurl}',$file_value);
        $file_value = str_replace('list.php?tid={$eyou.field.id}','{eyou:field name=\'typeurl\' /}',$file_value);

        return $file_value;
    }*/

    /**
     * 织梦模板标签转易优
     * @param  string $file_value [description]
     * @return [type]          [description]
     */
    private function tagDedeToEyou_new($file_value = '')
    {
        $prefix = PREFIX;
        // 模板编码
        $file_value = preg_replace('/{dede:global\.cfg_soft_lang(\s*)\/(\s*)}/i', 'utf-8', $file_value);
        // 基础前后包围标签替换
        $file_value = preg_replace('/{\/dede:/i', '{/eyou:', $file_value);
        $file_value = preg_replace('/{dede:/i', '{eyou:', $file_value);
        // include包含  include filename
        $file_value = preg_replace('/:include(\s+)filename(\s*)=(\s*)[\'|\"]([^\'\"]+)(_m)?([^\'\"]+)[\'|\"]/i', ':include file=\'${4}${6}\'', $file_value);
//        $file_value = preg_replace('/:include(\s+)filename(\s*)=(\s*)[\'|\"](\S+)(_m)?(\S+)[\'|\"]/i', ':include file=\'${4}${6}\'', $file_value);
        //去掉包含文件中的_m
        $file_value = str_replace('_m.htm','.htm',$file_value);


        // field 全局变量字段显示 [field:global.xxxxx/] 统一转为标准的全局标签 {eyou:global.xxxxx/}
        $file_value = preg_replace('/\[field:global\.([^\]]*)\/(\s*)\]/i', '{eyou:global.${1}/}', $file_value);
        // field 详细信息字段显示 [field:title/] [field:title function="xxx(@me)"]
        $file_value = preg_replace('/\[field:([\w\-]+)(\s*)([^\]]*)\/(\s*)\]/i', '{$field.${1}${2}${3}}', $file_value);
        // field 标签的第二种形式 {dede:field.title/} {dede:field.title function="xxx(@me)"/}
        $file_value = preg_replace('/\{eyou:field\.([\w\-]+)(\s*)([^\}]*)\/(\s*)\}/i', '{$eyou.field.${1}${2}${3}}', $file_value);
        // 去除{$field.xxx } 、{$eyou.field.xxx }里右侧空格
        $file_value = preg_replace('/{\$(eyou\.)?field\.([\w\-]+)(\s+)}/i', '{$${1}field.${2}}', $file_value);
        // 全局变量 {dede:global.xxxxx} 转为 {eyou:global name='xxxxx' /} ，{dede:global.xxxxx function='test(@me)'} 转为 {eyou:global name='xxxxx' function='test(@me)' /}
        $file_value = preg_replace('/:global\.([\w\-]+)(\s*)([^\}]*)\/(\s*)}/i', ':global name=\'${1}\'${2}${3} /}', $file_value);
        // 全局变量 去除function {eyou:global name='xxxxx' function='test(@me)' /} 转为 {eyou:global name='xxxxx' /}
        $file_value = preg_replace('/:global(\s+)name=[\'|\"]([^\'\"]+)[\'|\"](\s*)([^\}]*)\/(\s*)}/i', ':global name=\'${2}\' /}', $file_value);
        // 面包屑
        $file_value = preg_replace('/{eyou:field(\s+)name(\s*)=(\s*)[\'|\"]position[\'|\"](\s*)\/(\s*)}/i', '{eyou:position style=\'\' /}', $file_value);
        // 列表、详情页、channelartlist标签变量 {eyou:field name='typename'/} 转为 {$eyou.field.typename}
        $file_value = preg_replace('/{eyou:field(\s+)name(\s*)=(\s*)[\'|\"]([^\'\"]+)[\'|\"]([^\}]*)\/(\s*)}/i', '{$eyou.field.${4}${5}}', $file_value);

        // 所有标签的属性补上引号
        preg_match_all('/{eyou:([a-z]+)(\s+)([^\}]+)\/?}/i', $file_value, $matchs);
        if (!empty($matchs[3])) {
            foreach ($matchs[3] as $_kattr => $_vattr) {
                if (in_array($matchs[1][$_kattr], ['global','include'])) {
                    continue;
                }
                $new_vattr = preg_replace('/([a-z]+)(\s*)=(\s*)([\'|\"]?)([^ \f\n\r\t\v\'\"]+)([\'|\"]?)/i', '${1}=\'${5}\'', $_vattr); // 属性引导统一设置单引号
                if (stristr($new_vattr, 'channelid=')) { // 属性是否包含频道ID
                    preg_match_all('/([^\'\"]*)channelid(\s*)=(\s*)\'(\d+)\'/i', $new_vattr, $matchs2);
                    if (!empty($matchs2[4][0])) {
                        $ey_channelid = $this->DedeChannel(intval($matchs2[4][0]), 'add');
                        if ($ey_channelid > 100) { // 自定义模型ID转为对应易优的模型ID
                            $new_vattr = preg_replace('/([^\'\"]*)channelid(\s*)=(\s*)\'(\d+)\'/i', '${1}channelid=\''.$ey_channelid.'\'', $new_vattr);
                        } else {
                            $new_vattr = preg_replace('/([^\'\"]*)channelid(\s*)=(\s*)\'3\'/i', '${1}channelid=\'4\'', $new_vattr); // 软件频道转为对应易优的模型ID
                            $new_vattr = preg_replace('/([^\'\"]*)channelid(\s*)=(\s*)\'2\'/i', '${1}channelid=\'3\'', $new_vattr); // 图集频道转为对应易优的模型ID
                            $new_vattr = preg_replace('/([^\'\"]*)channelid(\s*)=(\s*)\'6\'/i', '${1}channelid=\'2\'', $new_vattr); // 商品频道转为对应易优的模型ID
                            $new_vattr = preg_replace('/([^\'\"]*)channelid(\s*)=(\s*)\'-1\'/i', '${1}channelid=\'7\'', $new_vattr); // 专题频道转为对应易优的模型ID
                        }
                    }
                }
                if ('flink' == $matchs[1][$_kattr]) {
                    $new_vattr = str_ireplace("type='textall'", "type='text'", $new_vattr);
                } else if (in_array($matchs[1][$_kattr], ['channelartlist','channel'])) {
                    $new_vattr = preg_replace('/([^\'\"]*)typeid(\s*)=(\s*)[\'|\"](\D+)[\'|\"]/i', '${1}type=\'${4}\'', $new_vattr);
                } else if ('myppt' == $matchs[1][$_kattr]) {
                    $new_vattr = preg_replace('/([^\'\"]*)typeid(\s*)=(\s*)[\'|\"](\d+)[\'|\"]/i', '${1}pid=\'${4}\'', $new_vattr);
                }
                $new_tag = str_ireplace($_vattr, $new_vattr, $matchs[0][$_kattr]);
                $file_value = str_ireplace($matchs[0][$_kattr], $new_tag, $file_value);
            }
        }

        // arclistsg替换标签名称，等同于arclist
        $file_value = preg_replace('/\:arclistsg(\s*)/i', ':arclist${1}', $file_value);
        // 正则修改arclist标签属性对应易优
        $file_value = preg_replace('/:arclist(.*)orderby(\s*)=(\s*)[\'|\"](now|pubdate|new|default|senddate)[\'|\"]/i', ':arclist${1}orderby=\'add_time\'', $file_value);
        $file_value = preg_replace('/:arclist(.*)orderby(\s*)=(\s*)[\'|\"](near|lastpost|scores|sortrank|weight)[\'|\"]/i', ':arclist${1}orderby=\'sort_order\'', $file_value);
        $file_value = preg_replace('/:arclist(.*)orderby(\s*)=(\s*)[\'|\"](id)[\'|\"]/i', ':arclist${1}orderby=\'aid\'', $file_value);
        // 正则修改list标签属性对应易优
        $file_value = preg_replace('/:list(.*)orderby(\s*)=(\s*)[\'|\"](now|pubdate|new|default|senddate)[\'|\"]/i', ':list${1}orderby=\'add_time\'', $file_value);
        $file_value = preg_replace('/:list(.*)orderby(\s*)=(\s*)[\'|\"](near|lastpost|scores|sortrank|weight)[\'|\"]/i', ':list${1}orderby=\'sort_order\'', $file_value);
        $file_value = preg_replace('/:list(.*)orderby(\s*)=(\s*)[\'|\"](postnum)[\'|\"]/i', ':list${1}orderby=\'click\'', $file_value);
        $file_value = preg_replace('/:list(.*)orderby(\s*)=(\s*)[\'|\"](id)[\'|\"]/i', ':list${1}orderby=\'aid\'', $file_value);
        // channelartlist标签里的{$eyou.field.xxx}替换成{eyou:field name='xxx'/}
        preg_match_all('/{eyou:channelartlist([^\}]*)}([\s\S]*?){\/eyou:channelartlist}/i', $file_value, $matchs);
        if (!empty($matchs[2])) {
            foreach ($matchs[2] as $_kcode => $_vcode) {
                $new_vcode = preg_replace('/{\$eyou\.field\.([\w\-]+)(\s*)}/i', '{eyou:field name=\'${1}\' /}', $_vcode);
                $new_code = str_ireplace($_vcode, $new_vcode, $matchs[0][$_kcode]);
                $file_value = str_ireplace($matchs[0][$_kcode], $new_code, $file_value);
            }
        }
        // myppt替换成广告标签
        preg_match_all('/{eyou:myppt([^\}]*)}([\s\S]*?){\/eyou:myppt}/i', $file_value, $matchs);
        if (!empty($matchs[2])) {
            foreach ($matchs[2] as $_kcode => $_vcode) {
                $new_vcode = $_vcode;
                $new_vcode = preg_replace('/{\$field\.url(\s*)([^\}]*)}/i', '{$field.links}', $new_vcode);
                $new_vcode = preg_replace('/{\$field\.pic(\s*)([^\}]*)}/i', '{$field.litpic}', $new_vcode);
                $new_code = str_ireplace($_vcode, $new_vcode, $matchs[0][$_kcode]);
                $file_value = str_ireplace($matchs[0][$_kcode], $new_code, $file_value);
            }
        }
        $file_value = preg_replace('/\:myppt(\s*)/i', ':adv${1}', $file_value);

        // productimagelist替换成图集模型的图集列表标签
        preg_match_all('/{eyou:productimagelist([^\}]*)}([\s\S]*?){\/eyou:productimagelist}/i', $file_value, $matchs);
        if (!empty($matchs[2])) {
            foreach ($matchs[2] as $_kcode => $_vcode) {
                $new_vcode = preg_replace('/{\$field\.imgsrc(\s*)([^\}]*)}/i', '{$field.image_url}', $_vcode);
                $new_vcode = preg_replace('/{\$field\.text(\s*)([^\}]*)}/i', '{$field.intro}', $new_vcode);
                $new_code = str_ireplace($_vcode, $new_vcode, $matchs[0][$_kcode]);
                $file_value = str_ireplace($matchs[0][$_kcode], $new_code, $file_value);
            }
        }
        $file_value = preg_replace('/{eyou:productimagelist([^\}]*)}/i', '{eyou:volist name="$eyou.field.image_list"}', $file_value);
        $file_value = preg_replace('/{\/eyou:productimagelist([^\}]*)}/i', '{/eyou:volist}', $file_value);
        // autochannel替换标签名称，等同于type
        $file_value = preg_replace('/:autochannel(\s*)/i', ':type${1}', $file_value);
        // 栏目链接typelink转为typeurl 
        $file_value = preg_replace('/\{\$(eyou\.)?field\.typelink(\s*)([^\}]*)}/i', '{$${1}field.typeurl${2}${3}}', $file_value);
        // 友情链接类型 {eyou:flink type="textall"} xxxxx {/eyou:flink}
        preg_match_all('/{eyou:flink([^\}]*)}([\s\S]*?){\/eyou:flink}/i', $file_value, $matchs);
        if (!empty($matchs[2])) {
            foreach ($matchs[2] as $_kcode => $_vcode) {
                if (preg_match('/([^\'\"]*)type(\s*)=(\s*)[\'|\"]image[\'|\"]/i', $matchs[1][$_kcode])) {
                    $new_vcode = preg_replace('/{\$field\.link(\s*)([^\}]*)}/i', '<a href="{$field.url}" target="_blank"><img src="{$field.logo}" width="88" height="31" border="0"></a>', $_vcode);
                } else {
                    $new_vcode = preg_replace('/{\$field\.link(\s*)([^\}]*)}/i', '<a href="{$field.url}" target="_blank">{$field.title}</a>', $_vcode);
                }
                $new_code = str_ireplace($_vcode, $new_vcode, $matchs[0][$_kcode]);
                $file_value = str_ireplace($matchs[0][$_kcode], $new_code, $file_value);
            }
        }
        // 友情链接类型 {eyou:flinktype type="dedecms"} xxxxx {/eyou:flinktype} ，将没有包含{eyou:flink/}友情链接标签的分组只留一个默认分组
        preg_match_all('/{eyou:flinktype([^\}]*)}([\s\S]*?){\/eyou:flinktype}/i', $file_value, $matchs);
        if (!empty($matchs[2])) {
            foreach ($matchs[2] as $_kattr => $_vattr) {
                if (!preg_match('/{eyou:flink(\s*)([^\}]*)\/(\s*)}/i', $_vattr) && !empty($matchs[2][$_kattr])) {
                    $tmp = preg_replace('/{\$field\.typename}/i', '默认分组', $matchs[2][$_kattr]);
                    $tmp = preg_replace('/{\$field\.([^\}]*)}/i', '', $tmp);
                    $tmp = preg_replace('/(\s+)href(\s*)=(\s*)[\'|\"]([^\'\"]*)[\'|\"]/i', ' href="javascript:void(0);"', $tmp);
                    $file_value = str_ireplace($matchs[0][$_kattr], $tmp, $file_value);
                }
            }
        }
        // 友情链接类型 {eyou:flinktype type="dedecms"} xxx {eyou:flink/} xx {/eyou:flinktype} ，将包含{eyou:flink/}友情链接标签的分组去除，只留友情链接标签
        $file_value = preg_replace('/{eyou:flinktype(\s*)([^\}]*)}/i', '', $file_value);
        $file_value = preg_replace('/{\/eyou:flinktype(\s*)}/i', '', $file_value);
        $file_value = preg_replace('/flink_{\$field\.id}/i', '', $file_value);
        // {eyou:flink/} 友情链接标签
        $file_value = preg_replace("/{eyou:flink(\s*)([^\}]*)\/(\s*)}/i", "\r\n{eyou:flink type='all' groupid='all' row='100' titlelen='30'}\r\n    <a href='{\$field.url}'>{\$field.title}</a>\r\n{/eyou:flink}\r\n", $file_value);
        $file_value = preg_replace('/(\s+)href(\s*)=(\s*)[\'|\"]([^\'\"]*)plus\/flink\.php([^\'\"]*)[\'|\"]/i', ' href="javascript:void(0);"', $file_value);
        $file_value = preg_replace('/(\s+)href(\s*)=(\s*)[\'|\"]([^\'\"]*)plus\/flink_add\.php([^\'\"]*)[\'|\"]/i', ' href="javascript:void(0);"', $file_value);
        // prenext 上下篇标签
        $file_value = preg_replace('/{eyou:prenext(\s+)get(\s*)=(\s*)[\'|\"]pre[\'|\"]([^\}]*)\/(\s*)}/i', "\r\n{eyou:prenext get='pre'}\r\n    <a href='{\$field.arcurl}' title='{\$field.title}'> 上一篇：{\$field.title} </a>\r\n{eyou:else /}\r\n    上一篇：暂无\r\n{/eyou:prenext}\r\n", $file_value);
        $file_value = preg_replace('/{eyou:prenext(\s+)get(\s*)=(\s*)[\'|\"]next[\'|\"]([^\}]*)\/(\s*)}/i', "\r\n{eyou:prenext get='next'}\r\n    <a href='{\$field.arcurl}' title='{\$field.title}'> 下一篇：{\$field.title} </a>\r\n{eyou:else /}\r\n    下一篇：暂无\r\n{/eyou:prenext}\r\n", $file_value);
        $file_value = preg_replace('/{eyou:prenext(\s+)get(\s*)=(\s*)[\'|\"]prewap[\'|\"]([^\}]*)\/(\s*)}/i', "\r\n{eyou:prenext get='pre'}\r\n    <a href='{\$field.arcurl}' title='{\$field.title}'> 上一篇：{\$field.title} </a>\r\n{eyou:else /}\r\n    上一篇：暂无\r\n{/eyou:prenext}\r\n", $file_value);
        $file_value = preg_replace('/{eyou:prenext(\s+)get(\s*)=(\s*)[\'|\"]nextwap[\'|\"]([^\}]*)\/(\s*)}/i', "\r\n{eyou:prenext get='next'}\r\n    <a href='{\$field.arcurl}' title='{\$field.title}'> 下一篇：{\$field.title} </a>\r\n{eyou:else /}\r\n    下一篇：暂无\r\n{/eyou:prenext}\r\n", $file_value);

        // 点击数
        $file_value = preg_replace('/<script(\s+)([^\>]*)src(\s*)=(\s*)[\'|\"]([^\>]*)\/count\.php\?view=yes\&aid=([^\>]*)>([\s\S]*?)<\/script>/i', '{eyou:arcclick /}', $file_value);

        //字段名称替换
        $file_value = preg_replace('/field\.picname/i', 'field.litpic', $file_value);
        $file_value = preg_replace('/field\.pubdate/i', 'field.add_time', $file_value);
        $file_value = preg_replace('/field\.body/i', 'field.content', $file_value);
        $file_value = preg_replace('/field\.writer/i', 'field.author', $file_value);
        $file_value = preg_replace('/field\.(description|info)/i', 'field.seo_description', $file_value);
        $file_value = preg_replace('/field\.keywords/i', 'field.seo_keywords', $file_value);


//        $file_value = preg_replace('/field\.title/i', 'field.seo_title', $file_value);

        $file_value = preg_replace('/field\.softrank/i', 'field.sort_order', $file_value);
        $file_value = preg_replace('/\.field\.introduce/i', '.field.content', $file_value);

        //global字段名称替换
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_webname[\'|\"]/i', '${1}=\'web_name\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"](cfg_basehost|cfg_mobileurl|cfg_phpurl|cfg_memberurl)[\'|\"]/i', '${1}=\'web_basehost\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_indexurl[\'|\"]/i', '${1}=\'web_cmsurl\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_indexname[\'|\"]/i', '${1}=\'web_title\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_powerby[\'|\"]/i', '${1}=\'web_copyright\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"](cfg_keywords|keyword)[\'|\"]/i', '${1}=\'web_keywords\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"](cfg_description|description)[\'|\"]/i', '${1}=\'web_description\'', $file_value);
        //备案号替换
        $file_value = preg_replace('/<a href=[\'|\"]http(.*?)beian(.*?)cfg_beian(.*?)<\/a>/i', '{eyou:global name=\'web_recordnum\' /}', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_beian[\'|\"]/i', '${1}=\'web_recordnum\'', $file_value);

        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_cmsurl[\'|\"]/i', '${1}=\'web_cmsurl\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_templets_skin[\'|\"]/i', '${1}=\'web_templets_pc\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_wap[\'|\"]/i', '${1}=\'web_templets_m\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_cmspath[\'|\"]/i', '${1}=\'web_cmspath\'', $file_value);
        $file_value = preg_replace('/(:global(\s+)name)(\s*)=(\s*)[\'|\"]cfg_templeturl[\'|\"]/i', '${1}=\'web_templeturl\'', $file_value);

        //function方法切换
        $file_value = preg_replace('/([\w\-]+)(\s+)function(\s*)=(\s*)([\w\-]+)([^\}]*)([\'\"]+)@me([\'\"]+)([^\}]*)}/i', '${1} function=${5}${6}@me${9}}', $file_value); // '@me' 替换为 @me
        $file_value = preg_replace('/([\w\-]+)(\s*)function(\s*)=(\s*)([\'|\"]?)([\w\-]+)([^\}]*)@me([^\}]*)}/i', '${1} function=${6}${7}@me${8}}', $file_value); // function前面强制留个空格
        $file_value = preg_replace('/([\w\-]+)(\s+)function(\s*)=(\s*)([\'|\"]?)(cn_substr|Html2Text|Text2Html|MyDate|GetDateMK|GetDateTimeMk|FloorTime|RemoveXSS|gettoptype|GetTopTypename|GetTopTypeurl|GetTopTypenameen|strftime|nl2br)(\s*)\((\s*)([^\@]*)@me([^\)]*)(\s*)\)([^\'\"\}]*)([\'|\"]?)([^\}]*)/i', '${1}|${6}=${9}###${10}', $file_value);
        $file_value = preg_replace('/([\w\-]+)(\s+)function(\s*)=(\s*)([\'|\"]?)([^\}]*)/i', '${1}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|GetDateTimeMk(\s*)=(\s*)([^\}]*)/i', '.${1}|MyDate=\'Y-m-d\',${4}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|GetDateMK(\s*)=(\s*)([^\}]*)/i', '.${1}|MyDate=\'Y-m-d\',${4}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|strftime(\s*)=(\s*)([^\}]*)/i', '.${1}|MyDate=\'Y-m-d\',###', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|MyDate(\s*)=(\s*)([\'|\"]?)([^\,\'\"]+)([\'|\"]?)(\s*)\,([^\}]*)/i', '.${1}|MyDate=\'${5}\',${8}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|cn_substr(\s*)=(\s*)###(\s*),(\s*)([^\}]*)/i', '.${1}|msubstr=###,0,${6}/2', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|Html2Text(\s*)=(\s*)([^\}]*)/i', '.${1}|html_msubstr=${4}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|Text2Html(\s*)=(\s*)([^\}]*)/i', '.${1}|htmlspecialchars_decode=${4}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|FloorTime(\s*)=(\s*)([^\}]*)/i', '.${1}|friend_date=${4}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|RemoveXSS(\s*)=(\s*)([^\}]*)/i', '.${1}', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|gettoptype(\s*)=(\s*)###(\s*),(\s*)([\w\-]+)/i', '.${1}|gettoptype=###,\'${6}\'', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|GetTopTypename(\s*)=(\s*)###(\s*)/i', '.${1}|gettoptype=###,\'typename\'', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|GetTopTypeurl(\s*)=(\s*)###(\s*)/i', '.${1}|gettoptype=###,\'typeurl\'', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|GetTopTypenameen(\s*)=(\s*)###(\s*)/i', '.${1}|gettoptype=###,\'englist_name\'', $file_value);
        $file_value = preg_replace('/\.([\w\-]+)\|nl2br(\s*)=(\s*)([^\}]*)/i', '.${1}|filter_line_return=${4},\'<br/>\'', $file_value);

        //最后特殊
        $file_value = preg_replace('/list\.php\?tid={\$field\.id(\s*)}/i', '{$field.typeurl}', $file_value);
        $file_value = preg_replace('/list\.php\?tid={\$eyou\.field\.id(\s*)}/i', '{eyou:field name=\'typeurl\' /}', $file_value);
        $file_value = preg_replace('/view\.php\?aid={\$field\.id(\s*)}/i', '{$field.arcurl}', $file_value);
        $file_value = preg_replace('/{eyou:global(\s+)name=\'web_basehost\'(\s*)\/}\/index_do\.php\?fmdo=user\&dopost=regnew/i', '{eyou:url link=\'user/Users/reg\' /}', $file_value);
        $file_value = preg_replace('/{eyou:global(\s+)name=\'web_basehost\'(\s*)\/}\/resetpassword\.php/i', '{eyou:url link=\'user/Users/retrieve_password\' /}', $file_value);
        $file_value = preg_replace('/{eyou:global(\s+)name=\'(itemindex|autoindex)\'(\s*)\/}/i', '{$key}', $file_value);
        $file_value = preg_replace('/{\$(eyou\.)?field\.image(\s*)}/i', '<img src="{$${1}field.litpic}" width="120" height="120" />', $file_value);
        $file_value = preg_replace('/{\$(eyou\.)?field\.scores(\s*)}/i', '', $file_value); // 去除不支持的字段名
        $file_value = preg_replace('/<meta(\s+)([^\>]*)http-equiv(\s*)=(\s*)([\'|\"]?)mobile-agent([\'|\"]?)([^\>]*)\/?>/i', '<!-- <meta ${2}http-equiv="mobile-agent"${5}/> -->', $file_value); // 注释手机端跳转的html代码

        //去掉跳转到手机端js代码
//        $file_value = preg_replace('/<script([^\>]*)>([\s\S]*?)(href\.indexOf\([\'|\"]\?mobile[\'|\"]\))([\s\S]*?)<\/script>/i', '<!-- <script${1}>${2}${3}${4}</script> -->', $file_value); // 注释手机端跳转的JS代码
//        $file_value = preg_replace('/(<script(\s?)\>|<script(\s?)type([\s\S]*?)\>)([\s\S]*?)(href\.indexOf\([\'|\"]\?mobile[\'|\"]\))([\s\S]*?)<\/script>/i', '<!-- ${1}${5}${6}${7}</script> -->', $file_value); // 注释手机端跳转的JS代码
//        preg_match('/(<script(\s?)\>|<script(\s?)type([\s\S]*?)\>)([\s\S]*?)(href\.indexOf\([\'|\"]\?mobile[\'|\"]\))([\s\S]*?)<\/script>/i',$file_value,$mobile_tran);  //删除手机端跳转js的代码（存在问题，会被误删前面部分）
//        if(!empty($mobile_tran)){
//            $file_value = str_replace($mobile_tran[0],'',$file_value);
//        }
//        $file_value = str_replace('window.location.href.indexOf("?mobile")<0','false',$file_value);  //修改进入的条件让手机端跳转js的代码无法执行
//        $file_value = preg_replace('/if\(window\.location\.toString\(\)\.indexOf\(\'pref=padindex\'\) \!= -1\)(.*?)<\/script>/i', '', $file_value);
        $file_value = preg_replace('/if\(window\.location\.toString\(\)\.indexOf\(\'pref=padindex\'\) \!= -1\)([\s\S]*?)(function|<\/script>)/i', '${2}', $file_value);




        $file_value = preg_replace('/\[field:global(\s+)name(\s*)=(\s*)([\'|\"]?)autoindex([\'|\"]?)(\s+)runphp(\s*)=(\s*)([\'|\"]?)yes([\'|\"]?)([^\]]*)\]([\s\S]*?)\[\/field:global\]/i', '{$i}', $file_value); // 自增标签
        $file_value = preg_replace('/\{\$field\.global(\s+)name(\s*)=(\s*)([\'|\"]?)autoindex([\'|\"]?)([^\}]*)}/i', '{$i}', $file_value); // 自增标签
        // 移除不支持标签
        $file_value = preg_replace('/{eyou:sql([^\}]*)}([\s\S]*?){\/eyou:sql}/i', '{eyou:sql sql=\'select id from '.$prefix.'arctype limit 1\'}不支持sql标签，请<a href="https://www.eyoucms.com/plus/view.php?aid=11933" target="_blank" style=\"color:red;\">【点击参考教程】</a>{/eyou:sql}', $file_value); // {eyou:sql}xxxx{/eyou:sql}标签
        $file_value = preg_replace('/{eyou:php([^\}]*)}([\s\S]*?){\/eyou:php}/i', '{eyou:php}echo "php语法报错，请<a href=\"https://www.eyoucms.com/plus/view.php?aid=11934\" target=\"_blank\" style=\"color:red;\">【点击参考教程】</a>";{/eyou:php}', $file_value); // {eyou:php}xxxx{/eyou:php}标签
        $file_value = preg_replace('/{eyou:qrcode(\s*)([^\}]*)\/(\s*)}/i', '', $file_value); // {eyou:qrcode/} 页面二维码标签
        $file_value = preg_replace('/{eyou:softmsg(\s*)([^\}]*)\/(\s*)}/i', '', $file_value); // {eyou:softmsg/} 下载说明
        $file_value = preg_replace('/{eyou:adminname(\s*)([^\}]*)\/(\s*)}/i', '{$eyou.field.author}', $file_value); // {eyou:adminname/} 责任编辑
        $file_value = preg_replace('/<\?php(\s+)([\s\S]*?)\?>/i', '{eyou:php}echo "php语法报错，请<a href=\"https://www.eyoucms.com/plus/view.php?aid=11934\" target=\"_blank\" style=\"color:red;\">【点击参考教程】</a>";{/eyou:php}', $file_value); // php 原生语法
        //特殊关键字替换
        $file_value = str_replace('.description','.seo_description',$file_value);
        $file_value = str_replace('.typenameen','.englist_name',$file_value);
        $file_value = str_replace('.typeimg','.litpic',$file_value);
        $file_value = str_replace('.shorttitle','.subtitle',$file_value);
        $file_value = str_replace('.source','.origin',$file_value);
        $file_value = str_replace('list.php?tid={$field.id}','{$field.typeurl}',$file_value);
        $file_value = str_replace('view.php?aid={$field.id}','{$field.arcurl}',$file_value);
        $file_value = str_replace('list.php?tid={$eyou.field.id}','{eyou:field name=\'typeurl\' /}',$file_value);
        $file_value = str_replace('list.php?tid={eyou:field name=\'id\' /}','{eyou:field name=\'typeurl\' /}',$file_value);
        //TDK下面添加
        $file_value = preg_replace("/<\/head>/i", "<link href=\"{eyou:global name='web_ico' /}\" rel=\"shortcut icon\" type=\"image/x-icon\" />\n</head>", $file_value);
//        $file_value = preg_replace('/:include(\s+)filename(\s*)=(\s*)[\'|\"]([^\'\"]+)(_m)?([^\'\"]+)[\'|\"]/i', ':include file=\'${4}${6}\'', $file_value);

        return $file_value;
    }

    /**
     * 检查所有开启的频道模型，如果没有模板文件，就进行补充
     * @return [type] [description]
     */
    private function supplyChanneltypeTpl()
    {
        $web_tpl_theme = tpCache('web.web_tpl_theme');
        $web_tpl_theme = !empty($web_tpl_theme) ? $web_tpl_theme : 'eyou';
        $view_suffix = config('template.view_suffix');
        $demopath = 'data/model/';
        $filelist = getDirFile($demopath);

        $channeltypeRow = Db::name('channeltype')->field('id, nid, ctl_name')->where(['status'=>1])->select();
        foreach ($channeltypeRow as $tkey => $tval) {
            foreach ($filelist as $key => $file) {
                if (!preg_match('/\.htm$/i', $file)) {
                    continue;
                }
                $src = $demopath.$file;
                $dst = $file;
                $dst = str_replace('CustomModel', $tval['ctl_name'], $dst);
                $dst = str_replace('custommodel', $tval['nid'], $dst);
                $dst = str_replace('template/pc/', 'template/'.$web_tpl_theme.'/pc/', $dst);
                if(!is_file($dst) && tp_mkdir(dirname($dst))) {
                    $fileContent = @file_get_contents($src);
                    $fileContent = str_replace('CustomModel', $tval['ctl_name'], $fileContent);
                    $fileContent = str_replace('custommodel', strtolower($tval['nid']), $fileContent);
                    $fileContent = str_replace('CUSTOMMODEL', strtoupper($tval['nid']), $fileContent);
                    if (stristr($file, 'lists_custommodel.'.$view_suffix)) {
                        $replace = <<<EOF
<section class="article-list">
                    {eyou:list pagesize="10" titlelen="38"}
                    <article>
                        {eyou:notempty name="\$field.is_litpic"}
                        <a href="{\$field.arcurl}" title="{\$field.title}" style="float: left; margin-right: 10px"> <img src="{\$field.litpic}" alt="{\$field.title}" height="100" /> </a>
                        {/eyou:notempty} 
                        <h2><a href="{\$field.arcurl}" class="">{\$field.title}</a><span>{\$field.click}°C</span></h2>
                        <div class="excerpt">
                            <p>{\$field.seo_description}</p>
                        </div>
                        <div class="meta">
                            <span class="item"><time>{\$field.add_time|MyDate='Y-m-d',###}</time></span>
                            <span class="item">{\$field.typename}</span>
                        </div>
                    </article>
                    {/eyou:list}
                </section>
                <section class="list-pager">
                    {eyou:pagelist listitem='index,pre,pageno,next,end' listsize='2' /}
                    <div class="clear"></div>
                </section>
EOF;
                        $fileContent = str_replace("<!-- #list# -->", $replace, $fileContent);
                    }

                    $puts = @file_put_contents($dst, $fileContent);
                    if ($puts) {
                        // 判断是否存在手机端目录，同时生成一份
                        $tplplan = "template/".$web_tpl_theme."/mobile";
                        $planPath = realpath($tplplan);
                        if (file_exists($planPath)) {
                            $dst_m = str_replace('template/'.$web_tpl_theme.'/pc/', 'template/'.$web_tpl_theme.'/mobile/', $dst);
                            @file_put_contents($dst_m, $fileContent);
                        }
                    }
                }
            }
        }
    }

    /**
     * 易优模板与栏目关联
     * @param  array  $tpl_relation_data [description]
     * @return [type]                    [description]
     */
    private function tplRelationEyou($tpl_relation_data = [], $tplfile = '', $is_relation = 0)
    {
        $ey_tpllist = [];
        $tempall_data = !empty($tpl_relation_data['tempall_data']) ? $tpl_relation_data['tempall_data'] : [];

        if (empty($tempall_data) || !empty($is_relation)) {
            $ey_tpllist = [$tplfile];
        }
        else {
            $arr = $tempall_data[$tplfile];
            if (!empty($arr)) {
                foreach ($arr as $key => $val) {
                    array_push($ey_tpllist, $val['ey_tplfile']);
                }
            } else {
                $ey_tpllist = [$tplfile];
            }
        }

        return [
            'ey_tpllist' => $ey_tpllist,
        ];
    }
    /*
     * 获取易优移动端模板文件名称集合
     */
    private function tplRelationEyouMobile($tpl_relation_data = [], $tplfile = '', $is_relation = 0){
        $ey_tpllist = [];
        $tempall_data = !empty($tpl_relation_data['tempall_m_data']) ? $tpl_relation_data['tempall_m_data'] : [];
        if (empty($tempall_data) || !empty($is_relation)) {
            $ey_tpllist = [$tplfile];
        }
        else {
            $arr = $tempall_data[$tplfile];
            if (!empty($arr)) {
                foreach ($arr as $key => $val) {
                    array_push($ey_tpllist, $val['ey_tplfile']);
                }
            }
        }

        return [
            'ey_tpllist' => $ey_tpllist,
        ];
    }

    /**
     * 织梦模板与易优模板对应
     * @return [type] [description]
     */
    private function tplDedeToEyou($templets_path = '')
    {
        $channeltypeRow = Db::name('channeltype')->field('id,nid')->getAllWithIndex('id');
        $dede_channeltypeRow = $this->DeDb('channeltype')->field('id,nid')->getAllWithIndex('id');

        $tempall_data = $templist_data = $temparticle_data = $tempall_m_data = [];
        $view_suffix = config('template.view_suffix');
        $dede_arctypeRow = $this->DeDb('arctype')->field('id,channeltype,ispart,tempindex,templist,temparticle')->select();
        foreach ($dede_arctypeRow as $key => $val) {
            $dd_typeid = $val['id'];
            $dd_channel_id = $val['channeltype'];
            $ey_channel_id = $this->DedeChannel($dd_channel_id, 'add');
            $dd_nid = $dede_channeltypeRow[$dd_channel_id]['nid'];
            $ey_nid = $channeltypeRow[$ey_channel_id]['nid'];
            if (empty($ey_nid)) {
                continue;
            }

            if (1 <= $val['ispart']) { // 单页模型 - 列表模板
                $tmp_tpl = explode('/', $val['tempindex']);
                $dd_filename = end($tmp_tpl);
                $dd_filename_arr = explode('.', $dd_filename);
                $dd_filename_m = $dd_filename_arr[0].".{$view_suffix}";
                if(empty($dd_filename) || !is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){  //移动端模板文件不存在
                    $dd_filename_m = "index_{$dd_nid}_m.{$view_suffix}";
                }
                if (empty($dd_filename) || !is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename)) {
                    $dd_tplfile = "index_{$dd_nid}.{$view_suffix}";
                    if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_tplfile)){  //模型默认列表不存在，则回去default文件
                        $dd_tplfile = "index_default.{$view_suffix}";
                    }
                    if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){
                        $dd_filename_m = "index_default_m.{$view_suffix}";
                        if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){
                            $dd_filename_m = $dd_tplfile;
                        }
                    }
                    $tpl_suffix = 'single';
                } else {
                    $dd_tplfile = $dd_filename;
                    $tpl_suffix = $dd_filename;
                    if (stristr($tpl_suffix, 'index_'.$dd_nid)) {
                        $tpl_suffix = str_ireplace('index_'.$dd_nid, '', $tpl_suffix);
                    } else if (stristr($tpl_suffix, 'index_')) {
                        $tpl_suffix = str_ireplace('index_', '', $tpl_suffix);
                    }
                    $tpl_suffix = str_ireplace('.htm', '', $tpl_suffix);
                    if (empty($tpl_suffix)) {
                        $tpl_suffix = 'single';
                    } else {
                        $tpl_suffix = str_replace('-', '_', $tpl_suffix);
                        $tpl_suffix = 'single'.'_'.ltrim($tpl_suffix, '_');
                    }
                }
                $ey_tplfile = "lists_{$tpl_suffix}.{$view_suffix}"; // 对应易优模板文件名
                $templist_data[$dd_tplfile][$val['id']] = [
                    'dd_typeid' => $dd_typeid,
                    'dd_channel_id' => $dd_channel_id,
                    'dd_tplfile'  => $dd_tplfile,
                    'dd_nid'    => $dd_nid,
                    'ey_channel_id' => 6,
                    'ey_tplfile'  => $ey_tplfile,
                    'ey_nid'    => 'single',
                ];
                $tempall_data[$dd_tplfile][$val['id']] = $templist_data[$dd_tplfile][$val['id']];
                $tempall_m_data[$dd_filename_m][$val['id']] = [
                    'dd_tplfile'  => $dd_filename_m,
                    'ey_tplfile'  => $ey_tplfile
                ];
            }
            else {
                // 列表模板
                $tmp_tpl = explode('/', $val['templist']);
                $dd_filename = end($tmp_tpl);
                $dd_filename_arr = explode('.', $dd_filename);
                $dd_filename_m = $dd_filename_arr[0].".{$view_suffix}";
                if(empty($dd_filename) || !is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){  //移动端模板文件不存在
                    $dd_filename_m = "list_{$dd_nid}_m.{$view_suffix}";
                }
                if (empty($dd_filename) || !is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename)) {   //不存在数据表中的指定的模板文件
                    $dd_tplfile = "list_{$dd_nid}.{$view_suffix}";
                    if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_tplfile)){  //模型默认列表不存在，则回去default文件
                        $dd_tplfile = "list_default.{$view_suffix}";
                    }
                    if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){
                        $dd_filename_m = "list_default_m.{$view_suffix}";
                        if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){
                            $dd_filename_m = $dd_tplfile;
                        }
                    }
                    $tpl_suffix = $ey_nid;
                } else {
                    $dd_tplfile = $dd_filename;
                    $tpl_suffix = $dd_filename;
                    if (stristr($tpl_suffix, 'list_'.$dd_nid)) {
                        $tpl_suffix = str_ireplace('list_'.$dd_nid, '', $tpl_suffix);
                    } else if (stristr($tpl_suffix, 'list_')) {
                        $tpl_suffix = str_ireplace('list_', '', $tpl_suffix);
                    }
                    $tpl_suffix = str_ireplace('.htm', '', $tpl_suffix);
                    if (empty($tpl_suffix)) {
                        $tpl_suffix = $ey_nid;
                    } else {
                        $tpl_suffix = str_replace('-', '_', $tpl_suffix);
                        $tpl_suffix = $ey_nid.'_'.ltrim($tpl_suffix, '_');
                    }
                }

                $ey_tplfile = "lists_{$tpl_suffix}.{$view_suffix}"; // 对应易优模板文件名
                $templist_data[$dd_tplfile][$val['id']] = [
                    'dd_typeid' => $dd_typeid,
                    'dd_channel_id' => $dd_channel_id,
                    'dd_tplfile'  => $dd_tplfile,
                    'dd_nid'    => $dd_nid,
                    'ey_channel_id' => $ey_channel_id,
                    'ey_tplfile'  => $ey_tplfile,
                    'ey_nid'    => $ey_nid,
                ];
                $tempall_data[$dd_tplfile][$val['id']] = $templist_data[$dd_tplfile][$val['id']];
                $tempall_m_data[$dd_filename_m][$val['id']] = [
                    'dd_tplfile'  => $dd_filename_m,
                    'ey_tplfile'  => $ey_tplfile
                ];

                // 文档模板
                $tmp_tpl = explode('/', $val['temparticle']);
                $dd_filename = end($tmp_tpl);
                $dd_filename_arr = explode('.', $dd_filename);
                $dd_filename_m = $dd_filename_arr[0].".{$view_suffix}";
                if(empty($dd_filename) || !is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){  //移动端模板文件不存在
                    $dd_filename_m = "article_{$dd_nid}_m.{$view_suffix}";
                }
                if (empty($dd_filename) || !is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename)) {//不存在数据表中的指定的模板文件
                    $dd_tplfile = "article_{$dd_nid}.{$view_suffix}";
                    if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_tplfile)){  //模型默认列表不存在，则回去default文件
                        $dd_tplfile = "article_default.{$view_suffix}";
                    }
                    if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){
                        $dd_filename_m = "article_default_m.{$view_suffix}";
                        if (!is_file(dirname(ROOT_PATH).$templets_path.'/'.$dd_filename_m)){
                            $dd_filename_m = $dd_tplfile;
                        }
                    }
                    $tpl_suffix = $ey_nid;
                } else {
                    $dd_tplfile = $dd_filename;
                    $tpl_suffix = $dd_filename;
                    if (stristr($tpl_suffix, 'article_'.$dd_nid)) {
                        $tpl_suffix = str_ireplace('article_'.$dd_nid, '', $tpl_suffix);
                    } else if (stristr($tpl_suffix, 'article_')) {
                        $tpl_suffix = str_ireplace('article_', '', $tpl_suffix);
                    }
                    $tpl_suffix = str_ireplace('.htm', '', $tpl_suffix);
                    if (empty($tpl_suffix)) {
                        $tpl_suffix = $ey_nid;
                    } else {
                        $tpl_suffix = str_replace('-', '_', $tpl_suffix);
                        $tpl_suffix = $ey_nid.'_'.ltrim($tpl_suffix, '_');
                    }
                }
                $ey_tplfile = "view_{$tpl_suffix}.{$view_suffix}"; // 对应易优模板文件名
                $temparticle_data[$dd_tplfile][$val['id']] = [
                    'dd_typeid' => $dd_typeid,
                    'dd_channel_id' => $dd_channel_id,
                    'dd_tplfile'  => $dd_tplfile,
                    'dd_nid'    => $dd_nid,
                    'ey_channel_id' => $ey_channel_id,
                    'ey_tplfile'  => $ey_tplfile,
                    'ey_nid'    => $ey_nid,
                ];
                $tempall_data[$dd_tplfile][$val['id']] = $temparticle_data[$dd_tplfile][$val['id']];
                $tempall_m_data[$dd_filename_m][$val['id']] = [
                    'dd_tplfile'  => $dd_filename_m,
                    'ey_tplfile'  => $ey_tplfile
                ];
            }
        }

        // 首页模板
        $homeTemplet = $this->DeDb('homepageset')->value('templet');
        if (empty($homeTemplet)) {
            $homeTemplet = 'default/index.htm';
        }
        $homeTempletArr = explode('/', $homeTemplet);
        $hometpl = end($homeTempletArr);
        $hometpl = !empty($hometpl) ? $hometpl : 'index.htm';
        $tempall_data[$hometpl][] = [
            'dd_tplfile'    => $hometpl,
            'ey_tplfile'    => 'index.htm',
        ];
        // 搜索模板
        $tempall_data['search.htm'][] = [
            'dd_tplfile'    => 'search.htm',
            'ey_tplfile'    => 'lists_search.htm',
        ];
        // tag主页模板
        $tempall_data['tag.htm'][] = [
            'dd_tplfile'    => 'tag.htm',
            'ey_tplfile'    => 'index_tags.htm',
        ];
        // tag列表模板
        $tempall_data['taglist.htm'][] = [
            'dd_tplfile'    => 'taglist.htm',
            'ey_tplfile'    => 'lists_tags.htm',
        ];

        $list = [];
        !empty($tempall_data) && $list['tempall_data'] = $tempall_data;
        !empty($templist_data) && $list['templist_data'] = $templist_data;
        !empty($temparticle_data) && $list['temparticle_data'] = $temparticle_data;
        !empty($tempall_m_data) && $list['tempall_m_data'] = $tempall_m_data;

        return $list;
    }

    /*
     * 修改
     * $num 匹配次数
     */
    /*private function tans($expression,$oringe,$target,$file_value,$num = 2){
        preg_match_all("/$expression/",$file_value,$matchList);
        if (!empty($matchList[$num])){
            foreach ($matchList[$num] as $key=>$val){
                $temp = $num;
                $target_str = $target;
                $oringe_str = $oringe;
                while ($temp){
                    $oringe_str = str_replace("{".$temp."}",$matchList[$temp][$key],$oringe_str);
                    $target_str = str_replace("{".$temp."}",$matchList[$temp][$key],$target_str);
                    $temp --;
                }
                $file_value = str_replace($oringe_str,$target_str,$file_value);
            }
        }

        return $file_value;
    }*/

    //搜索替换   单次--正则只有一个(.*?)
    /*private function tans_one($expression,$target,$file_value){
        $pre_expression = $this->regularStrTrans($expression);
        preg_match_all("/$pre_expression/",$file_value,$matchList);
        $num = count($matchList) - 1;
        if (!empty($matchList[$num])){
            $content_arr = $matchList[$num];
            foreach ($content_arr as $val){
                $expression_str = str_replace("(.*?)",$val,$expression);
                $target_str = str_replace("(.*?)",$val,$target);
                $file_value = str_replace($expression_str,$target_str,$file_value);
            }
        }

        return $file_value;
    }*/

    /*
     * 正则规则特殊字符处理
     */
    /*private function regularStrTrans($string){
        $string = str_replace('/','\/',$string);
        $string = str_replace('[','\[',$string);
        $string = str_replace(']','\]',$string);
        return $string;
    }*/

    //循环获取文件夹中的文件
    /*private function get_my_files($path){
        $list = array();
        foreach( glob( $path . '/*') as $item ){
            if( is_file( $item ) ) {
                $list[] = $item;
            }
        }

        return $list;
    }*/

    //旧有数据存文件(已经执行过一次生成文件，实际不需要再执行)
    /*private function writeSysConfig(){
        $sysconfig = $this->db->table("dede_sysconfig")->getField('varname',true);
        $sysconfig_str = json_encode($sysconfig);
        $file_name = "./sysconfig.txt";
        $myfile = fopen($file_name, "w") or die("无法打开文件，请检查目录权限!");
        fwrite($myfile, $sysconfig_str);
        fclose($myfile);
    }*/

    //导入织梦配置自定义数据
    public function importConfig()
    {
        // 织梦内置系统变量
        $sysconfig = ["cfg_addon_domain","cfg_addon_domainbind","cfg_addon_savetype","cfg_adminemail","cfg_album_col","cfg_album_ddwidth","cfg_album_mark","cfg_album_pagesize","cfg_album_row","cfg_album_style","cfg_album_width","cfg_allsearch_limit","cfg_arcautosp","cfg_arcautosp_size","cfg_arcdir","cfg_arcsptitle","cfg_arc_autokeyword","cfg_arc_autopic","cfg_arc_click","cfg_arc_dellink","cfg_arc_dirname","cfg_auot_description","cfg_backup_dir","cfg_baidunews_limit","cfg_basehost","cfg_beian","cfg_cache_type","cfg_caicai_add","cfg_caicai_sub","cfg_check_title","cfg_cli_time","cfg_cmspath","cfg_cookie_encode","cfg_cross_sectypeid","cfg_ddimg_bgcolor","cfg_ddimg_full","cfg_ddimg_height","cfg_ddimg_width","cfg_dede_log","cfg_delete","cfg_description","cfg_df_dutyadmin","cfg_df_style","cfg_digg_update","cfg_disable_funs","cfg_disable_tags","cfg_domain_cookie","cfg_face_adds","cfg_fck_xhtml","cfg_feedbackcheck","cfg_feedback_add","cfg_feedback_ck","cfg_feedback_forbid","cfg_feedback_guest","cfg_feedback_numip","cfg_feedback_sub","cfg_feedback_time","cfg_ftp_host","cfg_ftp_mkdir","cfg_ftp_port","cfg_ftp_pwd","cfg_ftp_root","cfg_ftp_user","cfg_html_editor","cfg_imgtype","cfg_indexname","cfg_indexurl","cfg_index_cache","cfg_index_max","cfg_jump_once","cfg_keywords","cfg_keyword_like","cfg_keyword_replace","cfg_list_son","cfg_list_symbol","cfg_login_adds","cfg_makeindex","cfg_makesign_cache","cfg_make_andcat","cfg_make_prenext","cfg_max_face","cfg_mb_addontype","cfg_mb_adminlock","cfg_mb_album","cfg_mb_allowncarc","cfg_mb_allowreg","cfg_mb_cktitle","cfg_mb_editday","cfg_mb_feedcheck","cfg_mb_idmin","cfg_mb_max","cfg_mb_msgischeck","cfg_mb_notallow","cfg_mb_open","cfg_mb_pwdmin","cfg_mb_pwdtype","cfg_mb_rank","cfg_mb_reginfo","cfg_mb_rmdown","cfg_mb_sendall","cfg_mb_spaceallarc","cfg_mb_spacesta","cfg_mb_upload","cfg_mb_upload_size","cfg_mb_wnameone","cfg_md_idurl","cfg_md_mailtest","cfg_medias_dir","cfg_mediatype","cfg_memcache_enable","cfg_memcache_mc_defa","cfg_memcache_mc_oth","cfg_money_scores","cfg_moreinfo_adds","cfg_multi_site","cfg_mysql_type","cfg_need_typeid2","cfg_notallowstr","cfg_online_type","cfg_powerby","cfg_puccache_time","cfg_qk_uploadlit","cfg_remote_site","cfg_replacestr","cfg_replace_num","cfg_rewrite","cfg_rm_remote","cfg_search_max","cfg_search_maxrc","cfg_search_time","cfg_sendarc_scores","cfg_sendfb_scores","cfg_sendmail_bysmtp","cfg_smtp_password","cfg_smtp_port","cfg_smtp_server","cfg_smtp_user","cfg_smtp_usermail","cfg_softtype","cfg_specnote","cfg_sphinx_article","cfg_sphinx_host","cfg_sphinx_port","cfg_task_pwd","cfg_title_maxlen","cfg_title_site","cfg_tplcache","cfg_tplcache_dir","cfg_typedir_df","cfg_updateperi","cfg_uplitpic_cut","cfg_upload_switch","cfg_userad_adds","cfg_vdcode_member","cfg_webname"];
        //清除易优自定义变量
        try {
            Db::name('config')->where(['name'=>['like', 'web_attr_%'], 'inc_type'=>'web'])->delete();
            Db::name("config_attribute")->where(['attr_id'=>['gt',0]])->delete();
            Db::execute('alter table '.PREFIX.'config AUTO_INCREMENT 1');
            Db::execute('alter table '.PREFIX.'config_attribute AUTO_INCREMENT 1');
        } catch (\Exception $e) {
            
        }
        //织梦中自定义配置变量，插入易优配置表中
        $customconfig = $this->DeDb('sysconfig')->where(['varname'=>['not in',$sysconfig]])->select();
        $addData = $configData = [];
        if (!empty($customconfig)){
            foreach ($customconfig as $val){
                if (preg_match('/^cfg_ask_/i', $val['varname'])) {
                    continue;
                }
                //0=文本框，1=下拉框，2=多行文本框，3=上传图片
                if(strtolower($val['type']) == 'bstring'){
                    $type = 2;
                }else{
                    $type = 0;
                }
                $addData[] = [
                    'inc_type' => 'web',
                    'attr_name' => $val['info'],
                    'attr_var_name' =>  'web_attr_'.$val['varname'],
                    'attr_input_type' => $type,
                    'lang' => $this->admin_lang,
                    'add_time' => getTime(),
                    'update_time' => getTime(),
                ];
                $configData['web_attr_'.$val['varname']] = $val['value'];
            }
            $rdata = model('ConfigAttribute')->saveAll($addData);
            if (!empty($rdata)) {
                $sql = "update `".PREFIX."config_attribute` set attr_var_name = CONCAT('web_attr_',attr_id)";
                if (false !== Db::execute($sql)) {
                    $saveData = [];
                    foreach ($rdata as $k1 => $v1) {
                        $attr_id = $v1->getData('attr_id');
                        $attr_var_name = $v1->getData('attr_var_name');
                        $saveData['web_attr_'.$attr_id] = !empty($configData[$attr_var_name]) ? $configData[$attr_var_name] : '';
                    }
                    tpCache('web', $saveData);
                }
            }
        }
    }

    /**
     * 清空全部缓存和数据表缓存文件生成
     */
    public function clear_cache()
    {
        Db::name('sql_cache_table')->where(['cache_id'=>['gt', 0]])->delete();
        delFile(rtrim(RUNTIME_PATH, '/'));

        /*重新生成全部数据表字段缓存文件*/
        try {
            schemaAllTable();
        } catch (\Exception $e) {}
        /*--end*/
    }

    /**
     * 判断表是否存在
     * @param  string  $table [description]
     * @return boolean        [description]
     */
    public function is_tables_exists($table = '')
    {
        $dbtables = Db::query('SHOW TABLE STATUS');
        $tableslist = array();
        foreach ($dbtables as $k => $v) {
            if ($table == $v['Name']) {
                return true;
            }
        }
        return false;
    }
    /*
     *  幻灯片转广告
     */
    public function DedeToAd($dede_prefix = ''){
        if ($this->is_tables_exists("{$dede_prefix}myppt") && $this->is_tables_exists("{$dede_prefix}myppttype")) {
            //广告位置
            $myppttypeRow = $this->DeDb('myppttype')->field('id,typename as title')->order('id asc')->select();
            if (!empty($myppttypeRow)) {
                foreach ($myppttypeRow as $key => $value) {
                    $value['title'] = htmlspecialchars($value['title']);
                    $value['lang'] = $this->admin_lang;
                    $value['intro'] = "";
                    $value['add_time'] = $value['update_time'] = getTime();
                    $myppttypeRow[$key] = $value;
                }
                if (!empty($myppttypeRow)) {
                    $del = Db::name('ad_position')->where('id','>',0)->delete();
                    if ($del !== false) {
                        Db::execute('alter table '.PREFIX.'ad_position AUTO_INCREMENT 1');
                        Db::name('ad_position')->insertAll($myppttypeRow);
                    }
                }
                // 广告数据
                $mypptRow = $this->DeDb('myppt')
                    ->field('aid as id,typeid as pid,title,introduce as intro,pic as litpic,url as links')
                    ->order('aid asc')->select();
                foreach ($mypptRow as $key => $value) {
                    $value['title'] = htmlspecialchars($value['title']);
                    $value['intro'] = htmlspecialchars($value['intro']);
                    $value['media_type']    = 1;
                    $value['status']    = 1;
                    $value['sort_order']    = 100;
                    $value['lang'] = $this->admin_lang;
                    $value['update_time'] = getTime();
                    $mypptRow[$key] = $value;
                }
                if (!empty($mypptRow)) {
                    $del = Db::name('ad')->where('id','>',0)->delete();
                    if ($del !== false) {
                        Db::execute('alter table '.PREFIX.'links AUTO_INCREMENT 1');
                        Db::name('ad')->insertAll($mypptRow);
                    }
                }
            }
        }
    }
    /**
     * 转友情链接
     */
    public function DedeToFlinktype($dede_prefix = '')
    {
        if ($this->is_tables_exists("{$dede_prefix}flinktype") && $this->is_tables_exists("{$dede_prefix}flink")) {
            $flinktypeRow = $this->DeDb('flinktype')->field('id,typename as group_name')->order('id asc')->select();
            if (!empty($flinktypeRow)) {
                foreach ($flinktypeRow as $key => $value) {
                    $value['group_name'] = htmlspecialchars($value['group_name']);
                    $value['sort_order']    = 100;
                    $value['lang'] = $this->admin_lang;
                    $value['add_time'] = $value['update_time'] = getTime();
                    $flinktypeRow[$key] = $value;
                }
                if (!empty($flinktypeRow)) {
                    $del = M('links_group')->where('id','>',0)->delete();
                    if ($del !== false) {
                        Db::execute('alter table '.PREFIX.'links_group AUTO_INCREMENT 1');
                        M('links_group')->insertAll($flinktypeRow);
                    }
                }

                // 友情数据
                $flinkRow = $this->DeDb('flink')->field('id,sortrank as sort_order,url,webname as title,email,msg as intro,logo,dtime as add_time,typeid as groupid,ischeck as status')->order('id asc')->select();
                foreach ($flinkRow as $key => $value) {
                    $value['title'] = htmlspecialchars($value['title']);
                    $value['intro'] = htmlspecialchars($value['intro']);
                    $value['status']    = !empty($value['status']) ? 1 : 0;
                    $value['typeid']    = !empty($value['logo']) ? 2 : 1;
                    $value['groupid']    = !empty($value['groupid']) ? $value['groupid'] : 1;
                    $value['lang'] = $this->admin_lang;
                    $value['update_time'] = $value['add_time'];
                    $flinkRow[$key] = $value;
                }
                if (!empty($flinkRow)) {
                    $del = M('links')->where('id','>',0)->delete();
                    if ($del !== false) {
                        Db::execute('alter table '.PREFIX.'links AUTO_INCREMENT 1');
                        M('links')->insertAll($flinkRow);
                    }
                }
            }
        }
    }

    /**
     * 数据表结构特殊处理
     * @return [type] [description]
     */
    public function eyouDatabase()
    {
        $Prefix = PREFIX;
        // 兼容字段长度
        @Db::execute("ALTER TABLE `{$Prefix}archives` MODIFY COLUMN `jumplinks`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '外链跳转' AFTER `arcrank`;");
        // 栏目文档规则等字段
        $getTableInfo = Db::query("SHOW COLUMNS FROM {$Prefix}arctype");
        $getTableInfo = get_arr_column($getTableInfo, 'Field');
        if (!empty($getTableInfo) && !in_array('diy_dirpath', $getTableInfo)) {
            $sql = "ALTER TABLE `{$Prefix}arctype` ADD COLUMN `diy_dirpath`  varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '列表静态文件存放规则' AFTER `dirpath`;";
            @Db::execute($sql);
            $sql = "DELETE FROM `{$Prefix}channelfield` WHERE `channel_id` = '-99' AND `name` IN ('diy_dirpath');";
            @Db::execute($sql);
            $sql = "INSERT INTO `{$Prefix}channelfield` (`name`, `channel_id`, `title`, `dtype`, `define`, `maxlength`, `dfvalue`, `dfvalue_unit`, `remark`, `is_screening`, `is_release`, `ifeditable`, `ifrequire`, `ifsystem`, `ifmain`, `ifcontrol`, `sort_order`, `status`, `add_time`, `update_time`) VALUES ('diy_dirpath', '-99', '自定义HTML保存路径', 'text', 'varchar(200)', '200', '', '', '', '0', '0', '1', '0', '1', '1', '1', '100', '1', '1533524780', '1533524780');";
            @Db::execute($sql);
            $sql = "UPDATE `{$Prefix}arctype` SET `diy_dirpath` = `dirpath`;";
            @Db::execute($sql);
            schemaTable('arctype');
        }
        if (!empty($getTableInfo) && !in_array('rulelist', $getTableInfo)) {
            $sql = "ALTER TABLE `{$Prefix}arctype` ADD COLUMN `rulelist`  varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '列表静态文件存放规则' AFTER `diy_dirpath`;";
            @Db::execute($sql);
            $sql = "DELETE FROM `{$Prefix}channelfield` WHERE `channel_id` = '-99' AND `name` IN ('rulelist');";
            @Db::execute($sql);
            $sql = "INSERT INTO `{$Prefix}channelfield` (`name`, `channel_id`, `title`, `dtype`, `define`, `maxlength`, `dfvalue`, `dfvalue_unit`, `remark`, `is_screening`, `is_release`, `ifeditable`, `ifrequire`, `ifsystem`, `ifmain`, `ifcontrol`, `sort_order`, `status`, `add_time`, `update_time`) VALUES ('rulelist', '-99', '列表静态文件存放规则', 'text', 'varchar(200)', '200', '', '', '', '0', '0', '1', '0', '1', '1', '1', '100', '1', '1533524780', '1533524780');";
            @Db::execute($sql);
            schemaTable('arctype');
        }
        if (!empty($getTableInfo) && !in_array('ruleview', $getTableInfo)) {
            $sql = "ALTER TABLE `{$Prefix}arctype` ADD COLUMN `ruleview`  varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '文档静态文件存放规则' AFTER `rulelist`;";
            @Db::execute($sql);
            $sql = "DELETE FROM `{$Prefix}channelfield` WHERE `channel_id` = '-99' AND `name` IN ('ruleview');";
            @Db::execute($sql);
            $sql = "INSERT INTO `{$Prefix}channelfield` (`name`, `channel_id`, `title`, `dtype`, `define`, `maxlength`, `dfvalue`, `dfvalue_unit`, `remark`, `is_screening`, `is_release`, `ifeditable`, `ifrequire`, `ifsystem`, `ifmain`, `ifcontrol`, `sort_order`, `status`, `add_time`, `update_time`) VALUES ('ruleview', '-99', '文档静态文件存放规则', 'text', 'varchar(200)', '200', '', '', '', '0', '0', '1', '0', '1', '1', '1', '100', '1', '1533524780', '1533524780');";
            @Db::execute($sql);
            schemaTable('arctype');
        }
    }
}
