DatabaseAction.class.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. /**
  3. *
  4. * Database(数据库)
  5. */
  6. if(!defined("Ainaphp")) exit("Access Denied");
  7. class DatabaseAction extends AdminbaseAction{
  8. protected $db = '', $datadir = '' , $startrow=0,$startfrom=0, $complete=true;
  9. function _initialize()
  10. {
  11. parent::_initialize();
  12. $this->datadir = RUNTIME_PATH.'Backup/';
  13. if(!is_dir($this->datadir))mkdir($this->datadir,0755,true);
  14. $db=D('');
  15. $this->db = DB::getInstance();
  16. }
  17. public function index()
  18. {
  19. $dataList = $this->db->query("SHOW TABLE STATUS LIKE '".C('DB_PREFIX')."%'");
  20. foreach ($dataList as $row){
  21. $total += $row['Data_length'];
  22. }
  23. $this->assign('totalSize', $total);
  24. $this->assign("dataList", $dataList);
  25. $this->display();
  26. }
  27. public function excuteQuery($sql='')
  28. {
  29. if(empty($sql)) {$this->error(L('do_empty'));}
  30. $queryType = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|TRUNCATE|REVOKE|LOCK|UNLOCK';
  31. if (preg_match('/^\s*"?(' . $queryType . ')\s+/i', $sql)) {
  32. $data['result'] = $this->db->execute($sql);
  33. $data['type'] = 'execute';
  34. }else {
  35. $data['result'] = $this->db->query($sql);
  36. $data['type'] = 'query';
  37. }
  38. return $data;
  39. }
  40. public function query(){
  41. $this->display();
  42. }
  43. public function doquery(){
  44. $sqls=explode("\n",stripcslashes($_POST['sql']));
  45. foreach ((array)$sqls as $sql){
  46. if($sql)$r =$this->excuteQuery($sql);
  47. }
  48. if($r['result']!=''){
  49. $this->success(L('do_ok'));
  50. }else{
  51. if($r['dberror']) $this->error(L($r['dberror']));
  52. }
  53. }
  54. public function recover(){
  55. if($_GET['do']=='delete'){
  56. foreach ((array)$_POST['files'] as $r){
  57. unlink($r);
  58. }
  59. $this->success(L('do_ok'));
  60. }elseif($_GET['do']=='import'){
  61. header('Content-Type: text/html; charset=UTF-8');
  62. $filename = $_GET['filename'];
  63. $filelist = dir_list($this->datadir);
  64. foreach ((array)$filelist as $r){
  65. $file = explode('-',basename($r));
  66. if($file[0] ==$filename){
  67. $files[] = $r;
  68. }
  69. }
  70. foreach((array)$files as $file){
  71. //读取数据文件
  72. $sqldata = file_get_contents($file);
  73. $sqlFormat = sql_split($sqldata, C('DB_PREFIX'));
  74. foreach ((array)$sqlFormat as $sql){
  75. $sql = trim($sql);
  76. if (strstr($sql, 'CREATE TABLE')){
  77. preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
  78. $ret =$this->excuteQuery($sql);
  79. //if($ret){echo L('CREATE_TABLE_OK').$matches[0].' <br />';}else{echo 'Error sql:'.$sql;}exit;
  80. }else{
  81. $ret = $this->excuteQuery($sql);
  82. }
  83. }
  84. echo L('CREATE_TABLE_OK').basename($file).'<br>';
  85. }
  86. }else{
  87. $filelist = dir_list($this->datadir);
  88. foreach ((array)$filelist as $r){
  89. $filename = explode('-',basename($r));
  90. $files[] = array('path'=> $r,'file'=>basename($r),'name' => $filename[0], 'size' => filesize($r), 'time' => filemtime($r));
  91. }
  92. $this->assign('files',$files);
  93. $this->display();
  94. }
  95. }
  96. public function docommand()
  97. {
  98. $tables = $_POST['tables'];
  99. $do= trim($_GET['do']);
  100. if(empty($do) || empty($tables)) $this->error(L('do_empty'));
  101. if($do=='show'){
  102. foreach ((array)$tables as $t){
  103. $this->db->execute("SHOW COLUMNS FROM {$t}");
  104. }
  105. }else{
  106. $tables = implode(',',$tables);
  107. $r=$this->db->execute($do.' TABLE '.$tables);
  108. if(false != $r){ $this->success(L('do_ok'));}else{ $this->error($r['dbError']);}
  109. }
  110. }
  111. public function backup(){
  112. $tableid = intval($_GET['tableid']);
  113. $this->startfrom = intval($_GET['startfrom']);
  114. $sizelimit = intval($_REQUEST['sizelimit']);
  115. $volume = intval($_GET['volume']) + 1;
  116. $dataList = $this->db->query("SHOW TABLE STATUS LIKE '".C('DB_PREFIX')."%'");
  117. foreach ($dataList as $row){
  118. $table_info[$row['Name']]=$row;
  119. }
  120. $tables = S('backuptables');
  121. if(empty( $_POST['tables']) && empty($tables)) {
  122. foreach ($dataList as $row){
  123. $tables[]= $row['Name'];
  124. }
  125. }else{
  126. $tables = array();
  127. if(!$tableid) {
  128. $tables=$_POST['tables'];
  129. S('backuptables',$tables);
  130. } else {
  131. $tables = S('backuptables');
  132. }
  133. if( !is_array($tables) || empty($tables)) {
  134. $this->success(L('do_empty'));
  135. }
  136. }
  137. unset($dataList);
  138. $sql='';
  139. if(!$tableid) {
  140. $sql .= "-- Ainatec SQL Backup\n-- Time:".toDate(time())."\n-- http://www.ainatec.com \n\n";
  141. foreach($tables as $key=>$table) {
  142. $sql .= "--\n-- Ainaphp Table `$table`\n-- \n";
  143. $sql .= "DROP TABLE IF EXISTS `$table`;\n";
  144. $info = $this->db->query("SHOW CREATE TABLE $table");
  145. $sql .= str_replace(array('USING BTREE','ROW_FORMAT=DYNAMIC'),'',$info[0]['Create Table']).";\n";
  146. }
  147. }
  148. for(; $this->complete && $tableid < count($tables) && strlen($sql) + 500 < $sizelimit * 1000; $tableid++) {
  149. if($table_info[$tables[$tableid]]['Rows']>0){
  150. $sql .= $this->dumptablesql($tables[$tableid], $this->startfrom, strlen($sql),$table_info[$tables[$tableid]]['Auto_increment']);
  151. if($this->complete) {
  152. $this->startfrom = 0;
  153. }
  154. }
  155. }
  156. !$this->complete && $tableid--;
  157. $filename = htmlspecialchars(strip_tags($_GET['filename']));
  158. $filename = !$filename ? 'Yp_'.rand_string(10).'_'.date('YmdH') : $filename;
  159. $filename_valume = sprintf($filename."-%s".'.sql', $volume);
  160. if(trim($sql)){
  161. $putfile=$this->datadir . $filename_valume;
  162. $r= file_put_contents($putfile , trim($sql));
  163. }
  164. if($tableid < count($tables) || $r){
  165. $this->assign ( 'waitSecond', 0);
  166. $urlarray=array(
  167. 'tableid' => $tableid,
  168. 'startfrom' => $this->startfrom,
  169. 'sizelimit' => $sizelimit,
  170. 'volume' => $volume,
  171. 'filename' => $filename,
  172. );
  173. $message = $filename_valume.' File Create Ok!';
  174. $forward = U("Database/backup",$urlarray);
  175. $this->assign ( 'jumpUrl', $forward);
  176. $this->success($message);
  177. }else{
  178. S('backuptables',null);
  179. $this->assign ( 'jumpUrl', U(MODULE_NAME.'/recover') );
  180. $this->success(L('do_ok'));
  181. }
  182. }
  183. public function dumptablesql($table, $startfrom = 0, $currsize = 0,$auto_increment=0) {
  184. $offset = 300;
  185. $insertsql = '';
  186. $sizelimit = intval($_REQUEST['sizelimit']);
  187. if(C('DB_PREFIX').'online'==$tbale)return '';
  188. $modelname=str_replace(C('DB_PREFIX'),'',$table);
  189. $model = M($modelname);
  190. $keyfield=$model->getPk ();
  191. $rows = $offset;
  192. while($currsize + strlen($insertsql) + 500 < $sizelimit * 1000 && $rows == $offset) {
  193. if($auto_increment) {
  194. $selectsql = "SELECT * FROM $table WHERE $keyfield > $startfrom ORDER BY $keyfield LIMIT $offset";
  195. } else {
  196. $selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
  197. }
  198. $tabledumped = 1;
  199. $row = $this->db->query($selectsql);
  200. $rows = count($row);
  201. foreach($row as $key=>$val) {
  202. foreach ($val as $k=>$field){
  203. if(is_string($field)) {
  204. $val[$k] = '\''. $this->db->escapeString($field).'\'';
  205. }elseif(empty($field)){
  206. $val[$k] = 'NULL';
  207. }
  208. }
  209. if($currsize + strlen($insertsql) + 500 < $sizelimit * 1000) {
  210. if($auto_increment) {
  211. $startfrom = $row[$key][$keyfield];
  212. } else {
  213. $startfrom++;
  214. }
  215. $insertsql .= "INSERT INTO `$table` VALUES (".implode(',', $val).");\n";
  216. } else {
  217. $this->complete=false;
  218. break 2;
  219. }
  220. }
  221. }
  222. $this->startfrom= $startfrom;
  223. return $insertsql;
  224. }
  225. }
  226. ?>