审查视图

simplewind/extend/org/Baksql.php 9.8 KB
董瑞恩 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
<?php
/*
明天见 QQ 386117932
*/
namespace org;

class Baksql {

    private $config=[];
    
    private $handler;
    
    private $tables = array();//需要备份的表
    private $begin; //开始时间
    private $error;//错误信息
    public function __construct($config) {
        $config['path']="databak/"; //默认目录 
        $config["sqlbakname"]=date("YmdHis",time()).".sql";//默认保存文件
        $this->config = $config;
        
        $this->begin = microtime(true);
        header("Content-type: text/html;charset=utf-8");
        $this->connect();
    }
    //首次进行pdo连接
    private function connect() {
        try{
           $this->handler =new \PDO("{$this->config['type']}:host={$this->config['hostname']};port={$this->config['hostport']};dbname={$this->config['database']};",
                $this->config['username'],
                $this->config['password'], 
                array(
                    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$this->config['charset']};",
                    \PDO::ATTR_ERRMODE =>  \PDO::ERRMODE_EXCEPTION, 
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
                )); 
        }catch (PDOException $e) {
            die ("Error!: " . $e->getMessage() . "<br/>");
        }
        
    }
     /**
     * 查询
     * @param string $sql
     * @return mixed
     */
    private function query($sql = '')
    {
        $stmt = $this->handler->query($sql);
        $stmt->setFetchMode(\PDO::FETCH_NUM);
        $list = $stmt->fetchAll();
        return $list;
    }
     /**
     * 获取全部表
     * @param string $dbName
     * @return array
     */
    private function get_dbname($dbName = '*') {
         $sql = 'SHOW TABLES';
        $list = $this->query($sql);
        $tables = array();
        foreach ($list as $value)
        {   
            $tables[] = $value[0];
        }
        return $tables;        
    }
    /**
     * 获取表定义语句
     * @param string $table
     * @return mixed
     */
    private function get_dbhead($table = '')
    {
        $sql = "SHOW CREATE TABLE `{$table}`";
        $ddl = $this->query($sql)[0][1] . ';';
        return $ddl;
    }
    /**
     * 获取表数据
     * @param string $table
     * @return mixed
     */
    private function get_dbdata($table = '')
    {
        $sql = "SHOW COLUMNS FROM `{$table}`";
        $list = $this->query($sql);
        //字段
        $columns = '';
        //需要返回的SQL
        $query = '';
        foreach ($list as $value)
        {
            $columns .= "`{$value[0]}`,";
        }
        $columns = substr($columns, 0, -1);
        $data = $this->query("SELECT * FROM `{$table}`");
        foreach ($data as $value)
        {
            $dataSql = '';
            foreach ($value as $v)
            {
                $dataSql .= "'{$v}',";
            }
            $dataSql = substr($dataSql, 0, -1);
            $query .= "INSERT INTO `{$table}` ({$columns}) VALUES ({$dataSql});\r\n";
        }
        return $query;
    }
    /**
     * 写入文件
     * @param array $tables
     * @param array $ddl
     * @param array $data
     */
    private function writeToFile($tables = array(), $ddl = array(), $data = array())
    {
        $str = "/*\r\nMySQL Database Backup Tools\r\n";
        $str .= "Server:{$this->config['hostname']}:{$this->config['hostport']}\r\n";
        $str .= "Database:{$this->config['database']}\r\n";
        $str .= "Data:" . date('Y-m-d H:i:s', time()) . "\r\n*/\r\n";
        $str .= "SET FOREIGN_KEY_CHECKS=0;\r\n";
        $i = 0;
        foreach ($tables as $table)
        {
            $str .= "-- ----------------------------\r\n";
            $str .= "-- Table structure for {$table}\r\n";
            $str .= "-- ----------------------------\r\n";
            $str .= "DROP TABLE IF EXISTS `{$table}`;\r\n";
            $str .= $ddl[$i] . "\r\n";
            $str .= "-- ----------------------------\r\n";
            $str .= "-- Records of {$table}\r\n";
            $str .= "-- ----------------------------\r\n";
            $str .= $data[$i] . "\r\n";
            $i++;
        }
              
        if(!file_exists($this->config['path'])){mkdir($this->config['path']);}
        if(file_put_contents($this->config['path'].$this->config['sqlbakname'], $str)){
            $ret['msg']='备份成功!花费时间' . round(microtime(true) - $this->begin,2) . 'ms';
            $ret['code']=1;
        }else{
            $ret['msg']='备份失败!';
            $ret['code']=0;
        }
        return $ret;
    }
    /**
     * 设置要备份的表
     * @param array $tables
     */
    private function setTables($tables = array())
    {
        if (!empty($tables) && is_array($tables))
        {
            //备份指定表
            $this->tables = $tables;
        }
        else
        {
            //备份全部表
            $this->tables = $this->get_dbname();
        }
    }
    /**
     * 备份
     * @param array $tables
     * @return bool
     */
    public function backup($tables = array())
    {
        //存储表定义语句的数组
        $ddl = array();
        //存储数据的数组
        $data = array();
        $this->setTables($tables);
        if (!empty($this->tables))
        {
            foreach ($this->tables as $table)
            {
                $ddl[] = $this->get_dbhead($table);
                $data[] = $this->get_dbdata($table);
            }
            
            //开始写入
            return $this->writeToFile($this->tables, $ddl, $data);
        }
        else
        {
            $ret['msg']='数据库中没有表!';
            $ret['code']=0;
            return false;
        }
    }
    /**
     * 错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }
    public function restore($filename = '')
    {
        $path=$this->config['path'].$filename;
        if (!file_exists($path))
        {
            $ret['msg']='SQL文件不存在!';
            $ret['code']=0;
            return $ret;
        }
        else
        {
            $sql = $this->parseSQL($path);
            //dump($sql);die;
            try
            {
                $this->handler->exec($sql);
                $ret['msg']='还原成功!花费时间'. round(microtime(true) - $this->begin,2) . 'ms';
                $ret['code']=1;
				return $ret;
            }
            catch (PDOException $e)
            {
                $ret['msg']=$e->getMessage();
                $ret['code']=0;
                return $ret;
            }
        }
    }
 
    /**
     * 解析SQL文件为SQL语句数组
     * @param string $path
     * @return array|mixed|string
     */
    private function parseSQL($path = '')
    {
        $sql = file_get_contents($path);
        $sql = explode("\r\n", $sql);
        //先消除--注释
        $sql = array_filter($sql, function ($data)
        {
            if (empty($data) || preg_match('/^--.*/', $data))
            {
                return false;
            }
            else
            {
                return true;
            }
        });
        $sql = implode('', $sql);
        //删除/**/注释
        $sql = preg_replace('/\/\*.*\*\//', '', $sql);
        return $sql;
    }
    /**
     * 下载备份
     * @param string $fileName
     * @return array|mixed|string
     */
    public function downloadFile($fileName) {
        $fileName=$this->config['path'].$fileName;
        if (file_exists($fileName)){
            ob_end_clean();
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Length: ' . filesize($fileName));
            header('Content-Disposition: attachment; filename=' . basename($fileName));
            readfile($fileName);
        }else{
            $ret['msg']="文件有错误!";
            $ret['code']=0;
        }

    }
    /**
     * 获取文件是时间
     * @param string $file
     * @return string
     */
    private function getfiletime($file){
        $path=$this->config['path'].$file;
        $a = filemtime($path);
        $time = date("Y-m-d H:i:s", $a);
        return $time;
    }
    /**
     * 获取文件是大小
     * @param string $file
     * @return string
     */
    private function getfilesize($file){
        $perms=stat($this->config['path'].$file);
        $size = $perms['size'];
        $a    = ['B', 'KB', 'MB', 'GB', 'TB'];
        $pos  = 0;
        while ($size >= 1024) {
            $size /= 1024;
            $pos++;
        }
        return round($size, 2). $a[$pos];
    }
    
    /**
     * 获取文件列表
     * @param string $Order 级别
     * @return array
     */
    public function get_filelist($Order = 0) {
        $FilePath=$this->config['path'];
        if(!file_exists($FilePath)){
            mkdir($FilePath);
        }
        $FilePath = opendir($FilePath);
        $FileAndFolderAyy=array();
        $i=1;
        while (false !== ($filename = readdir($FilePath))) {
            if ($filename!="." && $filename!=".."){
                $i++;
                $FileAndFolderAyy[$i]['name'] = $filename;
                $FileAndFolderAyy[$i]['time'] = $this->getfiletime($filename);
                $FileAndFolderAyy[$i]['size'] = $this->getfilesize($filename);
            }
            
        }
        $Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
        return $FileAndFolderAyy;
    }
    public function delfilename($filename){
        $path=$this->config['path'].$filename;          
        if (@unlink($path)) {
            $ret['msg']="删除成功!";
            $ret['code']=1;
        }else{
            $ret['msg']="删除失败!";
            $ret['code']=0;
        }
        return $ret;
    }
}

?>