<?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 arr2tree($array, $pid = 0, $level = 1, $maxlevel = 100) {  
    $return = array();  
    foreach($array as $k => $v) {  
        if($v['pid'] == $pid) {
            $v["level"] = $level;
            unset($array[$k]);
            if($v["level"] <= $maxlevel) {
                foreach($array as $subleaf) {
                    if($subleaf['pid'] == $v['id']) {
                        $v['children'] = arr2tree($array, $v['id'], $level+1, $maxlevel);
                        break;
                    }
                }
                $return[] = $v; 
            }
        } 
    } 
    return $return;  
}
function arr2tree_menu($array, $pid = 0, $level = 1, $maxlevel = 100) {  
    $return = array();  
    foreach($array as $k => $v) {  
        if($v['pid'] == $pid) {
            $v["level"] = $level;
            unset($array[$k]);
            if($v["level"] <= $maxlevel) {
                foreach($array as $subleaf) {
                    if($subleaf['pid'] == $v['id']) {
                        $v['child'] = arr2tree_menu($array, $v['id'], $level+1, $maxlevel); 
                        if(empty($v['child'])) unset($v['child']);
                        break;
                    }
                }
                $return[] = $v; 
            }
        } 
    } 
    return $return;  
}
// 根据id找一条数据
// 返回二维数组
function get_one($array, $id)
{
    $one = [];
    foreach ($array as $k => $v) {
        if ($v['id'] == $id) {
            $one[] = $v;
            break;
        }
    }
    return $one;
}
// 根据id获取所有子节点
function get_sons($array,$id)
{
    $sons = [];
    foreach($array as $v){
        if($v['pid'] == $id) {
            $sons[] = $v;
            $sons = array_merge($sons,get_sons($array,$v['id']));
        }

    }
    return $sons;
}
// 合并组
function get_me_sons_tree($array, $id)
{
    $me = [];
    foreach ($array as $v) {
        if($v['id']==$id) {
            $me[] = $v;
            break;
        }
    }
    $sons = get_sons($array,$id);
    // $me = get_one($array, $id);
    // $sons = get_sons($array, $id);
    return array_merge($me, $sons);
}

//列出目录
function scan_dir($dir,$type = 0,$filter = array())
{
    if(!is_dir($dir))return false;
    $files = array_diff(scandir($dir), array('.', '..'));
    if(is_array($files)){
        foreach($files as $key=>$value){
            if(is_dir($dir . '/' . $value) && $type !==0){
                $files[$value] = scan_dir($dir . '/' . $value, $type,$filter);
                unset($files[$key]);
                continue;
            } 
            $pathinfo = pathinfo($dir . '/' . $value);
            $extension = array_key_exists('extension', $pathinfo) ? $pathinfo['extension'] : '';
            if(!empty($filter) && !in_array($extension, $filter)){
                unset($files[$key]);
            }
        }
    }
    unset($key, $value);
    return array_merge($files);
}

