<?php
namespace addons\clearbom\controller;
use think\addons\Controller;
use Request;

class Admin extends Controller
{
    // 后台管理操作控制器必须判断管理员登陆
    protected function initialize()
    {
        parent::initialize();
        // 判断是否管理员登陆
        if(!session('?adminid')) abort(404,'访问的内容不存在');
    }

    // 管理入口
    public function index()
    {
    	if(Request::isPost()) {
    		$data = [];
    		$action = Request::post('action');
    		if($action == 'check') {
    			$data = checkdir('./public/'.config('tpl_path'),0);
    		} else if($action == 'clear') {
    			$data = checkdir('./public/'.config('tpl_path'),1);
    		}
    		return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
    	}
        return $this->fetch();
    }
}
function checkdir($basedir,$auto) {
	static $files = [];
    if ($dh = opendir($basedir)) {    
        while ( ($file = readdir ( $dh )) !== false ) {    
            if ($file != '.' && $file != '..') {    
                if (! is_dir ( $basedir . DS . $file )) { // 如果是文件
                	if(checkBOM ($basedir . DS . $file) !== 'BOM Not Found.') {
                		$files[] = ['filename' => $basedir . DS . $file,'checkres' => checkBOM ($basedir . DS . $file,$auto)];
                	}
                } else {    
                    $dirname = $basedir . DS .$file; // 如果是目录    
                    checkdir ( $dirname ,$auto); // 递归    
                }    
            }    
        }    
        closedir ( $dh );    
    }
    return $files; 
}    
 
function checkBOM($filename,$auto = 0) { 
    $contents = file_get_contents ( $filename );    
    $charset [1] = substr ( $contents, 0, 1 );    
    $charset [2] = substr ( $contents, 1, 1 );    
    $charset [3] = substr ( $contents, 2, 1 );    
    if (ord ( $charset [1] ) == 239 && ord ( $charset [2] ) == 187 && ord ( $charset [3] ) == 191) { // BOM 的前三个字符的ASCII 码分别为 239 187 191    
        if ($auto == 1) {    
            $rest = substr ( $contents, 3 );    
            rewrite ( $filename, $rest );    
            return ("<font color=green>清除BOM头成功.</font>");    
        } else {    
            return ("<font color=red>BOM头存在.</font>");    
        }    
    } else   
        return ("BOM Not Found.");    
}    
 
function rewrite($filename, $data) {    
    $filenum = fopen ( $filename, "w" );    
    flock ( $filenum, LOCK_EX );    
    fwrite ( $filenum, $data );    
    fclose ( $filenum );    
} 