dbbak.php 25 KB

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