<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
// 系统位数
function sys_bit() {
    $int = "9223372036854775807";
    $int = intval($int);
    if ($int == 9223372036854775807) {
        return 64;
    } else if ($int == 2147483647) {
        return 32;
    } else {
        return false;
    }
}
// 列表转树
function listToTree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0) {
    $tree = array();
    if (is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[ $data[ $pk ] ] = &$list[ $key ];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[ $pid ];
            if ($root == $parentId) {
                $tree[ $data[ $pk ] ] = &$list[ $key ];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[ $parentId ];
                    $parent[ $child ][ $data[ $pk ] ] = &$list[ $key ];
                    $parent[ $child ] = array_values($parent[ $child ]);
                }
            }
        }
    }
    return $tree;
}
// 数组层级缩进，不能多次调用
function arr2level($array, $pid = 0, $level = 1, $maxlevel = 100) {
    static $list = array();
    foreach ($array as $k => $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            unset($array[$k]);
            if($v['level'] < $maxlevel) {
                arr2level($array, $v['id'], $level + 1, $maxlevel);
            }            
        }
    }
    return $list;
}
// 二维数组求差异
function get_diff_array_by_filter($arr1, $arr2) { 
    try{
        return array_filter($arr1,function($v) use ($arr2){
            return !in_array($v,$arr2);
        });
    }catch (\Exception $exception){
        return $arr1;
    }
} 
// 向上递归
function get_father($array,$id)
{
    $result = [];
    foreach ($array as $k => $v) {
        if($v['id']==$id){
            $result[] = $v;
            unset($array[$k]);
            $result = array_merge(get_father($array,$v['pid']),$result);
        }
    }
    return $result;
}
// 栏目树
function navtree($data, $pid = 0, $level = 1) {  
    $return = array();  
    foreach($data as $leaf) {  
        if($leaf['pid'] == $pid) {
            $leaf["level"] = $level;
            if($leaf['link']) {
                $leaf['url'] = $leaf['link'];
            } else {
                $leaf['url'] = url('home/index/nav?id='.$leaf['id'].'&siteid='.$leaf['site_id']);
            }
            $leaf['children'] = '';
            foreach($data as $subleaf) {
                if($subleaf['pid'] == $leaf['id']) {
                    $leaf['children'] = navtree($data, $leaf['id'], $level+1); 
                    break;
                }
            }
            $return[] = $leaf; 
        } 
    } 
    return $return;  
}
// 内容栏目列表
function navforcontent($data)
{
    $dataids = array_column($data,'id');
    foreach ($data as $k => $v) {
        if($v['pid'] !== 0 && !in_array($v['pid'], $dataids)) {
            $data[$k]['pid'] = 0;
        }
    }
    return $data;
}
// 随机字符
function random($length=10, $type='letter', $convert=0)
{
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'letter';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string[mt_rand(0, $strlen)];
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    if($type = 'number') {
        $code = ltrim($code,'0');
    }
    return $code;
}
// 字符串截取
function cut_str($string, $sublen, $start =0, $code ='UTF-8')
{
    if($code =='UTF-8')
    {
        $pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);if(count($t_string[0])- $start > $sublen)return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    } else {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr ='';
        for($i=0; $i<$strlen; $i++)
        {
            if($i>=$start && $i<($start+$sublen)) {
                if(ord(substr($string, $i,1))>129) {
                    $tmpstr.= substr($string, $i,2);
                } else {
                    $tmpstr.= substr($string, $i,1);
                }
            }
            if(ord(substr($string, $i,1))>129) $i++;
        }
        if(strlen($tmpstr)<$strlen ) $tmpstr.="...";
        return $tmpstr;
    }
}
//获取用户真实IP 
function getIp()
{ 
    $ip=FALSE;
    //客户端IP 或 NONE 
    if(!empty($_SERVER["HTTP_CLIENT_IP"])){
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
        for ($i = 0; $i < count($ips); $i++) {
            if (!preg_match ("/^(10│172.16│192.168)./i", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    //客户端IP 或 (最后一个)代理服务器 IP
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
// 微信
function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } return false;
}
// qq
function is_qq() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false) {
        return true;
    } return false;
}
// 支付宝
function is_alipay() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        return true;
    } return false;
}

// 邮件发送
function sendMail($to, $title, $content,$config=[])
{
    if(!$config) {
        $config['email'] = config('app.email.email');
        $config['emailfrom'] = config('app.email.emailfrom');
        $config['emailfromname'] = config('app.email.emailfromname');
        $config['emailsmtp'] = config('app.email.emailsmtp');
        $config['emailsecure'] = config('app.email.emailsecure');
        $config['emailport'] = config('app.email.emailport');
        $config['emailusername'] = config('app.email.emailusername');
        $config['emailpassword'] = config('app.email.emailpassword');
    }
    if($config['email']){
        $mail = new \PHPMailer\PHPMailer\PHPMailer(); //实例化
        // 设置PHPMailer使用SMTP服务器发送Email
        $mail->IsSMTP();
        $mail->Mailer='smtp';
        $mail->IsHTML(true);
        // 设置邮件的字符编码，若不指定，则为'UTF-8'
        $mail->CharSet='UTF-8';
        // 添加收件人地址，可以多次使用来添加多个收件人
        $mail->AddAddress($to);
        // 设置邮件正文
        $mail->Body=$content;
        // 设置邮件头的From字段。
        $mail->From=$config['emailfrom'];
        // 设置发件人名字
        $mail->FromName=$config['emailfromname'];
        // 设置邮件标题
        $mail->Subject=$title;
        // 设置SMTP服务器。
        $mail->Host=$config['emailsmtp'];
        //by Rainfer
        // 设置SMTPSecure。
        $mail->SMTPSecure=$config['emailsecure'];
        // 设置SMTP服务器端口。
        $port=$config['emailport'];
        $mail->Port=empty($port)?"25":$port;
        // 设置为"需要验证"
        $mail->SMTPAuth=true;
        // 设置用户名和密码。
        $mail->Username=$config['emailusername'];
        $mail->Password=$config['emailpassword'];
        // 发送邮件。
        if(!$mail->Send()) {
            $mailerror=$mail->ErrorInfo;
            return array("code"=>0,"msg"=>$mailerror);
        }else{
            return array("code"=>1,"msg"=>"发送成功");
        }
    }else{
        return array("code"=>0,"msg"=>'邮件系统未开启');
    }
}

