dolibarr  7.0.0-beta
export.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2014 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
4  * Copyright (C) 2015 RaphaĆ«l Doursenaud <rdoursenaud@gpcsolutions.fr>
5  *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 
25 require '../../main.inc.php';
26 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
30 
31 $langs->load("admin");
32 
33 $action=GETPOST('action','alpha');
34 $what=GETPOST('what','alpha');
35 $export_type=GETPOST('export_type','alpha');
36 $file=GETPOST('filename_template','alpha');
37 
38 $sortfield = GETPOST('sortfield','alpha');
39 $sortorder = GETPOST('sortorder','alpha');
40 $page = GETPOST("page",'int');
41 if (! $sortorder) $sortorder="DESC";
42 if (! $sortfield) $sortfield="date";
43 if ($page < 0) { $page = 0; }
44 $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
45 $offset = $limit * $page;
46 
47 if (! $user->admin) accessforbidden();
48 
49 if ($file && ! $what)
50 {
51  //print DOL_URL_ROOT.'/dolibarr_export.php';
52  header("Location: ".DOL_URL_ROOT.'/admin/tools/dolibarr_export.php?msg='.urlencode($langs->trans("ErrorFieldRequired",$langs->transnoentities("ExportMethod"))));
53  exit;
54 }
55 
56 $errormsg='';
57 
58 
59 /*
60  * Actions
61  */
62 
63 if ($action == 'delete')
64 {
65  $file=$conf->admin->dir_output.'/'.GETPOST('urlfile');
66  $ret=dol_delete_file($file, 1);
67  if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
68  else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
69  $action='';
70 }
71 
72 
73 /*
74  * View
75  */
76 
77 $_SESSION["commandbackuplastdone"]='';
78 $_SESSION["commandbackuptorun"]='';
79 $_SESSION["commandbackupresult"]='';
80 
81 // Increase limit of time. Works only if we are not in safe mode
82 $ExecTimeLimit=600;
83 if (!empty($ExecTimeLimit))
84 {
85  $err=error_reporting();
86  error_reporting(0); // Disable all errors
87  //error_reporting(E_ALL);
88  @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
89  error_reporting($err);
90 }
91 $MemoryLimit=0;
92 if (!empty($MemoryLimit))
93 {
94  @ini_set('memory_limit', $MemoryLimit);
95 }
96 
97 $form=new Form($db);
98 $formfile = new FormFile($db);
99 
100 //$help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad';
101 //llxHeader('','',$help_url);
102 
103 //print load_fiche_titre($langs->trans("Backup"),'','title_setup');
104 
105 
106 // Start with empty buffer
107 $dump_buffer = '';
108 $dump_buffer_len = 0;
109 
110 // We will send fake headers to avoid browser timeout when buffering
111 $time_start = time();
112 
113 
114 $outputdir = $conf->admin->dir_output.'/backup';
115 $result=dol_mkdir($outputdir);
116 
117 
118 $utils = new Utils($db);
119 
120 
121 // MYSQL
122 if ($what == 'mysql')
123 {
124 
125  $cmddump=GETPOST("mysqldump"); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg
126  $cmddump=dol_sanitizePathName($cmddump);
127 
128  if (! empty($dolibarr_main_restrict_os_commands))
129  {
130  $arrayofallowedcommand=explode(',', $dolibarr_main_restrict_os_commands);
131  $ok=0;
132  dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that on of this command is inside ".$cmddump);
133  foreach($arrayofallowedcommand as $allowedcommand)
134  {
135  if (preg_match('/'.preg_quote($allowedcommand,'/').'/', $cmddump))
136  {
137  $ok=1;
138  break;
139  }
140  }
141  if (! $ok)
142  {
143  $errormsg=$langs->trans('CommandIsNotInsideAllowedCommands');
144  }
145  }
146 
147  if (! $errormsg && $cmddump)
148  {
149  dolibarr_set_const($db, 'SYSTEMTOOLS_MYSQLDUMP', $cmddump,'chaine',0,'',$conf->entity);
150  }
151 
152  if (! $errormsg)
153  {
154  $utils->dumpDatabase(GETPOST('compression','alpha'), $what, 0, $file);
155  $errormsg=$utils->error;
156  $_SESSION["commandbackuplastdone"]=$utils->result['commandbackuplastdone'];
157  $_SESSION["commandbackuptorun"]=$utils->result['commandbackuptorun'];
158  }
159 }
160 
161 // MYSQL NO BIN
162 if ($what == 'mysqlnobin')
163 {
164  $utils->dumpDatabase(GETPOST('compression','alpha'), $what, 0, $file);
165 
166  $errormsg=$utils->error;
167  $_SESSION["commandbackuplastdone"]=$utils->result['commandbackuplastdone'];
168  $_SESSION["commandbackuptorun"]=$utils->result['commandbackuptorun'];
169 }
170 
171 // POSTGRESQL
172 if ($what == 'postgresql')
173 {
174  $cmddump=GETPOST("postgresqldump"); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg
175  $cmddump=dol_sanitizePathName($cmddump);
176 
177  if (! $errormsg && $cmddump)
178  {
179  dolibarr_set_const($db, 'SYSTEMTOOLS_POSTGRESQLDUMP', $cmddump,'chaine',0,'',$conf->entity);
180  }
181 
182  if (! $errormsg)
183  {
184  $utils->dumpDatabase(GETPOST('compression','alpha'), $what, 0, $file);
185  $errormsg=$utils->error;
186  $_SESSION["commandbackuplastdone"]=$utils->result['commandbackuplastdone'];
187  $_SESSION["commandbackuptorun"]=$utils->result['commandbackuptorun'];
188  }
189 
190  $what=''; // Clear to show message to run command
191 }
192 
193 
194 
195 if ($errormsg)
196 {
197  setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors');
198 
199  $resultstring='';
200  $resultstring.='<div class="error">'.$langs->trans("Error")." : ".$errormsg.'</div>';
201 
202  $_SESSION["commandbackupresult"]=$resultstring;
203 }
204 else
205 {
206  if ($what)
207  {
208  setEventMessages($langs->trans("BackupFileSuccessfullyCreated").'.<br>'.$langs->trans("YouCanDownloadBackupFile"), null, 'mesgs');
209 
210  $resultstring='<div class="ok">';
211  $resultstring.=$langs->trans("BackupFileSuccessfullyCreated").'.<br>';
212  $resultstring.=$langs->trans("YouCanDownloadBackupFile");
213  $resultstring.='<div>';
214 
215  $_SESSION["commandbackupresult"]=$resultstring;
216  }
217  /*else
218  {
219  setEventMessages($langs->trans("YouMustRunCommandFromCommandLineAfterLoginToUser",$dolibarr_main_db_user,$dolibarr_main_db_user), null, 'warnings');
220  }*/
221 }
222 
223 
224 /*
225 $filearray=dol_dir_list($conf->admin->dir_output.'/backup','files',0,'','',$sortfield,(strtolower($sortorder)=='asc'?SORT_ASC:SORT_DESC),1);
226 $result=$formfile->list_of_documents($filearray,null,'systemtools','',1,'backup/',1,0,($langs->trans("NoBackupFileAvailable").'<br>'.$langs->trans("ToBuildBackupFileClickHere",DOL_URL_ROOT.'/admin/tools/dolibarr_export.php')),0,$langs->trans("PreviousDumpFiles"));
227 
228 print '<br>';
229 */
230 
231 // Redirect t backup page
232 header("Location: dolibarr_export.php");
233 
234 $time_end = time();
235 
236 $db->close();
237 
238 
239 
240 // MYSQL NO BINARIES (only php)
251 function backup_tables($outputfile, $tables='*')
252 {
253  global $db, $langs;
254  global $errormsg;
255 
256  // Set to UTF-8
257  if (is_a($db, 'DoliDBMysqli')) {
259  $db->db->set_charset('utf8');
260  } else {
262  $db->query('SET NAMES utf8');
263  $db->query('SET CHARACTER SET utf8');
264  }
265 
266  //get all of the tables
267  if ($tables == '*')
268  {
269  $tables = array();
270  $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
271  while($row = $db->fetch_row($result))
272  {
273  $tables[] = $row[0];
274  }
275  }
276  else
277  {
278  $tables = is_array($tables) ? $tables : explode(',',$tables);
279  }
280 
281  //cycle through
282  $handle = fopen($outputfile, 'w+');
283  if (fwrite($handle, '') === FALSE)
284  {
285  $langs->load("errors");
286  dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
287  $errormsg=$langs->trans("ErrorFailedToWriteInDir");
288  return -1;
289  }
290 
291  // Print headers and global mysql config vars
292  $sqlhead = '';
293  $sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
294 --
295 -- Host: ".$db->db->host_info." Database: ".$db->database_name."
296 -- ------------------------------------------------------
297 -- Server version ".$db->db->server_info."
298 ;;;;;;;;;;
309 
310 ";
311 
312  if (GETPOST("nobin_disable_fk")) $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
313  //$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
314  if (GETPOST("nobin_use_transaction")) $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
315 
316  fwrite($handle, $sqlhead);
317 
318  $ignore = '';
319  if (GETPOST("nobin_sql_ignore")) $ignore = 'IGNORE ';
320  $delayed = '';
321  if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
322 
323  // Process each table and print their definition + their datas
324  foreach($tables as $table)
325  {
326  // Saving the table structure
327  fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
328 
329  if (GETPOST("nobin_drop")) fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
330  fwrite($handle,"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
331  fwrite($handle,"/*!40101 SET character_set_client = utf8 */;\n");
332  $resqldrop=$db->query('SHOW CREATE TABLE '.$table);
333  $row2 = $db->fetch_row($resqldrop);
334  if (empty($row2[1]))
335  {
336  fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
337  }
338  else
339  {
340  fwrite($handle,$row2[1].";\n");
341  //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
342 
343  // Dumping the data (locking the table and disabling the keys check while doing the process)
344  fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
345  if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
346  if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
347  else fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
348 
349  $sql='SELECT * FROM '.$table;
350  $result = $db->query($sql);
351  while($row = $db->fetch_row($result))
352  {
353  // For each row of data we print a line of INSERT
354  fwrite($handle,'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
355  $columns = count($row);
356  for($j=0; $j<$columns; $j++) {
357  // Processing each columns of the row to ensure that we correctly save the value (eg: add quotes for string - in fact we add quotes for everything, it's easier)
358  if ($row[$j] == null && !is_string($row[$j])) {
359  // IMPORTANT: if the field is NULL we set it NULL
360  $row[$j] = 'NULL';
361  } elseif(is_string($row[$j]) && $row[$j] == '') {
362  // if it's an empty string, we set it as an empty string
363  $row[$j] = "''";
364  } elseif(is_numeric($row[$j]) && !strcmp($row[$j], $row[$j]+0) ) { // test if it's a numeric type and the numeric version ($nb+0) == string version (eg: if we have 01, it's probably not a number but rather a string, else it would not have any leading 0)
365  // if it's a number, we return it as-is
366 // $row[$j] = $row[$j];
367  } else { // else for all other cases we escape the value and put quotes around
368  $row[$j] = addslashes($row[$j]);
369  $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
370  $row[$j] = "'".$row[$j]."'";
371  }
372  }
373  fwrite($handle,implode(',', $row).");\n");
374  }
375  if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
376  if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
377  fwrite($handle,"\n\n\n");
378  }
379  }
380 
381  /* Backup Procedure structure*/
382  /*
383  $result = $db->query('SHOW PROCEDURE STATUS');
384  if ($db->num_rows($result) > 0)
385  {
386  while ($row = $db->fetch_row($result)) { $procedures[] = $row[1]; }
387  foreach($procedures as $proc)
388  {
389  fwrite($handle,"DELIMITER $$\n\n");
390  fwrite($handle,"DROP PROCEDURE IF EXISTS '$name'.'$proc'$$\n");
391  $resqlcreateproc=$db->query("SHOW CREATE PROCEDURE '$proc'");
392  $row2 = $db->fetch_row($resqlcreateproc);
393  fwrite($handle,"\n".$row2[2]."$$\n\n");
394  fwrite($handle,"DELIMITER ;\n\n");
395  }
396  }
397  */
398  /* Backup Procedure structure*/
399 
400  // Write the footer (restore the previous database settings)
401  $sqlfooter="\n\n";
402  if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
403  if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
404  $sqlfooter.="\n\n-- Dump completed on ".date('Y-m-d G-i-s');
405  fwrite($handle, $sqlfooter);
406 
407  fclose($handle);
408 
409  return 1;
410 }
Class to manage utility methods.
Definition: utils.class.php:28
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
Definition: admin.lib.php:485
if(empty($reshook)) $form
View.
Definition: perms.php:103
GETPOST($paramname, $check='none', $method=0, $filter=NULL, $options=NULL, $noreplace=0)
Return value of a param into GET or POST supervariable.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage generation of HTML components Only common components must be here.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
Class to offer components to list and upload files.
dol_mkdir($dir, $dataroot='', $newmask=null)
Creation of a directory (this can create recursive subdir)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null)
Remove a file or several files with a mask.
Definition: files.lib.php:1103