// 遍历所有文件夹和文件
function read_allfile ($dir,$type=0){
    $arr = array();
    if(!is_dir($dir)) return false;
    $hander = scandir($dir);
    foreach ($hander as $k => $v) {
        $encode = mb_detect_encoding($v, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5')); 
        $v = mb_convert_encoding($v, 'UTF-8', $encode);
        //$v = iconv('GBK','utf-8',$v);//转换成utf-8格式
        if (is_dir($dir . DS . $v) && $v != "." && $v != ".." && $type != 1) {
            $arr[$k]['title'] = $v;
            $arr[$k]['path'] = $dir . DS . $v;
            $arr[$k]['children'] = read_allfile($dir . DS . $v,$type);
        }else{
            if(is_file($dir . DS . $v) && $type != 0 && $v != "." && $v != ".."){
                $file = $dir . DS . $v;
                $arr[$k]['title'] = $v;
                $arr[$k]['path'] = $file;
                $arr[$k]['children']='';
                $arr[$k]['mtime'] = date('Y-m-d H:i:s',filemtime($file));
                $arr[$k]['size'] = format_bytes(filesize($file));
                $arr[$k]['type'] = filetype($file);
                $arr[$k]['ext'] = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
                $arr[$k]['isReadable'] = is_readable($file);
                $arr[$k]['isWritable'] = is_writable($file);
                $arr[$k]['edit'] = in_array($arr[$k]['ext'],['htm','html','css','js','txt','xml','scss']);
            }
 
        }
    }
    return array_merge($arr);
}

/**
 * 递归创建某目录
 * @param unknown $dirname
 * @return boolean
 */
function mk_dirs($dirname){
    if (!is_dir($dirname)) {
        if (!mk_dirs(dirname($dirname))) {
            return false;
        }
        if (!mkdir($dirname, 0777)) {
            return false;
        }
    }
    return true;
}

/**
 * 递归删除某目录
 * @param string $dirname
 * @return boolean
 */
function rm_dirs($dirname)
{
    if (!file_exists($dirname)) {
        return false;
    }
    if (is_file($dirname) || is_link($dirname)) {
        return unlink($dirname);
    }
    $dir = dir($dirname);
    if ($dir) {
        while (false !== $entry = $dir->read()) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            rm_dirs($dirname . DIRECTORY_SEPARATOR . $entry);
        }
    }
    $dir->close();
    return @rmdir($dirname);
}

// 删除目录
function delete_dir($dir_name,$rmself = true)
{
    $result = false;
    if(is_dir($dir_name)){ //检查指定的文件是否是一个目录
        if ($handle = opendir($dir_name)) {   //打开目录读取内容
            while (false !== ($item = readdir($handle))) { //读取内容
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);  //删除文件
                    }
                }
            }
            closedir($handle);  //打开一个目录，读取它的内容，然后关闭
            if($rmself) {
                if (rmdir($dir_name)) { //删除空白目录
                    $result = true;
                }
            }
        }
    }
    return $result;
}

// UE遍历获取目录下的指定类型的文件
function getfiles($path, $allowFiles, &$files = array())
{
    if (!is_dir($path)) return null;
    if(substr($path, strlen($path) - 1) != '/') $path .= '/';
    $handle = opendir($path);
    while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..') {
            $path2 = $path . $file;
            if (is_dir($path2)) {
                getfiles($path2, $allowFiles, $files);
            } else {
                if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                    $files[] = array(
                        'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                        'mtime'=> filemtime($path2)
                    );
                }
            }
        }
    }
    return $files;
}

// checkbox
function check_box($n, $str, $var)
{
    $list = explode($n, $str);
    if(in_array($var,$list)) {
        return 'checked';
    }
}

// 执行时间和消耗内存情况
function pagedebug()
{
    $dotime= \think\Container::get('debug')->getUseTime(3) .'S';
    $domemory = \think\Container::get('debug')->getUseMem();
    return '<div class="layui-word-aux text-right" style="font-size:12px;">页面执行：' . $dotime . ' / '. $domemory . '</div>';
}

//登陆日志
function adminlog($type,$content='',$status=1)
{
    // type 1:登陆 2:后台操作
    // status 状态1:成功，0:失败
    $data['admin_id'] = session('?adminid') ? session('adminid') : 0;
    $data['type'] = $type;
    $data['content'] = $content;
    $data['status'] = $status;
    $data['ip'] = request()->ip();
    $data['method'] = request()->method();
    $data['create_time'] = time();
    $data['query'] = request()->query();
    $data['controller'] = request()->controller();
    $data['action'] = request()->action();
    $adminlog = new \app\admin\model\Adminlog;
    $adminlog::create($data,true);
    if(config('sys.adminlog_count')) {
        $count = $adminlog->count()-config('sys.adminlog_count');
        if($count > 0) {
            $ids = $adminlog->limit($count)->order('id asc')->column('id');
            $adminlog->whereIn('id',$ids)->delete();
        }
    }
}