// 获取一个字符串
function getone($str,$n=1,$m='|')
{
    $array = explode($m, $str);
    return $array[$n-1];
}

// 内容转化为文本
function totxt($string)
{    
    $string = htmlspecialchars_decode($string);
    $string = str_replace("&nbsp;"," ",$string);
    $string = str_replace("　"," ",$string);
    $string = str_replace('"','＂',$string);    
    $string = str_replace("'",'＇',$string);
    $string = trim(htmlspecialchars(strip_tags($string)));     
    return $string;
}

// 无图默认值
function noimg($str)
{
    if(empty($str) || (!config('app.qiniu.qiniu') && !is_file(env('root_path').$str))) {
        return '/public/static/images/nopic.jpg';
    } else {
        return $str;
    }
}

// 获取自定义单选多选下拉对应值
function getrealvalue($model_id,$data)
{
    $diyfields = Db::name('modelfields')->where(['model_id' => $model_id,'status' => 1])->whereIn('type','t4,t5,t6,t7')->select();
    foreach ($diyfields as $k => $v) {
        $content_arry = explode("\n",$v['content']);
        if(!empty($data[$v['name']])) {
            switch ($v['type']) {
                // 下拉和单选
                case 't4':
                case 't5':
                    foreach ($content_arry as $value) {
                        if(strstr($value,'|') !== false) {
                            $c = explode('|',$value);
                            if($c[0] == $data[$v['name']]) {
                                $data[$v['name'].'_value'] = $c[1];
                            }
                        } else {
                            if($value == $data[$v['name']]) {
                                $data[$v['name'].'_value'] = $value;
                            }
                        }
                    }
                    break;
                // 多选
                case 't6':
                    $str = [];
                    $default = explode('|',$data[$v['name']]);
                    foreach ($content_arry as $value) {
                        if(strstr($value,'|') !== false) {
                            $c = explode('|',$value);
                            if(in_array($c[0],$default)) {
                                $str[] = $c[1];
                            }
                        } else {
                            if(in_array($value,$default)) {
                                $str[] = $value;
                            }
                        }
                    }
                    $data[$v['name'].'_value'] = implode('|',$str);
                    break;
                // 日期
                case 't7':
                    switch ($v['default']) {
                        case 'datetime':
                            $datetype = 'Y-m-d H:m:s';
                            break;
                        case 'year':
                            $datetype = 'Y';
                            break;
                        case 'month':
                            $datetype = 'Y-m';
                            break;
                        case 'date':
                            $datetype = 'Y-m-d';
                            break;
                        default:
                            $datetype = 'Y-m-d H:m:s';
                            break;
                    }
                    $data[$v['name']] = $data[$v['name'].'_value'] = empty($data[$v['name']]) ? '' : date($datetype,$data[$v['name']]);
                    break;
            }
        }
    }
    return $data;
}

// 查找子ID，不包含本身
function get_child_id($data, $pid = '0')
{
    $child = '';
    foreach ($data as $value) {
        if ($value['pid'] == $pid) {
            $child .= ',' . $value['id'];
            $child .= get_child_id($data, $value['id']);
        }
    }
    return $child;
}

// 查找子孙
function get_childs($arr,$item,$id) {
    $subs = array(); // 子孙数组
    foreach($arr as $v) {
        if($v['pid'] == $id) {
            $subs[] = $v[$item]; 
            $subs = array_merge($subs,get_childs($arr,$item,$v['id']));
        }
    }
    return $subs;
}

// 栏目和内容链接生成
function getlink($navinfo,$contentinfo = array())
{
    
    $url = '';
    // 栏目信息
    $navname = empty($navinfo['diyname']) ? 'nav' . $navinfo['id'] : $navinfo['diyname'];
    if(empty($contentinfo)) {
        // 栏目
        $url = url('home/nav/index',['sitealias' => URL_SITEALIAS,'nav' => $navname]);
    } else {
        // 内容
        $contentname = empty($contentinfo['alias']) ? $contentinfo['id'] : $contentinfo['alias'];
        // 处理单页
        if($navinfo['model']['contenttype'] == 1 && $contentinfo['status'] == 1) {
            $url = url('home/nav/index',['sitealias' => URL_SITEALIAS,'nav' => $navname]);
        } else {
            $url = url('home/content/index',['sitealias' => URL_SITEALIAS,'nav' => $navname,'con' => $contentname]);
        }
    }
    return $url;
}

// 外链处理
function getoutlink($linkdata)
{
    $url='';
    if(strpos($linkdata, 'sitelink|||') !== false) {
        $linkarr = explode('|||',$linkdata);
        $linknavid = $linkarr[1];
        $linkcontentid = $linkarr[2];
        $linknavinfo = model('navlist')->where(['status'=>1])->with('model')->get($linknavid);
        if($linknavinfo) {
            $linknavname = empty($linknavinfo['diyname']) ? 'nav' . $linknavinfo['id'] : $linknavinfo['diyname'];
            if($linkcontentid == 0) {
                // 栏目链接
                $url = url('home/nav/index',['sitealias' => URL_SITEALIAS,'nav' => $linknavname]);
            } else {
                // 内容链接
                $linkmodelinfo = $linknavinfo['model'];
                if($linkmodelinfo) {
                    $linktable = tablepref($linkmodelinfo['modeltype']).$linkmodelinfo['tablename'];
                    $linkcontentinfo = model('content')->name($linktable)->get($linkcontentid);
                    if($linkcontentinfo) {
                        $linkcontentname = empty($linkcontentinfo['alias']) ? $linkcontentid : $linkcontentinfo['alias'];
                        // 单页绑定的内容
                        if($linkmodelinfo['contenttype'] == 1 && $linkcontentinfo['status'] == 1) {
                            $url = url('home/nav/index',['sitealias' => URL_SITEALIAS,'nav' => $linknavname]);
                        } else {
                            // 其他内容
                            $url = url('home/content/index',['sitealias' => URL_SITEALIAS,'nav' => $linknavname,'con' => $linkcontentname]);
                        }
                    }
                }
            }
        }
    } else {
        // 其他外链
        switch ($linkdata) {
            case 'index':
                $url = url('home/index/index',['sitealias' => URL_SITEALIAS]).empty(URL_SITEALIAS) ? '' : '/';
                break;
            case 'user':
                $url = url('user/index/index');
                break;
            default:
                $url = $linkdata;
                break;
        }
    }
    return $url;
}

