-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
backup.php
700 lines (597 loc) · 21 KB
/
backup.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2018 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
include ('../inc/includes.php');
if (isset($_POST['check_version'])) {
Session::checkRight('backup', Backup::CHECKUPDATE);
Toolbox::checkNewVersionAvailable(0, true);
Html::back();
}
Session::checkRight("backup", READ);
Html::header(__('Maintenance'), $_SERVER['PHP_SELF'], "admin", "backup");
$max_time = min(get_cfg_var("max_execution_time"), get_cfg_var("max_input_time"));
if ($max_time == 0) {
$defaulttimeout = 60;
$defaultrowlimit = 5;
} else if ($max_time > 5) {
$defaulttimeout = $max_time-2;
$defaultrowlimit = 5;
} else {
$defaulttimeout = max(1, $max_time-2);
$defaultrowlimit = 2;
}
/**
* Generate an XML backup file of the database
* @global DB $DB
*/
function xmlbackup() {
global $CFG_GLPI, $DB;
//on parcoure la DB et on liste tous les noms des tables dans $table
//on incremente $query[] de "select * from $table" pour chaque occurence de $table
$result = $DB->listTables();
$i = 0;
while ($line = $result->next()) {
$table = $line['TABLE_NAME'];
$query[$i] = "SELECT *
FROM `$table`";
$i++;
}
// Filename
$time_file = date("Y-m-d-H-i");
$filename = GLPI_DUMP_DIR . "/glpi-backup-" . GLPI_VERSION . "-$time_file.xml";
$A = new XML();
// Your query
$A->SqlString = $query;
//File path
$A->FilePath = $filename;
// Define layout type
$A->Type = 4;
// Generate the XML file
$A->DoXML();
// In case of error, display it
if ($A->IsError == 1) {
printf(__('ERROR:'), $A->ErrorString);
}
}
/**
* Init time to computer time spend
* @global type $TPSDEB
* @global int $TPSCOUR
*/
function init_time() {
global $TPSDEB, $TPSCOUR;
list($usec,$sec) = explode(" ", microtime());
$TPSDEB = $sec;
$TPSCOUR = 0;
}
/**
* Get current time
* @global type $TPSDEB
* @global type $TPSCOUR
*/
function current_time() {
global $TPSDEB, $TPSCOUR;
list($usec,$sec) = explode(" ", microtime());
$TPSFIN = $sec;
if (round($TPSFIN-$TPSDEB, 1) >= $TPSCOUR+1) {//une seconde de plus
$TPSCOUR = round($TPSFIN-$TPSDEB, 1);
}
}
/**
* Get data of a table
* @param DB $DB
* @param string $table table name
* @param integer $from FROM xxx
* @param integer $limit LIMIT xxx
* @return string SQL query "INSERT INTO..."
*/
function get_content($DB, $table, $from, $limit) {
$content = "";
$iterator = $DB->request($table, ['START' => $from, 'LIMIT' => $limit]);
if ($iterator->count()) {
while ($row = $iterator->next()) {
$insert = "INSERT INTO `$table` VALUES (";
foreach ($row as $field_key => $field_val) {
if (is_null($field_val)) {
$insert .= "NULL,";
} else if ($field_val != "") {
$insert .= "'" . addslashes($field_val) . "',";
} else {
$insert .= "'',";
}
}
$insert = preg_replace("/,$/", "", $insert);
$insert .= ");\n";
$content .= $insert;
}
}
return $content;
}
/** Get structure of a table
*
* @param $DB DB object
* @param $table table name
**/
function get_def($DB, $table) {
$def = "### Dump table $table\n\n";
$def .= "DROP TABLE IF EXISTS `$table`;\n";
$query = "SHOW CREATE TABLE `$table`";
$result = $DB->query($query);
$DB->query("SET SESSION sql_quote_show_create = 1");
$row = $DB->fetch_row($result);
$def .= preg_replace("/AUTO_INCREMENT=\w+/i", "", $row[1]);
$def .= ";";
return $def."\n\n";
}
/** Restore a mysql dump
*
* @param $DB DB object
* @param $dumpFile dump file
* @param $duree max delay before refresh
**/
function restoreMySqlDump($DB, $dumpFile, $duree) {
global $DB, $TPSCOUR, $offset, $cpt;
// $dumpFile, fichier source
// $duree=timeout pour changement de page (-1 = aucun)
// Desactivation pour empecher les addslashes au niveau de la creation des tables
// En plus, au niveau du dump on considere qu'on est bon
// set_magic_quotes_runtime(0);
if (!file_exists($dumpFile)) {
echo sprintf(__('File %s not found.'), $dumpFile)."<br>";
return false;
}
if (substr($dumpFile, -2) == "gz") {
$fileHandle = gzopen($dumpFile, "rb");
} else {
$fileHandle = fopen($dumpFile, "rb");
}
if (!$fileHandle) {
//TRASN: %s is the name of the file
echo sprintf(__('Unauthorized access to the file %s'), $dumpFile)."<br>";
return false;
}
if ($offset != 0) {
if (substr($dumpFile, -2) == "gz") {
if (gzseek($fileHandle, $offset, SEEK_SET) != 0) { //erreur
//TRANS: %s is the number of the byte
printf(__("Unable to find the byte %s"), Html::formatNumber($offset, false, 0));
echo "<br>";
return false;
}
} else {
if (fseek($fileHandle, $offset, SEEK_SET) != 0) { //erreur
//TRANS: %s is the number of the byte
printf(__("Unable to find the byte %s"), Html::formatNumber($offset, false, 0));
echo "<br>";
return false;
}
}
Html::glpi_flush();
}
$formattedQuery = "";
if (substr($dumpFile, -2) == "gz") {
while (!gzeof($fileHandle)) {
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
// specify read length to be able to read long lines
$buffer = gzgets($fileHandle, 102400);
// do not strip comments due to problems when # in begin of a data line
$formattedQuery .= $buffer;
if (substr(rtrim($formattedQuery), -1) == ";") {
// Do not use the $DB->query
if ($DB->query($formattedQuery)) { //if no success continue to concatenate
$offset = gztell($fileHandle);
$formattedQuery = "";
$cpt++;
}
}
}
} else {
while (!feof($fileHandle)) {
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
// specify read length to be able to read long lines
$buffer = fgets($fileHandle, 102400);
// do not strip comments due to problems when # in begin of a data line
$formattedQuery .= $buffer;
if (substr(rtrim($formattedQuery), -1) == ";") {
// Do not use the $DB->query
if ($DB->query($formattedQuery)) { //if no success continue to concatenate
$offset = ftell($fileHandle);
$formattedQuery = "";
$cpt++;
}
}
}
}
if ($DB->error) {
echo "<hr>";
//TRANS: %s is the SQL query which generates the error
printf(__("SQL error starting from %s"), "[$formattedQuery]");
echo "<br>".$DB->error()."<hr>";
}
if (substr($dumpFile, -2) == "gz") {
gzclose($fileHandle);
} else {
fclose($fileHandle);
}
$offset = -1;
return true;
}
/** Backup a glpi DB
*
* @param $DB DB object
* @param $dumpFile dump file
* @param $duree max delay before refresh
* @param $rowlimit rowlimit to backup in one time
**/
function backupMySql($DB, $dumpFile, $duree, $rowlimit) {
global $TPSCOUR, $offsettable, $offsetrow, $cpt;
// $dumpFile, fichier source
// $duree=timeout pour changement de page (-1 = aucun)
if (function_exists('gzopen')) {
$fileHandle = gzopen($dumpFile, "a");
} else {
$fileHandle = gzopen64($dumpFile, "a");
}
if (!$fileHandle) {
//TRANS: %s is the name of the file
echo sprintf(__('Unauthorized access to the file %s'), $dumpFile)."<br>";
return false;
}
if ($offsettable == 0 && $offsetrow == -1) {
$time_file = date("Y-m-d-H-i");
$cur_time = date("Y-m-d H:i");
$todump = "#GLPI Dump database on $cur_time\n";
gzwrite ($fileHandle, $todump);
}
$result = $DB->listTables();
$numtab = 0;
while ($t = $result->next()) {
$tables[$numtab] = $t['TABLE_NAME'];
$numtab++;
}
for (; $offsettable<$numtab; $offsettable++) {
// Dump de la structure table
if ($offsetrow == -1) {
$todump = "\n".get_def($DB, $tables[$offsettable]);
gzwrite ($fileHandle, $todump);
$offsetrow++;
$cpt++;
}
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
$fin = 0;
while (!$fin) {
$todump = get_content($DB, $tables[$offsettable], $offsetrow, $rowlimit);
$rowtodump = substr_count($todump, "INSERT INTO");
if ($rowtodump > 0) {
gzwrite ($fileHandle, $todump);
$cpt += $rowtodump;
$offsetrow += $rowlimit;
if ($rowtodump<$rowlimit) {
$fin = 1;
}
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
} else {
$fin = 1;
$offsetrow = -1;
}
}
if ($fin) {
$offsetrow = -1;
}
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
}
if ($DB->error()) {
echo "<hr>";
//TRANS: %s is the SQL query which generates the error
printf(__("SQL error starting from %s"), "[$formattedQuery]");
echo "<br>".$DB->error()."<hr>";
}
$offsettable = -1;
gzclose($fileHandle);
return true;
}
// #################" DUMP sql#################################
if (isset($_GET["dump"]) && $_GET["dump"] != "") {
$time_file = date("Y-m-d-H-i");
$cur_time = date("Y-m-d H:i");
$filename = GLPI_DUMP_DIR . "/glpi-backup-".GLPI_VERSION."-$time_file.sql.gz";
if (!isset($_GET["duree"]) && is_file($filename)) {
echo "<div class='center'>".__('The file already exists')."</div>";
} else {
init_time(); //initialise le temps
//debut de fichier
if (!isset($_GET["offsettable"])) {
$offsettable = 0;
} else {
$offsettable = $_GET["offsettable"];
}
//debut de fichier
if (!isset($_GET["offsetrow"])) {
$offsetrow = -1;
} else {
$offsetrow = $_GET["offsetrow"];
}
//timeout de 5 secondes par defaut, -1 pour utiliser sans timeout
if (!isset($_GET["duree"])) {
$duree = $defaulttimeout;
} else {
$duree = $_GET["duree"];
}
//Limite de lignes a dumper a chaque fois
if (!isset($_GET["rowlimit"])) {
$rowlimit = $defaultrowlimit;
} else {
$rowlimit = $_GET["rowlimit"];
}
//si le nom du fichier n'est pas en parametre le mettre ici
if (!isset($_GET["fichier"])) {
$fichier = $filename;
} else {
$fichier = $_GET["fichier"];
}
$tot = $DB->listTables()->count();
if (isset($offsettable)) {
if ($offsettable >= 0) {
$percent = min(100, round(100*$offsettable/$tot, 0));
} else {
$percent = 100;
}
} else {
$percent = 0;
}
if ($percent >= 0) {
Html::displayProgressBar(400, $percent);
echo '<br>';
}
if ($offsettable >= 0) {
if (backupMySql($DB, $fichier, $duree, $rowlimit)) {
echo "<div class='center spaced'>".
"<a href=\"backup.php?dump=1&duree=$duree&rowlimit=$rowlimit&offsetrow=".
"$offsetrow&offsettable=$offsettable&cpt=$cpt&fichier=$fichier\">".
__('Automatic redirection, else click')."</a>";
echo "<script type='text/javascript'>" .
"window.location=\"backup.php?dump=1&duree=$duree&rowlimit=".
"$rowlimit&offsetrow=$offsetrow&offsettable=$offsettable&cpt=$cpt&fichier=".
"$fichier\";</script></div>";
Html::glpi_flush();
exit;
}
}
}
}
// ############################## fin dump sql########################""""
// ################################## dump XML #############################
if (isset($_GET["xmlnow"]) && ($_GET["xmlnow"] != "")) {
xmlbackup();
}
// ################################## fin dump XML #############################
if (isset($_GET["file"]) && ($_GET["file"] != "") && is_file(GLPI_DUMP_DIR . "/" . $_GET["file"])) {
$filepath = realpath(GLPI_DUMP_DIR . "/" . $_GET['file']);
if (is_file($filepath) && Toolbox::startsWith($filepath, GLPI_DUMP_DIR)) {
$_SESSION['TRY_OLD_CONFIG_FIRST'] = true;
init_time(); //initialise le temps
//debut de fichier
if (!isset($_GET["offset"])) {
$offset = 0;
} else {
$offset = $_GET["offset"];
}
//timeout de 5 secondes par defaut, -1 pour utiliser sans timeout
if (!isset($_GET["duree"])) {
$duree = $defaulttimeout;
} else {
$duree = $_GET["duree"];
}
$fsize = filesize($filepath);
if (isset($offset)) {
if ($offset == -1) {
$percent = 100;
} else {
$percent = min(100, round(100*$offset/$fsize, 0));
}
} else {
$percent = 0;
}
if ($percent >= 0) {
Html::displayProgressBar(400, $percent);
echo '<br>';
}
if ($offset != -1) {
if (restoreMySqlDump($DB, $filepath, $duree)) {
echo "<div class='center'>".
"<a href=\"backup.php?file=".$_GET["file"]."&duree=$duree&offset=".
"$offset&cpt=$cpt&donotcheckversion=1\">";
echo __('Automatic redirection, else click')."</a>";
echo "<script language='javascript' type='text/javascript'>".
"window.location=\"backup.php?file=".
$_GET["file"]."&duree=$duree&offset=$offset&cpt=$cpt&donotcheckversion=1\";".
"</script></div>";
Html::glpi_flush();
exit;
}
} else {
// Compatiblity for old version for utf8 complete conversion
$cnf = new Config();
$input['id'] = 1;
$input['utf8_conv'] = 1;
$cnf->update($input);
}
}
}
if (isset($_POST["delfile"])) {
if (isset($_POST['file']) && ($_POST["file"] != "")) {
$filepath = realpath(GLPI_DUMP_DIR . "/" . $_POST['file']);
if (is_file($filepath) && Toolbox::startsWith($filepath, GLPI_DUMP_DIR)) {
$filename = $_POST["file"];
unlink($filepath);
// TRANS: %s is a file name
echo "<div class ='center spaced'>".sprintf(__('%s deleted'), $filename)."</div>";
}
}
}
if (Session::haveRight('backup', Backup::CHECKUPDATE)) {
echo "<div class='center spaced'><table class='tab_glpi'>";
echo "<tr class='tab_bg_1'><td colspan='4' class='center b'>";
Html::showSimpleForm($_SERVER['PHP_SELF'], 'check_version',
__('Check if a new version is available'));
echo "</td></tr></table></div>";
}
// Title backup
echo "<div class='center'>";
if (Session::haveRight('backup', CREATE)) {
echo "<table class='tab_glpi'><tr><td colspan='4'>";
echo "<div class='warning'><i class='fa fa-exclamation-triangle fa-5x'></i><ul><li>";
echo __('GLPI internal backup system is a helper for very small instances.');
echo "<br/>" . __('You should rather use a dedicated tool on your server.');
echo "</li></ul></div>";
echo "</td></tr><tr><td>";
echo "<i class='far fa-save fa-3x'></i>";
"</td>";
echo "<td><a class='vsubmit'
href=\"#\" ".HTML::addConfirmationOnAction(__('Backup the database?'),
"window.location='".$CFG_GLPI["root_doc"].
"/front/backup.php?dump=dump'").
">".__('SQL Dump')."</a> </td>";
echo "<td><a class='vsubmit'
href=\"#\" ".HTML::addConfirmationOnAction(__('Backup the database?'),
"window.location='".$CFG_GLPI["root_doc"].
"/front/backup.php?xmlnow=xmlnow'").
">".__('XML Dump')."</a> </td>";
echo "</tr></table>";
}
echo "<br><table class='tab_cadre' cellpadding='5'>".
"<tr class='center'>".
"<th><u><i>".__('File')."</i></u></th>".
"<th><u><i>".__('Size')."</i></u></th>".
"<th><u><i>".__('Date')."</i></u></th>".
"<th colspan='3'> </th>".
"</tr>";
$dir = opendir(GLPI_DUMP_DIR);
$files = [];
while ($file = readdir($dir)) {
if (($file != ".") && ($file != "..")
&& (preg_match("/\.sql.gz$/i", $file)
|| preg_match("/\.sql$/i", $file))) {
$files[$file] = filemtime(GLPI_DUMP_DIR . "/" . $file);
}
}
arsort($files);
if (count($files)) {
foreach ($files as $file => $date) {
$taille_fic = filesize(GLPI_DUMP_DIR . "/" . $file);
echo "<tr class='tab_bg_2'><td>$file </td>".
"<td class='right'>".Toolbox::getSize($taille_fic)."</td>".
"<td> " . Html::convDateTime(date("Y-m-d H:i", $date)) . "</td>";
if (Session::haveRight('backup', PURGE)) {
echo "<td> ";
//TRANS: %s is the filename
$string = sprintf(__('Delete the file %s?'), $file);
Html::showSimpleForm($_SERVER['PHP_SELF'], 'delfile',
_x('button', 'Delete permanently'),
['file' => $file], '', '', $string);
echo "</td>";
echo "<td> ";
// Multiple confirmation
$string = [];
//TRANS: %s is the filename
$string[] = [sprintf(__('Replace the current database with the backup file %s?'),
$file)];
$string[] = [__('Warning, your actual database will be totaly overwriten by the database you want to restore !!!')];
echo "<a class='vsubmit' href=\"#\" ".HTML::addConfirmationOnAction($string,
"window.location='".$CFG_GLPI["root_doc"].
"/front/backup.php?file=$file&donotcheckversion=1'").
">".__('Restore')."</a> </td>";
}
if (Session::haveRight('backup', CREATE)) {
echo "<td> ".
"<a class='vsubmit' href=\"document.send.php?file=_dumps/$file\">".__('Download').
"</a></td>";
}
echo "</tr>";
}
}
closedir($dir);
$dir = opendir(GLPI_DUMP_DIR);
unset($files);
$files = [];
while ($file = readdir($dir)) {
if (($file != ".") && ($file != "..")
&& preg_match("/\.xml$/i", $file)) {
$files[$file] = filemtime(GLPI_DUMP_DIR . "/" . $file);
}
}
arsort($files);
if (count($files)) {
foreach ($files as $file => $date) {
$taille_fic = filesize(GLPI_DUMP_DIR . "/" . $file);
echo "<tr class='tab_bg_1'><td colspan='6'><hr noshade></td></tr>".
"<tr class='tab_bg_2'><td>$file </td>".
"<td class='right'>".Toolbox::getSize($taille_fic)."</td>".
"<td> " . Html::convDateTime(date("Y-m-d H:i", $date)) . "</td>";
if (Session::haveRight('backup', PURGE)) {
echo "<td colspan=2>";
//TRANS: %s is the filename
$string = sprintf(__('Delete the file %s?'), $file);
Html::showSimpleForm($_SERVER['PHP_SELF'], 'delfile', _x('button', 'Delete permanently'),
['file' => $file], '', '', $string);
echo "</td>";
}
if (Session::haveRight('backup', CREATE)) {
echo "<td> <a class='vsubmit' href=\"document.send.php?file=_dumps/$file\">".
__('Download')."</a></td>";
}
echo "</tr>";
}
}
closedir($dir);
echo "</table>";
echo "</div>";
Html::footer();