123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671 |
- <?php
- namespace Admin\Controller;
- class ToolsController extends AdminController
- {
- protected function _initialize(){
- parent::_initialize();
- $allow_action=array("index","cache","delcahe","getDirSize","queue","delcache","invoke","rmdirr","excel","export","import");
- if(!in_array(ACTION_NAME,$allow_action)){
- $this->error("页面不存在!");
- }
- }
- public function cache()
- {
- $size = $this->getDirSize('./Runtime/');
- $this->assign('cacheSize', round($size / pow(1024, $i = floor(log($size, 1024))), 2));
- $this->display();
- }
- public function delcahe()
- {
- $size = $this->getDirSize('./Runtime/');
- $this->assign('cacheSize', round($size / pow(1024, $i = floor(log($size, 1024))), 2));
- $this->display();
- }
- protected function getDirSize($dir)
- {
- $sizeResult = '';
- $handle = opendir($dir);
- while (false !== $FolderOrFile = readdir($handle)) {
- if (($FolderOrFile != '.') && ($FolderOrFile != '..')) {
- if (is_dir($dir . '/' . $FolderOrFile)) {
- $sizeResult += $this->getDirSize($dir . '/' . $FolderOrFile);
- }
- else {
- $sizeResult += filesize($dir . '/' . $FolderOrFile);
- }
- }
- }
- closedir($handle);
- return $sizeResult;
- }
- public function delcache()
- {
- if (APP_DEMO) {
- $this->error('测试站暂时不能修改!');
- }
- $dirs = array('./Runtime/');
- @(mkdir('Runtime', 511, true));
- foreach ($dirs as $value) {
- $this->rmdirr($value);
- }
- @(mkdir('Runtime', 511, true));
- $this->success('系统缓存清除成功!');
- }
- public function invoke()
- {
- $dirs = array('./Runtime/');
- @(mkdir('Runtime', 511, true));
- foreach ($dirs as $value) {
- $this->rmdirr($value);
- }
- @(mkdir('Runtime', 511, true));
- }
- protected function rmdirr($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;
- }
- $this->rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
- }
- }
- $dir->close();
- return rmdir($dirname);
- }
- public function dataExport()
- {
- redirect('/Admin/Tools/database?type=export');
- }
- public function dataImport()
- {
- redirect('/Admin/Tools/database?type=import');
- }
- public function database($type = NULL)
- {
- switch ($type) {
- case 'import':
- $path = realpath(DATABASE_PATH);
- $glob = self::FilesystemIterator($path);
- $list = array();
- for($i=0;$i<count($glob);$i++){
- $name=$glob[$i];
- $a = str_replace(".sql.gz","",$glob[$i]);
- $lv=explode("-",$a);
- if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
- $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
- $date = $name[0] . '-' . $name[1] . '-' . $name[2];
- $time = $name[3] . ':' . $name[4] . ':' . $name[5];
- $part = $name[6];
- $list[$i]['time']=strtotime($date." ".$time);
- $list[$i]['part']=$lv[2];
- $list[$i]['size']=filesize($path."/".$glob[$i])."B";
- $list[$i]['key']=$date." ".$time;
- }
- }
- break;
- case 'export':
- $Db = \Think\Db::getInstance();
- $list = $Db->query('SHOW TABLE STATUS');
- $list = array_map('array_change_key_case', $list);
- $title = '数据备份';
- break;
- default:
- $this->error('参数错误!');
- }
- $this->assign('meta_title', $title);
- $this->assign('list', $list);
- $this->display($type);
- }
- function FilesystemIterator($dir){
- exit;
- //PHP遍历文件夹下所有文件
- $handle=opendir($dir.".");
- //定义用于存储文件名的数组
- $array_file = array();
- while (false !== ($file = readdir($handle))) {
- if ($file != "." && $file != "..") {
- $array_file[] = $file; //输出文件名
- }
- }
- closedir($handle);
- for($i=0;$i<count($array_file);$i++){
- if(strstr($array_file[$i],'.sql.gz')){
- $date[]=$array_file[$i];
- }
- }
- return $date;
- }
- public function optimize($tables = NULL)
- {
- exit;
- if ($tables) {
- $Db = \Think\Db::getInstance();
- if (is_array($tables)) {
- $tables = implode('`,`', $tables);
- $list = $Db->query('OPTIMIZE TABLE `' . $tables . '`');
- if ($list) {
- $this->success('数据表优化完成!');
- }
- else {
- $this->error('数据表优化出错请重试!');
- }
- }
- else {
- $list = $Db->query('OPTIMIZE TABLE `' . $tables . '`');
- if ($list) {
- $this->success('数据表\'' . $tables . '\'优化完成!');
- }
- else {
- $this->error('数据表\'' . $tables . '\'优化出错请重试!');
- }
- }
- }
- else {
- $this->error('请指定要优化的表!');
- }
- }
- public function repair($tables = NULL)
- {
- exit;
- if ($tables) {
- $Db = \Think\Db::getInstance();
- if (is_array($tables)) {
- $tables = implode('`,`', $tables);
- $list = $Db->query('REPAIR TABLE `' . $tables . '`');
- if ($list) {
- $this->success('数据表修复完成!');
- }
- else {
- $this->error('数据表修复出错请重试!');
- }
- }
- else {
- $list = $Db->query('REPAIR TABLE `' . $tables . '`');
- if ($list) {
- $this->success('数据表\'' . $tables . '\'修复完成!');
- }
- else {
- $this->error('数据表\'' . $tables . '\'修复出错请重试!');
- }
- }
- }
- else {
- $this->error('请指定要修复的表!');
- }
- }
- public function del($time = 0)
- {
- exit;
- if (APP_DEMO) {
- $this->error('测试站暂时不能修改!');
- }
- if ($time) {
- $name = date('Ymd-His', $time) . '-*.sql*';
- $path = realpath(DATABASE_PATH) . DIRECTORY_SEPARATOR . $name;
- array_map('unlink', glob($path));
- if (count(glob($path))) {
- $this->success('备份文件删除失败,请检查权限!');
- }
- else {
- $this->success('备份文件删除成功!');
- }
- }
- else {
- $this->error('参数错误!');
- }
- }
- public function export($tables = NULL, $id = NULL, $start = NULL)
- {
- if (APP_DEMO) {
- $this->error('测试站暂时不能修改!');
- }
- if (C('web_close')) {
- $this->error('请先关闭网站再备份数据库!');
- }
- if (IS_POST && !empty($tables) && is_array($tables)) {
- $config = array('path' => realpath(DATABASE_PATH) . DIRECTORY_SEPARATOR, 'part' => 20971520, 'compress' => 1, 'level' => 9);
- $lock = $config['path'] . 'backup.lock';
- if (is_file($lock)) {
- $this->error('检测到有一个备份任务正在执行,请稍后再试!');
- }
- else {
- file_put_contents($lock, NOW_TIME);
- }
- is_writeable($config['path']) || $this->error('备份目录不存在或不可写,请检查后重试!');
- session('backup_config', $config);
- $file = array('name' => date('Ymd-His', NOW_TIME), 'part' => 1);
- session('backup_file', $file);
- session('backup_tables', $tables);
- $Database = new \OT\Database($file, $config);
- if (false !== $Database->create()) {
- $tab = array('id' => 0, 'start' => 0);
- $this->success('初始化成功!', '', array('tables' => $tables, 'tab' => $tab));
- }
- else {
- $this->error('初始化失败,备份文件创建失败!');
- }
- }
- else if (IS_GET && is_numeric($id) && is_numeric($start)) {
- $tables = session('backup_tables');
- $Database = new \OT\Database(session('backup_file'), session('backup_config'));
- $start = $Database->backup($tables[$id], $start);
- if (false === $start) {
- $this->error('备份出错!');
- }
- else if (0 === $start) {
- if (isset($tables[++$id])) {
- $tab = array('id' => $id, 'start' => 0);
- $this->success('备份完成!', '', array('tab' => $tab));
- }
- else {
- unlink(session('backup_config.path') . 'backup.lock');
- session('backup_tables', null);
- session('backup_file', null);
- session('backup_config', null);
- $this->success('备份完成!');
- }
- }
- else {
- $tab = array('id' => $id, 'start' => $start[0]);
- $rate = floor(100 * ($start[0] / $start[1]));
- $this->success('正在备份...(' . $rate . '%)', '', array('tab' => $tab));
- }
- }
- else {
- $this->error('参数错误!');
- }
- //$this->display();
- }
- public function import($time = 0, $part = NULL, $start = NULL)
- {
- if (APP_DEMO) {
- $this->error('测试站暂时不能修改!');
- }
- if (C('web_close')) {
- $this->error('请先关闭网站再还原数据库!');
- }
- if (is_numeric($time) && is_null($part) && is_null($start)) {
- $name = date('Ymd-His', $time) . '-*.sql*';
- $path = realpath(DATABASE_PATH) . DIRECTORY_SEPARATOR . $name;
- $files = glob($path);
- $list = array();
- foreach ($files as $name) {
- $basename = basename($name);
- $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
- $gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename);
- $list[$match[6]] = array($match[6], $name, $gz);
- }
- ksort($list);
- $last = end($list);
- if (count($list) === $last[0]) {
- session('backup_list', $list);
- $this->success('初始化完成!', '', array('part' => 1, 'start' => 0));
- }
- else {
- $this->error('备份文件可能已经损坏,请检查!');
- }
- }
- else if (is_numeric($part) && is_numeric($start)) {
- $list = session('backup_list');
- $db = new \OT\Database($list[$part], array('path' => realpath(DATABASE_PATH) . DIRECTORY_SEPARATOR, 'compress' => 1, 'level' => 9));
- $start = $db->import($start);
- if (false === $start) {
- $this->error('还原数据出错!');
- }
- else if (0 === $start) {
- if (isset($list[++$part])) {
- $data = array('part' => $part, 'start' => 0);
- $this->success('正在还原...#' . $part, '', $data);
- }
- else {
- session('backup_list', null);
- $this->success('还原完成!');
- }
- }
- else {
- $data = array('part' => $part, 'start' => $start[0]);
- if ($start[1]) {
- $rate = floor(100 * ($start[0] / $start[1]));
- $this->success('正在还原...#' . $part . ' (' . $rate . '%)', '', $data);
- }
- else {
- $data['gz'] = 1;
- $this->success('正在还原...#' . $part, '', $data);
- }
- }
- }
- else {
- $this->error('参数错误!');
- }
- //$this->display();
- }
- public function excel($tables = NULL)
- {
- if ($tables) {
- if (APP_DEMO) {
- $this->error('测试站暂时不能修改!');
- }
- $mo = M();
- $mo->execute('set autocommit=0');
- $mo->execute('lock tables ' . $tables . ' write');
- $rs = $mo->table($tables)->select();
- $zd = $mo->table($tables)->getDbFields();
- if ($rs) {
- $mo->execute('commit');
- $mo->execute('unlock tables');
- }
- else {
- $mo->execute('rollback');
- }
- $xlsName = $tables;
- $xls = array();
- foreach ($zd as $k => $v) {
- $xls[$k][0] = $v;
- $xls[$k][1] = $v;
- }
- $this->exportExcel($xlsName, $xls, $rs);
- }
- else {
- $this->error('请指定要导出的表!');
- }
- }
- public function exportExcel($expTitle, $expCellName, $expTableData)
- {
- import('Org.Util.PHPExcel');
- import('Org.Util.PHPExcel.Writer.Excel5');
- import('Org.Util.PHPExcel.IOFactory.php');
- $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);
- $fileName = $_SESSION['loginAccount'] . date('_YmdHis');
- $cellNum = count($expCellName);
- $dataNum = count($expTableData);
- $objPHPExcel = new PHPExcel();
- $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
- $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . ' Export time:' . date('Y-m-d H:i:s'));
- $i = 0;
- for (; $i < $cellNum; $i++) {
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
- }
- $i = 0;
- for (; $i < $dataNum; $i++) {
- $j = 0;
- for (; $j < $cellNum; $j++) {
- $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
- }
- }
- ob_end_clean();
- header('pragma:public');
- header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
- header('Content-Disposition:attachment;filename=' . $fileName . '.xls');
- $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
- $objWriter->save('php://output');
- exit();
- }
- public function importExecl($file)
- {
- exit;
- import('Org.Util.PHPExcel');
- import('Org.Util.PHPExcel.Writer.Excel5');
- import('Org.Util.PHPExcel.IOFactory.php');
- if (!file_exists($file)) {
- return array('error' => 0, 'message' => 'file not found!');
- }
- $objReader = PHPExcel_IOFactory::createReader('Excel5');
- try {
- $PHPReader = $objReader->load($file);
- }
- catch (Exception $e) {
- }
- if (!file_exists($file)) {
- return array('error' => 0, 'message' => 'read error!');
- }
- $allWorksheets = $PHPReader->getAllSheets();
- $i = 0;
- foreach ($allWorksheets as $objWorksheet) {
- $sheetname = $objWorksheet->getTitle();
- $allRow = $objWorksheet->getHighestRow();
- $highestColumn = $objWorksheet->getHighestColumn();
- $allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
- $array[$i]['Title'] = $sheetname;
- $array[$i]['Cols'] = $allColumn;
- $array[$i]['Rows'] = $allRow;
- $arr = array();
- $isMergeCell = array();
- foreach ($objWorksheet->getMergeCells() as $cells) {
- foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
- $isMergeCell[$cellReference] = true;
- }
- }
- $currentRow = 1;
- for (; $currentRow <= $allRow; $currentRow++) {
- $row = array();
- $currentColumn = 0;
- for (; $currentColumn < $allColumn; $currentColumn++) {
- $cell = $objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
- $afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn + 1);
- $bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn - 1);
- $col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);
- $address = $col . $currentRow;
- $value = $objWorksheet->getCell($address)->getValue();
- if (substr($value, 0, 1) == '=') {
- return array('error' => 0, 'message' => 'can not use the formula!');
- exit();
- }
- if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_NUMERIC) {
- $cellstyleformat = $cell->getParent()->getStyle($cell->getCoordinate())->getNumberFormat();
- $formatcode = $cellstyleformat->getFormatCode();
- if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $formatcode)) {
- $value = gmdate('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($value));
- }
- else {
- $value = PHPExcel_Style_NumberFormat::toFormattedString($value, $formatcode);
- }
- }
- if ($isMergeCell[$col . $currentRow] && $isMergeCell[$afCol . $currentRow] && !empty($value)) {
- $temp = $value;
- }
- else if ($isMergeCell[$col . $currentRow] && $isMergeCell[$col . ($currentRow - 1)] && empty($value)) {
- $value = $arr[$currentRow - 1][$currentColumn];
- }
- else if ($isMergeCell[$col . $currentRow] && $isMergeCell[$bfCol . $currentRow] && empty($value)) {
- $value = '';
- }
- $row[$currentColumn] = $value;
- }
- $arr[$currentRow] = $row;
- }
- $array[$i]['Content'] = $arr;
- $i++;
- }
- spl_autoload_register(array('Think', 'autoload'));
- unset($objWorksheet);
- unset($PHPReader);
- unset($PHPExcel);
- unlink($file);
- return array('error' => 1, 'data' => $array);
- }
- public function xiazai()
- {
- exit;
- if (APP_DEMO) {
- $this->error('测试站暂时不能修改!');
- }
- if (!check($_GET['file'], 'dw', '-.')) {
- $this->error('失败!');
- }
- DownloadFile(DATABASE_PATH . $_GET['file']);
- exit();
- }
- public function queue()
- {
- $file_path = DATABASE_PATH . '/check_queue.json';
- $time = time();
- $timeArr = array();
- if (file_exists($file_path)) {
- $timeArr = file_get_contents($file_path);
- $timeArr = json_decode($timeArr, true);
- }
- $str = '';
- foreach ($timeArr as $key => $val) {
- if ($key == 0) {
- $val = '上一次执行:' . addtime($val);
- }
- if ($key == 1) {
- $val = '上二次执行:' . addtime($val);
- }
- if ($key == 2) {
- $val = '上三次执行:' . addtime($val);
- }
- $str .= $val . ' ';
- }
- $status = '';
- $count = count($timeArr);
- if (3 <= $count) {
- $_t1 = $timeArr[2] - $timeArr[1];
- $_t2 = $timeArr[1] - $timeArr[0];
- if (60 < abs($timeArr[0] - time())) {
- $status = '<span class="btn btn-warning">队列停止运行</span>';
- }
- if ((50 < abs($_t1)) && (50 < abs($_t2))) {
- $status = '<span class="btn">队列运行正常</span>';
- }
- else {
- $status = '<span class="btn btn-warning">队列时间异常,请稍后再试</span>';
- }
- }
- else {
- $msg = '';
- if ($count == 0) {
- $msg = '队列还未开始运行,请1分钟后刷新';
- }
- if ($count == 1) {
- $msg = '队列运行一次请再等待2分钟检查';
- }
- if ($count == 2) {
- $msg = '队列运行两次请再等待1分钟检查';
- }
- $status = '<span class="btn btn-warning">' . $msg . '</span>';
- }
- $this->assign('status', $status);
- $this->assign('str', $str);
- $this->display();
- return NULL;
- }
- }
- ?>
|