/**
 * 将一个字符串部分字符用$re替代隐藏
 * @param string    $string   待处理的字符串
 * @param int       $start    规定在字符串的何处开始，
 *                            正数 - 在字符串的指定位置开始
 *                            负数 - 在从字符串结尾的指定位置开始
 *                            0 - 在字符串中的第一个字符处开始
 * @param int       $length   可选。规定要隐藏的字符串长度。默认是直到字符串的结尾。
 *                            正数 - 从 start 参数所在的位置隐藏
 *                            负数 - 从字符串末端隐藏
 * @param string    $re       替代符
 * @return string   处理后的字符串
 */
function hidestr($string, $start = 0, $length = 0, $re = '*')
{
    if (empty($string)) return false;
    $strarr = array();
    $mb_strlen = mb_strlen($string);
    while ($mb_strlen) {
    //循环把字符串变为数组
        $strarr[] = mb_substr($string, 0, 1, 'utf8');
        $string = mb_substr($string, 1, $mb_strlen, 'utf8');
        $mb_strlen = mb_strlen($string);
    }
    $strlen = count($strarr);
    $begin  = $start >= 0 ? $start : ($strlen - abs($start));
    $end    = $last   = $strlen - 1;
    if ($length > 0) {
        $end  = $begin + $length - 1;
    } elseif ($length < 0) {
        $end -= abs($length);
    }
    for ($i=$begin; $i<=$end; $i++) {
        $strarr[$i] = $re;
    }
    if ($begin >= $end || $begin >= $last || $end > $last) return false;
    return implode('', $strarr);
}

// 单位换算
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

// layui弹窗
function rgalert($str = "错误的请求！",$url = -1)
{
    switch ($url) {
        // 返回上一页
        case -1:
            $url = "{location.href='javascript:history.go(-1)'}"; 
            break;
        // 关闭当前弹窗
        case 0:
            $url = "{parent.layer.closeAll();return false;}"; 
            break;
        // 关闭当前弹窗并刷新父页
        case 1:
            $url = "{parent.layer.closeAll();parent.location.reload();}"; 
            break;
        // 关闭当前弹窗并刷新顶层页面
        case 2:
            $url = "{parent.layer.closeAll();top.location.reload();}"; 
            break;
        // 跳转url
        default:
            $url = "{location.href='".$url."'}"; 
            break;
    }
    echo "<script>{parent.layer.msg('".$str."',{icon: 2,time: 1500}, function()".$url.");}</script>";
    die();
}

function rg_encode($string,$key = '', $expiry = 0)
{  
    $ckeyLength = 4;  
    $key = md5($key ? $key : 'a!takA:dlmcldEv,e');
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = substr(md5(microtime()), - $ckeyLength);  
    $cryptkey = $keya . md5($keya . $keyc);    
    $keyLength = strlen($cryptkey);  
    $string = sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string . $keyb), 0, 16) . $string;  
    $stringLength = strlen($string);  

    $rndkey = array();    
    for($i = 0; $i <= 255; $i++) {    
        $rndkey[$i] = ord($cryptkey[$i % $keyLength]);  
    }  

    $box = range(0, 255);     
    // 打乱密匙簿，增加随机性  
    for($j = $i = 0; $i < 256; $i++) {  
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;  
        $tmp = $box[$i];  
        $box[$i] = $box[$j];  
        $box[$j] = $tmp;  
    }     
    // 加解密，从密匙簿得出密匙进行异或，再转成字符  
    $result = '';  
    for($a = $j = $i = 0; $i < $stringLength; $i++) {  
        $a = ($a + 1) % 256;  
        $j = ($j + $box[$a]) % 256;  
        $tmp = $box[$a];  
        $box[$a] = $box[$j];  
        $box[$j] = $tmp;   
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  
    }  
    $result = $keyc . str_replace('=', '', base64_encode($result));  
    $result = str_replace(array('+', '/', '='),array('-', '_', '.'), $result);  
    return $result;  
}

function rg_decode($string,$key = '')  
{  
    $string = str_replace(array('-', '_', '.'),array('+', '/', '='), $string);  
    $ckeyLength = 4;  
    $key = md5($key ? $key : 'a!takA:dlmcldEv,e'); 
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = substr($string, 0, $ckeyLength);  
    $cryptkey = $keya . md5($keya . $keyc);
    $keyLength = strlen($cryptkey);  
    $string = base64_decode(substr($string, $ckeyLength));  
    $stringLength = strlen($string);  

    $rndkey = array();    
    for($i = 0; $i <= 255; $i++) {    
        $rndkey[$i] = ord($cryptkey[$i % $keyLength]);  
    }  

    $box = range(0, 255);  
    // 打乱密匙簿，增加随机性  
    for($j = $i = 0; $i < 256; $i++) {  
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;  
        $tmp = $box[$i];  
        $box[$i] = $box[$j];  
        $box[$j] = $tmp;  
    }  
    // 加解密，从密匙簿得出密匙进行异或，再转成字符  
    $result = '';  
    for($a = $j = $i = 0; $i < $stringLength; $i++) {  
        $a = ($a + 1) % 256;  
        $j = ($j + $box[$a]) % 256;  
        $tmp = $box[$a];  
        $box[$a] = $box[$j];  
        $box[$j] = $tmp;   
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  
    }  
    if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0)  
    && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)  
    ) {  
        return substr($result, 26);  
    } else {  
        return '';  
    }   
}

// 获取多图第X张图
function get_img($imgs,$n=1)
{
    $imgs = json_decode($imgs,true);
    if(is_array($imgs)) {
        return $imgs[$n-1]['img'];
    }
}
// 判断是否是时间戳
function is_timestamp($timestamp) {
    if(strtotime(date('m-d-Y H:i:s',$timestamp)) === $timestamp) {
        return true;
    } else return false;
}
// 字符串转布尔
function is_true($val, $return_null=false){
    $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
    return ( $boolval===null && !$return_null ? false : $boolval );
}

