Completed
Push — work-fleets ( b49239...9e446e )
by SuperNova.WS
07:19
created

Sypex_Dumper::getDBList()   F

Complexity

Conditions 20
Paths 273

Size

Total Lines 39
Code Lines 29

Duplication

Lines 2
Ratio 5.13 %

Importance

Changes 0
Metric Value
cc 20
dl 2
loc 39
rs 3.6338
c 0
b 0
f 0
eloc 29
nc 273
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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