Database.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace app\admin\controller\general;
  3. use addons\database\library\Backup;
  4. use app\common\controller\Backend;
  5. use think\Db;
  6. use think\Debug;
  7. use think\Exception;
  8. use think\exception\PDOException;
  9. use ZipArchive;
  10. /**
  11. * 数据库管理
  12. *
  13. * @icon fa fa-database
  14. * @remark 可在线进行一些简单的数据库表优化或修复,查看表结构和数据。也可以进行SQL语句的操作
  15. */
  16. class Database extends Backend
  17. {
  18. protected $noNeedRight = ['backuplist'];
  19. public function _initialize()
  20. {
  21. if (!config("app_debug")) {
  22. $this->error("数据库管理插件只允许在开发环境下使用");
  23. }
  24. return parent::_initialize();
  25. }
  26. /**
  27. * 查看
  28. */
  29. public function index()
  30. {
  31. $tables_data_length = $tables_index_length = $tables_free_length = $tables_data_count = 0;
  32. $tables = $list = [];
  33. $list = Db::query("SHOW TABLES");
  34. foreach ($list as $key => $row) {
  35. $tables[] = ['name' => reset($row), 'rows' => 0];
  36. }
  37. $data['tables'] = $tables;
  38. $data['saved_sql'] = [];
  39. $this->view->assign($data);
  40. return $this->view->fetch();
  41. }
  42. /**
  43. * SQL查询
  44. */
  45. public function query()
  46. {
  47. $do_action = $this->request->post('do_action');
  48. echo '<style type="text/css">
  49. xmp,body{margin:0;padding:0;line-height:18px;font-size:12px;font-family:"Helvetica Neue", Helvetica, Microsoft Yahei, Hiragino Sans GB, WenQuanYi Micro Hei, sans-serif;}
  50. hr{height:1px;margin:5px 1px;background:#e3e3e3;border:none;}
  51. </style>';
  52. if ($do_action == '') {
  53. exit(__('Invalid parameters'));
  54. }
  55. $tablename = $this->request->post("tablename/a");
  56. if (in_array($do_action, array('doquery', 'optimizeall', 'repairall'))) {
  57. $this->$do_action();
  58. } elseif (count($tablename) == 0) {
  59. exit(__('Invalid parameters'));
  60. } else {
  61. foreach ($tablename as $table) {
  62. $this->$do_action($table);
  63. echo "<br />";
  64. }
  65. }
  66. }
  67. /**
  68. * 备份列表
  69. * @internal
  70. */
  71. public function backuplist()
  72. {
  73. $config = get_addon_config('database');
  74. $backupDir = ROOT_PATH . 'public' . DS . $config['backupDir'];
  75. $backuplist = [];
  76. foreach (glob($backupDir . "*.zip") as $filename) {
  77. $time = filemtime($filename);
  78. $backuplist[$time] =
  79. [
  80. 'file' => str_replace($backupDir, '', $filename),
  81. 'date' => date("Y-m-d H:i:s", $time),
  82. 'size' => format_bytes(filesize($filename))
  83. ];
  84. }
  85. krsort($backuplist);
  86. $this->success("", null, ['backuplist' => array_values($backuplist)]);
  87. }
  88. /**
  89. * 还原
  90. */
  91. public function restore($ids = '')
  92. {
  93. $config = get_addon_config('database');
  94. $backupDir = ROOT_PATH . 'public' . DS . $config['backupDir'];
  95. if ($this->request->isPost()) {
  96. $action = $this->request->request('action');
  97. $file = $this->request->request('file');
  98. if (!preg_match("/^backup\-([a-z0-9\-]+)\.zip$/i", $file)) {
  99. $this->error(__("Invalid parameters"));
  100. }
  101. $file = $backupDir . $file;
  102. if ($action == 'restore') {
  103. if (!class_exists('ZipArchive')) {
  104. $this->error("服务器缺少php-zip组件,无法进行还原操作");
  105. }
  106. try {
  107. $dir = RUNTIME_PATH . 'database' . DS;
  108. if (!is_dir($dir)) {
  109. mkdir($dir, 0755);
  110. }
  111. $zip = new ZipArchive;
  112. if ($zip->open($file) !== true) {
  113. throw new Exception(__('Can not open zip file'));
  114. }
  115. if (!$zip->extractTo($dir)) {
  116. $zip->close();
  117. throw new Exception(__('Can not unzip file'));
  118. }
  119. $zip->close();
  120. $filename = basename($file);
  121. $sqlFile = $dir . str_replace('.zip', '.sql', $filename);
  122. if (!is_file($sqlFile)) {
  123. throw new Exception(__('Sql file not found'));
  124. }
  125. $filesize = filesize($sqlFile);
  126. $list = Db::query('SELECT @@global.max_allowed_packet');
  127. if (isset($list[0]['@@global.max_allowed_packet']) && $filesize >= $list[0]['@@global.max_allowed_packet']) {
  128. Db::execute('SET @@global.max_allowed_packet = ' . ($filesize + 1024));
  129. //throw new Exception('备份文件超过配置max_allowed_packet大小,请修改Mysql服务器配置');
  130. }
  131. $sql = file_get_contents($sqlFile);
  132. Db::clear();
  133. //必须重连一次
  134. Db::connect([], true)->query("select 1");
  135. Db::getPdo()->exec($sql);
  136. } catch (Exception $e) {
  137. $this->error($e->getMessage());
  138. } catch (PDOException $e) {
  139. $this->error($e->getMessage());
  140. }
  141. $this->success(__('Restore successful'));
  142. } elseif ($action == 'delete') {
  143. unlink($file);
  144. $this->success(__('Delete successful'));
  145. }
  146. }
  147. }
  148. /**
  149. * 备份
  150. */
  151. public function backup()
  152. {
  153. $config = get_addon_config('database');
  154. $backupDir = ROOT_PATH . 'public' . DS . $config['backupDir'];
  155. if ($this->request->isPost()) {
  156. if (!class_exists('ZipArchive')) {
  157. $this->error("服务器缺少php-zip组件,无法进行备份操作");
  158. }
  159. $database = config('database');
  160. try {
  161. $backup = new Backup($database['hostname'], $database['username'], $database['database'], $database['password'], $database['hostport']);
  162. $backup->setIgnoreTable($config['backupIgnoreTables'])->backup($backupDir);
  163. } catch (Exception $e) {
  164. $this->error($e->getMessage());
  165. }
  166. $this->success(__('Backup successful'));
  167. }
  168. return;
  169. }
  170. private function viewinfo($name)
  171. {
  172. $row = Db::query("SHOW CREATE TABLE `{$name}`");
  173. $row = array_values($row[0]);
  174. $info = $row[1];
  175. echo "<xmp>{$info};</xmp>";
  176. }
  177. private function viewdata($name = '')
  178. {
  179. $sqlquery = "SELECT * FROM `{$name}`";
  180. $this->doquery($sqlquery);
  181. }
  182. private function optimize($name = '')
  183. {
  184. if (Db::execute("OPTIMIZE TABLE `{$name}`")) {
  185. echo __('Optimize table %s done', $name);
  186. } else {
  187. echo __('Optimize table %s fail', $name);
  188. }
  189. }
  190. private function optimizeall($name = '')
  191. {
  192. $list = Db::query("SHOW TABLES");
  193. foreach ($list as $key => $row) {
  194. $name = reset($row);
  195. if (Db::execute("OPTIMIZE TABLE {$name}")) {
  196. echo __('Optimize table %s done', $name);
  197. } else {
  198. echo __('Optimize table %s fail', $name);
  199. }
  200. echo "<br />";
  201. }
  202. }
  203. private function repair($name = '')
  204. {
  205. if (Db::execute("REPAIR TABLE `{$name}`")) {
  206. echo __('Repair table %s done', $name);
  207. } else {
  208. echo __('Repair table %s fail', $name);
  209. }
  210. }
  211. private function repairall($name = '')
  212. {
  213. $list = Db::query("SHOW TABLES");
  214. foreach ($list as $key => $row) {
  215. $name = reset($row);
  216. if (Db::execute("REPAIR TABLE {$name}")) {
  217. echo __('Repair table %s done', $name);
  218. } else {
  219. echo __('Repair table %s fail', $name);
  220. }
  221. echo "<br />";
  222. }
  223. }
  224. private function doquery($sql = null)
  225. {
  226. $sqlquery = $sql ? $sql : $this->request->post('sqlquery');
  227. if ($sqlquery == '') {
  228. exit(__('SQL can not be empty'));
  229. }
  230. $sqlquery = str_replace('__PREFIX__', config('database.prefix'), $sqlquery);
  231. $sqlquery = str_replace("\r", "", $sqlquery);
  232. $sqls = preg_split("/;[ \t]{0,}\n/i", $sqlquery);
  233. $maxreturn = 100;
  234. $r = '';
  235. foreach ($sqls as $key => $val) {
  236. if (trim($val) == '') {
  237. continue;
  238. }
  239. $val = rtrim($val, ';');
  240. $r .= "SQL:<span style='color:green;'>{$val}</span> ";
  241. if (preg_match("/^(select|explain)(.*)/i ", $val)) {
  242. Debug::remark("begin");
  243. $limit = stripos(strtolower($val), "limit") !== false ? true : false;
  244. $count = Db::execute($val);
  245. if ($count > 0) {
  246. $resultlist = Db::query($val . (!$limit && $count > $maxreturn ? ' LIMIT ' . $maxreturn : ''));
  247. } else {
  248. $resultlist = [];
  249. }
  250. Debug::remark("end");
  251. $time = Debug::getRangeTime('begin', 'end', 4);
  252. $usedseconds = __('Query took %s seconds', $time) . "<br />";
  253. if ($count <= 0) {
  254. $r .= __('Query returned an empty result');
  255. } else {
  256. $r .= (__('Total:%s', $count) . (!$limit && $count > $maxreturn ? ',' . __('Max output:%s', $maxreturn) : ""));
  257. }
  258. $r = $r . ',' . $usedseconds;
  259. $j = 0;
  260. foreach ($resultlist as $m => $n) {
  261. $j++;
  262. if (!$limit && $j > $maxreturn) {
  263. break;
  264. }
  265. $r .= "<hr/>";
  266. $r .= "<font color='red'>" . __('Row:%s', $j) . "</font><br />";
  267. foreach ($n as $k => $v) {
  268. $r .= "<font color='blue'>{$k}:</font>{$v}<br/>\r\n";
  269. }
  270. }
  271. } else {
  272. Debug::remark("begin");
  273. $count = Db::getPdo()->exec($val);
  274. Debug::remark("end");
  275. $time = Debug::getRangeTime('begin', 'end', 4);
  276. $r .= __('Query affected %s rows and took %s seconds', $count, $time) . "<br />";
  277. }
  278. }
  279. echo $r;
  280. }
  281. }