// 自定义字段列表显示
function DiyTableCol($model_id,$recycle=false) {
    $Cmsfields = new app\common\model\Cmsfields();
    $list = $Cmsfields::whereCmsmodelsId($model_id)->whereIsShow(1)->order('torder asc')->select();
    $str = '';
    if($list->isEmpty()) return $str;
    foreach ($list as $k => $v) {
        if($recycle) $v->is_edit = false;
        if($v->is_sort) {
            $sort = ',sort:true';
        } else {
            $sort = '';
        }
        if($v->width) {
            $width = 'width:'.$v->width.',';
        } else {
            $width = '';
        }
        switch ($v->type) {
            case 'input':
            case 'integer':
            case 'decimal':
                if($v->is_edit) {
                    $edit = ',edit:"text"';
                } else {
                    $edit = '';
                }
                $str .= <<<EOF
{{$width}field:'{$v->name}', title:'{$v->title}'{$edit}{$sort}},
EOF;
                break;
            case 'switch':
                if($v->is_edit) {
                    $edit = 'lay-filter="status"';
                } else {
                    $edit = 'disabled';
                }
                $str .= <<<EOF
{{$width}field:'{$v->name}',align: 'center', title: '{$v->title}', templet:function(d){return '<input type="checkbox" name="{$v->name}" lay-skin="primary" value="'+d.id+'" {$edit} '+(d.{$v->name} == 1 ? "checked" : "")+'>';}{$sort}},
EOF;
                break;
            case 'img':
                $str .= <<<EOF
{{$width}align: 'center',title:'{$v->title}',templet: function(d){if(!d.{$v->name}) d.{$v->name} = '/public/static/images/nopic.jpg';return '<img src="'+d.{$v->name}+'" style="height:28px;width:30px;" onclick=viewpic("'+d.{$v->name}+'")>';}},
EOF;
                break;
            case 'file':
                $str .= <<<EOF
{{$width}align: 'center',title:'{$v->title}',templet: function(d){if(!d.{$v->name}) d.{$v->name} = 'javascript:;';return '<a href="'+d.{$v->name}+'" style="color:#01AAED;">下载</a>';}},
EOF;
                break;
            case 'datetime':
                $v->time_format = $v->time_format?:'yyyy-MM-dd HH:mm:ss';
                $str .= <<<EOF
{{$width}field:'{$v->name}', title:'{$v->title}',templet:function(d){return layui.util.toDateString(d.{$v->name}*1000,"{$v->time_format}");}{$sort}},
EOF;
                break;
        }
    }
    return $str;
}
// 自定义动态字段包括全局变量
function DiyFields_dynamic($tablename,$cid) {
    $Fields_dynamic = new app\common\model\Diyfields();
    $list = $Fields_dynamic::whereTablename($tablename)->whereCid($cid)->order('torder asc')->select();
    $str = '';
    if(!empty($list)) {
        foreach ($list as $k => $v) {
            switch ($v->type) {
                case 'input':
                    $str .= <<<EOF
<div class="layui-form-item">
    <input type="hidden" name="data[$k][id]" value="{$v->id}">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><input type="text" name="data[$k][value]" placeholder="请输入{$v->title}" class="layui-input" value="{$v->value}"></div>
</div>
EOF;
                    break;
                case 'textarea':
                    $str .= <<<EOF
<div class="layui-form-item">
    <input type="hidden" name="data[$k][id]" value="{$v->id}">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><textarea name="data[$k][value]" placeholder="请输入{$v->title}" class="layui-textarea">{$v->value}</textarea></div>
</div>
EOF;
                    break;
                case 'color':
                    $str .= <<<EOF
<div class="layui-form-item">
    <input type="hidden" name="data[$k][id]" value="{$v->id}">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline" style="width: 120px;"><input type="text" name="data[$k][value]" id="{$v->name}_value" value="{$v->value}" placeholder="请选择颜色" class="layui-input"></div><div class="layui-inline" style="left: -11px;"><div class="rgcms_color" id="{$v->name}"></div></div>
</div>
EOF;
                    break;
                case 'img':
                    $defaultimg = empty($v->value) ? '/public/static/images/nopic.jpg' : $v->value;
                    $str .= <<<EOF
<div class="layui-form-item">
    <input type="hidden" name="data[$k][id]" value="{$v->id}">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline" style="width:50%;">
        <input type="text" class="layui-input" name="data[$k][value]" id="{$v->name}" value="{$v->value}">
    </div>
    <div class="layui-word-aux">
        <button type="button" class="layui-btn rgcms_uploadimage" lay-data="{id:'{$v->name}',config:{water:false,thumb:false,action:'uploadimage'}}">上传</button>
    </div>
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <img src="{$defaultimg}" id="{$v->name}pic" style="max-height:60px; border:#efefef 1px solid;">
    </div>
</div>
EOF;
                    break;
                case 'imgs':
                    $pics = '';
                    if(!empty($v->value)) {
                        $imgsdefault = json_decode($v->value,true);
                        foreach ($imgsdefault as $i) {
                            $pics .= '<li class="item_img"><div class="operate"><i class="toleft layui-icon layui-icon-left"></i><i class="toright layui-icon layui-icon-right"></i><span class="close">删</span><span class="view">预</span></div><img src="'.$i['src'].'" class="img" ><input type="text" class="layui-input imgstitle" placeholder="标题" value="'.$i['title'].'"/></li>';
                        }
                    }
                    $str .= <<<EOF
<div class="layui-form-item">
    <input type="hidden" name="data[$k][id]" value="{$v->id}">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadimages" lay-data="{id:'{$v->name}',config:{water:false,thumb:false,action:'uploadimage'}}">上传</button>
        </div>
    </div>
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <div class="pic-more"><ul class="pic-more-upload-list slide-pc-priview" id="{$v->name}">{$pics}</ul><input type="hidden" name="data[$k][value]" value='{$v->value}' id="{$v->name}_value"></div>
    </div>
</div>
EOF;
                    break;
                case 'ueditor':
                    $ueditor_url = url('upload/upload').'?water=false&thumb=false';
                    $str .= <<<EOF
<div class="layui-form-item">
    <input type="hidden" name="data[$k][id]" value="{$v->id}">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <textarea name="data[$k][value]" class="layui-textarea" id="{$v->name}">{$v->value}</textarea>
        <script>var {$v->name}_content = new UE.getEditor("{$v->name}",{zIndex:0,serverUrl:"{$ueditor_url}"});</script>
    </div>
</div>
EOF;
                    break;
            }
        }
    }
    return $str;
}

