PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/sxd/index.php

https://bitbucket.org/ssimpledecision/simpledecision
PHP | 1976 lines | 1882 code | 39 blank | 55 comment | 381 complexity | de56fc1519f9837c0c8b44ee13ec4d75 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. session_start();
  3. include '../../inc/connect_db.php';
  4. function getUserType(){
  5. if (isset($_SESSION['user_id'])){
  6. global $pref;
  7. $sql = "select * from {$pref}db_users where id='{$_SESSION['user_id']}' limit 1";
  8. return mysql_result(mysql_query($sql),0, 'type');
  9. }
  10. }
  11. /***************************************************************************\
  12. | Sypex Dumper version 2.0.10 |
  13. | (c) 2003-2011 zapimir zapimir@zapimir.net http://sypex.net/ |
  14. | (c) 2005-2011 BINOVATOR info@sypex.net |
  15. |---------------------------------------------------------------------------|
  16. | created: 2003.09.02 19:07 modified: 2012.11.14 06:27 |
  17. |---------------------------------------------------------------------------|
  18. | Sypex Dumper is released under the terms of the BSD license |
  19. | http://sypex.net/bsd_license.txt |
  20. \***************************************************************************/
  21. header("Expires: Wed, 19 Nov 2008 19:19:19 GMT");
  22. header("Cache-Control: no-store, no-cache, must-revalidate");
  23. header("Content-Type: text/html; charset=utf-8");
  24. //error_reporting(E_ALL);
  25. error_reporting(0);
  26. if (!ini_get('zlib.output_compression') && function_exists('ob_gzhandler')) ob_start('ob_gzhandler');
  27. set_error_handler('sxd_error_handler');
  28. register_shutdown_function('sxd_shutdown');
  29. $SXD = new Sypex_Dumper();
  30. chdir(dirname(__FILE__));
  31. $SXD->init(!empty($argc) && $argc > 1 ? $argv : false);
  32. class Sypex_Dumper {
  33. function Sypex_Dumper() {
  34. define('C_DEFAULT', 1);
  35. define('C_RESULT', 2);
  36. define('C_ERROR', 3);
  37. define('C_WARNING', 4);
  38. define('SXD_DEBUG', false);
  39. define('TIMER', array_sum(explode(' ', microtime())));
  40. define('V_SXD', 20010);
  41. define('V_PHP', sxd_ver2int(phpversion()));
  42. $this->name = 'Sypex Dumper 2.0.10';
  43. }
  44. function loadLang($lng_name = 'auto'){
  45. if($lng_name == 'auto'){
  46. include('lang/list.php');
  47. $this->langs = &$langs;
  48. $lng = 'en';
  49. if(preg_match_all('/[a-z]{2}(-[a-z]{2})?/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $m)) {
  50. foreach($m[0] AS $l){
  51. if(isset($langs[$l])){
  52. $lng_name = $l;
  53. break;
  54. }
  55. }
  56. }
  57. }
  58. if(file_exists("lang/lng_{$lng_name}.php")) include("lang/lng_{$lng_name}.php");
  59. else include("lang/lng_en.php");
  60. $this->LNG = &$LNG;
  61. $this->LNG['name'] = $lng_name;
  62. return true;
  63. }
  64. function init($args = false){
  65. if (get_magic_quotes_gpc()) {
  66. $_POST = sxd_antimagic($_POST);
  67. }
  68. include('cfg.php');
  69. $this->loadLang($CFG['lang']);
  70. if (!ini_get('safe_mode') && function_exists('set_time_limit') && strpos(ini_get('disable_functions'), 'set_time_limit') === false) @set_time_limit($CFG['time_web']);
  71. elseif (ini_get('max_execution_time') < $CFG['time_web']) $CFG['time_web'] = ini_get('max_execution_time');
  72. $this->CFG = &$CFG;
  73. $this->try = false;
  74. $this->virtualize = false;
  75. $this->cron_mode = false;
  76. // Проверяем авторизацию и делаем коннект к базе
  77. if(empty($this->CFG['my_user'])){
  78. $this->CFG['my_host'] = 'localhost';
  79. $this->CFG['my_port'] = 3306;
  80. $this->CFG['my_user'] = 'root';
  81. $this->CFG['my_pass'] = '';
  82. $this->CFG['my_comp'] = 0;
  83. $this->CFG['my_db'] = '';
  84. }
  85. if ($args) { // консольный режим
  86. foreach($args AS $key => $arg){
  87. if (preg_match("/^-([hupoj])=(.*?)$/", $arg, $m)){
  88. switch ($m[1]) {
  89. case 'h': $this->CFG['my_host'] = $m[2]; break; // хост
  90. case 'o': $this->CFG['my_port'] = $m[2]; break; // порт
  91. case 'u': $this->CFG['my_user'] = $m[2]; break; // логин
  92. case 'p': $this->CFG['my_pass'] = $m[2]; break; // пароль
  93. case 'j': $this->CFG['sjob'] = $m[2]; break; // job-файл
  94. }
  95. }
  96. }
  97. $this->cron_mode = true;
  98. set_time_limit($CFG['time_cron']);
  99. // Загружаем конфиг файл, если нужно
  100. $auth = $this->connect();
  101. if($auth && !empty($this->CFG['sjob'])){
  102. $this->ajax($this->loadJob($this->CFG['sjob']));
  103. echo file_get_contents($this->JOB['file_log']);
  104. if(file_exists($this->JOB['file_log'])) unlink($this->JOB['file_log']);
  105. if(file_exists($this->JOB['file_rtl'])) unlink($this->JOB['file_rtl']);
  106. }
  107. else echo 'Auth error';
  108. exit;
  109. }
  110. elseif(!empty($this->CFG['auth'])){ // Авторизация
  111. $auth = false;
  112. $sfile = 'ses.php';
  113. if(!empty($_COOKIE['sxd']) && preg_match('/^[\da-f]{32}$/', $_COOKIE['sxd'])){
  114. include($sfile);
  115. if(isset($SES[$_COOKIE['sxd']])) {
  116. $auth = true;
  117. $this->CFG = $SES[$_COOKIE['sxd']]['cfg'];
  118. $this->SES = &$SES;
  119. $this->loadLang($this->CFG['lang']);
  120. }
  121. }
  122. if(!$auth) {
  123. if (!empty($_SESSION['user_id']) && getUserType()==2){
  124. global $db_user,$db_pass,$db_host;
  125. $user = $db_user;
  126. $pass = $db_pass;
  127. $host = $db_host;
  128. $port = 3306;
  129. } else{
  130. $user = !empty($_POST['user']) ? $_POST['user'] : '';
  131. $pass = !empty($_POST['pass']) ? $_POST['pass'] : '';
  132. $host = !empty($_POST['host']) ? $_POST['host'] : (!empty($this->CFG['my_host']) ? $this->CFG['my_host'] : 'localhost');
  133. $port = !empty($_POST['port']) && is_numeric($_POST['port']) ? $_POST['port'] : 3306;
  134. }
  135. $temp = preg_split('/\s+/', $this->CFG['auth']);
  136. if(!empty($_REQUEST['lang']) && preg_match('/^[a-z]{2}(-[a-z]{2})?$/', $_REQUEST['lang'])) {$this->loadLang($_REQUEST['lang']);}
  137. foreach($temp AS $a){
  138. switch($a) {
  139. case 'cfg': if(empty($user)) {continue;}
  140. $auth = !empty($CFG['user']) && isset($CFG['pass']) && $CFG['user']== $user && $CFG['pass'] == $pass;
  141. break;
  142. case 'mysql': if(empty($user)) {continue;}
  143. if($host != 'localhost' && !empty($this->CFG['my_host']) && $this->CFG['my_host'] != $host) {continue;}
  144. $auth = $this->connect($host, $port, $user, $pass);
  145. break;
  146. default: $file = 'auth_' . $a . '.php';
  147. if(!file_exists($file)) continue;
  148. include $file;
  149. }
  150. if($auth) break;
  151. }
  152. if($auth){
  153. $key = md5(rand(1,100000) . $user . microtime());
  154. $CFG['lang'] = $this->LNG['name'];
  155. $_COOKIE['sxd'] = $key;
  156. $this->saveCFG();
  157. if(V_PHP > 50200) setcookie('sxd', $key, !empty($_POST['save']) ? time() + 31536000 : 0, '', '', false, true);
  158. else setcookie('sxd', $key, !empty($_POST['save']) ? time() + 31536000 : 0, '', '', false);
  159. header("Location: ./");
  160. exit;
  161. }
  162. foreach(array('user', 'pass', 'host', 'port') AS $key){
  163. $_POST[$key] = !empty($_POST[$key]) ? htmlspecialchars($_POST[$key], ENT_NOQUOTES) : '';
  164. }
  165. $_POST['save'] = !empty($_POST['save']) ? ' CHECKED' : '';
  166. }
  167. if (!$auth) {
  168. if(!empty($_POST['ajax'])){
  169. echo "sxd.hideLoading();alert('Session not found');";
  170. exit;
  171. }
  172. $this->lng_list = '<option value="auto">- auto -</opinion>';
  173. if(!isset($this->langs)) {include('lang/list.php');$this->langs = &$langs;}
  174. foreach($this->langs AS $k => $v){
  175. $this->lng_list .= "<option value=\"{$k}\"" . ($k == (!empty($_REQUEST['lang']) ? $this->LNG['name'] : $this->CFG['lang']) ? ' SELECTED' : '') . ">{$v}</opinion>";
  176. }
  177. echo sxd_tpl_auth();
  178. exit;
  179. }
  180. }
  181. if(empty($_POST['ajax']['act']) || $_POST['ajax']['act'] != 'save_connect') $this->connect();
  182. if(isset($_POST['ajax'])) $this->ajax($_POST['ajax']);
  183. else $this->main();exit;
  184. }
  185. function saveToFile($name, $content){
  186. $fp = fopen($name, "w");
  187. fwrite($fp, $content);
  188. fclose($fp);
  189. }
  190. function connect($host = null, $port = null, $user = null, $pass = null){
  191. $this->error = '';
  192. $this->try = true;
  193. if(!empty($user) && isset($pass)) {
  194. $this->CFG['my_host'] = $host;
  195. $this->CFG['my_port'] = $port;
  196. $this->CFG['my_user'] = $user;
  197. $this->CFG['my_pass'] = $pass;
  198. }
  199. if(mysql_connect($this->CFG['my_host'] . ($this->CFG['my_host']{0} != ':' ? ":{$this->CFG['my_port']}" : ''), $this->CFG['my_user'], $this->CFG['my_pass'])) {
  200. if(V_PHP > 50202) mysql_set_charset('utf8') or sxd_my_error();
  201. else mysql_query('SET NAMES utf8') or sxd_my_error();
  202. define('V_MYSQL', sxd_ver2int(mysql_get_server_info()));
  203. }
  204. else {
  205. define('V_MYSQL', 0);
  206. $this->error = "sxd.actions.tab_connects();alert(" . sxd_esc(mysql_error()) . ");";
  207. }
  208. $this->try = false;
  209. return V_MYSQL ? true: false;
  210. }
  211. function main(){
  212. // Тулбар
  213. $this->VAR['toolbar'] = sxd_php2json(
  214. array(
  215. array('backup', $this->LNG['tbar_backup'], 1, 3),
  216. array('restore', $this->LNG['tbar_restore'], 2, 3),
  217. array('|'),
  218. array('files', $this->LNG['tbar_files'], 3, 1),
  219. array('services', $this->LNG['tbar_services'], 5, 1),
  220. array('|'),
  221. array('createdb', $this->LNG['tbar_createdb'], 7, 0),
  222. array('connects', $this->LNG['tbar_connects'], 6, 0),
  223. array('|'),
  224. array('options', $this->LNG['tbar_options'], 4, 1),
  225. array('|'),
  226. array('exit', $this->LNG['tbar_exit'], 8, 1),
  227. )
  228. );
  229. $this->db = 'temp';
  230. $zip = array($this->LNG['zip_none']);
  231. if (function_exists("gzopen")) {
  232. for($i = 1; $i <10; $i++){
  233. $zip[] = "GZip: {$i}";
  234. }
  235. $zip[1] .= " ({$this->LNG['zip_min']})";
  236. $zip[7] .= " ({$this->LNG['default']})";
  237. }
  238. if (function_exists("bzopen")) {
  239. $zip[10] = "BZip";
  240. }
  241. end($zip);
  242. $zip[key($zip)] .= " ({$this->LNG['zip_max']})";
  243. $this->VAR['combos'] =
  244. $this->addCombo('backup_db', $this->db, 11, 'db', array()/*$this->getDBList()*/) .
  245. $this->addCombo('backup_charset', 0, 9, 'charset', $this->getCharsetList()) .
  246. $this->addCombo('backup_zip', 7, 10, 'zip', $zip) .
  247. $this->addCombo('restore_db', $this->db, 11, 'db') .
  248. $this->addCombo('restore_charset', 0, 9, 'charset') .
  249. $this->addCombo('restore_file', 0, 12, 'files', $this->getFileList()) .
  250. $this->addCombo('restore_type', 0, 13, 'types', array("CREATE + INSERT ({$this->LNG['default']})", 'TRUNCATE + INSERT', 'REPLACE', 'INSERT IGNORE')) .
  251. $this->addCombo('services_db', $this->db, 11, 'db') .
  252. $this->addCombo('services_check', 0, 5, 'check', array("- {$this->LNG['default']} -", 'QUICK', 'FAST', 'CHANGED', 'MEDIUM', 'EXTENDED')) .
  253. $this->addCombo('services_repair', 0, 5, 'repair', array("- {$this->LNG['default']} -", 'QUICK', 'EXTENDED')) .
  254. $this->addCombo('db_charset', 0, 9, 'collation', $this->getCollationList()) .
  255. $this->addCombo('db_charset_col', 0, 15, 'collation:db_charset')
  256. ;
  257. if (!V_MYSQL) $this->VAR['combos'] .= $this->error;
  258. $this->VAR['combos'] .= $this->getSavedJobs() . "sxd.confirms = {$this->CFG['confirm']};sxd.actions.dblist();";
  259. $this->LNG['del_date'] = sprintf($this->LNG['del_date'], '<input type="text" id="del_time" class=txt style="width:24px;" maxlength="3">');
  260. $this->LNG['del_count'] = sprintf($this->LNG['del_count'], '<input id="del_count" type="text" class=txt style="width:18px;" maxlength="2">');
  261. echo sxd_tpl_page();
  262. }
  263. function addCombo($name, $sel, $ico, $opt_name, $opts = ''){
  264. $opts = !empty($opts) ? "{{$opt_name}:" . sxd_php2json($opts) . '}' : "'{$opt_name}'";
  265. return "sxd.addCombo('{$name}', '{$sel}', {$ico}, {$opts});\n";
  266. }
  267. function ajax($req){
  268. $res = '';
  269. $act = $req['act'];
  270. if($req['act'] == 'run_savedjob'){
  271. $req = $this->loadJob($req);
  272. }
  273. switch($req['act']){
  274. case 'load_db':
  275. $res = $this->getObjects(str_replace('_db', '', $req['name']), $req['value']);
  276. break;
  277. case 'load_files':
  278. $res = $this->getFileObjects('restore', $req['value']);
  279. break;
  280. case 'filelist':
  281. $res = "sxd.clearOpt('files');sxd.addOpt(" . sxd_php2json(array('files' => $this->getFileList())) . ");";
  282. break;
  283. case 'dblist':
  284. $res = "sxd.clearOpt('db');sxd.addOpt(" . sxd_php2json(array('db' => $this->getDBList())) . ");sxd.combos.restore_db.select(0,'-');sxd.combos.services_db.select(0,'-');sxd.combos.backup_db.select(0,'-');";
  285. break;
  286. case 'load_connect':
  287. $CFG = $this->cfg2js($this->CFG);
  288. $res = "z('con_host').value = '{$CFG['my_host']}', z('con_port').value = '{$CFG['my_port']}', z('con_user').value = '{$CFG['my_user']}',
  289. z('con_pass').value = '', z('con_comp').checked = {$CFG['my_comp']}, z('con_db').value = '{$CFG['my_db']}', z('con_pass').changed = false;" ;
  290. break;
  291. case 'save_connect':
  292. $res = $this->saveConnect($req);
  293. break;
  294. case 'save_job':
  295. unset($req['act']);
  296. $this->saveJob('sj_' . $req['job'] , $req);
  297. $res = $this->getSavedJobs();
  298. break;
  299. case 'add_db':
  300. $res = $this->addDb($req);
  301. break;
  302. case 'load_options':
  303. $CFG = $this->cfg2js($this->CFG);
  304. $res = "z('time_web').value = '{$CFG['time_web']}', z('time_cron').value = '{$CFG['time_cron']}', z('backup_path').value = '{$CFG['backup_path']}',
  305. z('backup_url').value = '{$CFG['backup_url']}', z('globstat').checked = {$CFG['globstat']}, z('charsets').value = '{$CFG['charsets']}', z('only_create').value = '{$CFG['only_create']}', z('auth').value = '{$CFG['auth']}', z('conf_import').checked = {$CFG['confirm']} & 1, z('conf_file').checked = {$CFG['confirm']} & 2, z('conf_db').checked = {$CFG['confirm']} & 4;sxd.confirms = {$this->CFG['confirm']};";
  306. break;
  307. case 'save_options':
  308. $res = $this->saveOptions($req);
  309. break;
  310. case 'delete_file':
  311. if(preg_match('/^[^\/]+?\.sql(\.(gz|bz2))?$/', $req['name'])) {
  312. $file = $this->CFG['backup_path'] . $req['name'];
  313. if(file_exists($file)) unlink($file);
  314. }
  315. $res = $this->getFileListExtended();
  316. break;
  317. case 'delete_db':
  318. $res = $this->deleteDB($req['name']);
  319. break;
  320. case 'load_files_ext':
  321. $res .= $this->getFileListExtended();
  322. break;
  323. case 'services':
  324. $this->runServices($req);
  325. break;
  326. case 'backup':
  327. $this->addBackupJob($req);
  328. break;
  329. case 'restore':
  330. $this->addRestoreJob($req);
  331. break;
  332. case 'resume':
  333. $this->resumeJob($req);
  334. break;
  335. case 'exit':
  336. setcookie('sxd', '', 0);
  337. $res = "top.location.href = " . sxd_esc($this->CFG['exitURL']) . ";";
  338. break;
  339. }
  340. echo $res;
  341. }
  342. function loadJob($job){
  343. $file = $this->CFG['backup_path'] . 'sj_' . (is_array($job) ? $job['job'] : $job) . '.job.php';
  344. if(!file_exists($file)) return;
  345. include($file);
  346. $JOB['act'] = $JOB['type'];
  347. $JOB['type'] = 'run';
  348. return $JOB;
  349. }
  350. function deleteDB($name){
  351. $r = mysql_query('DROP DATABASE `' . sxd_esc($name, false) . '`') or sxd_my_error();
  352. if($r){
  353. echo "sxd.clearOpt('db');sxd.addOpt(" . sxd_php2json(array('db' => $this->getDBList())) . ");sxd.combos.services_db.select(0,'-');";
  354. }
  355. else
  356. echo "alert(" . sxd_esc(mysql_error()) . ");";
  357. }
  358. function cfg2js($cfg){
  359. foreach($cfg AS $k => $v){
  360. $cfg[$k] = sxd_esc($v, false);
  361. }
  362. return $cfg;
  363. }
  364. function addDb($req){
  365. $r = mysql_query('CREATE DATABASE `' . sxd_esc($req['name'], false) . '`' . (V_MYSQL > 40100 ? "CHARACTER SET {$req['charset']} COLLATE {$req['collate']}" : ''));
  366. if($r)
  367. echo "sxd.addOpt(" . sxd_php2json(array('db' => array($req['name'] => "{$req['name']} (0)"))) . ");";
  368. else
  369. sxd_my_error();
  370. }
  371. function saveConnect($req){
  372. $this->CFG['my_host'] = $req['host'];
  373. $this->CFG['my_port'] = (int)$req['port'];
  374. $this->CFG['my_user'] = $req['user'];
  375. if(isset($req['pass'])) $this->CFG['my_pass'] = $req['pass'];
  376. $this->CFG['my_comp'] = $req['comp'] ? 1 : 0;
  377. $this->CFG['my_db'] = $req['db'];
  378. $this->saveCFG();
  379. $this->connect();
  380. if (V_MYSQL) {
  381. $tmp = array(
  382. 'db' => $this->getDBList(),
  383. 'charset' => $this->getCharsetList(),
  384. 'collation' => $this->getCollationList()
  385. );
  386. echo "sxd.clearOpt('db');sxd.clearOpt('charset');sxd.clearOpt('collation');sxd.addOpt(" . sxd_php2json($tmp) . ");sxd.combos.backup_db.select(0,'-');sxd.combos.restore_db.select(0,'-');sxd.combos.services_db.select(0,'-');sxd.combos.backup_charset.select(0,'-');sxd.combos.services_db.select(0,'-');sxd.combos.db_charset.select(0,'-');";
  387. }
  388. else {
  389. echo $this->error;
  390. }
  391. }
  392. function saveOptions($req){
  393. $this->CFG['time_web'] = $req['time_web'];
  394. $this->CFG['time_cron'] = $req['time_cron'];
  395. $this->CFG['backup_path'] = $req['backup_path'];
  396. $this->CFG['backup_url'] = $req['backup_url'];
  397. $this->CFG['globstat'] = $req['globstat'] ? 1 : 0;
  398. $this->CFG['charsets'] = $req['charsets'];
  399. $this->CFG['only_create'] = $req['only_create'];
  400. $this->CFG['auth'] = $req['auth'];
  401. $this->CFG['confirm'] = $req['confirm'];
  402. $this->saveCFG();
  403. }
  404. function saveCFG(){
  405. if (isset($_COOKIE['sxd'])) {
  406. $this->SES[$_COOKIE['sxd']] = array('cfg' => $this->CFG, 'time' => time(), 'lng' => $this->LNG['name']);
  407. $this->saveToFile('ses.php', "<?php\n\$SES = " . var_export($this->SES, true) . ";\n" . "?>");
  408. }
  409. if (!$this->virtualize){
  410. $this->saveToFile('cfg.php', "<?php\n\$CFG = " . var_export($this->CFG, true) . ";\n" . "?>");
  411. }
  412. }
  413. function runServices($job) {
  414. $serv = array('optimize' => 'OPTIMIZE', 'analyze' => 'ANALYZE', 'check' => 'CHECK', 'repair' => 'REPAIR');
  415. $add = array('check' => array('', 'QUICK', 'FAST', 'CHANGED', 'MEDIUM', 'EXTENDED'), 'repair' => array('', 'QUICK', 'EXTENDED'));
  416. if(isset($serv[$job['type']])) {
  417. mysql_select_db($job['db']);
  418. $filter = $object = array();
  419. $this->createFilters($job['obj'], $filter, $object);
  420. $r = mysql_query('SHOW TABLE STATUS') or sxd_my_error();
  421. if (!$r) return;
  422. $tables = array();
  423. while($item = mysql_fetch_assoc($r)){
  424. if(V_MYSQL > 40101 && is_null($item['Engine']) && preg_match('/^VIEW/i', $item['Comment'])) continue;
  425. if(sxd_check($item['Name'], $object['TA'], $filter['TA'])) $tables[] = "`{$item['Name']}`";
  426. }
  427. $sql = $serv[$job['type']] . ' TABLE ' . implode(',', $tables);
  428. if ($job['type'] == 'check' || $job['type'] == 'repair') {
  429. $sql .= isset($add[$job['type']][$job[$job['type']]]) ? ' ' . $add[$job['type']][$job[$job['type']]] : '';
  430. }
  431. $r = mysql_query($sql) or sxd_my_error();
  432. if (!$r) return;
  433. $res = array();
  434. while($item = mysql_fetch_row($r)){
  435. $res[] = $item;
  436. }
  437. echo 'sxd.result.add(' . sxd_php2json($res). ');';
  438. }
  439. }
  440. function createFilters(&$obj, &$filter, &$object){
  441. $types = array('TA', 'TC', 'VI', 'PR', 'FU', 'TR', 'EV');
  442. foreach($types AS $type){
  443. $filter[$type] = array();
  444. $object[$type] = array();
  445. if(!empty($obj[$type])){
  446. foreach($obj[$type] AS $v){
  447. if(strpos($v, '*') !== false) {
  448. $filter[$type][] = str_replace('*', '.*?', $v);
  449. }
  450. else {
  451. $object[$type][$v] = true;
  452. }
  453. }
  454. $filter[$type] = count($filter[$type]) > 0 ? '/^(' . implode('|', $filter[$type]) . ')$/i' : '';
  455. }
  456. }
  457. }
  458. function closeConnect(){
  459. //return;
  460. @ignore_user_abort(1);
  461. header("SXD: {$this->name}");
  462. header("Connection: close");
  463. header("Content-Length: 0");
  464. @ob_end_flush();
  465. @flush();
  466. }
  467. function resumeJob($job){
  468. $this->closeConnect();
  469. include($this->CFG['backup_path'] . $job['job'] . '.job.php');
  470. $this->JOB = &$JOB;
  471. if(file_exists($this->JOB['file_stp'])) unlink($this->JOB['file_stp']);
  472. $this->fh_rtl = fopen($this->JOB['file_rtl'], 'r+b');
  473. $this->fh_log = fopen($this->JOB['file_log'], 'ab');
  474. $t = fgets($this->fh_rtl);
  475. if(!empty($t)){
  476. $this->rtl = explode("\t", $t);
  477. }
  478. else {
  479. $this->addLog($this->LNG['not_found_rtl']);
  480. exit;
  481. }
  482. // TODO: проверить удаление кодировки
  483. //$this->rtl[6] = '';
  484. fseek($this->fh_rtl, 0);
  485. $this->rtl[1] = time();
  486. $this->rtl[9] = 0;
  487. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  488. if ($this->JOB['act'] == 'backup') $this->runBackupJob(true);
  489. elseif ($this->JOB['act'] == 'restore') $this->runRestoreJob(true);
  490. }
  491. function addRestoreJob($job) {
  492. $this->closeConnect();
  493. $this->JOB = $job;
  494. // Создаем список объектов и фильтр
  495. $filter = $object = array();
  496. $this->createFilters($this->JOB['obj'], $filter, $object);
  497. $objects = $this->getFileObjects('restore', $this->JOB['file'], false);
  498. $todo = array();
  499. $rows = 0;
  500. $this->tab_rows = array();
  501. $todo = array();
  502. foreach($objects AS $t => $list){
  503. if($t == 'TA' && (!empty($object['TC']) || !empty($filter['TC']))) {}
  504. elseif(empty($object[$t]) && empty($filter[$t])) {continue;}
  505. if (empty($list)) continue;
  506. foreach($list AS $item){
  507. switch($t){
  508. case 'TA':
  509. $type = '';
  510. if(sxd_check($item[0], $object['TA'], $filter['TA'])){
  511. $type = empty($item[1]) ? 'TC' : 'TA';
  512. }
  513. elseif(sxd_check($item[0], $object['TC'], $filter['TC'])) {
  514. $type = 'TC';
  515. }
  516. else continue;
  517. $todo['TA'][] = array($type, $item[0], $item[1], $item[2]);
  518. $rows += $type == 'TA' ? $item[1] : 0;
  519. break;
  520. default:
  521. if(sxd_check($item, $object[$t], $filter[$t])) {
  522. $todo[$t][] = array($t, $item);
  523. }
  524. }
  525. }
  526. }
  527. $this->JOB['file_tmp'] = $this->JOB['file_name'] = $this->CFG['backup_path'] . $this->JOB['file'];
  528. $this->JOB['file_rtl'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.rtl';
  529. $this->JOB['file_log'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.log';
  530. $this->JOB['file_stp'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.stp';
  531. if(file_exists($this->JOB['file_stp'])) unlink($this->JOB['file_stp']);
  532. $this->fh_tmp = $this->openFile($this->JOB['file_tmp'], 'r');
  533. // Для чужих дампов определяем разделители строк
  534. if(is_null($this->JOB['obj'])) {
  535. $s = fread($this->fh_tmp, 2048);
  536. if(strpos($s, "\r\n")) $this->JOB['eol'] = "\r\n";
  537. elseif(strpos($s, "\n")) $this->JOB['eol'] = "\n";
  538. else $this->JOB['eol'] = "\r";
  539. $bom = strncmp($s, "\xEF\xBB\xBF", 3) == 0 ? 3 : ((strncmp($s, "\xFE\xFF", 2) == 0 || strncmp($s, "\xFF\xFE", 2) == 0) ? 2 : 0);
  540. fseek($this->fh_tmp, $bom);
  541. }
  542. $this->JOB['todo'] = $todo;
  543. $this->saveJob($this->JOB['job'], $this->JOB);
  544. $this->fh_rtl = fopen($this->JOB['file_rtl'], 'wb');
  545. $this->fh_log = fopen($this->JOB['file_log'], 'wb');
  546. $this->rtl = array(time(), time(), $rows, 0, '', '', '', 0, 0, 0, 0, TIMER, "\n");
  547. $this->addLog(sprintf($this->LNG['restore_begin'], $this->JOB['db']));
  548. $this->addLog("{$this->LNG['combo_file']} {$this->JOB['file']}");
  549. $this->runRestoreJob();
  550. }
  551. function runRestoreJob($continue = false){
  552. $ei = false;
  553. if($continue){
  554. $this->fh_tmp = $this->openFile($this->JOB['file_tmp'], 'r');
  555. fseek($this->fh_tmp, $this->rtl[3]);
  556. if(!empty($this->rtl[6])) $this->setNames($this->JOB['correct'] == 1 && !empty($this->JOB['charset']) ? $this->JOB['charset'] : $this->rtl[6]);
  557. if($this->rtl[7] < $this->rtl[10]) $ei = true;
  558. }
  559. mysql_select_db($this->JOB['db']);
  560. if(is_null($this->JOB['obj'])) $this->runRestoreJobForeign($continue);
  561. //mysql_query("SET NAMES 'UTF8'");
  562. $types = array('VI' => 'View', 'PR' => 'Procedure', 'FU' => 'Function', 'TR' => 'Trigger', 'EV' => 'Event');
  563. $fcache = '';
  564. $writes = 0;
  565. $old_charset = '';
  566. $tab = '';
  567. $seek = 0;
  568. $this->rtl[3] = ftell($this->fh_tmp);
  569. fseek($this->fh_rtl, 0);
  570. $this->rtl[1] = time();
  571. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  572. $c = 0;
  573. switch($this->JOB['strategy']){
  574. case 1: $tc = 'TRUNCATE'; $td = 'INSERT'; break;
  575. case 2: $tc = ''; $td = 'REPLACE'; break;
  576. case 3: $tc = ''; $td = 'INSERT IGNORE'; break;
  577. default: $tc = 'DROP TABLE IF EXISTS'; $td = 'INSERT';
  578. }
  579. $tab_exists = array();
  580. if($this->JOB['strategy'] > 0){
  581. $r = mysql_query("SHOW TABLES") or sxd_my_error();
  582. while($item = mysql_fetch_row($r)){
  583. $tab_exists[$item[0]] = true;
  584. }
  585. }
  586. $insert = $continue && $this->rtl[7] < $this->rtl[10] ? "{$td} INTO `{$this->rtl[5]}` VALUES " : '';
  587. //$enable_index = array();
  588. if(V_MYSQL > 40014) {
  589. mysql_query("SET UNIQUE_CHECKS=0");
  590. mysql_query("SET FOREIGN_KEY_CHECKS=0");
  591. if(V_MYSQL > 40101) mysql_query("SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
  592. if(V_MYSQL > 40111) mysql_query("SET SQL_NOTES=0");
  593. }
  594. $log_sql = false;
  595. $fields = '';
  596. $time_old = time();
  597. $exit_time = $time_old + $this->CFG['time_web'] - 1;
  598. while($q = sxd_read_sql($this->fh_tmp, $seek, $ei)){
  599. if($time_old < time()) {
  600. if(file_exists($this->JOB['file_stp'])){
  601. $type = file_get_contents($this->JOB['file_stp']);
  602. $this->rtl[9] = !empty($type) ? $type : 2;
  603. fseek($this->fh_rtl, 0);
  604. $this->rtl[1] = time();
  605. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  606. /*if($type == 1) {
  607. }*/
  608. unset($this->rtl);
  609. exit;
  610. }
  611. $time_old = time();
  612. if($time_old >= $exit_time){
  613. $this->rtl[9] = 3;
  614. fseek($this->fh_rtl, 0);
  615. $this->rtl[1] = time();
  616. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  617. unset($this->rtl);
  618. exit;
  619. }
  620. clearstatcache();
  621. }
  622. switch($q{0}){
  623. case '(':
  624. if($continue) {
  625. $this->addLog(sprintf("{$this->LNG['restore_TC']} {$this->LNG['continue_from']}", $this->rtl[5], $this->rtl[3]));
  626. $continue = false;
  627. }
  628. $q = $insert . $q;
  629. $ex = 1;
  630. $c = 1;
  631. break;
  632. case 'I':
  633. if (preg_match('/^INSERT( INTO `(.+?)`) VALUES/', $q, $m)) {
  634. $insert = $td . $m[1] . $fields . " VALUES \n";
  635. $tab = $m[2];
  636. $this->rtl[7] = 0;
  637. $this->rtl[8] = 0;
  638. foreach($this->JOB['todo']['TA'] AS $t){
  639. if($t[1] == $tab) {
  640. $this->rtl[8] = $t[2];
  641. }
  642. }
  643. if($this->JOB['strategy']) {
  644. $q = substr_replace($q, $insert, 0, strlen($m[0]));
  645. }
  646. //mysql_query("LOCK TABLES `{$tab}` WRITE") or die (mysql_error());
  647. mysql_query("ALTER TABLE `{$tab}` DISABLE KEYS") or sxd_my_error();
  648. //if(!empty($this->JOB['autoinc'])) mysql_query("ALTER TABLE `{$tab}` AUTO_INCREMENT = 1") or sxd_my_error();
  649. $ex = 1;
  650. }
  651. break;
  652. case 'C':
  653. $ex = 1;
  654. if (preg_match('/^CREATE TABLE `/', $q)) {
  655. if($this->JOB['strategy'] != 0 && isset($tab_exists[$this->rtl[5]])) $ex = 0;
  656. else {
  657. $ex = 1;
  658. if((!empty($this->JOB['correct']) && !empty($this->JOB['charset']))){
  659. $q = preg_replace('/(DEFAULT)?\s*(CHARSET|CHARACTER SET|COLLATE)[=\s]+\w+/i', '', $q) . (V_MYSQL < 40100 ? '' : ' DEFAULT CHARSET=' . $this->JOB['charset']);
  660. }
  661. if(!empty($this->JOB['autoinc'])) $q = preg_replace("/AUTO_INCREMENT=\d+/", "AUTO_INCREMENT=1", $q);
  662. }
  663. // Достаем имена полей таблицы
  664. $fields = $this->JOB['strategy'] > 0 && preg_match_all('/^\s+(`.+?`) /m', $q, $f, PREG_PATTERN_ORDER) ? '(' . implode(',', $f[1]) . ')' : '';
  665. }
  666. break;
  667. case '#': // Команды для дампера
  668. if (preg_match("/\#\t(TC|TD|VI|PR|FU|TR|EV)`(.+?)`(([^_]+?)_.+?)?$/", $q, $m)) {
  669. //if(!empty($tab)) $enable_index[] = $tab;
  670. // $this->setNames($this->JOB['correct'] == 1 && !empty($this->JOB['charset']) ? $this->JOB['charset'] : empty($m[3]) ? '' : $m[3]);
  671. $this->setNames('binary');
  672. if($m[1] == 'TC') {
  673. $this->addLog(sprintf($this->LNG['restore_TC'], $m[2]));
  674. $insert = '';
  675. $tab = '';
  676. $this->rtl[4] = 'TD';
  677. $this->rtl[5] = $m[2];
  678. $ei = 0;
  679. if($tc && ($this->JOB['strategy'] == 0 || isset($tab_exists[$m[2]]))) {
  680. mysql_query("{$tc} `{$m[2]}`") or sxd_my_error();
  681. }
  682. }
  683. elseif($m[1] == 'TD'){
  684. $ei = 1;
  685. }
  686. else {
  687. $this->rtl[4] = $m[1];
  688. $this->rtl[5] = $m[2];
  689. $this->rtl[7] = 0;
  690. $this->rtl[8] = 0;
  691. mysql_query("DROP {$types[$m[1]]} IF EXISTS `{$m[2]}`") or sxd_my_error();
  692. $this->addLog(sprintf($this->LNG["restore_{$m[1]}"], $m[2]));
  693. $ei = 0;
  694. }
  695. }
  696. $ex = 0;
  697. break;
  698. default:
  699. $insert = '';
  700. $ex = 1;
  701. }
  702. if($ex) {
  703. $this->rtl[3] = ftell($this->fh_tmp) - $seek;
  704. fseek($this->fh_rtl, 0);
  705. $this->rtl[1] = time();
  706. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  707. if(mysql_query($q)) {
  708. if($insert) {
  709. $c = 1;
  710. }
  711. }
  712. else {
  713. error_log(date('r') . "\n----------\n{$q}\n", 3, "backup/sql_error.log");
  714. sxd_my_error();
  715. }
  716. if($c){
  717. $i = mysql_affected_rows();
  718. $this->rtl[3] = ftell($this->fh_tmp) - $seek;
  719. $this->rtl[7] += $i;
  720. $this->rtl[10] += $i;
  721. fseek($this->fh_rtl, 0);
  722. $this->rtl[1] = time();
  723. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  724. $c = 1;
  725. }
  726. }
  727. }
  728. // Включаем ключи
  729. $this->addLog($this->LNG['restore_keys']);
  730. $this->rtl[4] = 'EK';
  731. $this->rtl[5] = '';
  732. $this->rtl[6] = '';
  733. $this->rtl[7] = 0;
  734. $this->rtl[8] = 0;
  735. foreach($this->JOB['todo']['TA'] AS $tab){
  736. if ($tab[0] == 'TC') continue;
  737. mysql_query("ALTER TABLE `{$tab[1]}` ENABLE KEYS") or sxd_my_error();
  738. $this->rtl[1] = time();
  739. $this->rtl[5] = $tab[1];
  740. fseek($this->fh_rtl, 0);
  741. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  742. }
  743. $this->rtl[4] = 'EOJ';
  744. $this->rtl[5] = round(array_sum(explode(' ', microtime())) - $this->rtl[11], 4);
  745. fseek($this->fh_rtl, 0);
  746. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  747. $this->addLog(sprintf($this->LNG['restore_end'], $this->JOB['db']));
  748. fclose($this->fh_log);
  749. fclose($this->fh_rtl);
  750. }
  751. function runRestoreJobForeign($continue = false){
  752. $ei = false;
  753. $fcache = '';
  754. $writes = 0;
  755. $old_charset = '';
  756. $tab = '';
  757. $seek = 0;
  758. $this->rtl[3] = ftell($this->fh_tmp);
  759. fseek($this->fh_rtl, 0);
  760. $this->rtl[1] = time();
  761. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  762. $c = 0;
  763. $log_sql = false;
  764. $fields = '';
  765. $insert = '';
  766. $last_tab = '';
  767. $time_old = time();
  768. $exit_time = $time_old + $this->CFG['time_web'] - 1;
  769. $delimiter = ";";
  770. while($q = sxd_read_sql($this->fh_tmp, $seek, $ei, $delimiter, $this->JOB['eol'])){
  771. $q = ltrim($q);
  772. if(empty($q)) break;
  773. if($time_old < time()) {
  774. if(file_exists($this->JOB['file_stp'])){
  775. $type = file_get_contents($this->JOB['file_stp']);
  776. $this->rtl[9] = !empty($type) ? $type : 2;
  777. fseek($this->fh_rtl, 0);
  778. $this->rtl[1] = time();
  779. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  780. /*if($type == 1) {
  781. }*/
  782. unset($this->rtl);
  783. exit;
  784. }
  785. $time_old = time();
  786. if($time_old >= $exit_time){
  787. $this->rtl[9] = 3;
  788. fseek($this->fh_rtl, 0);
  789. $this->rtl[1] = time();
  790. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  791. unset($this->rtl);
  792. exit;
  793. }
  794. clearstatcache();
  795. }
  796. do {
  797. $repeat = false;
  798. switch($q{0}){
  799. case '(':
  800. if($continue) {
  801. $this->addLog(sprintf("{$this->LNG['restore_TC']} {$this->LNG['continue_from']}", $this->rtl[5], $this->rtl[3]));
  802. $continue = false;
  803. }
  804. $q = $insert . $q;
  805. $ex = 1;
  806. $c = 1;
  807. break;
  808. case 'I':
  809. if (preg_match('/^(INSERT( INTO `?(.+?)`?).+?\sVALUES)/s', $q, $m)) {
  810. $insert = trim($m[1]) . ' ';
  811. $tab = $m[3];
  812. $this->rtl[7] = 0;
  813. $this->rtl[8] = 0;
  814. $ex = 1;
  815. }
  816. break;
  817. case 'C':
  818. $ex = 1;
  819. $ei = 1;
  820. if (preg_match('/^CREATE TABLE.+?`(.+?)`/', $q, $m)) {
  821. $ex = 1;
  822. $tab = $m[1];
  823. $this->addLog(sprintf($this->LNG['restore_TC'], $tab));
  824. //mysql_query("DROP TABLE IF EXISTS `{$tab}`");
  825. if((!empty($this->JOB['correct']) && !empty($this->JOB['charset']))){
  826. $q = preg_replace('/(DEFAULT)?\s*(CHARSET|CHARACTER SET|COLLATE)[=\s]+\w+/i', '', $q) . (V_MYSQL < 40100 ? '' : ' DEFAULT CHARSET=' . $this->JOB['charset']);
  827. }
  828. elseif(empty($this->JOB['charset'])){
  829. if(preg_match("/(CHARACTER SET|CHARSET)[=\s]+(\w+)/i", $q, $charset)){
  830. $this->setNames($charset[2]);
  831. }
  832. }
  833. }
  834. break;
  835. case '-' && $q{1} == '-':
  836. case '#':
  837. $repeat = true;
  838. $q = ltrim(substr($q, strpos($q, $this->JOB['eol'])));
  839. $ex = 0;
  840. break;
  841. case '/':
  842. case 'S':
  843. if (preg_match('/SET NAMES (\w+)/', $q, $m)) {
  844. $this->JOB['charset'] = $m[1];
  845. $this->setNames($this->JOB['charset']);
  846. $ex = 0;
  847. }
  848. else $ex = 1;
  849. break;
  850. default:
  851. $insert = '';
  852. $ex = 1;
  853. $ei = 0;
  854. }
  855. } while ($repeat);
  856. if($ex) {
  857. $this->rtl[3] = ftell($this->fh_tmp) - $seek;
  858. fseek($this->fh_rtl, 0);
  859. $this->rtl[1] = time();
  860. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  861. if(mysql_query($q)) {
  862. if($insert) {
  863. $c = 1;
  864. }
  865. }
  866. else {
  867. error_log("-----------------\n{$q}\n", 3, "error.log");
  868. sxd_my_error();
  869. }
  870. if($c){
  871. $i = mysql_affected_rows();
  872. $this->rtl[3] = ftell($this->fh_tmp) - $seek;
  873. $this->rtl[7] += $i;
  874. $this->rtl[10] += $i;
  875. fseek($this->fh_rtl, 0);
  876. $this->rtl[1] = time();
  877. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  878. $c = 1;
  879. }
  880. }
  881. }
  882. $this->rtl[4] = 'EOJ';
  883. $this->rtl[5] = round(array_sum(explode(' ', microtime())) - $this->rtl[11], 4);
  884. $this->rtl[7] = 0;
  885. $this->rtl[8] = 0;
  886. fseek($this->fh_rtl, 0);
  887. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  888. $this->addLog(sprintf($this->LNG['restore_end'], $this->JOB['db']));
  889. fclose($this->fh_log);
  890. fclose($this->fh_rtl);
  891. }
  892. function addBackupJob($job) {
  893. $this->closeConnect();
  894. // Создаем новое задание
  895. $this->JOB = $job;
  896. mysql_select_db($this->JOB['db']);
  897. // Создаем список объектов и фильтр
  898. $filter = $object = array();
  899. $this->createFilters($this->JOB['obj'], $filter, $object);
  900. $queries = array(
  901. array('TABLE STATUS', 'Name', 'TA')
  902. );
  903. if (V_MYSQL > 50014) {
  904. $queries[] = array("PROCEDURE STATUS WHERE db='{$this->JOB['db']}'", 'Name', 'PR');
  905. $queries[] = array("FUNCTION STATUS WHERE db='{$this->JOB['db']}'", 'Name', 'FU');
  906. $queries[] = array('TRIGGERS', 'Trigger', 'TR');
  907. if(V_MYSQL > 50100) $queries[] = array('EVENTS', 'Name', 'EV');
  908. }
  909. $todo = $header = array();
  910. $tabs = $rows = 0;
  911. $only_create = explode(' ', $this->CFG['only_create']);
  912. foreach($queries AS $query){
  913. $t = $query[2];
  914. if($t == 'TA' && (!empty($object['TC']) || !empty($filter['TC']))) {}
  915. elseif(empty($object[$t]) && empty($filter[$t])) continue;
  916. $r = mysql_query('SHOW ' . $query[0]) or sxd_my_error();
  917. if (!$r) continue;
  918. $todo[$t] = array();
  919. $header[$t] = array();
  920. while($item = mysql_fetch_assoc($r)){
  921. $n = $item[$query[1]];
  922. switch($t){
  923. case 'TA':
  924. case 'TC':
  925. if(V_MYSQL > 40101 && is_null($item['Engine']) && preg_match('/^VIEW/i', $item['Comment'])) {
  926. if(sxd_check($n, $object['VI'], $filter['VI'])){
  927. $todo['VI'] = array();
  928. $header['VI']= array();
  929. }
  930. continue;
  931. }
  932. elseif(sxd_check($n, $object['TA'], $filter['TA'])){
  933. $engine = V_MYSQL > 40101 ? $item['Engine'] : $item['Type'];
  934. $t = in_array($engine, $only_create) ? 'TC' : 'TA';
  935. }
  936. elseif(sxd_check($n, $object['TC'], $filter['TC'])) {
  937. $t = 'TC';
  938. $item['Rows'] = $item['Data_length'] = '';
  939. }
  940. else continue;
  941. $todo['TA'][] = array($t, $n, !empty($item['Collation']) ? $item['Collation'] : '', $item['Auto_increment'], $item['Rows'], $item['Data_length']);
  942. $header['TA'][] = "{$n}`{$item['Rows']}`{$item['Data_length']}";
  943. $tabs++;
  944. $rows += $item['Rows'];
  945. break;
  946. default:
  947. if(sxd_check($n, $object[$t], $filter[$t])) {
  948. $todo[$t][] = array($t, $n, !empty($item['collation_connection']) ? $item['collation_connection'] : '');
  949. $header[$t][] = $n;
  950. }
  951. }
  952. }
  953. }
  954. if (V_MYSQL > 50014 && (!empty($object['VI']) || !empty($filter['VI']))) {
  955. // Бэкап обзоров, нужно отсортировать зависимые
  956. $r = mysql_query("SELECT table_name, view_definition /*!50121 , collation_connection */ FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = '{$this->JOB['db']}'") or sxd_my_error();
  957. $views = $dumped = $views_collation = array();
  958. $re = "/`{$this->JOB['db']}`.`(.+?)`/";
  959. while($item = mysql_fetch_assoc($r)){
  960. preg_match_all($re, preg_replace("/^select.+? from/i", '', $item['view_definition']), $m);
  961. $used = $m[1];
  962. $views_collation[$item['table_name']] = !empty($item['collation_connection']) ? $item['collation_connection'] : '';
  963. $views[$item['table_name']] = $used;
  964. }
  965. while (count($views) > 0) {
  966. foreach($views AS $n => $view) {
  967. $can_dumped = true;
  968. foreach($view AS $k) {
  969. if (isset($views[$k]) && !isset($dumped[$k])) $can_dumped = false;
  970. }
  971. if ($can_dumped) {
  972. if(sxd_check($n, $object['VI'], $filter['VI'])){
  973. $todo['VI'][] = array('VI', $n, $views_collation[$n]);
  974. $header['VI'][] = $n;
  975. }
  976. $dumped[$n] = 1;
  977. unset($views[$n]);
  978. }
  979. }
  980. }
  981. unset($dumped);
  982. unset($views);
  983. unset($views_collation);
  984. }
  985. $this->JOB['file_tmp'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.tmp';
  986. $this->JOB['file_rtl'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.rtl';
  987. $this->JOB['file_log'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.log';
  988. $this->JOB['file_stp'] = $this->CFG['backup_path'] . $this->JOB['job'] . '.stp';
  989. if(file_exists($this->JOB['file_stp'])) unlink($this->JOB['file_stp']);
  990. $this->fh_tmp = $this->openFile($this->JOB['file_tmp'], 'w');
  991. $this->JOB['file'] = sprintf('%s_%s.%s', (isset($this->JOB['title']) ? $this->JOB['job'] : $this->JOB['db']), date('Y-m-d_H-i-s'), $this->JOB['file_ext']);
  992. $this->JOB['file_name'] = $this->CFG['backup_path'] . $this->JOB['file'];
  993. $this->JOB['todo'] = $todo;
  994. $this->saveJob($this->JOB['job'], $this->JOB);
  995. $fcache = implode('|', array('#SXD20', V_SXD, V_MYSQL, V_PHP, date('Y.m.d H:i:s'), $this->JOB['db'], $this->JOB['charset'], $tabs, $rows, sxd_esc($this->JOB['comment'], false))) . "\n";
  996. foreach($header AS $t => $o){
  997. if (!empty($o)) $fcache .= "#{$t} " . implode('|', $o) . "\n";
  998. }
  999. $this->fh_rtl = fopen($this->JOB['file_rtl'], 'wb');
  1000. $this->fh_log = fopen($this->JOB['file_log'], 'wb');
  1001. $this->rtl = array(time(), time(), $rows, 0, '', '', '', 0, 0, 0, 0, TIMER, "\n");
  1002. $fcache .= "#EOH\n\n";
  1003. $this->write($fcache);
  1004. $this->addLog(sprintf($this->LNG['backup_begin'], $this->JOB['db']));
  1005. $this->runBackupJob();
  1006. }
  1007. function runBackupJob($continue = false){
  1008. if($continue){
  1009. $this->fh_tmp = $this->openFile($this->JOB['file_tmp'], 'a');
  1010. mysql_select_db($this->JOB['db']);
  1011. }
  1012. mysql_query("SET SQL_QUOTE_SHOW_CREATE = 1");
  1013. $types = array('VI' => 'View', 'PR' => 'Procedure', 'FU' => 'Function', 'TR' => 'Trigger', 'EV' => 'Event');
  1014. $fcache = '';
  1015. $writes = 0;
  1016. if(V_MYSQL > 40101) mysql_query("SET SESSION character_set_results = '" . ($this->JOB['charset'] ? $this->JOB['charset'] : 'binary') ."'") or sxd_my_error();
  1017. $time_old = time();
  1018. $exit_time = $time_old + $this->CFG['time_web'] - 1;
  1019. $no_cache = V_MYSQL < 40101 ? 'SQL_NO_CACHE ' : '';
  1020. foreach($this->JOB['todo'] AS $t => $o){
  1021. if (empty($this->rtl[4])) $this->rtl[4] = $t;
  1022. elseif ($this->rtl[4] != $t) continue;
  1023. foreach($o AS $n){
  1024. if (empty($this->rtl[5])) {
  1025. $this->rtl[5] = $n[1];
  1026. $this->rtl[7] = 0;
  1027. $this->rtl[8] = !empty($n[4]) ? $n[4] : 0;
  1028. }
  1029. elseif ($this->rtl[5] != $n[1]) continue;
  1030. // Делаем бэкап
  1031. switch($n[0]){
  1032. case 'TC':
  1033. case 'TD':
  1034. case 'TA':
  1035. $from = '';
  1036. if ($n[0] == 'TC' || $this->rtl[7] == 0){
  1037. // Бэкап структуры таблицы
  1038. $r = mysql_query("SHOW CREATE TABLE `{$n[1]}`") or sxd_my_error();
  1039. $item = mysql_fetch_assoc($r);
  1040. $fcache .= "#\tTC`{$n[1]}`{$n[2]}\t;\n{$item['Create Table']}\t;\n";
  1041. $this->addLog(sprintf($this->LNG['backup_TC'], $n[1]));
  1042. $this->rtl[7] = 0;
  1043. if($n[0] == 'TC' || !$n[4]) break;
  1044. // Бэкапим данные таблицы
  1045. $fcache .= "#\tTD`{$n[1]}`{$n[2]}\t;\nINSERT INTO `{$n[1]}` VALUES \n";
  1046. }
  1047. else {
  1048. $from = " LIMIT {$this->rtl[7]}, {$this->rtl[8]}";
  1049. $this->addLog(sprintf("{$this->LNG['backup_TC']} {$this->LNG['continue_from']}", $n[1], $this->rtl[7]));
  1050. }
  1051. // Определяем типы полей
  1052. $notNum = array();
  1053. $r = mysql_query("SHOW COLUMNS FROM `{$n[1]}`") or sxd_my_error();
  1054. $fields = 0;
  1055. while($col = mysql_fetch_array($r)) {
  1056. // TODO: проверить типы SET, ENUM и BIT
  1057. $notNum[$fields] = preg_match("/^(tinyint|smallint|mediumint|bigint|int|float|double|real|decimal|numeric|year)/", $col['Type']) ? 0 : 1;
  1058. $fields++;
  1059. }
  1060. $time_old = time();
  1061. $z = 0;
  1062. // Достаем данные
  1063. $r = mysql_unbuffered_query("SELECT {$no_cache}* FROM `{$n[1]}`{$from}");
  1064. while($row = mysql_fetch_row($r)) {
  1065. if (strlen($fcache) >= 61440) {
  1066. $z = 0;
  1067. if($time_old < time()) {
  1068. if(file_exists($this->JOB['file_stp'])){
  1069. $type = file_get_contents($this->JOB['file_stp']);
  1070. $this->rtl[9] = !empty($type) ? $type : 2;
  1071. $this->write($fcache);
  1072. if($type == 1) {
  1073. }
  1074. unset($this->rtl);
  1075. exit;
  1076. }
  1077. $time_old = time();
  1078. if($time_old >= $exit_time){
  1079. $this->rtl[9] = 3;
  1080. $this->write($fcache);
  1081. unset($this->rtl);
  1082. exit;
  1083. }
  1084. clearstatcache();
  1085. }
  1086. $this->write($fcache);
  1087. }
  1088. for($k = 0; $k < $fields; $k++){
  1089. if(!isset($row[$k])) {$row[$k] = '\N';}
  1090. elseif($notNum[$k]) {$row[$k] = '\'' . mysql_real_escape_string($row[$k]) . '\'';} // TODO: Потестить скорость эскэйпинга строк
  1091. }
  1092. $fcache .= '(' . implode(',', $row) . "),\n";
  1093. $this->rtl[7]++;
  1094. $this->rtl[10]++;
  1095. }
  1096. unset($row);
  1097. mysql_free_result($r);
  1098. $fcache = substr_replace($fcache, "\t;\n", -2, 2);
  1099. break;
  1100. default:
  1101. if(V_MYSQL < 50121 && $n[0] == 'TR'){
  1102. // SHOW CREATE TRIGGER отсутствует до MySQL 5.1.21
  1103. $r = mysql_query("SELECT * FROM `INFORMATION_SCHEMA`.`TRIGGERS` WHERE `TRIGGER_SCHEMA` = '{$this->JOB['db']}' AND `TRIGGER_NAME` = '{$n[1]}'") or sxd_my_error();
  1104. $item = mysql_fetch_assoc($r);
  1105. $fcache .= "#\tTR`{$n[1]}`{$n[2]}\t;\nCREATE TRIGGER `{$item['TRIGGER_NAME']}` {$item['ACTION_TIMING']} {$item['EVENT_MANIPULATION']} ON `{$item['EVENT_OBJECT_TABLE']}` FOR EACH ROW {$item['ACTION_STATEMENT']}\t;\n";
  1106. }
  1107. else {
  1108. $this->addLog(sprintf($this->LNG['backup_' . $n[0]], $n[1]));
  1109. $r = mysql_query("SHOW CREATE {$types[$n[0]]} `{$n[1]}`") or sxd_my_error();
  1110. $item = mysql_fetch_assoc($r);
  1111. $fcache .= "#\t{$n[0]}`{$n[1]}`{$n[2]}\t;\n" . preg_replace("/DEFINER=`.+?`@`.+?` /", '', ($n[0] == 'TR' ? $item['SQL Original Statement'] : $item['Create ' . $types[$n[0]]])) . "\t;\n";
  1112. }
  1113. }
  1114. $this->rtl[5] = '';
  1115. }
  1116. $this->rtl[4] = '';
  1117. }
  1118. $this->rtl[4] = 'EOJ';
  1119. $this->rtl[5] = round(array_sum(explode(' ', microtime())) - $this->rtl[11], 4);
  1120. $this->rtl[6] = '';
  1121. $this->rtl[7] = 0;
  1122. $this->rtl[8] = 0;
  1123. $this->write($fcache);
  1124. fclose($this->fh_tmp);
  1125. rename($this->JOB['file_tmp'], $this->JOB['file_name']);
  1126. $this->addLog(sprintf($this->LNG['backup_end'], $this->JOB['db']));
  1127. if ($this->JOB['del_time'] || $this->JOB['del_count']) {
  1128. $this->addLog($this->LNG['autodelete']);
  1129. $deldate = '';
  1130. if (!empty($this->JOB['del_time'])){ // Удаление по дням
  1131. $deldate = date("Y-m-d_H-i-s", time() - intval($this->JOB['del_time']) * 86400);
  1132. }
  1133. $deleted = false;
  1134. if ($dh = opendir($this->CFG['backup_path'])) {
  1135. $files = array();
  1136. $name = isset($this->JOB['title']) ? $this->JOB['job'] : $this->JOB['db'];
  1137. while (false !== ($file = readdir($dh))) {
  1138. if (preg_match("/^{$name}_(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.sql/", $file, $m)) {
  1139. if ($deldate && $m[1] < $deldate) {
  1140. if(unlink($this->CFG['backup_path'] . $file)) $this->addLog(sprintf($this->LNG['del_by_date'], $file));
  1141. else $this->addLog(sprintf($this->LNG['del_fail'], $file));
  1142. $deleted = true;
  1143. }
  1144. else {$files[$m[1]] = $file;}
  1145. }
  1146. }
  1147. closedir($dh);
  1148. // Сортируем файлы по дате и удаляем самые старые
  1149. if (!empty($this->JOB['del_count'])){
  1150. ksort($files);
  1151. $file_to_delete = count($files) - $this->JOB['del_count'];
  1152. foreach ($files AS $file){
  1153. if ($file_to_delete-- > 0){
  1154. if(unlink($this->CFG['backup_path'] . $file)) $this->addLog(sprintf($this->LNG['del_by_count'], $file));
  1155. else $this->addLog(sprintf($this->LNG['del_fail'], $file));
  1156. $deleted = true;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. if(!$deleted) $this->addLog($this->LNG['del_nothing']);
  1162. }
  1163. fclose($this->fh_log);
  1164. fclose($this->fh_rtl);
  1165. }
  1166. function setNames($collation){
  1167. if(empty($collation)) return;
  1168. if($this->rtl[6] != $collation) {
  1169. mysql_query('SET NAMES \'' . preg_replace('/^(\w+?)_/', '\\1\' COLLATE \'\\1_', $collation) . '\'') or sxd_my_error();
  1170. /*if(!$this->rtl[7])*/ $this->addLog(sprintf($this->LNG['set_names'], $collation));
  1171. $this->rtl[6] = $collation;
  1172. }
  1173. }
  1174. function write(&$str){
  1175. fseek($this->fh_rtl, 0);
  1176. $this->rtl[1] = time();
  1177. $this->rtl[3] += fwrite($this->fh_tmp, $str);
  1178. fwrite($this->fh_rtl, implode("\t", $this->rtl));
  1179. $str = '';
  1180. }
  1181. function addLog($str, $type = 1){
  1182. fwrite($this->fh_log, date('Y.m.d H:i:s') . "\t{$type}\t{$str}\n");
  1183. }
  1184. function getDBList(){
  1185. $dbs = $items = array();
  1186. if (!V_MYSQL) return $dbs;
  1187. $qq = (V_MYSQL < 50000) ? '' : '\'';
  1188. if ($this->CFG['my_db']) {
  1189. $tmp = explode(',', $this->CFG['my_db']);
  1190. foreach($tmp AS $d){
  1191. $d = trim($d);
  1192. $items[] = $qq . sxd_esc($d, false) . $qq;
  1193. $dbs[$d] = "{$d} (0)";
  1194. }
  1195. }
  1196. else{
  1197. $result = mysql_query("SHOW DATABASES") or sxd_my_error();
  1198. while($item = mysql_fetch_row($result)){
  1199. if($item[0] == 'information_schema' || $item[0] == 'mysql' || $item[0] == 'performance_schema') continue;
  1200. $items[] = $qq . sxd_esc($item[0], false) . $qq;
  1201. $dbs[$item[0]] = "{$item[0]} (0)";
  1202. }
  1203. }
  1204. if(V_MYSQL < 50000){
  1205. foreach($items AS $item){
  1206. $tables = mysql_query("SHOW TABLES FROM `{$item}`") or sxd_my_error();
  1207. if ($tables) {
  1208. $tabs = mysql_num_rows($tables);
  1209. $dbs[$item] = "{$item} ({$tabs})";
  1210. }
  1211. }
  1212. }
  1213. else {
  1214. $where = (count($items) > 0) ? 'WHERE `table_schema` IN (' . implode(',', $items) . ')' : '';
  1215. $result = mysql_query("SELECT `table_schema`, COUNT(*) FROM `information_schema`.`tables` {$where} GROUP BY `table_schema`") or sxd_my_error();
  1216. while($item = mysql_fetch_row($result)){
  1217. if($item[0] == 'information_schema' || $item[0] == 'mysql' || $item[0] == 'performance_schema') continue;
  1218. $dbs[$item[0]] = "{$item[0]} ({$item[1]})";
  1219. }
  1220. }
  1221. return $dbs;
  1222. }
  1223. function getCharsetList(){
  1224. $tmp = array(0 => '- auto -');
  1225. if (!V_MYSQL) return $tmp;
  1226. if(V_MYSQL > 40101) {
  1227. $def_charsets = '';
  1228. if(!empty($this->CFG['charsets'])){
  1229. $def_charsets = preg_match_all("/([\w*?]+)\s*/", $this->CFG['charsets'], $m, PREG_PATTERN_ORDER) ? '/^(' . str_replace(array('?','*'), array('.','\w+?'), implode('|', $m[1])) . ')$/i' : '';
  1230. }
  1231. $r = mysql_query("SHOW CHARACTER SET") or sxd_my_error();
  1232. if ($r) {
  1233. while($item = mysql_fetch_assoc($r)){
  1234. if (empty($def_charsets) || preg_match($def_charsets, $item['Charset'])) $tmp[$item['Charset']] = "{$item['Charset']}"; // ({$item['Description']})
  1235. }
  1236. }
  1237. }
  1238. return $tmp;
  1239. }
  1240. function getCollationList(){
  1241. $tmp = array();
  1242. if (!V_MYSQL) return $tmp;
  1243. if(V_MYSQL > 40101) {
  1244. $def_charsets = '';
  1245. if(!empty($this->CFG['charsets'])){
  1246. $def_charsets = preg_match_all("/([\w*?]+)\s*/", $this->CFG['charsets'], $m, PREG_PATTERN_ORDER) ? '/^(' . str_replace(array('?','*'), array('.','\w+?'), implode('|', $m[1])) . ')$/i' : '';
  1247. }
  1248. $r = mysql_query("SHOW COLLATION") or sxd_my_error();
  1249. if ($r) {
  1250. while($item = mysql_fetch_assoc($r)){
  1251. if (empty($def_charsets) || preg_match($def_charsets, $item['Charset'])) $tmp[$item['Charset']][$item['Collation']] = $item['Default'] == 'Yes' ? 1 : 0;
  1252. }
  1253. }
  1254. }
  1255. return $tmp;
  1256. }
  1257. function getObjects($tree, $db_name){
  1258. mysql_select_db($db_name);
  1259. // Достаем таблицы
  1260. $r = mysql_query('SHOW TABLE STATUS');
  1261. $tab_prefix_last = $tab_prefix = '*';
  1262. $objects = array('TA' => array(), 'VI' => array(), 'PR' => array(), 'FU' => array(), 'TR' => array(), 'EV' => array());
  1263. if($r){
  1264. while($item = mysql_fetch_assoc($r)){
  1265. if(V_MYSQL > 40101 && is_null($item['Engine']) && preg_match('/^VIEW/i', $item['Comment'])) {
  1266. $objects['VI'][]= $item['Name'];
  1267. }
  1268. else{
  1269. $objects['TA'][] = array($item['Name'], $item['Rows'], $item['Data_length']);
  1270. }
  1271. }
  1272. if (V_MYSQL > 50014 && $tree != 'services') {
  1273. $shows = array(
  1274. "PROCEDURE STATUS WHERE db='{$db_name}'",
  1275. "FUNCTION STATUS WHERE db='{$db_name}'",
  1276. 'TRIGGERS'
  1277. );
  1278. if(V_MYSQL > 50100) $shows[] = "EVENTS WHERE db='{$db_name}'";
  1279. // TODO: Поправить проверку событий и триггеров
  1280. for($i = 0,

Large files files are truncated, but you can click here to view the full file