PageRenderTime 53ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/source/admincp/admincp_db.php

https://github.com/kuaileshike/upload
PHP | 1204 lines | 1037 code | 161 blank | 6 comment | 293 complexity | 32bfdde3f0f22a37d40ab51508aa3df6 MD5 | raw file
  1. <?php
  2. /**
  3. * [Discuz!] (C)2001-2099 Comsenz Inc.
  4. * This is NOT a freeware, use is subject to license terms
  5. *
  6. * $Id: admincp_db.php 28648 2012-03-07 02:24:19Z monkey $
  7. */
  8. if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
  9. exit('Access Denied');
  10. }
  11. $db = & DB::object();
  12. $tabletype = $db->version() > '4.1' ? 'Engine' : 'Type';
  13. $tablepre = $_G['config']['db'][1]['tablepre'];
  14. $dbcharset = $_G['config']['db'][1]['dbcharset'];
  15. require_once libfile('function/attachment');
  16. cpheader();
  17. if(!isfounder()) cpmsg('noaccess_isfounder', '', 'error');
  18. $excepttables = array($tablepre.'common_admincp_session', $tablepre.'common_syscache', $tablepre.'common_failedlogin', $tablepre.'forum_rsscache', $tablepre.'common_searchindex', $tablepre.'forum_spacecache', $tablepre.'common_session');
  19. $backupdir = C::t('common_setting')->fetch('backupdir');
  20. if(!$backupdir) {
  21. $backupdir = random(6);
  22. @mkdir('./data/backup_'.$backupdir, 0777);
  23. C::t('common_setting')->update('backupdir',$backupdir);
  24. }
  25. $backupdir = 'backup_'.$backupdir;
  26. if(!is_dir('./data/'.$backupdir)) {
  27. mkdir('./data/'.$backupdir, 0777);
  28. }
  29. if($operation == 'export') {
  30. if(!submitcheck('exportsubmit', 1)) {
  31. $shelldisabled = function_exists('shell_exec') ? '' : 'disabled';
  32. $tables = '';
  33. $dztables = array();
  34. $tables = C::t('common_setting')->fetch('custombackup', true);
  35. $discuz_tables = fetchtablelist($tablepre);
  36. foreach($discuz_tables as $table) {
  37. $dztables[$table['Name']] = $table['Name'];
  38. }
  39. $defaultfilename = date('ymd').'_'.random(8);
  40. include DISCUZ_ROOT.'./config/config_ucenter.php';
  41. $uc_tablepre = explode('.', UC_DBTABLEPRE);
  42. $uc_tablepre = $uc_tablepre[1] ? $uc_tablepre[1] : $uc_tablepre[0];
  43. $uc_tablepre = substr($uc_tablepre, '0', '-8');
  44. if(UC_CONNECT == 'mysql' && UC_DBHOST == $_G['config']['db'][1]['dbhost'] && UC_DBNAME == $_G['config']['db'][1]['dbname'] && $uc_tablepre == $tablepre) {
  45. $db_export = 'db_export_discuz_uc';
  46. $db_export_key = 'discuz_uc';
  47. $db_export_tips = cplang('db_export_tips_uc', array('uc_backup_url' => $uc_backup_url)).cplang('db_export_tips');
  48. $db_export_discuz_table = cplang('db_export_discuz_table_uc');
  49. } else {
  50. $db_export = 'db_export_discuz';
  51. $db_export_key = 'discuz';
  52. $uc_backup_url = UC_API.'/admin.php?m=db&a=ls&iframe=1';
  53. $db_export_tips = cplang('db_export_tips_nouc', array('uc_backup_url' => $uc_backup_url)).cplang('db_export_tips');
  54. $db_export_discuz_table = cplang('db_export_discuz_table');
  55. }
  56. shownav('founder', 'nav_db', 'nav_db_export');
  57. showsubmenu('nav_db', array(
  58. array('nav_db_export', 'db&operation=export', 1),
  59. array('nav_db_import', 'db&operation=import', 0),
  60. array('nav_db_runquery', 'db&operation=runquery', 0),
  61. array('nav_db_optimize', 'db&operation=optimize', 0),
  62. array('nav_db_dbcheck', 'db&operation=dbcheck', 0)
  63. ));
  64. showtips($db_export_tips);
  65. showformheader('db&operation=export&setup=1');
  66. showtableheader();
  67. showsetting('db_export_type', array('type', array(
  68. array($db_export_key, $lang[$db_export], array('showtables' => 'none')),
  69. array('custom', $lang['db_export_custom'], array('showtables' => ''))
  70. )), $db_export_key, 'mradio');
  71. showtagheader('tbody', 'showtables');
  72. showtablerow('', '', '<input class="checkbox" name="chkall" onclick="checkAll(\'prefix\', this.form, \'customtables\', \'chkall\', true)" checked="checked" type="checkbox" id="chkalltables" /><label for="chkalltables"> '.cplang('db_export_custom_select_all').' - '.$db_export_discuz_table ).'</label>';
  73. showtablerow('', 'colspan="2"', mcheckbox('customtables', $dztables));
  74. showtagfooter('tbody');
  75. showtagheader('tbody', 'advanceoption');
  76. showsetting('db_export_method', '', '', '<ul class="nofloat"><li><input class="radio" type="radio" name="method" value="shell" '.$shelldisabled.' onclick="if(\''.intval($db->version() < '4.1').'\') {if(this.form.sqlcompat[2].checked==true) this.form.sqlcompat[0].checked=true; this.form.sqlcompat[2].disabled=true; this.form.sizelimit.disabled=true;} else {this.form.sqlcharset[0].checked=true; for(var i=1; i<=5; i++) {if(this.form.sqlcharset[i]) this.form.sqlcharset[i].disabled=true;}}" id="method_shell" /><label="method_shell"> '.$lang['db_export_shell'].'</label></li><li><input class="radio" type="radio" name="method" value="multivol" checked="checked" onclick="this.form.sqlcompat[2].disabled=false; this.form.sizelimit.disabled=false; for(var i=1; i<=5; i++) {if(this.form.sqlcharset[i]) this.form.sqlcharset[i].disabled=false;}" id="method_multivol" /><label for="method_multivol"> '.$lang['db_export_multivol'].'</label> <input type="text" class="txt" size="40" name="sizelimit" value="2048" /></li></ul>');
  77. showtitle('db_export_options');
  78. showsetting('db_export_options_extended_insert', 'extendins', 0, 'radio');
  79. showsetting('db_export_options_sql_compatible', array('sqlcompat', array(
  80. array('', $lang['default']),
  81. array('MYSQL40', 'MySQL 3.23/4.0.x'),
  82. array('MYSQL41', 'MySQL 4.1.x/5.x')
  83. )), '', 'mradio');
  84. showsetting('db_export_options_charset', array('sqlcharset', array(
  85. array('', cplang('default')),
  86. $dbcharset ? array($dbcharset, strtoupper($dbcharset)) : array(),
  87. $db->version() > '4.1' && $dbcharset != 'utf8' ? array('utf8', 'UTF-8') : array()
  88. ), TRUE), 0, 'mradio');
  89. showsetting('db_export_usehex', 'usehex', 1, 'radio');
  90. if(function_exists('gzcompress')) {
  91. showsetting('db_export_usezip', array('usezip', array(
  92. array('1', $lang['db_export_zip_1']),
  93. array('2', $lang['db_export_zip_2']),
  94. array('0', $lang['db_export_zip_3'])
  95. )), 0, 'mradio');
  96. }
  97. showsetting('db_export_filename', '', '', '<input type="text" class="txt" name="filename" value="'.$defaultfilename.'" />.sql');
  98. showtagfooter('tbody');
  99. showsubmit('exportsubmit', 'submit', '', 'more_options');
  100. showtablefooter();
  101. showformfooter();
  102. } else {
  103. DB::query('SET SQL_QUOTE_SHOW_CREATE=0', 'SILENT');
  104. if(!$_GET['filename'] || preg_match("/(\.)(exe|jsp|asp|aspx|cgi|fcgi|pl)(\.|$)/i", $_GET['filename'])) {
  105. cpmsg('database_export_filename_invalid', '', 'error');
  106. }
  107. $time = dgmdate(TIMESTAMP);
  108. if($_GET['type'] == 'discuz' || $_GET['type'] == 'discuz_uc') {
  109. $tables = arraykeys2(fetchtablelist($tablepre), 'Name');
  110. } elseif($_GET['type'] == 'custom') {
  111. $tables = array();
  112. if(empty($_GET['setup'])) {
  113. $tables = C::t('common_setting')->fetch('custombackup', true);
  114. } else {
  115. C::t('common_setting')->update('custombackup', empty($_GET['customtables'])? '' : $_GET['customtables']);
  116. $tables = & $_GET['customtables'];
  117. }
  118. if( !is_array($tables) || empty($tables)) {
  119. cpmsg('database_export_custom_invalid', '', 'error');
  120. }
  121. }
  122. $memberexist = array_search(DB::table('common_member'), $tables);
  123. if($memberexist !== FALSE) {
  124. unset($tables[$memberexist]);
  125. array_unshift($tables, DB::table('common_member'));
  126. }
  127. $volume = intval($_GET['volume']) + 1;
  128. $idstring = '# Identify: '.base64_encode("$_G[timestamp],".$_G['setting']['version'].",{$_GET['type']},{$_GET['method']},{$volume},{$tablepre},{$dbcharset}")."\n";
  129. $dumpcharset = $_GET['sqlcharset'] ? $_GET['sqlcharset'] : str_replace('-', '', $_G['charset']);
  130. $setnames = ($_GET['sqlcharset'] && $db->version() > '4.1' && (!$_GET['sqlcompat'] || $_GET['sqlcompat'] == 'MYSQL41')) ? "SET NAMES '$dumpcharset';\n\n" : '';
  131. if($db->version() > '4.1') {
  132. if($_GET['sqlcharset']) {
  133. DB::query('SET NAMES %s', array($_GET['sqlcharset']));
  134. }
  135. if($_GET['sqlcompat'] == 'MYSQL40') {
  136. DB::query("SET SQL_MODE='MYSQL40'");
  137. } elseif($_GET['sqlcompat'] == 'MYSQL41') {
  138. DB::query("SET SQL_MODE=''");
  139. }
  140. }
  141. $backupfilename = './data/'.$backupdir.'/'.str_replace(array('/', '\\', '.', "'"), '', $_GET['filename']);
  142. if($_GET['usezip']) {
  143. require_once './source/class/class_zip.php';
  144. }
  145. if($_GET['method'] == 'multivol') {
  146. $sqldump = '';
  147. $tableid = intval($_GET['tableid']);
  148. $startfrom = intval($_GET['startfrom']);
  149. if(!$tableid && $volume == 1) {
  150. foreach($tables as $table) {
  151. $sqldump .= sqldumptablestruct($table);
  152. }
  153. }
  154. $complete = TRUE;
  155. for(; $complete && $tableid < count($tables) && strlen($sqldump) + 500 < $_GET['sizelimit'] * 1000; $tableid++) {
  156. $sqldump .= sqldumptable($tables[$tableid], $startfrom, strlen($sqldump));
  157. if($complete) {
  158. $startfrom = 0;
  159. }
  160. }
  161. $dumpfile = $backupfilename."-%s".'.sql';
  162. !$complete && $tableid--;
  163. if(trim($sqldump)) {
  164. $sqldump = "$idstring".
  165. "# <?php exit();?>\n".
  166. "# Discuz! Multi-Volume Data Dump Vol.$volume\n".
  167. "# Version: Discuz! {$_G[setting][version]}\n".
  168. "# Time: $time\n".
  169. "# Type: {$_GET['type']}\n".
  170. "# Table Prefix: $tablepre\n".
  171. "#\n".
  172. "# Discuz! Home: http://www.discuz.com\n".
  173. "# Please visit our website for newest infomation about Discuz!\n".
  174. "# --------------------------------------------------------\n\n\n".
  175. "$setnames".
  176. $sqldump;
  177. $dumpfilename = sprintf($dumpfile, $volume);
  178. @$fp = fopen($dumpfilename, 'wb');
  179. @flock($fp, 2);
  180. if(@!fwrite($fp, $sqldump)) {
  181. @fclose($fp);
  182. cpmsg('database_export_file_invalid', '', 'error');
  183. } else {
  184. fclose($fp);
  185. if($_GET['usezip'] == 2) {
  186. $fp = fopen($dumpfilename, "r");
  187. $content = @fread($fp, filesize($dumpfilename));
  188. fclose($fp);
  189. $zip = new zipfile();
  190. $zip->addFile($content, basename($dumpfilename));
  191. $fp = fopen(sprintf($backupfilename."-%s".'.zip', $volume), 'w');
  192. if(@fwrite($fp, $zip->file()) !== FALSE) {
  193. @unlink($dumpfilename);
  194. }
  195. fclose($fp);
  196. }
  197. unset($sqldump, $zip, $content);
  198. cpmsg('database_export_multivol_redirect', "action=db&operation=export&type=".rawurlencode($_GET['type'])."&saveto=server&filename=".rawurlencode($_GET['filename'])."&method=multivol&sizelimit=".rawurlencode($_GET['sizelimit'])."&volume=".rawurlencode($volume)."&tableid=".rawurlencode($tableid)."&startfrom=".rawurlencode($startrow)."&extendins=".rawurlencode($_GET['extendins'])."&sqlcharset=".rawurlencode($_GET['sqlcharset'])."&sqlcompat=".rawurlencode($_GET['sqlcompat'])."&exportsubmit=yes&usehex={$_GET['usehex']}&usezip={$_GET['usezip']}", 'loading', array('volume' => $volume));
  199. }
  200. } else {
  201. $volume--;
  202. $filelist = '<ul>';
  203. cpheader();
  204. if($_GET['usezip'] == 1) {
  205. $zip = new zipfile();
  206. $zipfilename = $backupfilename.'.zip';
  207. $unlinks = array();
  208. for($i = 1; $i <= $volume; $i++) {
  209. $filename = sprintf($dumpfile, $i);
  210. $fp = fopen($filename, "r");
  211. $content = @fread($fp, filesize($filename));
  212. fclose($fp);
  213. $zip->addFile($content, basename($filename));
  214. $unlinks[] = $filename;
  215. $filelist .= "<li><a href=\"$filename\">$filename</a></li>\n";
  216. }
  217. $fp = fopen($zipfilename, 'w');
  218. if(@fwrite($fp, $zip->file()) !== FALSE) {
  219. foreach($unlinks as $link) {
  220. @unlink($link);
  221. }
  222. } else {
  223. cpmsg('database_export_multivol_succeed', '', 'succeed', array('volume' => $volume, 'filelist' => $filelist));
  224. }
  225. unset($sqldump, $zip, $content);
  226. fclose($fp);
  227. @touch('./data/'.$backupdir.'/index.htm');
  228. $filename = $zipfilename;
  229. cpmsg('database_export_zip_succeed', '', 'succeed', array('filename' => $filename));
  230. } else {
  231. @touch('./data/'.$backupdir.'/index.htm');
  232. for($i = 1; $i <= $volume; $i++) {
  233. $filename = sprintf($_GET['usezip'] == 2 ? $backupfilename."-%s".'.zip' : $dumpfile, $i);
  234. $filelist .= "<li><a href=\"$filename\">$filename</a></li>\n";
  235. }
  236. cpmsg('database_export_multivol_succeed', '', 'succeed', array('volume' => $volume, 'filelist' => $filelist));
  237. }
  238. }
  239. } else {
  240. $tablesstr = '';
  241. foreach($tables as $table) {
  242. $tablesstr .= '"'.$table.'" ';
  243. }
  244. require DISCUZ_ROOT . './config/config_global.php';
  245. list($dbhost, $dbport) = explode(':', $dbhost);
  246. $query = DB::query("SHOW VARIABLES LIKE 'basedir'");
  247. list(, $mysql_base) = DB::fetch($query, MYSQL_NUM);
  248. $dumpfile = addslashes(dirname(dirname(__FILE__))).'/'.$backupfilename.'.sql';
  249. @unlink($dumpfile);
  250. $mysqlbin = $mysql_base == '/' ? '' : addslashes($mysql_base).'bin/';
  251. @shell_exec($mysqlbin.'mysqldump --force --quick '.($db->version() > '4.1' ? '--skip-opt --create-options' : '-all').' --add-drop-table'.($_GET['extendins'] == 1 ? ' --extended-insert' : '').''.($db->version() > '4.1' && $_GET['sqlcompat'] == 'MYSQL40' ? ' --compatible=mysql40' : '').' --host="'.$dbhost.($dbport ? (is_numeric($dbport) ? ' --port='.$dbport : ' --socket="'.$dbport.'"') : '').'" --user="'.$dbuser.'" --password="'.$dbpw.'" "'.$dbname.'" '.$tablesstr.' > '.$dumpfile);
  252. if(@file_exists($dumpfile)) {
  253. if($_GET['usezip']) {
  254. require_once libfile('class/zip');
  255. $zip = new zipfile();
  256. $zipfilename = $backupfilename.'.zip';
  257. $fp = fopen($dumpfile, "r");
  258. $content = @fread($fp, filesize($dumpfile));
  259. fclose($fp);
  260. $zip->addFile($idstring."# <?php exit();?>\n ".$setnames."\n #".$content, basename($dumpfile));
  261. $fp = fopen($zipfilename, 'w');
  262. @fwrite($fp, $zip->file());
  263. fclose($fp);
  264. @unlink($dumpfile);
  265. @touch('./data/'.$backupdir.'/index.htm');
  266. $filename = $backupfilename.'.zip';
  267. unset($sqldump, $zip, $content);
  268. cpmsg('database_export_zip_succeed', '', 'succeed', array('filename' => $filename));
  269. } else {
  270. if(@is_writeable($dumpfile)) {
  271. $fp = fopen($dumpfile, 'rb+');
  272. @fwrite($fp, $idstring."# <?php exit();?>\n ".$setnames."\n #");
  273. fclose($fp);
  274. }
  275. @touch('./data/'.$backupdir.'/index.htm');
  276. $filename = $backupfilename.'.sql';
  277. cpmsg('database_export_succeed', '', 'succeed', array('filename' => $filename));
  278. }
  279. } else {
  280. cpmsg('database_shell_fail', '', 'error');
  281. }
  282. }
  283. }
  284. } elseif($operation == 'import') {
  285. checkpermission('dbimport');
  286. if(!submitcheck('deletesubmit')) {
  287. $exportlog = $exportsize = $exportziplog = array();
  288. if(is_dir(DISCUZ_ROOT.'./data/'.$backupdir)) {
  289. $dir = dir(DISCUZ_ROOT.'./data/'.$backupdir);
  290. while($entry = $dir->read()) {
  291. $entry = './data/'.$backupdir.'/'.$entry;
  292. if(is_file($entry)) {
  293. if(preg_match("/\.sql$/i", $entry)) {
  294. $filesize = filesize($entry);
  295. $fp = fopen($entry, 'rb');
  296. $identify = explode(',', base64_decode(preg_replace("/^# Identify:\s*(\w+).*/s", "\\1", fgets($fp, 256))));
  297. fclose($fp);
  298. $key = preg_replace('/^(.+?)(\-\d+)\.sql$/i', '\\1', basename($entry));
  299. $exportlog[$key][$identify[4]] = array(
  300. 'version' => $identify[1],
  301. 'type' => $identify[2],
  302. 'method' => $identify[3],
  303. 'volume' => $identify[4],
  304. 'filename' => $entry,
  305. 'dateline' => filemtime($entry),
  306. 'size' => $filesize
  307. );
  308. $exportsize[$key] += $filesize;
  309. } elseif(preg_match("/\.zip$/i", $entry)) {
  310. $filesize = filesize($entry);
  311. $exportziplog[] = array(
  312. 'type' => 'zip',
  313. 'filename' => $entry,
  314. 'size' => filesize($entry),
  315. 'dateline' => filemtime($entry)
  316. );
  317. }
  318. }
  319. }
  320. $dir->close();
  321. } else {
  322. cpmsg('database_export_dest_invalid', '', 'error');
  323. }
  324. $restore_url = $_G['siteurl'].'data/restore.php';
  325. shownav('founder', 'nav_db', 'nav_db_import');
  326. showsubmenu('nav_db', array(
  327. array('nav_db_export', 'db&operation=export', 0),
  328. array('nav_db_import', 'db&operation=import', 1),
  329. array('nav_db_runquery', 'db&operation=runquery', 0),
  330. array('nav_db_optimize', 'db&operation=optimize', 0),
  331. array('nav_db_dbcheck', 'db&operation=dbcheck', 0)
  332. ));
  333. showtips('db_import_tips');
  334. showtableheader('db_import');
  335. showtablerow('', array('colspan="9" class="tipsblock"'), array(cplang('do_import_option', array('restore_url' => $restore_url))));
  336. showformheader('db&operation=import');
  337. showtitle('db_export_file');
  338. showsubtitle(array('', 'filename', 'version', 'time', 'type', 'size', 'db_method', 'db_volume', ''));
  339. $datasiteurl = $_G['siteurl'].'data/';
  340. foreach($exportlog as $key => $val) {
  341. $info = $val[1];
  342. $info['dateline'] = is_int($info['dateline']) ? dgmdate($info['dateline']) : $lang['unknown'];
  343. $info['size'] = sizecount($exportsize[$key]);
  344. $info['volume'] = count($val);
  345. $info['method'] = $info['type'] != 'zip' ? ($info['method'] == 'multivol' ? $lang['db_multivol'] : $lang['db_shell']) : '';
  346. $datafile_server = '.'.$info['filename'];
  347. showtablerow('', '', array(
  348. "<input class=\"checkbox\" type=\"checkbox\" name=\"delete[]\" value=\"".$key."\">",
  349. "<a href=\"javascript:;\" onclick=\"display('exportlog_$key')\">".$key."</a>",
  350. $info['version'],
  351. $info['dateline'],
  352. $lang['db_export_'.$info['type']],
  353. $info['size'],
  354. $info['method'],
  355. $info['volume'],
  356. $info['type'] == 'zip' ? "<a href=\"".$datasiteurl."restore.php?operation=importzip&datafile_server=$datafile_server&importsubmit=yes\" onclick=\"return confirm('$lang[db_import_confirm_zip]');\" class=\"act\" target=\"_blank\">$lang[db_import_unzip]</a>" : "<a class=\"act\" href=\"".$datasiteurl."restore.php?operation=import&from=server&datafile_server=$datafile_server&importsubmit=yes\"".($info['version'] != $_G['setting']['version'] ? " onclick=\"return confirm('$lang[db_import_confirm]');\"" : " onclick=\"return confirm('$lang[db_import_confirm_sql]');\"")." class=\"act\" target=\"_blank\">$lang[import]</a>"
  357. ));
  358. echo '<tbody id="exportlog_'.$key.'" style="display:none">';
  359. foreach($val as $info) {
  360. $info['dateline'] = is_int($info['dateline']) ? dgmdate($info['dateline']) : $lang['unknown'];
  361. $info['size'] = sizecount($info['size']);
  362. showtablerow('', '', array(
  363. '',
  364. "<a href=\"$info[filename]\">".substr(strrchr($info['filename'], "/"), 1)."</a>",
  365. $info['version'],
  366. $info['dateline'],
  367. '',
  368. $info['size'],
  369. '',
  370. $info['volume'],
  371. ''
  372. ));
  373. }
  374. echo '</tbody>';
  375. }
  376. foreach($exportziplog as $info) {
  377. $info['dateline'] = is_int($info['dateline']) ? dgmdate($info['dateline']) : $lang['unknown'];
  378. $info['size'] = sizecount($info['size']);
  379. $info['method'] = $info['method'] == 'multivol' ? $lang['db_multivol'] : $lang['db_zip'];
  380. $datafile_server = '.'.$info['filename'];
  381. showtablerow('', '', array(
  382. "<input class=\"checkbox\" type=\"checkbox\" name=\"delete[]\" value=\"".basename($info['filename'])."\">",
  383. "<a href=\"$info[filename]\">".substr(strrchr($info['filename'], "/"), 1)."</a>",
  384. '',
  385. $info['dateline'],
  386. $lang['db_export_'.$info['type']],
  387. $info['size'],
  388. $info['method'],
  389. '',
  390. "<a href=\"".$datasiteurl."restore.php?operation=importzip&datafile_server=$datafile_server&importsubmit=yes\" onclick=\"return confirm('$lang[db_import_confirm_zip]');\" class=\"act\" target=\"_blank\">$lang[db_import_unzip]</a>"
  391. ));
  392. }
  393. showsubmit('deletesubmit', 'submit', 'del');
  394. showformfooter();
  395. showtablefooter();
  396. } else {
  397. if(is_array($_GET['delete'])) {
  398. foreach($_GET['delete'] as $filename) {
  399. $file_path = './data/'.$backupdir.'/'.str_replace(array('/', '\\'), '', $filename);
  400. if(is_file($file_path)) {
  401. @unlink($file_path);
  402. } else {
  403. $i = 1;
  404. while(1) {
  405. $file_path = './data/'.$backupdir.'/'.str_replace(array('/', '\\'), '', $filename.'-'.$i.'.sql');
  406. if(is_file($file_path)) {
  407. @unlink($file_path);
  408. $i++;
  409. } else {
  410. break;
  411. }
  412. }
  413. }
  414. }
  415. cpmsg('database_file_delete_succeed', '', 'succeed');
  416. } else {
  417. cpmsg('database_file_delete_invalid', '', 'error');
  418. }
  419. }
  420. } elseif($operation == 'runquery') {
  421. $checkperm = checkpermission('runquery', 0);
  422. $runquerys = array();
  423. include_once(DISCUZ_ROOT.'source/admincp/admincp_quickquery.php');
  424. if(!submitcheck('sqlsubmit')) {
  425. $runqueryselect = '';
  426. foreach($simplequeries as $key => $query) {
  427. if(empty($query['sql'])) {
  428. $runqueryselect .= "<optgroup label=\"$query[comment]\">";
  429. } else {
  430. $runqueryselect .= '<option value="'.$key.'">'.$query['comment'].'</option>';
  431. }
  432. }
  433. if($runqueryselect) {
  434. $runqueryselect = '<select name="queryselect" style="width:500px">'.$runqueryselect.'</select>';
  435. }
  436. $queryselect = intval($_GET['queryselect']);
  437. $queries = $queryselect ? $runquerys[$queryselect] : '';
  438. shownav('founder', 'nav_db', 'nav_db_runquery');
  439. showsubmenu('nav_db', array(
  440. array('nav_db_export', 'db&operation=export', 0),
  441. array('nav_db_import', 'db&operation=import', 0),
  442. array('nav_db_runquery', 'db&operation=runquery', 1),
  443. array('nav_db_optimize', 'db&operation=optimize', 0),
  444. array('nav_db_dbcheck', 'db&operation=dbcheck', 0)
  445. ));
  446. showtips('db_runquery_tips');
  447. showtableheader();
  448. showformheader('db&operation=runquery&option=simple');
  449. showsetting('db_runquery_simply', '', '', $runqueryselect);
  450. showsetting('', '', '', '<input type="checkbox" class="checkbox" name="createcompatible" value="1" checked="checked" />'.cplang('db_runquery_createcompatible'));
  451. showsubmit('sqlsubmit');
  452. showformfooter();
  453. if($checkperm) {
  454. showformheader('db&operation=runquery&option=');
  455. showsetting('db_runquery_sql', '', '', '<textarea cols="85" rows="10" name="queries" style="width:500px;">'.$queries.'</textarea>');
  456. showsetting('', '', '', '<input type="checkbox" class="checkbox" name="createcompatible" value="1" checked="checked" />'.cplang('db_runquery_createcompatible'));
  457. showsubmit('sqlsubmit', 'submit', '', cplang('db_runquery_comment'));
  458. showformfooter();
  459. }
  460. showtablefooter();
  461. } else {
  462. $queries = $_GET['queries'];
  463. if($_GET['option'] == 'simple') {
  464. $queryselect = intval($_GET['queryselect']);
  465. $queries = isset($simplequeries[$queryselect]) && $simplequeries[$queryselect]['sql'] ? $simplequeries[$queryselect]['sql'] : '';
  466. } elseif(!$checkperm) {
  467. cpmsg('database_run_query_denied', '', 'error');
  468. }
  469. $sqlquery = splitsql(str_replace(array(' {tablepre}', ' cdb_', ' `cdb_', ' pre_', ' `pre_'), array(' '.$tablepre, ' '.$tablepre, ' `'.$tablepre, ' '.$tablepre, ' `'.$tablepre), $queries));
  470. $affected_rows = 0;
  471. foreach($sqlquery as $sql) {
  472. if(trim($sql) != '') {
  473. $sql = !empty($_GET['createcompatible']) ? syntablestruct(trim($sql), $db->version() > '4.1', $dbcharset) : $sql;
  474. DB::query($sql, 'SILENT');
  475. if($sqlerror = DB::error()) {
  476. break;
  477. } else {
  478. $affected_rows += intval(DB::affected_rows());
  479. }
  480. }
  481. }
  482. $sqlerror ? cpmsg('database_run_query_invalid', '', 'error', array('sqlerror' => $sqlerror)) : cpmsg('database_run_query_succeed', '', 'succeed', array('affected_rows' => $affected_rows));
  483. }
  484. } elseif($operation == 'optimize') {
  485. $optimizetable = '';
  486. $totalsize = 0;
  487. $tablearray = array( 0 => $tablepre);
  488. shownav('founder', 'nav_db', 'nav_db_optimize');
  489. showsubmenu('nav_db', array(
  490. array('nav_db_export', 'db&operation=export', 0),
  491. array('nav_db_import', 'db&operation=import', 0),
  492. array('nav_db_runquery', 'db&operation=runquery', 0),
  493. array('nav_db_optimize', 'db&operation=optimize', 1),
  494. array('nav_db_dbcheck', 'db&operation=dbcheck', 0)
  495. ));
  496. showtips('db_optimize_tips');
  497. showformheader('db&operation=optimize');
  498. showtableheader('db_optimize_tables');
  499. showsubtitle(array('', 'db_optimize_table_name', 'type', 'db_optimize_rows', 'db_optimize_data', 'db_optimize_index', 'db_optimize_frag'));
  500. if(!submitcheck('optimizesubmit')) {
  501. foreach($tablearray as $tp) {
  502. $query = DB::query("SHOW TABLE STATUS LIKE '$tp%'", 'SILENT');
  503. while($table = DB::fetch($query)) {
  504. if($table['Data_free'] && $table[$tabletype] == 'MyISAM') {
  505. $checked = $table[$tabletype] == 'MyISAM' ? 'checked' : 'disabled';
  506. showtablerow('', '', array(
  507. "<input class=\"checkbox\" type=\"checkbox\" name=\"optimizetables[]\" value=\"$table[Name]\" $checked>",
  508. $table[Name],
  509. $table[$tabletype],
  510. $table[Rows],
  511. $table[Data_length],
  512. $table[Index_length],
  513. $table[Data_free],
  514. ));
  515. $totalsize += $table['Data_length'] + $table['Index_length'];
  516. }
  517. }
  518. }
  519. if(empty($totalsize)) {
  520. showtablerow('', 'colspan="6"', $lang['db_optimize_done']);
  521. } else {
  522. showtablerow('', 'colspan="6"', $lang['db_optimize_used'].' '.sizecount($totalsize));
  523. showsubmit('optimizesubmit', 'submit', '<input name="chkall" id="chkall" class="checkbox" onclick="checkAll(\'prefix\', this.form)" checked="checked" type="checkbox" /><label for="chkall">'.$lang[db_optimize_opt].'</label>');
  524. }
  525. } else {
  526. foreach($tablearray as $tp) {
  527. $query = DB::query("SHOW TABLE STATUS LIKE '$tp%'", 'SILENT');
  528. while($table = DB::fetch($query)) {
  529. if($table['Data_free'] && $table[$tabletype] == 'MyISAM') {
  530. $optimizeinput = "<input class=\"checkbox\" type=\"checkbox\" name=\"optimizetables[]\" value=\"$table[Name]\" $checked>";
  531. if(is_array($_GET['optimizetables']) && in_array($table['Name'], $_GET['optimizetables'])) {
  532. DB::query("OPTIMIZE TABLE $table[Name]");
  533. $table[Data_free] = 0;
  534. $optimizeinput = '';
  535. }
  536. showtablerow('', '', array(
  537. $optimizeinput,
  538. $table[Name],
  539. $db->version() > '4.1' ? $table['Engine'] : $table['Type'],
  540. $table[Rows],
  541. $table[Data_length],
  542. $table[Index_length],
  543. $table[Data_free]
  544. ));
  545. $totalsize += $table['Data_length'] + $table['Index_length'];
  546. }
  547. }
  548. }
  549. showtablerow('', 'colspan="6"', $lang['db_optimize_used'].' '.sizecount($totalsize));
  550. }
  551. showtablefooter();
  552. showformfooter();
  553. } elseif($operation == 'dbcheck') {
  554. if(!C::t('common_setting')->fetch_all_field()) {
  555. cpmsg('dbcheck_permissions_invalid', '', 'error');
  556. }
  557. $step = max(1, intval($_GET['step']));
  558. if($step == 3) {
  559. if(!file_exists('source/admincp/discuzdb.md5')) {
  560. cpmsg('dbcheck_nofound_md5file', '', 'error');
  561. }
  562. $dbcharset = $discuz->config['db'][1]['dbcharset'];
  563. unset($dbuser, $dbpw, $dbname);
  564. $fp = fopen(DISCUZ_ROOT.'./source/admincp/discuzdb.md5', "rb");
  565. $discuzdb = fread($fp, filesize(DISCUZ_ROOT.'./source/admincp/discuzdb.md5'));
  566. fclose($fp);
  567. $dbmd5 = substr($discuzdb, 0, 32);
  568. $discuzdb = dunserialize(substr($discuzdb, 34));
  569. $settingsdata = $discuzdb[1];
  570. $discuzdb = $discuzdb[0][0];
  571. $repair = !empty($_GET['repair']) ? $_GET['repair'] : array();
  572. $setting = !empty($_GET['setting']) ? $_GET['setting'] : array();
  573. $missingtable = !empty($_GET['missingtable']) ? $_GET['missingtable'] : array();
  574. $repairtable = is_array($_GET['repairtable']) && !empty($_GET['repairtable']) ? $_GET['repairtable'] : array();
  575. $except = array('threads' => array('sgid'));
  576. foreach(C::t('common_member_profile_setting')->range() as $profilefields) {
  577. $except['memberfields'][] = 'field_'.$profilefields[$fieldid];
  578. }
  579. if(submitcheck('repairsubmit') && (!empty($repair) || !empty($setting) || !empty($repairtable) || !empty($missingtable))) {
  580. $error = '';
  581. $errorcount = 0;
  582. $alter = $fielddefault = array();
  583. foreach($missingtable as $value) {
  584. if(!isset($installdata)) {
  585. $fp = fopen(DISCUZ_ROOT.'./install/install.sql', "rb");
  586. $installdata = fread($fp, filesize(DISCUZ_ROOT.'./install/install.sql'));
  587. fclose($fp);
  588. }
  589. preg_match("/CREATE TABLE ".DB::table($value)."\s+\(.+?;/is", $installdata, $a);
  590. DB::query(createtable($a[0], $dbcharset));
  591. }
  592. foreach($repair as $value) {
  593. if(!in_array($r_table, $repairtable)) {
  594. list($r_table, $r_field, $option) = explode('|', $value);
  595. if(!isset($repairrtable[$r_table]) && $fieldsquery = DB::query("SHOW FIELDS FROM ".DB::table($r_table), 'SILENT')) {
  596. while($fields = DB::fetch($fieldsquery)) {
  597. $fielddefault[$r_table][$fields['Field']] = $fields['Default'];
  598. }
  599. }
  600. $field = $discuzdb[$r_table][$r_field];
  601. $altersql = '`'.$field['Field'].'` '.$field['Type'];
  602. $altersql .= $field['Null'] == 'NO' ? ' NOT NULL' : '';
  603. $altersql .= in_array($fielddefault[$r_table][$field['Field']], array('', '0')) && in_array($field['Default'], array('', '0')) ||
  604. $field['Null'] == 'NO' && $field['Default'] == '' ||
  605. preg_match('/text/i', $field['Type']) || preg_match('/auto_increment/i', $field['Extra']) ?
  606. '' : ' default \''.$field['Default'].'\'';
  607. $altersql .= $field['Extra'] != '' ? ' '.$field['Extra'] : '';
  608. $altersql = $option == 'modify' ? "MODIFY COLUMN ".$altersql : "ADD COLUMN ".$altersql;
  609. $alter[$r_table][] = $altersql;
  610. }
  611. }
  612. foreach($alter as $r_table => $sqls) {
  613. DB::query("ALTER TABLE `$tablepre$r_table` ".implode(',', $sqls), 'SILENT');
  614. if($sqlerror = DB::error()) {
  615. $errorcount += count($sqls);
  616. $error .= $sqlerror.'<br /><br />';
  617. }
  618. }
  619. $alter = array();
  620. foreach($repairtable as $value) {
  621. foreach($discuzdb[$value] as $field) {
  622. if(!isset($fielddefault[$value]) && $fieldsquery = DB::query("SHOW FIELDS FROM ".DB::table($value), 'SILENT')) {
  623. while($fields = DB::fetch($fieldsquery)) {
  624. $fielddefault[$value][$fields['Field']] = $fields['Default'];
  625. }
  626. }
  627. $altersql = '`'.$field['Field'].'` '.$field['Type'];
  628. $altersql .= $field['Null'] == 'NO' ? ' NOT NULL' : '';
  629. $altersql .= in_array($fielddefault[$value][$field['Field']], array('', '0')) && in_array($field['Default'], array('', '0')) ||
  630. $field['Null'] == 'NO' && $field['Default'] == '' ||
  631. preg_match('/text/i', $field['Type']) || preg_match('/auto_increment/i', $field['Extra']) ?
  632. '' : ' default \''.$field['Default'].'\'';
  633. $altersql .= $field['Extra'] != '' ? ' '.$field['Extra'] : '';
  634. $altersql = "MODIFY COLUMN ".$altersql;
  635. $alter[$value][] = $altersql;
  636. }
  637. }
  638. foreach($alter as $r_table => $sqls) {
  639. DB::query("ALTER TABLE `".DB::table($r_table)."` ".implode(',', $sqls), 'SILENT');
  640. if($sqlerror = DB::error()) {
  641. $errorcount += count($sqls);
  642. $error .= $sqlerror.'<br /><br />';
  643. }
  644. }
  645. if(!empty($setting)) {
  646. $settingsdatanow = $newsettings = array();
  647. $allsetting = C::t('common_setting')->fetch_all();
  648. $settingsdatanew = array_keys($allsetting);
  649. unset($allsetting);
  650. $settingsdellist = @array_diff($settingsdata, $settingsdatanew);
  651. if($setting['del'] && is_array($settingsdellist)) {
  652. foreach($settingsdellist as $variable) {
  653. $newsettings[$variable] = '';
  654. }
  655. }
  656. if($newsettings) {
  657. C::t('common_setting')->update_batch($newsettings);
  658. updatecache('setting');
  659. }
  660. }
  661. if($errorcount) {
  662. cpmsg('dbcheck_repair_error', '', 'error', array('errorcount' => $errorcount, 'error' => $error));
  663. } else {
  664. cpmsg('dbcheck_repair_completed', 'action=db&operation=dbcheck&step=3', 'succeed');
  665. }
  666. }
  667. $installexists = file_exists(DISCUZ_ROOT.'./install/install.sql');
  668. $discuzdbnew = $deltables = $excepttables = $missingtables = $charseterror = array();
  669. foreach($discuzdb as $dbtable => $fields) {
  670. if($fieldsquery = DB::query("SHOW FIELDS FROM ".DB::table($dbtable), 'SILENT')) {
  671. while($fields = DB::fetch($fieldsquery)) {
  672. $r = '/^'.$tablepre.'/';
  673. $cuttable = preg_replace($r, '', $dbtable);
  674. if($db->version() < '4.1' && $cuttable == 'sessions' && $fields['Field'] == 'sid') {
  675. $fields['Type'] = str_replace(' binary', '', $fields['Type']);
  676. }
  677. if($cuttable == 'memberfields' && preg_match('/^field\_\d+$/', $fields['Field'])) {
  678. unset($discuzdbnew[$cuttable][$fields['Field']]);
  679. continue;
  680. }
  681. $discuzdbnew[$cuttable][$fields['Field']]['Field'] = $fields['Field'];
  682. $discuzdbnew[$cuttable][$fields['Field']]['Type'] = $fields['Type'];
  683. $discuzdbnew[$cuttable][$fields['Field']]['Null'] = $fields['Null'] == '' ? 'NO' : $fields['Null'];
  684. $discuzdbnew[$cuttable][$fields['Field']]['Extra'] = $fields['Extra'];
  685. $discuzdbnew[$cuttable][$fields['Field']]['Default'] = $fields['Default'] == '' || $fields['Default'] == '0' ? '' : $fields['Default'];
  686. }
  687. ksort($discuzdbnew[$cuttable]);
  688. } else {
  689. $missingtables[] = '<span style="float:left;width:33%">'.(($installexists ? '<input name="missingtable[]" type="checkbox" class="checkbox" value="'.$dbtable.'">' : '').$tablepre.$dbtable).'</span>';
  690. $excepttables[] = $dbtable;
  691. }
  692. }
  693. if($db->version() > '4.1') {
  694. $dbcharset = strtoupper($dbcharset) == 'UTF-8' ? 'UTF8' : strtoupper($dbcharset);
  695. $query = DB::query("SHOW TABLE STATUS LIKE '$tablepre%'");
  696. while($tables = DB::fetch($query)) {
  697. $r = '/^'.$tablepre.'/';
  698. $cuttable = preg_replace($r, '', $tables['Name']);
  699. $tabledbcharset = substr($tables['Collation'], 0, strpos($tables['Collation'], '_'));
  700. if($dbcharset != strtoupper($tabledbcharset)) {
  701. $charseterror[] = '<span style="float:left;width:33%">'.$tablepre.$cuttable.'('.$tabledbcharset.')</span>';
  702. }
  703. }
  704. }
  705. $dbmd5new = md5(serialize($discuzdbnew));
  706. $settingsdatanow = array();
  707. $allsetting = C::t('common_setting')->fetch_all();
  708. $settingsdatanew = array_keys($allsetting);
  709. unset($allsetting);
  710. $settingsdellist = @array_diff($settingsdata, $settingsdatanew);
  711. if($dbmd5 == $dbmd5new && empty($charseterror) && empty($settingsdellist)) {
  712. cpmsg('dbcheck_ok', '', 'succeed');
  713. }
  714. $showlist = $addlists = '';
  715. foreach($discuzdb as $dbtable => $fields) {
  716. $addlist = $modifylist = $dellist = array();
  717. if($fields != $discuzdbnew[$dbtable]) {
  718. foreach($discuzdb[$dbtable] as $key => $value) {
  719. $tempvalue = str_replace('mediumtext', 'text', $value);
  720. $discuzdbnew[$dbtable][$key] = str_replace('mediumtext', 'text', $discuzdbnew[$dbtable][$key]);
  721. if(is_array($missingtables) && in_array($tablepre.$dbtable, $missingtables)) {
  722. } elseif(!isset($discuzdbnew[$dbtable][$key])) {
  723. $dellist[] = $value;
  724. } elseif($tempvalue != $discuzdbnew[$dbtable][$key]) {
  725. $modifylist[] = $value;
  726. }
  727. }
  728. if(is_array($discuzdbnew[$dbtable])) {
  729. foreach($discuzdbnew[$dbtable] as $key => $value) {
  730. if(!isset($discuzdb[$dbtable][$key]) && !@in_array($value['Field'], $except[$dbtable])) {
  731. $addlist[] = $value;
  732. }
  733. }
  734. }
  735. }
  736. if(($modifylist || $dellist) && !in_array($dbtable, $excepttables)) {
  737. $showlist .= showtablerow('', '', array("<span class=\"diffcolor3\">$tablepre$dbtable</span> $lang[dbcheck_field]", $lang[dbcheck_org_field], $lang[dbcheck_status]), TRUE);
  738. foreach($modifylist as $value) {
  739. $slowstatus = slowcheck($discuzdbnew[$dbtable][$value['Field']]['Type'], $value['Type']);
  740. $showlist .= "<tr><td><input name=\"repair[]\" class=\"checkbox\" type=\"checkbox\" value=\"$dbtable|$value[Field]|modify\"> <b>".$value['Field']."</b> ".
  741. $discuzdbnew[$dbtable][$value['Field']]['Type'].
  742. ($discuzdbnew[$dbtable][$value['Field']]['Null'] == 'NO' ? ' NOT NULL' : '').
  743. (!preg_match('/auto_increment/i', $discuzdbnew[$dbtable][$value['Field']]['Extra']) && !preg_match('/text/i', $discuzdbnew[$dbtable][$value['Field']]['Type']) ? ' default \''.$discuzdbnew[$dbtable][$value['Field']]['Default'].'\'' : '').
  744. ' '.$discuzdbnew[$dbtable][$value['Field']]['Extra'].
  745. "</td><td><b>".$value['Field']."</b> ".$value['Type'].
  746. ($value['Null'] == 'NO' ? ' NOT NULL' : '').
  747. (!preg_match('/auto_increment/i', $value['Extra']) && !preg_match('/text/i', $value['Type']) ? ' default \''.$value['Default'].'\'' : '').
  748. ' '.$value['Extra']."</td><td>".
  749. (!$slowstatus ? "<em class=\"edited\">$lang[dbcheck_modify]</em></td></tr>" : "<em class=\"unknown\">$lang[dbcheck_slow]</em>")."</td></tr>";
  750. }
  751. if($modifylist) {
  752. $showlist .= showtablerow('', 'colspan="3"', "<input onclick=\"setrepaircheck(this, this.form, '$dbtable')\" name=\"repairtable[]\" class=\"checkbox\" type=\"checkbox\" value=\"$dbtable\"> <b>$lang[dbcheck_repairtable]</b>", TRUE);
  753. }
  754. foreach($dellist as $value) {
  755. $showlist .= "<tr><td><input name=\"repair[]\" class=\"checkbox\" type=\"checkbox\" value=\"$dbtable|$value[Field]|add\"> <strike><b>".$value['Field']."</b></strike></td><td> <b>".$value['Field']."</b> ".$value['Type'].($value['Null'] == 'NO' ? ' NOT NULL' : '')."</td><td>".
  756. "<em class=\"del\">$lang[dbcheck_delete]</em></td></tr>";
  757. }
  758. }
  759. if($addlist) {
  760. $addlists .= "<tr><td colspan=\"3\"><b>$tablepre$dbtable</b> $lang[dbcheck_new_field]</td></tr>";
  761. foreach($addlist as $value) {
  762. $addlists .= "<tr><td colspan=\"3\">&nbsp;&nbsp;&nbsp;&nbsp;<b>".$value['Field']."</b> ".$discuzdbnew[$dbtable][$value['Field']]['Type'].($discuzdbnew[$dbtable][$value['Field']]['Null'] == 'NO' ? ' NOT NULL' : '')."</td></tr>";
  763. }
  764. }
  765. }
  766. if($showlist) {
  767. $showlist = showtablerow('', 'colspan="3" class="partition"', $lang['dbcheck_errorfields_tables'], TRUE).$showlist;
  768. }
  769. if($missingtables) {
  770. $showlist .= showtablerow('', 'colspan="3" class="partition"', $lang['dbcheck_missing_tables'], TRUE);
  771. $showlist .= showtablerow('', 'colspan="3" class="partition"', implode('', $missingtables), TRUE);
  772. }
  773. if($settingsdellist) {
  774. $showlist .= "<tr class=\"partition\"><td colspan=\"3\">$lang[dbcheck_setting]</td></tr>";
  775. $showlist .= '<tr><td colspan="3">';
  776. $showlist .= "<input name=\"setting[del]\" class=\"checkbox\" type=\"checkbox\" value=\"1\"> ".implode(', ', $settingsdellist).'<br />';
  777. $showlist .= '</td></tr>';
  778. }
  779. if($showlist) {
  780. $showlist .= '<tr><td colspan="3"><input class="btn" type="submit" value="'.$lang['dbcheck_repair'].'" name="repairsubmit"></td></tr>';
  781. }
  782. if($charseterror) {
  783. $showlist .= "<tr><td class=\"partition\" colspan=\"3\">$lang[dbcheck_charseterror_tables] ($lang[dbcheck_charseterror_notice] $dbcharset)</td></tr>";
  784. $showlist .= '<tr><td colspan="3">'.implode('', $charseterror).'</td></tr>';
  785. }
  786. if($addlists) {
  787. $showlist .= '<tr><td class="partition" colspan="3">'.$lang['dbcheck_userfields'].'</td></tr>'.$addlists;
  788. }
  789. }
  790. shownav('founder', 'nav_db', 'nav_db_dbcheck');
  791. showsubmenu('nav_db', array(
  792. array('nav_db_export', 'db&operation=export', 0),
  793. array('nav_db_import', 'db&operation=import', 0),
  794. array('nav_db_runquery', 'db&operation=runquery', 0),
  795. array('nav_db_optimize', 'db&operation=optimize', 0),
  796. array('nav_db_dbcheck', 'db&operation=dbcheck', 1)
  797. ));
  798. showsubmenusteps('', array(
  799. array('nav_filecheck_confirm', $step == 1),
  800. array('nav_filecheck_verify', $step == 2),
  801. array('nav_filecheck_completed', $step == 3)
  802. ));
  803. if($step == 1) {
  804. cpmsg(cplang('dbcheck_tips_step1'), 'action=db&operation=dbcheck&step=2', 'button', '', FALSE);
  805. } elseif($step == 2) {
  806. cpmsg(cplang('dbcheck_verifying'), "action=db&operation=dbcheck&step=3", 'loading', '', FALSE);
  807. } elseif($step == 3) {
  808. showtips('dbcheck_tips');
  809. echo <<<EOT
  810. <script type="text/JavaScript">
  811. function setrepaircheck(obj, form, table) {
  812. eval('var rem = /^' + table + '\\\\|.+?\\\\|modify$/;');
  813. eval('var rea = /^' + table + '\\\\|.+?\\\\|add$/;');
  814. for(var i = 0; i < form.elements.length; i++) {
  815. var e = form.elements[i];
  816. if(e.type == 'checkbox' && e.name == 'repair[]') {
  817. if(rem.exec(e.value) != null) {
  818. if(obj.checked) {
  819. e.checked = false;
  820. e.disabled = true;
  821. } else {
  822. e.checked = false;
  823. e.disabled = false;
  824. }
  825. }
  826. if(rea.exec(e.value) != null) {
  827. if(obj.checked) {
  828. e.checked = true;
  829. e.disabled = false;
  830. } else {
  831. e.checked = false;
  832. e.disabled = false;
  833. }
  834. }
  835. }
  836. }
  837. }
  838. </script>
  839. EOT;
  840. showformheader('db&operation=dbcheck&step=3', 'fixpadding');
  841. showtableheader();
  842. echo $showlist;
  843. showtablefooter();
  844. showformfooter();
  845. }
  846. }
  847. function createtable($sql, $dbcharset) {
  848. $type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
  849. $type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
  850. return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
  851. (mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type");
  852. }
  853. function fetchtablelist($tablepre = '') {
  854. global $db;
  855. $arr = explode('.', $tablepre);
  856. $dbname = $arr[1] ? $arr[0] : '';
  857. $tablepre = str_replace('_', '\_', $tablepre);
  858. $sqladd = $dbname ? " FROM $dbname LIKE '$arr[1]%'" : "LIKE '$tablepre%'";
  859. $tables = $table = array();
  860. $query = DB::query("SHOW TABLE STATUS $sqladd");
  861. while($table = DB::fetch($query)) {
  862. $table['Name'] = ($dbname ? "$dbname." : '').$table['Name'];
  863. $tables[] = $table;
  864. }
  865. return $tables;
  866. }
  867. function arraykeys2($array, $key2) {
  868. $return = array();
  869. foreach($array as $val) {
  870. $return[] = $val[$key2];
  871. }
  872. return $return;
  873. }
  874. function syntablestruct($sql, $version, $dbcharset) {
  875. if(strpos(trim(substr($sql, 0, 18)), 'CREATE TABLE') === FALSE) {
  876. return $sql;
  877. }
  878. $sqlversion = strpos($sql, 'ENGINE=') === FALSE ? FALSE : TRUE;
  879. if($sqlversion === $version) {
  880. return $sqlversion && $dbcharset ? preg_replace(array('/ character set \w+/i', '/ collate \w+/i', "/DEFAULT CHARSET=\w+/is"), array('', '', "DEFAULT CHARSET=$dbcharset"), $sql) : $sql;
  881. }
  882. if($version) {
  883. return preg_replace(array('/TYPE=HEAP/i', '/TYPE=(\w+)/is'), array("ENGINE=MEMORY DEFAULT CHARSET=$dbcharset", "ENGINE=\\1 DEFAULT CHARSET=$dbcharset"), $sql);
  884. } else {
  885. return preg_replace(array('/character set \w+/i', '/collate \w+/i', '/ENGINE=MEMORY/i', '/\s*DEFAULT CHARSET=\w+/is', '/\s*COLLATE=\w+/is', '/ENGINE=(\w+)(.*)/is'), array('', '', 'ENGINE=HEAP', '', '', 'TYPE=\\1\\2'), $sql);
  886. }
  887. }
  888. function sqldumptablestruct($table) {
  889. global $_G, $db, $excepttables;
  890. if(in_array($table, $excepttables)) {
  891. return;
  892. }
  893. $createtable = DB::query("SHOW CREATE TABLE $table", 'SILENT');
  894. if(!DB::error()) {
  895. $tabledump = "DROP TABLE IF EXISTS $table;\n";
  896. } else {
  897. return '';
  898. }
  899. $create = $db->fetch_row($createtable);
  900. if(strpos($table, '.') !== FALSE) {
  901. $tablename = substr($table, strpos($table, '.') + 1);
  902. $create[1] = str_replace("CREATE TABLE $tablename", 'CREATE TABLE '.$table, $create[1]);
  903. }
  904. $tabledump .= $create[1];
  905. if($_GET['sqlcompat'] == 'MYSQL41' && $db->version() < '4.1') {
  906. $tabledump = preg_replace("/TYPE\=(.+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
  907. }
  908. if($db->version() > '4.1' && $_GET['sqlcharset']) {
  909. $tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=.+/", "DEFAULT CHARSET=".$_GET['sqlcharset'], $tabledump);
  910. }
  911. $tablestatus = DB::fetch_first("SHOW TABLE STATUS LIKE '$table'");
  912. $tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
  913. if($_GET['sqlcompat'] == 'MYSQL40' && $db->version() >= '4.1' && $db->version() < '5.1') {
  914. if($tablestatus['Auto_increment'] <> '') {
  915. $temppos = strpos($tabledump, ',');
  916. $tabledump = substr($tabledump, 0, $temppos).' auto_increment'.substr($tabledump, $temppos);
  917. }
  918. if($tablestatus['Engine'] == 'MEMORY') {
  919. $tabledump = str_replace('TYPE=MEMORY', 'TYPE=HEAP', $tabledump);
  920. }
  921. }
  922. return $tabledump;
  923. }
  924. function sqldumptable($table, $startfrom = 0, $currsize = 0) {
  925. global $_G, $db, $startrow, $dumpcharset, $complete, $excepttables;
  926. $offset = 300;
  927. $tabledump = '';
  928. $tablefields = array();
  929. $query = DB::query("SHOW FULL COLUMNS FROM $table", 'SILENT');
  930. if(strexists($table, 'adminsessions')) {
  931. return ;
  932. } elseif(!$query && DB::errno() == 1146) {
  933. return;
  934. } elseif(!$query) {
  935. $_GET['usehex'] = FALSE;
  936. } else {
  937. while($fieldrow = DB::fetch($query)) {
  938. $tablefields[] = $fieldrow;
  939. }
  940. }
  941. if(!in_array($table, $excepttables)) {
  942. $tabledumped = 0;
  943. $numrows = $offset;
  944. $firstfield = $tablefields[0];
  945. if($_GET['extendins'] == '0') {
  946. while($currsize + strlen($tabledump) + 500 < $_GET['sizelimit'] * 1000 && $numrows == $offset) {
  947. if($firstfield['Extra'] == 'auto_increment') {
  948. $selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom ORDER BY $firstfield[Field] LIMIT $offset";
  949. } else {
  950. $selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
  951. }
  952. $tabledumped = 1;
  953. $rows = DB::query($selectsql);
  954. $numfields = $db->num_fields($rows);
  955. $numrows = DB::num_rows($rows);
  956. while($row = $db->fetch_row($rows)) {
  957. $comma = $t = '';
  958. for($i = 0; $i < $numfields; $i++) {
  959. $t .= $comma.($_GET['usehex'] && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
  960. $comma = ',';
  961. }
  962. if(strlen($t) + $currsize + strlen($tabledump) + 500 < $_GET['sizelimit'] * 1000) {
  963. if($firstfield['Extra'] == 'auto_increment') {
  964. $startfrom = $row[0];
  965. } else {
  966. $startfrom++;
  967. }
  968. $tabledump .= "INSERT INTO $table VALUES ($t);\n";
  969. } else {
  970. $complete = FALSE;
  971. break 2;
  972. }
  973. }
  974. }
  975. } else {
  976. while($currsize + strlen($tabledump) + 500 < $_GET['sizelimit'] * 1000 && $numrows == $offset) {
  977. if($firstfield['Extra'] == 'auto_increment') {
  978. $selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom LIMIT $offset";
  979. } else {
  980. $selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
  981. }
  982. $tabledumped = 1;
  983. $rows = DB::query($selectsql);
  984. $numfields = $db->num_fields($rows);
  985. if($numrows = DB::num_rows($rows)) {
  986. $t1 = $comma1 = '';
  987. while($row = $db->fetch_row($rows)) {
  988. $t2 = $comma2 = '';
  989. for($i = 0; $i < $numfields; $i++) {
  990. $t2 .= $comma2.($_GET['usehex'] && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text'))? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
  991. $comma2 = ',';
  992. }
  993. if(strlen($t1) + $currsize + strlen($tabledump) + 500 < $_GET['sizelimit'] * 1000) {
  994. if($firstfield['Extra'] == 'auto_increment') {
  995. $startfrom = $row[0];
  996. } else {
  997. $startfrom++;
  998. }
  999. $t1 .= "$comma1 ($t2)";
  1000. $comma1 = ',';
  1001. } else {
  1002. $tabledump .= "INSERT INTO $table VALUES $t1;\n";
  1003. $complete = FALSE;
  1004. break 2;
  1005. }
  1006. }
  1007. $tabledump .= "INSERT INTO $table VALUES $t1;\n";
  1008. }
  1009. }
  1010. }
  1011. $startrow = $startfrom;
  1012. $tabledump .= "\n";
  1013. }
  1014. return $tabledump;
  1015. }
  1016. function splitsql($sql) {
  1017. $sql = str_replace("\r", "\n", $sql);
  1018. $ret = array();
  1019. $num = 0;
  1020. $queriesarray = explode(";\n", trim($sql));
  1021. unset($sql);
  1022. foreach($queriesarray as $query) {
  1023. $queries = explode("\n", trim($query));
  1024. foreach($queries as $query) {
  1025. $ret[$num] .= $query[0] == "#" ? NULL : $query;
  1026. }
  1027. $num++;
  1028. }
  1029. return($ret);
  1030. }
  1031. function slowcheck($type1, $type2) {
  1032. $t1 = explode(' ', $type1);$t1 = $t1[0];
  1033. $t2 = explode(' ', $type2);$t2 = $t2[0];
  1034. $arr = array($t1, $t2);
  1035. sort($arr);
  1036. if($arr == array('mediumtext', 'text')) {
  1037. return TRUE;
  1038. } elseif(substr($arr[0], 0, 4) == 'char' && substr($arr[1], 0, 7) == 'varchar') {
  1039. return TRUE;
  1040. }
  1041. return FALSE;
  1042. }
  1043. ?>