// 栏目扩展字段
function DiyFields_navlist($config='') {
    $Fields_dynamic = new app\common\model\Diyfields();
    $list = $Fields_dynamic::whereTablename('navlist')->whereCid(session('siteid'))->order('torder asc')->select();
    $str = '';
    if(!empty($list)) {
        foreach ($list as $k => $v) {
            $value = !empty($config[$v->name])?$config[$v->name]:'';
            switch ($v->type) {
                case 'input':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><input type="text" name="config[{$v->name}]" placeholder="请输入{$v->title}" class="layui-input" value="{$value}"></div>
</div>
EOF;
                    break;
                case 'textarea':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><textarea name="config[{$v->name}]" placeholder="请输入{$v->title}" class="layui-textarea">{$value}</textarea></div>
</div>
EOF;
                    break;
                case 'color':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline" style="width: 120px;"><input type="text" name="config[{$v->name}]" id="{$v->name}_value" value="{$value}" placeholder="请选择颜色" class="layui-input"></div><div class="layui-inline" style="left: -11px;"><div class="rgcms_color" id="{$v->name}"></div></div>
</div>
EOF;
                    break;
                case 'img':
                    $defaultimg = empty($value) ? '/public/static/images/nopic.jpg' : $value;
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline" style="width:50%;">
        <input type="text" class="layui-input" name="config[{$v->name}]" id="{$v->name}" value="{$value}">
    </div>
    <div class="layui-word-aux">
        <button type="button" class="layui-btn rgcms_uploadimage" lay-data="{id:'{$v->name}',config:{water:false,thumb:false,action:'uploadimage'}}">上传</button>
    </div>
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <img src="{$defaultimg}" id="{$v->name}pic" style="max-height:60px; border:#efefef 1px solid;">
    </div>
</div>
EOF;
                    break;
                case 'imgs':
                    $pics = '';
                    if(!empty($value)) {
                        $imgsdefault = json_decode($value,true);
                        foreach ($imgsdefault as $i) {
                            $pics .= '<li class="item_img"><div class="operate"><i class="toleft layui-icon layui-icon-left"></i><i class="toright layui-icon layui-icon-right"></i><span class="close">删</span><span class="view">预</span></div><img src="'.$i['src'].'" class="img" ><input type="text" class="layui-input imgstitle" placeholder="标题" value="'.$i['title'].'"/></li>';
                        }
                    }
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadimages" lay-data="{id:'{$v->name}',config:{water:false,thumb:false,action:'uploadimage'}}">上传</button>
        </div>
    </div>
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <div class="pic-more"><ul class="pic-more-upload-list slide-pc-priview" id="{$v->name}">{$pics}</ul><input type="hidden" name="config[{$v->name}]" value='{$value}' id="{$v->name}_value"></div>
    </div>
</div>
EOF;
                    break;
                case 'ueditor':
                    $ueditor_url = url('upload/upload').'?water=false&thumb=false';
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <textarea name="config[{$v->name}]" class="layui-textarea" id="{$v->name}">{$value}</textarea>
        <script>var {$v->name}_content = new UE.getEditor("{$v->name}",{zIndex:0,serverUrl:"{$ueditor_url}"});</script>
    </div>
</div>
EOF;
                    break;
            }
        }
    }
    return $str;
}


