dbbak.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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: dbbak.php 35016 2014-10-13 08:16:14Z nemohou $
  7. */
  8. @define('IN_API', true);
  9. @define('CURSCRIPT', 'api');
  10. error_reporting(0);
  11. $code = @$_GET['code'];
  12. $apptype = @$_GET['apptype'];
  13. $apptype = strtolower($apptype);
  14. define('IN_COMSENZ', TRUE);
  15. if($apptype == 'discuzx') {
  16. define('ROOT_PATH', dirname(__FILE__).'/../../');
  17. } else {
  18. define('ROOT_PATH', dirname(__FILE__).'/../');
  19. }
  20. define('EXPLOR_SUCCESS', 0);
  21. define('IMPORT_SUCCESS', 0);
  22. define('DELETE_SQLPATH_SUCCESS', 4);
  23. define('MKDIR_ERROR', 1);
  24. define('DATABASE_EXPORT_FILE_INVALID', 2);
  25. define('RUN_SQL_ERROR', 3);
  26. define('SQLPATH_NULL_NOEXISTS', 4);
  27. define('SQLPATH_NOMATCH_BAKFILE', 5);
  28. define('BAK_FILE_LOSE', 6);
  29. define('DIR_NO_EXISTS', 7);
  30. define('DELETE_DUMPFILE_ERROR', 8);
  31. define('DB_API_NO_MATCH', 9);
  32. $sizelimit = 2000;
  33. $usehex = true;
  34. if($apptype == 'discuz') {
  35. require ROOT_PATH.'./config.inc.php';
  36. } elseif($apptype == 'uchome' || $apptype == 'supesite' || $apptype == 'supev') {
  37. require ROOT_PATH.'./config.php';
  38. } elseif($apptype == 'ucenter') {
  39. require ROOT_PATH.'./data/config.inc.php';
  40. } elseif($apptype == 'ecmall') {
  41. require ROOT_PATH.'./data/inc.config.php';
  42. } elseif($apptype == 'ecshop') {
  43. require ROOT_PATH.'./data/config.php';
  44. } elseif($apptype == 'discuzx') {
  45. require ROOT_PATH.'./config/config_global.php';
  46. require ROOT_PATH.'./config/config_ucenter.php';
  47. } else {
  48. api_msg('db_api_no_match', $apptype);
  49. }
  50. parse_str(_authcode($code, 'DECODE', UC_KEY), $get);
  51. if(get_magic_quotes_gpc()) {
  52. $get = _stripslashes($get);
  53. }
  54. if(empty($get)) {
  55. exit('Invalid Request');
  56. }
  57. $timestamp = time();
  58. if($timestamp - $get['time'] > 3600) {
  59. exit('Authracation has expiried');
  60. }
  61. $get['time'] = $timestamp;
  62. class dbstuff {
  63. var $querynum = 0;
  64. var $link;
  65. var $histories;
  66. var $time;
  67. var $tablepre;
  68. function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset, $pconnect = 0, $tablepre='', $time = 0) {
  69. $this->time = $time;
  70. $this->tablepre = $tablepre;
  71. if($pconnect) {
  72. if(!$this->link = mysql_pconnect($dbhost, $dbuser, $dbpw)) {
  73. $this->halt('Can not connect to MySQL server');
  74. }
  75. } else {
  76. if(!$this->link = mysql_connect($dbhost, $dbuser, $dbpw, 1)) {
  77. $this->halt('Can not connect to MySQL server');
  78. }
  79. }
  80. if($this->version() > '4.1') {
  81. if($dbcharset) {
  82. mysql_query("SET character_set_connection=".$dbcharset.", character_set_results=".$dbcharset.", character_set_client=binary", $this->link);
  83. }
  84. if($this->version() > '5.0.1') {
  85. mysql_query("SET sql_mode=''", $this->link);
  86. }
  87. }
  88. if($dbname) {
  89. mysql_select_db($dbname, $this->link);
  90. }
  91. }
  92. function fetch_array($query, $result_type = MYSQL_ASSOC) {
  93. return mysql_fetch_array($query, $result_type);
  94. }
  95. function result_first($sql) {
  96. $query = $this->query($sql);
  97. return $this->result($query, 0);
  98. }
  99. function fetch_first($sql) {
  100. $query = $this->query($sql);
  101. return $this->fetch_array($query);
  102. }
  103. function fetch_all($sql) {
  104. $arr = array();
  105. $query = $this->query($sql);
  106. while($data = $this->fetch_array($query)) {
  107. $arr[] = $data;
  108. }
  109. return $arr;
  110. }
  111. function cache_gc() {
  112. $this->query("DELETE FROM {$this->tablepre}sqlcaches WHERE expiry<$this->time");
  113. }
  114. function query($sql, $type = '', $cachetime = FALSE) {
  115. $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query';
  116. if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
  117. $this->halt('MySQL Query Error', $sql);
  118. }
  119. $this->querynum++;
  120. $this->histories[] = $sql;
  121. return $query;
  122. }
  123. function affected_rows() {
  124. return mysql_affected_rows($this->link);
  125. }
  126. function error() {
  127. return (($this->link) ? mysql_error($this->link) : mysql_error());
  128. }
  129. function errno() {
  130. return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
  131. }
  132. function result($query, $row) {
  133. $query = @mysql_result($query, $row);
  134. return $query;
  135. }
  136. function num_rows($query) {
  137. $query = mysql_num_rows($query);
  138. return $query;
  139. }
  140. function num_fields($query) {
  141. return mysql_num_fields($query);
  142. }
  143. function free_result($query) {
  144. return mysql_free_result($query);
  145. }
  146. function insert_id() {
  147. return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
  148. }
  149. function fetch_row($query) {
  150. $query = mysql_fetch_row($query);
  151. return $query;
  152. }
  153. function fetch_fields($query) {
  154. return mysql_fetch_field($query);
  155. }
  156. function version() {
  157. return mysql_get_server_info($this->link);
  158. }
  159. function escape_string($str) {
  160. return mysql_escape_string($str);
  161. }
  162. function close() {
  163. return mysql_close($this->link);
  164. }
  165. function halt($message = '', $sql = '') {
  166. api_msg('run_sql_error', $message.'<br /><br />'.$sql.'<br /> '.mysql_error());
  167. }
  168. }
  169. class dbstuffi {
  170. var $querynum = 0;
  171. var $link;
  172. var $histories;
  173. var $time;
  174. var $tablepre;
  175. function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset, $pconnect = 0, $tablepre='', $time = 0) {
  176. $this->time = $time;
  177. $this->tablepre = $tablepre;
  178. $this->link = new mysqli();
  179. if(!$this->link->real_connect($dbhost, $dbuser, $dbpw, $dbname, null, null, MYSQLI_CLIENT_COMPRESS)) {
  180. $this->halt('Can not connect to MySQL server');
  181. }
  182. if($this->version() > '4.1') {
  183. if($dbcharset) {
  184. $this->link->set_charset($dbcharset);
  185. }
  186. if($this->version() > '5.0.1') {
  187. $this->query("SET sql_mode=''");
  188. }
  189. }
  190. }
  191. function fetch_array($query, $result_type = MYSQLI_ASSOC) {
  192. return $query ? $query->fetch_array($result_type) : null;
  193. }
  194. function result_first($sql) {
  195. $query = $this->query($sql);
  196. return $this->result($query, 0);
  197. }
  198. function fetch_first($sql) {
  199. $query = $this->query($sql);
  200. return $this->fetch_array($query);
  201. }
  202. function fetch_all($sql) {
  203. $arr = array();
  204. $query = $this->query($sql);
  205. while($data = $this->fetch_array($query)) {
  206. $arr[] = $data;
  207. }
  208. return $arr;
  209. }
  210. function cache_gc() {
  211. $this->query("DELETE FROM {$this->tablepre}sqlcaches WHERE expiry<$this->time");
  212. }
  213. function query($sql, $type = '', $cachetime = FALSE) {
  214. $resultmode = $type == 'UNBUFFERED' ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT;
  215. if(!($query = $this->link->query($sql, $resultmode)) && $type != 'SILENT') {
  216. $this->halt('MySQL Query Error', $sql);
  217. }
  218. $this->querynum++;
  219. $this->histories[] = $sql;
  220. return $query;
  221. }
  222. function affected_rows() {
  223. return $this->link->affected_rows;
  224. }
  225. function error() {
  226. return (($this->link) ? $this->link->error : mysqli_error());
  227. }
  228. function errno() {
  229. return intval(($this->link) ? $this->link->errno : mysqli_errno());
  230. }
  231. function result($query, $row) {
  232. if(!$query || $query->num_rows == 0) {
  233. return null;
  234. }
  235. $query->data_seek($row);
  236. $assocs = $query->fetch_row();
  237. return $assocs[0];
  238. }
  239. function num_rows($query) {
  240. $query = $query ? $query->num_rows : 0;
  241. return $query;
  242. }
  243. function num_fields($query) {
  244. return $query ? $query->field_count : 0;
  245. }
  246. function free_result($query) {
  247. return $query ? $query->free() : false;
  248. }
  249. function insert_id() {
  250. return ($id = $this->link->insert_id) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
  251. }
  252. function fetch_row($query) {
  253. $query = $query ? $query->fetch_row() : null;
  254. return $query;
  255. }
  256. function fetch_fields($query) {
  257. return $query ? $query->fetch_field() : null;
  258. }
  259. function version() {
  260. return $this->link->server_info;
  261. }
  262. function escape_string($str) {
  263. return $this->link->escape_string($str);
  264. }
  265. function close() {
  266. return $this->link->close();
  267. }
  268. function halt($message = '', $sql = '') {
  269. api_msg('run_sql_error', $message.'<br /><br />'.$sql.'<br /> '.$this->link->error());
  270. }
  271. }
  272. $db = function_exists("mysql_connect") ? new dbstuff() : new dbstuffi();
  273. $version = '';
  274. if($apptype == 'discuz') {
  275. define('BACKUP_DIR', ROOT_PATH.'forumdata/');
  276. $tablepre = $tablepre;
  277. if(empty($dbcharset)) {
  278. $dbcharset = in_array(strtolower($charset), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $charset) : '';
  279. }
  280. $db->connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $pconnect, $tablepre);
  281. define('IN_DISCUZ', true);
  282. include ROOT_PATH.'discuz_version.php';
  283. $version = DISCUZ_VERSION;
  284. } elseif($apptype == 'uchome' || $apptype == 'supesite') {
  285. define('BACKUP_DIR', ROOT_PATH.'./data/');
  286. $tablepre = $_SC['tablepre'];
  287. $dbcharset = $_SC['dbcharset'];
  288. $db->connect($_SC['dbhost'], $_SC['dbuser'], $_SC['dbpw'], $_SC['dbname'], $dbcharset, $_SC['pconnect'], $tablepre);
  289. } elseif($apptype == 'ucenter') {
  290. define('BACKUP_DIR', ROOT_PATH.'./data/backup/');
  291. $tablepre = UC_DBTABLEPRE;
  292. $dbcharset = UC_DBCHARSET;
  293. $db->connect(UC_DBHOST, UC_DBUSER, UC_DBPW, UC_DBNAME, $dbcharset, UC_DBCONNECT, $tablepre);
  294. } elseif($apptype == 'ecmall') {
  295. define('BACKUP_DIR', ROOT_PATH.'./data/backup/');
  296. $tablepre = DB_PREFIX;
  297. $dbcharset = strtolower(str_replace('-', '', strstr(LANG, '-')));
  298. $cfg = parse_url(DB_CONFIG);
  299. if(empty($cfg['pass'])) {
  300. $cfg['pass'] = '';
  301. } else {
  302. $cfg['pass'] = urldecode($cfg['pass']);
  303. }
  304. $cfg['user'] = urldecode($cfg['user']);
  305. $cfg['path'] = str_replace('/', '', $cfg['path']);
  306. $db->connect($cfg['host'].':'.$cfg['port'], $cfg['user'], $cfg['pass'], $cfg['path'], $dbcharset, 0, $tablepre);
  307. } elseif($apptype == 'supev') {
  308. define('BACKUP_DIR', ROOT_PATH.'data/backup/');
  309. $tablepre = $tablepre;
  310. if(empty($dbcharset)) {
  311. $dbcharset = in_array(strtolower($_config['output']['charset']), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', CHARSET) : '';
  312. }
  313. $db->connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $pconnect, $tablepre);
  314. } elseif($apptype == 'ecshop') {
  315. define('BACKUP_DIR', ROOT_PATH.'data/backup/');
  316. $tablepre = $prefix;
  317. $dbcharset = 'utf8';
  318. $db->connect($db_host, $db_user, $db_pass, $db_name, $dbcharset, 0, $tablepre);
  319. } elseif($apptype == 'discuzx') {
  320. define('BACKUP_DIR', ROOT_PATH.'data/');
  321. extract($_config['db']['1']);
  322. if(empty($dbcharset)) {
  323. $dbcharset = in_array(strtolower(CHARSET), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $_config['output']['charset']) : '';
  324. }
  325. $db->connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $pconnect, $tablepre);
  326. define('IN_DISCUZ', true);
  327. include ROOT_PATH.'source/discuz_version.php';
  328. $version = DISCUZ_VERSION;
  329. }
  330. if($get['method'] == 'export') {
  331. $db->query('SET SQL_QUOTE_SHOW_CREATE=0', 'SILENT');
  332. $time = date("Y-m-d H:i:s", $timestamp);
  333. $tables = array();
  334. $tables = arraykeys2(fetchtablelist($tablepre), 'Name');
  335. if($apptype == 'discuz') {
  336. $query = $db->query("SELECT datatables FROM {$tablepre}plugins WHERE datatables<>''");
  337. while($plugin = $db->fetch_array($query)) {
  338. foreach(explode(',', $plugin['datatables']) as $table) {
  339. if($table = trim($table)) {
  340. $tables[] = $table;
  341. }
  342. }
  343. }
  344. }
  345. if($apptype == 'discuzx') {
  346. $query = $db->query("SELECT datatables FROM {$tablepre}common_plugin WHERE datatables<>''");
  347. while($plugin = $db->fetch_array($query)) {
  348. foreach(explode(',', $plugin['datatables']) as $table) {
  349. if($table = trim($table)) {
  350. $tables[] = $table;
  351. }
  352. }
  353. }
  354. }
  355. $memberexist = array_search("{$tablepre}common_member", $tables);
  356. if($memberexist !== FALSE) {
  357. unset($tables[$memberexist]);
  358. array_unshift($tables, "{$tablepre}common_member");
  359. }
  360. $get['volume'] = isset($get['volume']) ? intval($get['volume']) : 0;
  361. $get['volume'] = $get['volume'] + 1;
  362. $version = $version ? $version : $apptype;
  363. $idstring = '# Identify: '.base64_encode("$timestamp,$version,$apptype,multivol,$get[volume]")."\n";
  364. if(!isset($get['sqlpath']) || empty($get['sqlpath'])) {
  365. $get['sqlpath'] = 'backup_'.date('ymd', $timestamp).'_'.random(6);
  366. if(!mkdir(BACKUP_DIR.'./'.$get['sqlpath'], 0777)) {
  367. api_msg('mkdir_error', 'make dir error:'.BACKUP_DIR.'./'.$get['sqlpath']);
  368. }
  369. } else {
  370. $get['sqlpath'] = str_replace(array('/', '\\', '.', "'"), '', $get['sqlpath']);
  371. if(!is_dir(BACKUP_DIR.'./'.$get['sqlpath'])) {
  372. if(!mkdir(BACKUP_DIR.'./'.$get['sqlpath'], 0777)) {
  373. api_msg('mkdir_error', 'make dir error:'.BACKUP_DIR.'./'.$get['sqlpath']);
  374. }
  375. }
  376. }
  377. if(!isset($get['backupfilename']) || empty($get['backupfilename'])) {
  378. $get['backupfilename'] = date('ymd', $timestamp).'_'.random(6);
  379. }
  380. $sqldump = '';
  381. $get['tableid'] = isset($get['tableid']) ? intval($get['tableid']) : 0;
  382. $get['startfrom'] = isset($get['startfrom']) ? intval($get['startfrom']) : 0;
  383. if(!$get['tableid'] && $get['volume'] == 1) {
  384. foreach($tables as $table) {
  385. $sqldump .= sqldumptablestruct($table);
  386. }
  387. }
  388. $complete = TRUE;
  389. for(; $complete && $get['tableid'] < count($tables) && strlen($sqldump) + 500 < $sizelimit * 1000; $get['tableid']++) {
  390. $sqldump .= sqldumptable($tables[$get['tableid']], strlen($sqldump));
  391. if($complete) {
  392. $get['startfrom'] = 0;
  393. }
  394. }
  395. !$complete && $get['tableid']--;
  396. $dumpfile = BACKUP_DIR.$get['sqlpath'].'/'.$get['backupfilename'].'-'.$get['volume'].'.sql';
  397. if(trim($sqldump)) {
  398. $sqldump = "$idstring".
  399. "# <?exit();?>\n".
  400. "# $apptype Multi-Volume Data Dump Vol.$get[volume]\n".
  401. "# Time: $time\n".
  402. "# Type: $apptype\n".
  403. "# Table Prefix: $tablepre\n".
  404. "# $dbcharset\n".
  405. "# $apptype Home: http://www.comsenz.com\n".
  406. "# Please visit our website for newest infomation about $apptype\n".
  407. "# --------------------------------------------------------\n\n\n".
  408. $sqldump;
  409. @$fp = fopen($dumpfile, 'wb');
  410. @flock($fp, 2);
  411. if(@!fwrite($fp, $sqldump)) {
  412. @fclose($fp);
  413. api_msg('database_export_file_invalid', $dumpfile);
  414. } else {
  415. fclose($fp);
  416. auto_next($get, $dumpfile);
  417. }
  418. } else {
  419. @touch(ROOT_PATH.$get['sqlpath'].'/index.htm');
  420. api_msg('explor_success', 'explor_success');
  421. }
  422. } elseif($get['method'] == 'import') {
  423. if(!isset($get['dumpfile']) || empty($get['dumpfile'])) {
  424. $get['dumpfile'] = get_dumpfile_by_path($get['sqlpath']);
  425. $get['volume'] = 0;
  426. }
  427. $get['volume']++;
  428. $next_dumpfile = preg_replace('/^(\d+)\_(\w+)\-(\d+)\.sql$/', '\\1_\\2-'.$get['volume'].'.sql', $get['dumpfile']);
  429. if(!is_file(BACKUP_DIR.$get['sqlpath'].'/'.$get['dumpfile'])) {
  430. if(is_file(BACKUP_DIR.$get['sqlpath'].'/'.$next_dumpfile)) {
  431. api_msg('bak_file_lose', $get['dumpfile']);
  432. } else {
  433. api_msg('import_success', 'import_success');
  434. }
  435. }
  436. $sqldump = file_get_contents(BACKUP_DIR.$get['sqlpath'].'/'.$get['dumpfile']);
  437. $sqlquery = splitsql($sqldump);
  438. unset($sqldump);
  439. foreach($sqlquery as $sql) {
  440. $sql = syntablestruct(trim($sql), $db->version() > '4.1', $dbcharset);
  441. if($sql != '') {
  442. $db->query($sql, 'SILENT');
  443. if(($sqlerror = $db->error()) && $db->errno() != 1062) {
  444. $db->halt('MySQL Query Error', $sql);
  445. }
  446. }
  447. }
  448. $cur_file = $get['dumpfile'];
  449. $get['dumpfile'] = $next_dumpfile;
  450. auto_next($get, BACKUP_DIR.$get['sqlpath'].'/'.$cur_file);
  451. } elseif($get['method'] == 'ping') {
  452. if($get['dir'] && is_dir(BACKUP_DIR.$get['dir'])) {
  453. echo "1";exit;
  454. } else {
  455. echo "-1";exit;
  456. }
  457. } elseif($get['method'] == 'list') {
  458. $str = "<root>\n";
  459. $directory = dir(BACKUP_DIR);
  460. while($entry = $directory->read()) {
  461. $filename = BACKUP_DIR.$entry;
  462. if(is_dir($filename) && preg_match('/backup_(\d+)_\w+$/', $filename, $match)) {
  463. $str .= "\t<dir>\n";
  464. $str .= "\t\t<dirname>$filename</dirname>\n";
  465. $str .= "\t\t<dirdate>$match[1]</dirdate>\n";
  466. $str .= "\t</dir>\n";
  467. }
  468. }
  469. $directory->close();
  470. $str .= "</root>";
  471. echo $str;
  472. exit;
  473. } elseif($get['method'] == 'view') {
  474. $sqlpath = trim($get['sqlpath']);
  475. if(empty($sqlpath) || !is_dir(BACKUP_DIR.$sqlpath)) {
  476. api_msg('dir_no_exists', $sqlpath);
  477. }
  478. $str = "<root>\n";
  479. $directory = dir(BACKUP_DIR.$sqlpath);
  480. while($entry = $directory->read()) {
  481. $filename = BACKUP_DIR.$sqlpath.'/'.$entry;
  482. if(is_file($filename) && preg_match('/\d+_\w+\-(\d+).sql$/', $filename, $match)) {
  483. $str .= "\t<file>\n";
  484. $str .= "\t\t<file_name>$match[0]</file_name>\n";
  485. $str .= "\t\t<file_size>".filesize($filename)."</file_size>\n";
  486. $str .= "\t\t<file_num>$match[1]</file_num>\n";
  487. $str .= "\t\t<file_url>".str_replace(ROOT_PATH, 'http://'.$_SERVER['HTTP_HOST'].'/', $filename)."</file_url>\n";
  488. $str .= "\t\t<last_modify>".filemtime($filename)."</last_modify>\n";
  489. $str .= "\t</file>\n";
  490. }
  491. }
  492. $directory->close();
  493. $str .= "</root>";
  494. echo $str;
  495. exit;
  496. } elseif($get['method'] == 'delete') {
  497. $sqlpath = trim($get['sqlpath']);
  498. if(empty($sqlpath) || !is_dir(BACKUP_DIR.$sqlpath)) {
  499. api_msg('dir_no_exists', $sqlpath);
  500. }
  501. $directory = dir(BACKUP_DIR.$sqlpath);
  502. while($entry = $directory->read()) {
  503. $filename = BACKUP_DIR.$sqlpath.'/'.$entry;
  504. if(is_file($filename) && preg_match('/\d+_\w+\-(\d+).sql$/', $filename) && !@unlink($filename)) {
  505. api_msg('delete_dumpfile_error', $filename);
  506. }
  507. }
  508. $directory->close();
  509. @rmdir(BACKUP_DIR.$sqlpath);
  510. api_msg('delete_sqlpath_success', 'delete_sqlpath_success');
  511. }
  512. function syntablestruct($sql, $version, $dbcharset) {
  513. if(strpos(trim(substr($sql, 0, 18)), 'CREATE TABLE') === FALSE) {
  514. return $sql;
  515. }
  516. $sqlversion = strpos($sql, 'ENGINE=') === FALSE ? FALSE : TRUE;
  517. if($sqlversion === $version) {
  518. return $sqlversion && $dbcharset ? preg_replace(array('/ character set \w+/i', '/ collate \w+/i', "/DEFAULT CHARSET=\w+/is"), array('', '', "DEFAULT CHARSET=$dbcharset"), $sql) : $sql;
  519. }
  520. if($version) {
  521. return preg_replace(array('/TYPE=HEAP/i', '/TYPE=(\w+)/is'), array("ENGINE=MEMORY DEFAULT CHARSET=$dbcharset", "ENGINE=\\1 DEFAULT CHARSET=$dbcharset"), $sql);
  522. } else {
  523. 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);
  524. }
  525. }
  526. function splitsql($sql) {
  527. $sql = str_replace("\r", "\n", $sql);
  528. $ret = array();
  529. $num = 0;
  530. $queriesarray = explode(";\n", trim($sql));
  531. unset($sql);
  532. foreach($queriesarray as $query) {
  533. $ret[$num] = isset($ret[$num]) ? $ret[$num] : '';
  534. $queries = explode("\n", trim($query));
  535. foreach($queries as $query) {
  536. $ret[$num] .= isset($query[0]) && $query[0] == "#" ? NULL : $query;
  537. }
  538. $num++;
  539. }
  540. return($ret);
  541. }
  542. function get_dumpfile_by_path($path) {
  543. if(empty($path) || !is_dir(BACKUP_DIR.$path)) {
  544. api_msg('sqlpath_null_noexists', $path);
  545. }
  546. $directory = dir(BACKUP_DIR.$path);
  547. while($entry = $directory->read()) {
  548. $filename = BACKUP_DIR.$path.'/'.$entry;
  549. if(is_file($filename)) {
  550. if(preg_match('/^\d+\_\w+\-\d+\.sql$/', $entry)) {
  551. $file_bakfile = preg_replace('/^(\d+)\_(\w+)\-(\d+)\.sql$/', '\\1_\\2-1.sql', $entry);
  552. if(is_file(BACKUP_DIR.$path.'/'.$file_bakfile)) {
  553. return $file_bakfile;
  554. } else {
  555. api_msg('sqlpath_nomatch_bakfile', $path);
  556. }
  557. }
  558. }
  559. }
  560. $directory->close();
  561. api_msg('sqlpath_nomatch_bakfile', $path);
  562. }
  563. function api_msg($code, $msg) {
  564. $msg = htmlspecialchars($msg);
  565. $out = "<root>\n";
  566. $out .= "\t<error errorCode=\"".constant(strtoupper($code))."\" errorMessage=\"$msg\" />\n";
  567. $out .= "\t<fileinfo>\n";
  568. $out .= "\t\t<file_num></file_num>\n";
  569. $out .= "\t\t<file_size></file_size>\n";
  570. $out .= "\t\t<file_name></file_name>\n";
  571. $out .= "\t\t<file_url></file_url>\n";
  572. $out .= "\t\t<last_modify></last_modify>\n";
  573. $out .= "\t</fileinfo>\n";
  574. $out .= "\t<nexturl></nexturl>\n";
  575. $out .= "</root>";
  576. echo $out;
  577. exit;
  578. }
  579. function arraykeys2($array, $key2) {
  580. $return = array();
  581. foreach($array as $val) {
  582. $return[] = $val[$key2];
  583. }
  584. return $return;
  585. }
  586. function auto_next($get, $sqlfile) {
  587. $next_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?apptype='.$GLOBALS['apptype'].'&code='.urlencode(encode_arr($get));
  588. $out = "<root>\n";
  589. $out .= "\t<error errorCode=\"0\" errorMessage=\"ok\" />\n";
  590. $out .= "\t<fileinfo>\n";
  591. $out .= "\t\t<file_num>$get[volume]</file_num>\n";
  592. $out .= "\t\t<file_size>".filesize($sqlfile)."</file_size>\n";
  593. $out .= "\t\t<file_name>".basename($sqlfile)."</file_name>\n";
  594. $out .= "\t\t<file_url>".str_replace(ROOT_PATH, 'http://'.$_SERVER['HTTP_HOST'].'/', $sqlfile)."</file_url>\n";
  595. $out .= "\t\t<last_modify>".filemtime($sqlfile)."</last_modify>\n";
  596. $out .= "\t</fileinfo>\n";
  597. $out .= "\t<nexturl><![CDATA[$next_url]]></nexturl>\n";
  598. $out .= "</root>";
  599. echo $out;
  600. exit;
  601. }
  602. function encode_arr($get) {
  603. $tmp = '';
  604. foreach($get as $key => $val) {
  605. $tmp .= '&'.$key.'='.$val;
  606. }
  607. return _authcode($tmp, 'ENCODE', UC_KEY);
  608. }
  609. function sqldumptablestruct($table) {
  610. global $db;
  611. $createtable = $db->query("SHOW CREATE TABLE $table", 'SILENT');
  612. if(!$db->error()) {
  613. $tabledump = "DROP TABLE IF EXISTS $table;\n";
  614. } else {
  615. return '';
  616. }
  617. $create = $db->fetch_row($createtable);
  618. if(strpos($table, '.') !== FALSE) {
  619. $tablename = substr($table, strpos($table, '.') + 1);
  620. $create[1] = str_replace("CREATE TABLE $tablename", 'CREATE TABLE '.$table, $create[1]);
  621. }
  622. $tabledump .= $create[1];
  623. $tablestatus = $db->fetch_first("SHOW TABLE STATUS LIKE '$table'");
  624. $tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
  625. return $tabledump;
  626. }
  627. function sqldumptable($table, $currsize = 0) {
  628. global $get, $db, $sizelimit, $startrow, $extendins, $sqlcompat, $sqlcharset, $dumpcharset, $usehex, $complete, $excepttables;
  629. $offset = 300;
  630. $tabledump = '';
  631. $tablefields = array();
  632. $query = $db->query("SHOW FULL COLUMNS FROM $table", 'SILENT');
  633. if(strexists($table, 'adminsessions')) {
  634. return ;
  635. } elseif(!$query && $db->errno() == 1146) {
  636. return;
  637. } elseif(!$query) {
  638. $usehex = FALSE;
  639. } else {
  640. while($fieldrow = $db->fetch_array($query)) {
  641. $tablefields[] = $fieldrow;
  642. }
  643. }
  644. $tabledumped = 0;
  645. $numrows = $offset;
  646. $firstfield = $tablefields[0];
  647. while($currsize + strlen($tabledump) + 500 < $sizelimit * 1000 && $numrows == $offset) {
  648. if($firstfield['Extra'] == 'auto_increment') {
  649. $selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $get[startfrom] LIMIT $offset";
  650. } else {
  651. $selectsql = "SELECT * FROM $table LIMIT $get[startfrom], $offset";
  652. }
  653. $tabledumped = 1;
  654. $rows = $db->query($selectsql);
  655. $numfields = $db->num_fields($rows);
  656. $numrows = $db->num_rows($rows);
  657. while($row = $db->fetch_row($rows)) {
  658. $comma = $t = '';
  659. for($i = 0; $i < $numfields; $i++) {
  660. $t .= $comma.($usehex && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.$db->escape_string($row[$i]).'\'');
  661. $comma = ',';
  662. }
  663. if(strlen($t) + $currsize + strlen($tabledump) + 500 < $sizelimit * 1000) {
  664. if($firstfield['Extra'] == 'auto_increment') {
  665. $get['startfrom'] = $row[0];
  666. } else {
  667. $get['startfrom']++;
  668. }
  669. $tabledump .= "INSERT INTO $table VALUES ($t);\n";
  670. } else {
  671. $complete = FALSE;
  672. break 2;
  673. }
  674. }
  675. }
  676. $tabledump .= "\n";
  677. return $tabledump;
  678. }
  679. function random($length, $numeric = 0) {
  680. PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
  681. if($numeric) {
  682. $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
  683. } else {
  684. $hash = '';
  685. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
  686. $max = strlen($chars) - 1;
  687. for($i = 0; $i < $length; $i++) {
  688. $hash .= $chars[mt_rand(0, $max)];
  689. }
  690. }
  691. return $hash;
  692. }
  693. function fetchtablelist($tablepre = '') {
  694. global $db;
  695. $arr = explode('.', $tablepre);
  696. $dbname = isset($arr[1]) && $arr[1] ? $arr[0] : '';
  697. $tablepre = str_replace('_', '\_', $tablepre);
  698. $sqladd = $dbname ? " FROM $dbname LIKE '$arr[1]%'" : "LIKE '$tablepre%'";
  699. $tables = $table = array();
  700. $query = $db->query("SHOW TABLE STATUS $sqladd");
  701. while($table = $db->fetch_array($query)) {
  702. $table['Name'] = ($dbname ? "$dbname." : '').$table['Name'];
  703. $tables[] = $table;
  704. }
  705. return $tables;
  706. }
  707. function _stripslashes($string) {
  708. if(is_array($string)) {
  709. foreach($string as $key => $val) {
  710. $string[$key] = _stripslashes($val);
  711. }
  712. } else {
  713. $string = stripslashes($string);
  714. }
  715. return $string;
  716. }
  717. function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
  718. $ckey_length = 4;
  719. $key = md5($key ? $key : UC_KEY);
  720. $keya = md5(substr($key, 0, 16));
  721. $keyb = md5(substr($key, 16, 16));
  722. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
  723. $cryptkey = $keya.md5($keya.$keyc);
  724. $key_length = strlen($cryptkey);
  725. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
  726. $string_length = strlen($string);
  727. $result = '';
  728. $box = range(0, 255);
  729. $rndkey = array();
  730. for($i = 0; $i <= 255; $i++) {
  731. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  732. }
  733. for($j = $i = 0; $i < 256; $i++) {
  734. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  735. $tmp = $box[$i];
  736. $box[$i] = $box[$j];
  737. $box[$j] = $tmp;
  738. }
  739. for($a = $j = $i = 0; $i < $string_length; $i++) {
  740. $a = ($a + 1) % 256;
  741. $j = ($j + $box[$a]) % 256;
  742. $tmp = $box[$a];
  743. $box[$a] = $box[$j];
  744. $box[$j] = $tmp;
  745. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  746. }
  747. if($operation == 'DECODE') {
  748. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
  749. return substr($result, 26);
  750. } else {
  751. return '';
  752. }
  753. } else {
  754. return $keyc.str_replace('=', '', base64_encode($result));
  755. }
  756. }
  757. function strexists($haystack, $needle) {
  758. return !(strpos($haystack, $needle) === FALSE);
  759. }
  760. ?>