Projet

Général

Profil

Paste
Statistiques
| Branche: | Révision:

ryxeo-glpi-git / front / backup.php @ b67d8923

Historique | Voir | Annoter | Télécharger (15,6 ko)

1
<?php
2
/*
3
 * @version $Id: backup.php 7883 2009-01-23 18:37:53Z moyo $
4
 -------------------------------------------------------------------------
5
 GLPI - Gestionnaire Libre de Parc Informatique
6
 Copyright (C) 2003-2009 by the INDEPNET Development Team.
7

8
 http://indepnet.net/   http://glpi-project.org
9
 -------------------------------------------------------------------------
10

11
 LICENSE
12

13
 This file is part of GLPI.
14

15
 GLPI is free software; you can redistribute it and/or modify
16
 it under the terms of the GNU General Public License as published by
17
 the Free Software Foundation; either version 2 of the License, or
18
 (at your option) any later version.
19

20
 GLPI is distributed in the hope that it will be useful,
21
 but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 GNU General Public License for more details.
24

25
 You should have received a copy of the GNU General Public License
26
 along with GLPI; if not, write to the Free Software
27
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28
 --------------------------------------------------------------------------
29
 */
30

    
31
// ----------------------------------------------------------------------
32
// Original Author of file:
33
// Purpose of file:
34
// ----------------------------------------------------------------------
35

    
36

    
37

    
38

    
39
$NEEDED_ITEMS=array("xml");
40
define('GLPI_ROOT', '..');
41
include (GLPI_ROOT . "/inc/includes.php");
42

    
43
checkRight("backup","w");
44

    
45
// full path 
46
$path = GLPI_DUMP_DIR ;
47

    
48

    
49

    
50
commonHeader($LANG["common"][12],$_SERVER['PHP_SELF'],"admin","backup");
51

    
52

    
53
$max_time=min(get_cfg_var("max_execution_time"),get_cfg_var("max_input_time"));
54
if ($max_time==0) {$defaulttimeout=60;$defaultrowlimit=5;}
55
else if ($max_time>5) {$defaulttimeout=$max_time-2;$defaultrowlimit=5;}
56
else {$defaulttimeout=max(1,$max_time-2);$defaultrowlimit=2;}
57

    
58

    
59

    
60
?>
61
<script language="JavaScript" type="text/javascript">
62
<!--
63
function dump(what3){
64
        if (confirm("<?php echo $LANG["backup"][18];?> " + what3 +  "?")) {
65
                window.location = "backup.php?dump=" + what3;
66
        }
67
}
68
function restore(what) {
69
        if (confirm("<?php echo $LANG["backup"][16];?> " + what +  "?")) {
70
                window.location = "backup.php?file=" + what +"&donotcheckversion=1";
71
        }
72
}
73

    
74
function erase(what2){
75
        if (confirm("<?php echo $LANG["backup"][17];?> " + what2 +  "?")) {
76
                window.location = "backup.php?delfile=" + what2;
77
        }
78
}
79

    
80
function xmlnow(what4){
81
        if (confirm("<?php echo $LANG["backup"][18] ;?> " + what4 +  "?")) {
82
                window.location = "backup.php?xmlnow=" + what4;
83
        }
84
}
85

    
86

    
87
//-->
88
</script>
89

    
90

    
91
<?php
92

    
93

    
94

    
95
// les deux options qui suivent devraient �re incluses dans le fichier de config plutot non ?
96
// 1 only with ZLib support, else change value to 0
97
$compression = 0;
98

    
99

    
100

    
101
if ($compression==1) $filetype = "sql.gz";
102
else $filetype = "sql";
103

    
104
/// genere un fichier backup.xml a partir de base dbhost connecte avec l'utilisateur dbuser et le mot de passe dbpassword sur le serveur dbdefault
105
function xmlbackup()
106
{
107
        global $CFG_GLPI,$DB;
108

    
109
        //on parcoure la DB et on liste tous les noms des tables dans $table
110
        //on incremente $query[] de "select * from $table"  pour chaque occurence de $table
111

    
112
        $result = $DB->list_tables();
113
        $i = 0;
114
        while ($line = $DB->fetch_array($result))
115
        {
116

    
117

    
118
                // on se  limite aux tables pr�ix�s _glpi
119
                if (ereg("glpi_",$line[0])){
120

    
121
                        $table = $line[0];
122

    
123

    
124
                        $query[$i] = "select * from ".$table.";";
125
                        $i++;
126
                }
127
        }
128

    
129
        //le nom du fichier a generer...
130
        //Si fichier existe deja il sera remplac�par le nouveau
131

    
132
        $chemin = GLPI_DUMP_DIR."/backup.xml";
133

    
134
        // Creation d'une nouvelle instance de la classe
135
        // et initialisation des variables
136
        $A=new XML();
137

    
138
        // Your query
139
        $A->SqlString=$query;
140

    
141
        //File path
142
        $A->FilePath = $chemin;
143

    
144

    
145
        // Type of layout : 1,2,3,4
146
        // For details about Type see file genxml.php
147
        if (empty($Type))
148
        {
149
                $A->Type=4;
150
        }
151
        else
152
        {
153
                $A->Type=$Type;
154
        }
155

    
156
        //appelle de la methode g��ant le fichier XML
157
        $A->DoXML();
158

    
159

    
160
        // Affichage, si erreur affiche erreur
161
        //sinon affiche un lien vers le fichier XML g���
162

    
163

    
164
        if ($A->IsError==1)
165
        {
166
                echo "ERR : ".$A->ErrorString;
167
        }
168

    
169
        //fin de fonction xmlbackup
170
}
171
////////////////////////// DUMP SQL FUNCTIONS
172
/// Init time to computer time spend
173
function init_time() {
174
        global $TPSDEB,$TPSCOUR;
175

    
176

    
177
        list ($usec,$sec)=explode(" ",microtime());
178
        $TPSDEB=$sec;
179
        $TPSCOUR=0;
180

    
181
}
182

    
183
/// Get current time
184
function current_time() {
185
        global $TPSDEB,$TPSCOUR;
186
        list ($usec,$sec)=explode(" ",microtime());
187
        $TPSFIN=$sec;
188
        if (round($TPSFIN-$TPSDEB,1)>=$TPSCOUR+1) //une seconde de plus
189
        {
190
                $TPSCOUR=round($TPSFIN-$TPSDEB,1);
191
        }
192
}
193

    
194
/**  Get data of a table
195
* @param $DB DB object
196
* @param $table table  name
197
* @param $from begin from
198
* @param $limit limit to 
199
*/
200
function get_content($DB, $table,$from,$limit){
201
        $content="";
202
        $result = $DB->query("SELECT * FROM `$table` LIMIT ".intval($from).",".intval($limit));
203
        if($result)
204
                while($row = $DB->fetch_row($result)) {
205
                        if (get_magic_quotes_runtime()) $row=addslashes_deep($row);
206
                        $insert = "INSERT INTO $table VALUES (";
207
                        for($j=0; $j<$DB->num_fields($result);$j++) {
208
                                if(is_null($row[$j])) $insert .= "NULL,";
209
                                else if($row[$j] != "") $insert .= "'".addslashes($row[$j])."',";
210
                                else $insert .= "'',";
211
                        }
212
                        $insert = ereg_replace(",$","",$insert);
213
                        $insert .= ");\n";
214
                        $content .= $insert;
215
                }
216
        return $content;
217
}
218

    
219
/**  Get structure of a table
220
* @param $DB DB object
221
* @param $table table  name
222
*/
223
function get_def($DB, $table) {
224

    
225

    
226
        $def = "### Dump table $table\n\n";
227
        $def .= "DROP TABLE IF EXISTS `$table`;\n";
228
        $query = "SHOW CREATE TABLE `$table`";
229
        $result=$DB->query($query);
230
        $row=$DB->fetch_array($result);
231

    
232
        // DELETE charset definition : UNEEDED WHEN UTF8 CONVERSION OF THE DATABASE
233
        $def.=$row[1];
234
        //$def.=preg_replace("/DEFAULT CHARSET=\w+/i","",$row[1]);
235
        $def.=";";
236
        return $def."\n\n";
237
}
238

    
239

    
240
/**  Restore a mysql dump
241
* @param $DB DB object
242
* @param $dumpFile dump file
243
* @param $duree max delay before refresh
244
*/
245
function restoreMySqlDump($DB,$dumpFile , $duree){
246
        // $dumpFile, fichier source
247
        // $duree=timeout pour changement de page (-1 = aucun)
248

    
249
        // Desactivation pour empecher les addslashes au niveau de la creation des tables
250
        // En plus, au niveau du dump on considere qu'on est bon
251
        //set_magic_quotes_runtime(0);
252

    
253
        global $DB,$TPSCOUR,$offset,$cpt,$LANG;
254

    
255
        if(!file_exists($dumpFile)){
256
                echo $LANG["document"][38].": $dumpFile<br>";
257
                return FALSE;
258
        }
259
        $fileHandle = fopen($dumpFile, "rb");
260

    
261
        if(!$fileHandle)
262
        {
263
                echo $LANG["document"][45].": $dumpFile<br>";
264
                return FALSE;
265
        }
266

    
267
        if ($offset!=0)
268
        {
269
                if (fseek($fileHandle,$offset,SEEK_SET)!=0) //erreur
270
                {
271
                        echo $LANG["backup"][22]." ".formatNumber($offset,false,0)."<br>";
272
                        return FALSE;
273
                }
274
                glpi_flush();
275
        }
276

    
277
        $formattedQuery = "";
278

    
279
        while(!feof($fileHandle))
280
        {
281
                current_time();
282
                if ($duree>0 and $TPSCOUR>=$duree) //on atteint la fin du temps imparti
283
                        return TRUE;
284

    
285
                //    echo $TPSCOUR."<br>";
286

    
287
                // on indique le  length pour la fonction fgets pour compatibilit�avec les versions <=PHP 4.2
288
                $buffer=fgets($fileHandle,102400);
289

    
290
                if(substr($buffer, 0, 1) != "#")
291
                {
292
                        $formattedQuery .= $buffer;
293
                        if (get_magic_quotes_runtime()) $formattedQuery=stripslashes($formattedQuery);
294
                        if (substr(rtrim($formattedQuery),-1)==";"){
295

    
296
                                // Do not use the $DB->query 
297
                                if ($DB->query($formattedQuery)) //r�ssie sinon continue �conca&t�er
298
                                {
299

    
300
                                        $offset=ftell($fileHandle);
301
                                        $formattedQuery = "";
302
                                        $cpt++;
303
                                }
304
                        }
305
                }
306

    
307
        }
308

    
309
        if ($DB->error){
310
                echo "<hr>".$LANG["backup"][23]." [$formattedQuery]<br>".$DB->error()."<hr>";
311
        }
312

    
313
        fclose($fileHandle);
314
        $offset=-1;
315
        return TRUE;
316
}
317

    
318
/**  Backup a glpi DB
319
* @param $DB DB object
320
* @param $dumpFile dump file
321
* @param $duree max delay before refresh
322
* @param $rowlimit rowlimit to backup in one time
323
*/
324
function backupMySql($DB,$dumpFile, $duree,$rowlimit){
325
        // $dumpFile, fichier source
326
        // $duree=timeout pour changement de page (-1 = aucun)
327

    
328
        global $TPSCOUR,$offsettable,$offsetrow,$cpt,$LANG;
329

    
330
        $fileHandle = fopen($dumpFile, "a");
331

    
332
        if(!$fileHandle)
333
        {
334
                echo $LANG["document"][45].": $dumpFile<br>";
335
                return FALSE;
336
        }
337

    
338
        if ($offsettable==0&&$offsetrow==-1){
339
                $time_file=date("Y-m-d-H-i");
340
                $cur_time=date("Y-m-d H:i");
341
                $todump="#GLPI Dump database on $cur_time\n";
342
//                $todump.="SET NAMES 'utf8';\n";
343
                fwrite ($fileHandle,$todump);
344

    
345
        }
346

    
347
        $result=$DB->list_tables();
348
        $numtab=0;
349
        while ($t=$DB->fetch_array($result)){
350

    
351
                // on se  limite aux tables pr�ix�s _glpi
352
                if (ereg("glpi_",$t[0])){
353
                        $tables[$numtab]=$t[0];
354
                        $numtab++;
355
                }
356
        }
357

    
358

    
359
        for (;$offsettable<$numtab;$offsettable++){
360

    
361
                // Dump de la structure table
362
                if ($offsetrow==-1){
363
                        $todump="\n".get_def($DB,$tables[$offsettable]);
364
                        fwrite ($fileHandle,$todump);
365
                        $offsetrow++;
366
                        $cpt++;
367
                }
368
                current_time();
369
                if ($duree>0 and $TPSCOUR>=$duree) //on atteint la fin du temps imparti
370
                        return TRUE;
371

    
372
                $fin=0;
373
                while (!$fin){
374
                        $todump=get_content($DB,$tables[$offsettable],$offsetrow,$rowlimit);
375
                        $rowtodump=substr_count($todump, "INSERT INTO");
376
                        if ($rowtodump>0){
377
                                fwrite ($fileHandle,$todump);
378
                                $cpt+=$rowtodump;
379
                                $offsetrow+=$rowlimit;
380
                                if ($rowtodump<$rowlimit) $fin=1;
381
                                current_time();
382
                                if ($duree>0 and $TPSCOUR>=$duree) //on atteint la fin du temps imparti
383
                                        return TRUE;
384
                        } else {
385
                                $fin=1;
386
                                $offsetrow=-1;
387
                        }
388
                }
389
                if ($fin) $offsetrow=-1;
390
                current_time();
391
                if ($duree>0 and $TPSCOUR>=$duree) //on atteint la fin du temps imparti
392
                        return TRUE;
393
        }
394
        if ($DB->error())
395
                echo "<hr>".$LANG["backup"][23]." [$formattedQuery]<br>".$DB->error()."<hr>";
396
        $offsettable=-1;
397
        fclose($fileHandle);
398
        return TRUE;
399
}
400

    
401

    
402
// #################" DUMP sql#################################
403

    
404
if (isset($_GET["dump"]) && $_GET["dump"] != ""){
405

    
406
        $time_file=date("Y-m-d-H-i");
407
        $cur_time=date("Y-m-d H:i");
408
        $filename=$path."/glpi-".GLPI_VERSION."-$time_file.$filetype";
409

    
410

    
411
        if (!isset($_GET["duree"])&&is_file($filename)){
412
                echo "<div align='center'>".$LANG["backup"][21]."</div>";
413
        } else {
414
                init_time(); //initialise le temps
415
                //d�ut de fichier
416
                if (!isset($_GET["offsettable"])) $offsettable=0; 
417
                else $offsettable=$_GET["offsettable"]; 
418
                //d�ut de fichier
419
                if (!isset($_GET["offsetrow"])) $offsetrow=-1; 
420
                else $offsetrow=$_GET["offsetrow"];
421
                //timeout de 5 secondes par d�aut, -1 pour utiliser sans timeout
422
                if (!isset($_GET["duree"])) $duree=$defaulttimeout; 
423
                else $duree=$_GET["duree"];
424
                //Limite de lignes �dumper �chaque fois
425
                if (!isset($_GET["rowlimit"])) $rowlimit=$defaultrowlimit; 
426
                else  $rowlimit=$_GET["rowlimit"];
427

    
428
                //si le nom du fichier n'est pas en param�re le mettre ici
429
                if (!isset($_GET["fichier"])) {
430
                        $fichier=$filename;
431
                } else $fichier=$_GET["fichier"];
432

    
433
                $tab=$DB->list_tables();
434
                $tot=$DB->numrows($tab);
435
                if(isset($offsettable)){
436
                        if ($offsettable>=0)
437
                                $percent=min(100,round(100*$offsettable/$tot,0));
438
                        else $percent=100;
439
                }
440
                else $percent=0;
441

    
442
                if ($percent >= 0) {
443
                        displayProgressBar(400,$percent);
444
                }
445

    
446
                if ($offsettable>=0){
447
                        if (backupMySql($DB,$fichier,$duree,$rowlimit))
448
                        {
449
                                echo "<br> <a href=\"backup.php?dump=1&duree=$duree&rowlimit=$rowlimit&offsetrow=$offsetrow&offsettable=$offsettable&cpt=$cpt&fichier=$fichier\">".$LANG["backup"][24]."</a>";
450
                                echo "<script>window.location=\"backup.php?dump=1&duree=$duree&rowlimit=$rowlimit&offsetrow=$offsetrow&offsettable=$offsettable&cpt=$cpt&fichier=$fichier\";</script>";
451
                                glpi_flush();    
452
                                exit;
453

    
454
                        }
455
                }
456
                else  { //echo "<div align='center'><p>Termin� Nombre de requ�es totales trait�s : $cpt</p></div>";
457

    
458
                }
459

    
460
        }        
461
}
462

    
463
// ##############################   fin dump sql########################""""
464

    
465

    
466

    
467

    
468
// ################################## dump XML #############################
469

    
470
if (isset($_GET["xmlnow"]) && $_GET["xmlnow"] !=""){
471

    
472
        xmlbackup();
473

    
474

    
475
}
476
// ################################## fin dump XML #############################
477

    
478

    
479

    
480
if (isset($_GET["file"]) && $_GET["file"] != ""&&is_file($path."/".$_GET["file"])) {
481

    
482
        init_time(); //initialise le temps
483
        //d�ut de fichier
484
        if (!isset($_GET["offset"])) $offset=0;
485
        else  $offset=$_GET["offset"];
486
        //timeout de 5 secondes par d�aut, -1 pour utiliser sans timeout
487
        if (!isset($_GET["duree"])) $duree=$defaulttimeout; 
488
        else $duree=$_GET["duree"];
489

    
490
        $fsize=filesize($path."/".$_GET["file"]);
491
        if(isset($offset)){
492
                if ($offset==-1)
493
                        $percent=100;
494
                else $percent=min(100,round(100*$offset/$fsize,0));
495
        }
496
        else $percent=0;
497

    
498
        if ($percent >= 0) {
499

    
500
                displayProgressBar(400,$percent);
501

    
502
        }
503

    
504
        if ($offset!=-1){
505
                if (restoreMySqlDump($DB,$path."/".$_GET["file"],$duree))
506
                {
507
                        echo "<br><a href=\"backup.php?file=".$_GET["file"]."&amp;duree=$duree&amp;offset=$offset&amp;cpt=$cpt&amp;donotcheckversion=1\">".$LANG["backup"][24]."</a>";
508
                        echo "<script language=\"javascript\" type=\"text/javascript\">window.location=\"backup.php?file=".$_GET["file"]."&duree=$duree&offset=$offset&cpt=$cpt&donotcheckversion=1\";</script>";
509
                        glpi_flush();
510
                        exit;
511
                }
512
        } else   { //echo "<div align='center'><p>Termin� Nombre de requ�es totales trait�s : $cpt<p></div>";
513
                optimize_tables();
514
                // Compatiblity for old version for utf8 complete conversion
515
                $cnf=new Config();
516
                $input['ID']=1;
517
                $input['utf8_conv']=1;
518
                $cnf->update($input);
519
        }
520

    
521

    
522
}
523

    
524
if (isset($_GET["delfile"]) && $_GET["delfile"] != ""){
525

    
526
        $filename=$_GET["delfile"];
527
        if (is_file($path."/".$_GET["delfile"])){
528
                unlink($path."/".$_GET["delfile"]);
529
                echo "<div align ='center'>".$filename." ".$LANG["common"][28]."</div>";
530
        }
531

    
532
}
533

    
534
// Title backup
535
echo " <div align='center'> <table border='0'><tr><td><img src=\"".$CFG_GLPI["root_doc"]."/pics/sauvegardes.png\" alt='".$LANG["common"][28]."'></td> <td><a href=\"javascript:dump('".$LANG["backup"][19]."')\"  class='icon_consol'><b>". $LANG["backup"][0]."</b></a></td><td><a href=\"javascript:xmlnow('".$LANG["backup"][19]."')\" class='icon_consol'><b>". $LANG["backup"][1]."</b></a></td></tr></table>";
536

    
537

    
538
?>
539

    
540

    
541

    
542

    
543
<br>
544
<table class='tab_cadre'  cellpadding="5">
545
<tr align="center"> 
546
<th><u><i><?php echo $LANG["document"][2]; ?></i></u></th>
547
<th><u><i><?php echo $LANG["backup"][11]; ?></i></u></th>
548
<th><u><i><?php echo $LANG["common"][27]; ?></i></u></th>
549
<th colspan='3'>&nbsp;</th>
550
</tr>
551
<?php
552
$dir=opendir($path); 
553
$files=array();
554
while ($file = readdir ($dir)) { 
555
        if ($file != "." && $file != ".." && eregi("\.sql",$file)) { 
556
                $files[$file]=filemtime($path."/".$file);
557
        }
558
}
559
arsort($files);
560
if (count($files)){
561
        foreach ($files as $file => $date){
562
                $taille_fic = filesize($path."/".$file)/1024;
563
                $taille_fic = (int)$taille_fic;
564
                echo "<tr class='tab_bg_2'><td>$file&nbsp;</td>
565
                        <td align=\"right\">&nbsp;" . $taille_fic . " kB&nbsp;</td>
566
                        <td>&nbsp;" . convDateTime(date("Y-m-d H:i",$date)) . "</td>
567
                        <td>&nbsp;<a href=\"javascript:erase('$file')\">".$LANG["buttons"][6]."</a>&nbsp;</td>
568

569
                        <td>&nbsp;<a href=\"javascript:restore('$file')\">".$LANG["buttons"][21]."</a>&nbsp;</td>
570
                        <td>&nbsp;<a href=\"document.send.php?file=_dumps/$file\">".$LANG["backup"][13]."</a></td></tr>";
571
        }
572
}
573
closedir($dir);
574
$dir=opendir($path);
575
unset($files);
576
$files=array();
577
while ($file = readdir ($dir)) {
578
        if ($file != "." && $file != ".." && eregi("\.xml",$file)) {
579
                $files[$file]=filemtime($path."/".$file);
580
        }
581
}
582
arsort($files);
583
if (count($files)){
584
        foreach ($files as $file => $date){
585
                $taille_fic = filesize($path."/".$file)/1024;
586
                $taille_fic = (int)$taille_fic;
587
                echo "
588
                        <tr class='tab_bg_1'><td colspan='6' ><hr noshade></td></tr>
589
                        <tr class='tab_bg_2'><td>$file&nbsp;</td>
590
                        <td align=\"right\">&nbsp;" . $taille_fic . " kB&nbsp;</td>
591
                        <td>&nbsp;" . convDateTime(date("Y-m-d H:i",$date)) . "</td>
592
                        <td>&nbsp;<a href=\"javascript:erase('$file')\">".$LANG["buttons"][6]."</a>&nbsp;</td>
593
                        <td>&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;</td>
594

595
                        <td>&nbsp;<a  href=\"document.send.php?file=_dumps/$file\">".$LANG["backup"][13]."</a></td></tr>";
596
        }
597
}
598
closedir($dir);
599
?>
600
</table>
601
</div>
602
<?php
603

    
604
commonFooter();
605
?>
606

    
607

    
608

    
609

    
Redmine Appliance - Powered by TurnKey Linux