// 自定义字段显示
function DiyFields($model_id,$data='') {
    $Cmsfields = new app\common\model\Cmsfields();
    $list = $Cmsfields::whereCmsmodelsId($model_id)->whereStatus(1)->order('torder asc')->select();
    $switch_list = $list->where('type','switch');
    $other_list = $list->where('type','<>','switch');
    $str = '';
    // 非开关
    if(!$other_list->isEmpty()) {
        foreach ($other_list as $k => $v) {
            if(empty($data)) {
                $default = $v->defaultval;
            } else {
                $default = $data[$v->name];
            }
            $required = $v->require ? 'required' : '';
            $disabled = (!empty($data) && !$v->is_edit) ? 'disabled' : '';
            switch ($v->type) {
                case 'input':
                case 'decimal':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><input type="text" name="{$v->name}" lay-verify="{$required}" {$disabled} placeholder="请输入{$v->title}" class="layui-input" value="{$default}"></div>
</div>
EOF;
                    break;
                case 'textarea':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><textarea name="{$v->name}" lay-verify="{$required}" {$disabled} placeholder="请输入{$v->title}" class="layui-textarea">{$default}</textarea></div>
</div>
EOF;
                    break;
                case 'integer':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><input type="number" name="{$v->name}" lay-verify="{$required}" {$disabled} placeholder="请输入{$v->title}" class="layui-input" value="{$default}"></div>
</div>
EOF;
                    break;
                case 'select':
                    $selectdata = getSourceData($v);
                    $option = '<option value="">请选择</option>';
                    if(!empty($selectdata)) {
                        if($v->source_type == 'navlist') {
                            $selectdata = rg\PHPTree::makeTreeForHtml($selectdata);
                            foreach ($selectdata as $vv) {
                                $line = '';
                                for ($i=0; $i < $vv->level; $i++) { 
                                    $line .= '—';
                                }
                                if(isset($vv[$v["source_value"]]) && isset($vv[$v["source_title"]])) {
                                    $option .= '<option value="'.$vv[$v["source_value"]].'" '.($default ==$vv[$v["source_value"]] ? 'selected' : '') .'>'.$line.' '.$vv[$v["source_title"]].'</option>';
                                }
                            }
                        } else {
                            foreach ($selectdata as $vv) {
                                if(isset($vv[$v["source_value"]]) && isset($vv[$v["source_title"]])) {
                                    $option .= '<option value="'.$vv[$v["source_value"]].'" '.($default ==$vv[$v["source_value"]] ? 'selected' : '') .'>'.$vv[$v["source_title"]].'</option>';
                                }
                            }
                        }
                    }
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><select name="{$v->name}" lay-verify="{$required}" {$disabled}>{$option}</select></div>
</div>
EOF;
                    break;
                case 'radio':
                    $radiodata = getSourceData($v);
                    $radio = '';
                    if(!empty($radiodata)) {
                        foreach ($radiodata as $vv) {
                            if(isset($vv[$v["source_value"]]) && isset($vv[$v["source_title"]])) {
                                $radio .= '<input type="radio" name="'.$v->name.'" title="'.$vv[$v["source_title"]].'" value="'.$vv[$v["source_value"]].'" '.($default ==$vv[$v["source_value"]] ? 'checked' : '') .' '.$disabled.'>';
                            }
                        }
                    }
                    $str .= <<<EOF
<div class="layui-form-item" pane>
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">{$radio}</div>
</div>
EOF;
                    break;
                case 'checkbox':
                    $checkboxdata = getSourceData($v);
                    $checkbox = '';
                    $default_arr = explode(",",$default);
                    if(!empty($checkboxdata)) {
                        foreach ($checkboxdata as $vv) {
                            if(isset($vv[$v["source_value"]]) && isset($vv[$v["source_title"]])) {
                                $checked = in_array($vv[$v["source_value"]],$default_arr) ? 'checked' : '';
                                $checkbox .= '<input type="checkbox" lay-skin="primary" lay-filter="rgcms_checkbox" '.$checked.' title="'.$vv[$v["source_title"]].'" value="'.$vv[$v["source_value"]].'" '.$disabled.'>';
                            }
                        }
                    }
                    $str .= <<<EOF
<div class="layui-form-item" pane>
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">{$checkbox}<input type="hidden" name="{$v->name}" value="{$default}"></div>
</div>
EOF;
                    break;
                case 'transfer':
                    $transferdata = json_encode(getSourceData($v));
                    $default_arr = json_encode(explode(",",$default));
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block"><div class="rgcms_transfer" data-source='{$transferdata}' data-default='{$default_arr}' data-title="{$v['source_title']}" data-value="{$v['source_value']}" data-disabled="{$disabled}" id="{$v->name}"></div><input type="hidden" name="{$v->name}" value="{$default}"></div>
</div>
EOF;
                    break;
                case 'color':
                    if($disabled !== 'disabled') {
                        $colorblock = '<div class="layui-inline" style="left: -11px;"><div class="rgcms_color" id="'.$v->name.'"></div></div>';
                    } else {
                        $colorblock = '';
                    }
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline" style="width: 120px;"><input type="text" name="{$v->name}" id="{$v->name}_value" lay-verify="{$required}" value="{$default}" placeholder="请选择颜色" class="layui-input" {$disabled}></div>{$colorblock}
</div>
EOF;
                    break;
                case 'img':
                    $thumb = !empty($v->thumb) ? 'true' : 'false';
                    $water = !empty($v->water) ? 'true' : 'false';
                    $defaultimg = empty($default) ? '/public/static/images/nopic.jpg' : $default;
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline">
        <input type="text" class="layui-input" name="{$v->name}" id="{$v->name}" value="{$default}" lay-verify="{$required}" {$disabled}>
    </div>
EOF;
                    if($disabled !== 'disabled') {
                        $str .= <<<EOF
    <div class="layui-word-aux">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadimage" lay-data="{id:'{$v->name}',config:{water:{$water},thumb:{$thumb},action:'uploadimage'}}">上传</button>
        </div>
    </div>
EOF;
                    }
                    $str .= <<<EOF
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <img src="{$defaultimg}" id="{$v->name}pic" style="max-height:60px; border:#efefef 1px solid;">
    </div>
</div>
EOF;
                    break;
                case 'video':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline">
        <input type="text" class="layui-input" name="{$v->name}" id="{$v->name}" value="{$default}" lay-verify="{$required}" {$disabled}>
    </div>
EOF;
                    if($disabled !== 'disabled') {
                        $str .= <<<EOF
    <div class="layui-word-aux">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadvideo" lay-data="{id:'{$v->name}',config:{action:'uploadvideo'}}">上传</button>
        </div>
    </div>
EOF;
                    }
                    $str .= <<<EOF
</div>
EOF;
                    break;
                case 'file':
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline">
        <input type="text" class="layui-input" name="{$v->name}" id="{$v->name}" value="{$default}" lay-verify="{$required}" {$disabled}>
    </div>
EOF;
                    if($disabled !== 'disabled') {
                        $str .= <<<EOF
    <div class="layui-word-aux">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadfile" lay-data="{id:'{$v->name}',config:{action:'uploadfile'}}">上传</button>
        </div>
    </div>
EOF;
                    }
                    $str .= <<<EOF
</div>
EOF;
                    break;
                case 'imgs':
                    $thumb = !empty($v->thumb) ? 'true' : 'false';
                    $water = !empty($v->water) ? 'true' : 'false';
                    $viewstr = $v->name=='imgs' ? '<span class="tothumb">缩</span>' : '<span class="view">预</span>';
                    $disabledstr = $disabled !== 'disabled' ? '<i class="toleft layui-icon layui-icon-left"></i><i class="toright layui-icon layui-icon-right"></i><span class="close">删</span>' : '';
                    $pics = '';
                    if(!empty($default)) {
                        $imgsdefault = json_decode($default,true);
                        foreach ($imgsdefault as $i) {
                            $pics .= '<li class="item_img"><div class="operate">'.$disabledstr.$viewstr.'</div><img src="'.$i['src'].'" class="img" ><input type="text" class="layui-input imgstitle" placeholder="标题" value="'.$i['title'].'" '.$disabled.'/></li>';
                        }
                    }
                    if($disabled == 'disabled') {
                        $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div class="pic-more"><ul class="pic-more-upload-list slide-pc-priview">{$pics}</ul><input type="hidden" name="{$v->name}" lay-verify="{$required}" value='{$default}'></div>
    </div>
</div>
EOF;
                    } else {
                        $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadimages" lay-data="{id:'{$v->name}',config:{water:{$water},thumb:{$thumb},action:'uploadimage'}}">上传</button>
        </div>
    </div>
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <div class="pic-more"><ul class="pic-more-upload-list slide-pc-priview" id="{$v->name}">{$pics}</ul><input type="hidden" name="{$v->name}" lay-verify="{$required}" value='{$default}'></div>
    </div>
</div>
EOF;
                    }
                    break;
                case 'files':
                    $files = '';
                    if($disabled !== 'disabled') {
                        if(!empty($default)) {
                            $filesdefault = json_decode($default,true);
                            foreach ($filesdefault as $i) {
                                $files .= '<tr><td><input type="hidden" class="md5" value="'.$i['md5'].'"><input type="hidden" class="size" value="'.$i['size'].'"><input type="hidden" class="src" value="'.$i['src'].'"><input type="text" class="layui-input layui-sm title" placeholder="标题" value="'.$i['title'].'"></td><td>'.$i['size'].'</td><td>'.$i['src'].'</td><td><span style="color: #5FB878;">上传成功</span></td><td style="text-align:center"><a class="layui-btn layui-btn-xs layui-btn-danger this-delete">删除</a><a class="layui-btn layui-btn-xs moveUpOrDown">上移</a><a class="layui-btn layui-btn-xs moveUpOrDown">下移</a></td></tr>';
                            }
                        }
                        $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div class="layui-btn-group">
            <button type="button" class="layui-btn rgcms_uploadfiles" lay-data={id:'{$v->name}',config:{action:'uploadfile'}}>选择多文件</button>
        </div>
    </div>
</div>
<div class="layui-form-item">
    <div class="layui-block">
        <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>文件路径</th>
                        <th>状态</th>
                        <th style="text-align:center">操作</th>
                    </tr>
                </thead>
                <tbody id="{$v->name}_list">{$files}</tbody>
            </table>
        </div>
        <input type="hidden" name="{$v->name}" lay-verify="{$required}" value='{$default}'>
    </div>
</div>
EOF;
                    } else {
                        if(!empty($default)) {
                            $filesdefault = json_decode($default,true);
                            foreach ($filesdefault as $i) {
                                $files .= '<tr><td>'.$i['title'].'</td><td>'.$i['size'].'</td><td>'.$i['src'].'</td><td><span style="color: #5FB878;">上传成功</span></td></tr>';
                            }
                        }
                        $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>文件路径</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody id="{$v->name}_list">{$files}</tbody>
            </table>
        </div>
        <input type="hidden" name="{$v->name}" lay-verify="{$required}" value='{$default}'>
    </div>
</div>
EOF;
                    }
                    break;
                case 'datetime':
                    if(ctype_digit($default) && strlen($default) == 10) {
                        $defaulttime = $default;
                    } else {
                        $defaulttime = strtotime($default);
                    }
                    $v->time_format = $v->time_format?:'yyyy-MM-dd HH:mm:ss';
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-inline">
        <input type="text" class="layui-input rgcms_date" readonly datetype="{$v->time_format}" dateval='{$defaulttime}' placeholder="请选择{$v->title}" {$disabled}>
        <input type="hidden" name="{$v->name}" lay-verify="{$required}" value='{$defaulttime}'>
    </div>
</div>
EOF;
                    break;
                case 'ueditor':
                    $thumb = !empty($v->thumb) ? 'true' : 'false';
                    $water = !empty($v->water) ? 'true' : 'false';
                    $ueditor_url = url('upload/upload').'?water='.$water.'&thumb='.$thumb;
                    if($disabled == 'disabled') {
                        $script = $v->name.'_content.ready(function () {'.$v->name.'_content.setDisabled();});';
                    } else {
                        $script = '';
                    }
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <textarea name="{$v->name}" class="layui-textarea" id="{$v->name}">{$default}</textarea>
        <script>var {$v->name}_content = new UE.getEditor("{$v->name}",{zIndex:0,serverUrl:"{$ueditor_url}"});{$script}</script>
    </div>
</div>
EOF;
                    break;
                case 'ueditors':
                    $thumb = !empty($v->thumb) ? 'true' : 'false';
                    $water = !empty($v->water) ? 'true' : 'false';
                    $ueditor_url = url('upload/upload').'?water='.$water.'&thumb='.$thumb;
                    
                    if(empty($default)) {
                        $default = [['title' => '内容标题','content' => '']];
                    } else {
                        $default = json_decode($default,true);
                    }
                    $tab_title = $tab_content = '';
                    foreach ($default as $dk => $dv) {
                        if($dk==0) {
                            $layuithis = 'layui-this';
                            $layuishow = 'layui-show';
                        } else {
                            $layuithis = '';
                            $layuishow = '';
                        }
                        if($disabled == 'disabled') {
                            $script = $v->name.'_editor_'.($dk+1).'.ready(function () {'.$v->name.'_editor_'.($dk+1).'.setDisabled();});';
                            $tab_title .= '<li class="'.$layuithis.'" lay-id="'.($dk+1).'"><span>'.$dv['title'].'</span><input type="hidden" name="'.$v->name.'_title" value="'.$dv['title'].'"></li>';
                        } else {
                            $script = '';
                            $tab_title .= '<li class="'.$layuithis.'" lay-id="'.($dk+1).'"><i class="layui-icon layui-icon-left tableft tab_i" title="左移"></i><span>'.$dv['title'].'</span><i class="layui-icon layui-icon-right tabright tab_i" title="右移"></i><i class="layui-icon layui-icon-edit tabedit tab_i_edit" title="编辑"></i><i class="layui-icon layui-icon-close tabdelete tab_i_del" title="删除"></i><input type="hidden" name="'.$v->name.'_title" value="'.$dv['title'].'"></li>';
                        }
                        $tab_content .= '<div class="layui-tab-item '.$layuishow.'"><textarea name="'.$v->name.'_content" id="'.$v->name.'_'.($dk+1).'">'.$dv['content'].'</textarea><script>var '.$v->name.'_editor_'.($dk+1).' = new UE.getEditor("'.$v->name.'_'.($dk+1).'",{zIndex:0,serverUrl:"'.$ueditor_url.'"});'.$script.'</script></div>';
                    }
                    if($disabled == 'disabled') {
                        $tabadd = '';
                    } else {
                        $tabadd = '<br><a style="cursor:pointer;text-decoration:underline;color:#01AAED !important;text-shadow:none;" href="javascript:;" class="tabadd" data-id="'.$v->name.'">新增</a>';
                    }
                    $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}" style="height:65px;">{$v->title}{$tabadd}</label>
    <div class="layui-input-block">
        <div class="layui-tab layui-tab-card tabcontents" lay-filter="{$v->name}" id="{$v->name}_id">
            <ul class="layui-tab-title">
                {$tab_title}
            </ul>
            <div class="layui-tab-content">
                {$tab_content}
            </div>
        </div>
    </div>
</div>
EOF;
                    break;
                case 'layedit':
                    if($disabled !== 'disabled') {
                        $str .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <textarea name="{$v->name}" id="{$v->name}" style="display: none;" class="rgcms_layedit">{$default}</textarea>
    </div>
</div>
EOF;
                    }else{
                        $str .= <<<EOF
<div class="layui-form-item" pane>
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block" style="padding:10px 20px;">
        {$default}
    </div>
</div>
EOF;
                    }
                    break;
                case 'hidden':
                    # code...
                    break;
                case 'slider':
                    if($disabled == 'disabled') {
                        $disabled = 'true';
                    } else {
                        $disabled = 'false';
                    }
                    $str .= <<<EOF
<div class="layui-form-item" pane>
    <label class="layui-form-label" title="字段名：{$v->name}">{$v->title}</label>
    <div class="layui-input-block">
        <div id="{$v->name}" class="rgcms_slider" style="padding:15px 15px 0 15px;" default="{$default}" isdisabled="{$disabled}"></div>
        <input type="hidden" name="{$v->name}" lay-verify="{$required}" value='{$default}'>
    </div>
</div>
EOF;
                    break;
            }
        }
    }
    // 开关
    if(!$switch_list->isEmpty()) {
        $switch = '';
        foreach ($switch_list as $k => $v) {
            if(empty($data)) {
                $default = $v->defaultval?1:0;
            } else {
                $default = $data[$v->name]?1:0;
            }
            $disabled = (!empty($data) && !$v->is_edit) ? 'disabled' : '';
            $switch .= '<input type="checkbox" lay-skin="primary" data-name="'.$v->name.'" lay-filter="rgcms_onoff" '.($default ? 'checked' : '').' title="'.$v->title.'" '.$disabled.'><input type="hidden" name="'.$v->name.'" value="'.$default.'">';
        }
        $str .= <<<EOF
<div class="layui-form-item" pane>
    <label class="layui-form-label">开关</label>
    <div class="layui-input-block">{$switch}</div>
</div>
EOF;
    }
    return $str;
}

// 自定义搜索字段
function DiySearchFields($model_id)
{
    $Cmsfields = new app\common\model\Cmsfields();
    $list = $Cmsfields::whereCmsmodelsId($model_id)->whereStatus(1)->where('is_search > 0')->order('torder asc')->select();
    $str = '';
    foreach ($list as $k => $v) {
        switch ($v->type) {
            case 'input':
            case 'decimal':
                $str .= <<<EOF
<div class="layui-inline">
<label class="layui-form-label">{$v->title}</label>
<div class="layui-input-inline"><input type="text" name="{$v->name}" class="layui-input"></div>
</div>
EOF;
                break;
            case 'integer':
                $str .= <<<EOF
<div class="layui-inline">
<label class="layui-form-label">{$v->title}</label>
<div class="layui-input-inline"><input type="number" name="{$v->name}" class="layui-input"></div>
</div>
EOF;
                break;
            case 'datetime':
                $str .= <<<EOF
<div class="layui-inline">
<label class="layui-form-label">{$v->title}</label>
<div class="layui-input-inline">
    <input type="text" class="layui-input rgcms_date" readonly datetype="{$v->time_format}">
    <input type="hidden" name="{$v->name}">
</div>
</div>
EOF;
                break;
        }
    }
    return $str;
}

// 获取数据源数据
function getSourceData($field)
{
    $data = [];
    switch ($field['source_type']) {
        case 'attr':
            $attr = new app\common\model\Attr();
            $data = $attr::whereAttrgroupId($field['source_id'])->whereStatus(1)->order('torder')->select();
            break;
        case 'model':
            $_model = new app\common\model\Cmsmodels();
            $classname = $_model::getFieldById($field['source_id'],'classname');
            $Class = 'app\\common\\model\\'.$classname;
            $_class = new $Class;
            $data = $_class::whereStatus(1)->whereSiteId(session('siteid'))->order('torder')->select();
            break;
        case 'other':
            $tablename = $field['source_name'];
            $data = Db::name($tablename)->select();
            break;
        case 'about':
            $about = new app\common\model\About();
            $data = $about::whereStatus(1)->whereSiteId(session('siteid'))->order('torder')->select();
            break;
        case 'sitelist':
            $sitelist = new app\common\model\Site();
            $data = $sitelist::whereStatus(1)->order('torder')->select();
            break;
        case 'navlist':
            $navlist = new app\common\model\Navlist();
            $data = $navlist::whereStatus(1)->whereSiteId(session('siteid'))->order('pid asc,id asc')->select();
            break;
    }
    return $data;
}
//二维码生成
function qrcode($url='')
{
    $url = empty($url)?request()->url(true):$url;
    //打开缓冲区
    ob_start();
    //生成二维码图片
    \PHPQRCode\QRcode::png($url,false,'L', 5, 2);
    $imageString = base64_encode(ob_get_contents());
    //关闭缓冲区
    ob_end_clean();
    $str = "data:image/png;base64,".$imageString;
    return $str;
}

// 驼峰转换
function convertUnderline($str)
{
    $str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
        return strtoupper($matches[2]);
    },$str);
    return $str;
}

// 获取文件内容
function rg_getfile($url){
    if (trim($url) == '') {
        return false;
    }
    $opts = array(
      'http'=>array(
        'method'=>"GET",
        'timeout'=>3,//单位秒
       )
    );
    $cnt=0;
    while($cnt<3 && ($res=@file_get_contents($url, false, stream_context_create($opts)))===FALSE) $cnt++;
    if ($res === false) {
        return false;
    } else {
        return $res;
    }
}
// 多维数组转一维数组
function arr2one($array,$str)
{
    $arr = array();
    foreach ($array as $k => $v) {
        if(is_array($v)) {
            $arr[$k] = arr2one($v,$str.'_'.$k);
            $arr = array_merge($arr,$arr[$k]);
            unset($arr[$k]);
        } else {
            $arr[$str.'_'.$k] = $v;
        }
    }
    return $arr;
}
// hasAddons
function isInstall($name)
{
    $has = Db::name('addons')->whereName(strtolower($name))->whereStatus(1)->find();
    if($has) {
        return true;
    } else {
        return false;
    }
}
// 会员中心url生成
function uUrl($model='user',$controller='index',$action , $param = [], $suffix = 'html', $domain = false) 
{
    if($controller == 'index') {
        return url($model .'/index/:action',array_merge(['action' => $action], $param), $suffix, $domain);
    }
    return url($model .'/:controller/:action',array_merge(['controller' => $controller,'action' => $action], $param), $suffix, $domain);
}
// 由于在获取请求参数时，5.1.37会多出一个路由参数，需要过滤
function getparam()
{
    $query = parse_url(request()->url(true));
    if(!empty($query['query'])) {
        return convertUrlQuery($query['query']);
    }
    return [];
}
// url的query转换成数组
function convertUrlQuery($query)
{
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = urldecode($item[1]);
    }
    return $params;
}