export.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. /**
  20. * \file htdocs/admin/tools/export.php
  21. * \brief Page to export a database into a dump file
  22. */
  23. require '../../main.inc.php';
  24. require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  28. $langs->load("admin");
  29. $action=GETPOST('action','alpha');
  30. $what=GETPOST('what','alpha');
  31. $export_type=GETPOST('export_type','alpha');
  32. $file=GETPOST('filename_template','alpha');
  33. $sortfield = GETPOST('sortfield','alpha');
  34. $sortorder = GETPOST('sortorder','alpha');
  35. $page = GETPOST("page",'int');
  36. if (! $sortorder) $sortorder="DESC";
  37. if (! $sortfield) $sortfield="date";
  38. if ($page < 0) { $page = 0; }
  39. $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
  40. $offset = $limit * $page;
  41. if (! $user->admin) accessforbidden();
  42. if ($file && ! $what)
  43. {
  44. //print DOL_URL_ROOT.'/dolibarr_export.php';
  45. header("Location: ".DOL_URL_ROOT.'/admin/tools/dolibarr_export.php?msg='.urlencode($langs->trans("ErrorFieldRequired",$langs->transnoentities("ExportMethod"))));
  46. exit;
  47. }
  48. $errormsg='';
  49. /*
  50. * Actions
  51. */
  52. if ($action == 'delete')
  53. {
  54. $file=$conf->admin->dir_output.'/'.GETPOST('urlfile');
  55. $ret=dol_delete_file($file, 1);
  56. if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
  57. else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
  58. $action='';
  59. }
  60. /*
  61. * View
  62. */
  63. $_SESSION["commandbackuplastdone"]='';
  64. $_SESSION["commandbackuptorun"]='';
  65. $_SESSION["commandbackupresult"]='';
  66. // Increase limit of time. Works only if we are not in safe mode
  67. $ExecTimeLimit=600;
  68. if (!empty($ExecTimeLimit))
  69. {
  70. $err=error_reporting();
  71. error_reporting(0); // Disable all errors
  72. //error_reporting(E_ALL);
  73. @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
  74. error_reporting($err);
  75. }
  76. if (!empty($MemoryLimit))
  77. {
  78. @ini_set('memory_limit', $MemoryLimit);
  79. }
  80. $form=new Form($db);
  81. $formfile = new FormFile($db);
  82. //$help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad';
  83. //llxHeader('','',$help_url);
  84. //print load_fiche_titre($langs->trans("Backup"),'','title_setup');
  85. // Start with empty buffer
  86. $dump_buffer = '';
  87. $dump_buffer_len = 0;
  88. // We will send fake headers to avoid browser timeout when buffering
  89. $time_start = time();
  90. $outputdir = $conf->admin->dir_output.'/backup';
  91. $result=dol_mkdir($outputdir);
  92. $utils = new Utils($db);
  93. // MYSQL
  94. if ($what == 'mysql')
  95. {
  96. $cmddump=GETPOST("mysqldump"); // Do not sanitize here with 'alpha', will be sanitize later by escapeshellarg
  97. if (! empty($dolibarr_main_restrict_os_commands))
  98. {
  99. $arrayofallowedcommand=explode(',', $dolibarr_main_restrict_os_commands);
  100. $ok=0;
  101. dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that on of this command is inside ".$cmddump);
  102. foreach($arrayofallowedcommand as $allowedcommand)
  103. {
  104. if (preg_match('/'.preg_quote($allowedcommand,'/').'/', $cmddump))
  105. {
  106. $ok=1;
  107. break;
  108. }
  109. }
  110. if (! $ok)
  111. {
  112. $errormsg=$langs->trans('CommandIsNotInsideAllowedCommands');
  113. }
  114. }
  115. if (! $errormsg && $cmddump)
  116. {
  117. dolibarr_set_const($db, 'SYSTEMTOOLS_MYSQLDUMP', $cmddump,'chaine',0,'',$conf->entity);
  118. }
  119. if (! $errormsg)
  120. {
  121. $utils->dumpDatabase(GETPOST('compression','alpha'), $what, 0, $file);
  122. $errormsg=$utils->error;
  123. $_SESSION["commandbackuplastdone"]=$utils->result['commandbackuplastdone'];
  124. $_SESSION["commandbackuptorun"]=$utils->result['commandbackuptorun'];
  125. }
  126. }
  127. // MYSQL NO BIN
  128. if ($what == 'mysqlnobin')
  129. {
  130. $utils->dumpDatabase(GETPOST('compression','alpha'), $what, 0, $file);
  131. $errormsg=$utils->error;
  132. $_SESSION["commandbackuplastdone"]=$utils->result['commandbackuplastdone'];
  133. $_SESSION["commandbackuptorun"]=$utils->result['commandbackuptorun'];
  134. }
  135. // POSTGRESQL
  136. if ($what == 'postgresql')
  137. {
  138. $cmddump=GETPOST("postgresqldump"); // Do not sanitize here with 'alpha', will be sanitize later by escapeshellarg
  139. if (! $errormsg && $cmddump)
  140. {
  141. dolibarr_set_const($db, 'SYSTEMTOOLS_POSTGRESQLDUMP', $cmddump,'chaine',0,'',$conf->entity);
  142. }
  143. if (! $errormsg)
  144. {
  145. $utils->dumpDatabase(GETPOST('compression','alpha'), $what, 0, $file);
  146. $errormsg=$utils->error;
  147. $_SESSION["commandbackuplastdone"]=$utils->result['commandbackuplastdone'];
  148. $_SESSION["commandbackuptorun"]=$utils->result['commandbackuptorun'];
  149. }
  150. $what=''; // Clear to show message to run command
  151. }
  152. if ($errormsg)
  153. {
  154. setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors');
  155. $resultstring='';
  156. $resultstring.='<div class="error">'.$langs->trans("Error")." : ".$errormsg.'</div>';
  157. $_SESSION["commandbackupresult"]=$resultstring;
  158. }
  159. else
  160. {
  161. if ($what)
  162. {
  163. setEventMessages($langs->trans("BackupFileSuccessfullyCreated").'.<br>'.$langs->trans("YouCanDownloadBackupFile"), null, 'mesgs');
  164. $resultstring='<div class="ok">';
  165. $resultstring.=$langs->trans("BackupFileSuccessfullyCreated").'.<br>';
  166. $resultstring.=$langs->trans("YouCanDownloadBackupFile");
  167. $resultstring.='<div>';
  168. $_SESSION["commandbackupresult"]=$resultstring;
  169. }
  170. else
  171. {
  172. setEventMessages($langs->trans("YouMustRunCommandFromCommandLineAfterLoginToUser",$dolibarr_main_db_user,$dolibarr_main_db_user), null, 'mesgs');
  173. }
  174. }
  175. /*
  176. $filearray=dol_dir_list($conf->admin->dir_output.'/backup','files',0,'','',$sortfield,(strtolower($sortorder)=='asc'?SORT_ASC:SORT_DESC),1);
  177. $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"));
  178. print '<br>';
  179. */
  180. // Redirect t backup page
  181. header("Location: dolibarr_export.php");
  182. $time_end = time();
  183. $db->close();
  184. // MYSQL NO BINARIES (only php)
  185. /** Backup the db OR just a table without mysqldump binary (does not require any exec permission)
  186. * Author: David Walsh (http://davidwalsh.name/backup-mysql-database-php)
  187. * Updated and enhanced by Stephen Larroque (lrq3000) and by the many commentators from the blog
  188. * Note about foreign keys constraints: for Dolibarr, since there are a lot of constraints and when imported the tables will be inserted in the dumped order, not in constraints order, then we ABSOLUTELY need to use SET FOREIGN_KEY_CHECKS=0; when importing the sql dump.
  189. * Note2: db2SQL by Howard Yeend can be an alternative, by using SHOW FIELDS FROM and SHOW KEYS FROM we could generate a more precise dump (eg: by getting the type of the field and then precisely outputting the right formatting - in quotes, numeric or null - instead of trying to guess like we are doing now).
  190. *
  191. * @param string $outputfile Output file name
  192. * @param string $tables Table name or '*' for all
  193. * @return int <0 if KO, >0 if OK
  194. */
  195. function backup_tables($outputfile, $tables='*')
  196. {
  197. global $db, $langs;
  198. global $errormsg;
  199. // Set to UTF-8
  200. if(is_a($db, 'DoliDBMysqli')) {
  201. /** @var DoliDBMysqli $db */
  202. $db->db->set_charset('utf8');
  203. } else {
  204. /** @var DoliDB $db */
  205. $db->query('SET NAMES utf8');
  206. $db->query('SET CHARACTER SET utf8');
  207. }
  208. //get all of the tables
  209. if ($tables == '*')
  210. {
  211. $tables = array();
  212. $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
  213. while($row = $db->fetch_row($result))
  214. {
  215. $tables[] = $row[0];
  216. }
  217. }
  218. else
  219. {
  220. $tables = is_array($tables) ? $tables : explode(',',$tables);
  221. }
  222. //cycle through
  223. $handle = fopen($outputfile, 'w+');
  224. if (fwrite($handle, '') === FALSE)
  225. {
  226. $langs->load("errors");
  227. dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
  228. $errormsg=$langs->trans("ErrorFailedToWriteInDir");
  229. return -1;
  230. }
  231. // Print headers and global mysql config vars
  232. $sqlhead = '';
  233. $sqlhead .= "-- ".$db::LABEL." dump via php
  234. --
  235. -- Host: ".$db->db->host_info." Database: ".$db->database_name."
  236. -- ------------------------------------------------------
  237. -- Server version ".$db->db->server_info."
  238. /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
  239. /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
  240. /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
  241. /*!40101 SET NAMES utf8 */;
  242. ";
  243. if (GETPOST("nobin_disable_fk")) $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
  244. $sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
  245. if (GETPOST("nobin_use_transaction")) $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
  246. fwrite($handle, $sqlhead);
  247. $ignore = '';
  248. if (GETPOST("nobin_sql_ignore")) $ignore = 'IGNORE ';
  249. $delayed = '';
  250. if (GETPOST("nobin_delayed")) $delayed = 'DELAYED ';
  251. // Process each table and print their definition + their datas
  252. foreach($tables as $table)
  253. {
  254. // Saving the table structure
  255. fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
  256. if (GETPOST("nobin_drop")) fwrite($handle,"DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
  257. //fwrite($handle,"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
  258. //fwrite($handle,"/*!40101 SET character_set_client = utf8 */;\n");
  259. $resqldrop=$db->query('SHOW CREATE TABLE '.$table);
  260. $row2 = $db->fetch_row($resqldrop);
  261. if (empty($row2[1]))
  262. {
  263. fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
  264. }
  265. else
  266. {
  267. fwrite($handle,$row2[1].";\n");
  268. //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
  269. // Dumping the data (locking the table and disabling the keys check while doing the process)
  270. fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
  271. if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
  272. if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
  273. $sql='SELECT * FROM '.$table;
  274. $result = $db->query($sql);
  275. while($row = $db->fetch_row($result))
  276. {
  277. // For each row of data we print a line of INSERT
  278. fwrite($handle,'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES (');
  279. $columns = count($row);
  280. for($j=0; $j<$columns; $j++) {
  281. // 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)
  282. if ($row[$j] == null && !is_string($row[$j])) {
  283. // IMPORTANT: if the field is NULL we set it NULL
  284. $row[$j] = 'NULL';
  285. } elseif(is_string($row[$j]) && $row[$j] == '') {
  286. // if it's an empty string, we set it as an empty string
  287. $row[$j] = "''";
  288. } 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)
  289. // if it's a number, we return it as-is
  290. // $row[$j] = $row[$j];
  291. } else { // else for all other cases we escape the value and put quotes around
  292. $row[$j] = addslashes($row[$j]);
  293. $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
  294. $row[$j] = "'".$row[$j]."'";
  295. }
  296. }
  297. fwrite($handle,implode(',', $row).");\n");
  298. }
  299. if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
  300. if (!GETPOST("nobin_nolocks")) fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
  301. fwrite($handle,"\n\n\n");
  302. }
  303. }
  304. /* Backup Procedure structure*/
  305. /*
  306. $result = $db->query('SHOW PROCEDURE STATUS');
  307. if ($db->num_rows($result) > 0)
  308. {
  309. while ($row = $db->fetch_row($result)) { $procedures[] = $row[1]; }
  310. foreach($procedures as $proc)
  311. {
  312. fwrite($handle,"DELIMITER $$\n\n");
  313. fwrite($handle,"DROP PROCEDURE IF EXISTS '$name'.'$proc'$$\n");
  314. $resqlcreateproc=$db->query("SHOW CREATE PROCEDURE '$proc'");
  315. $row2 = $db->fetch_row($resqlcreateproc);
  316. fwrite($handle,"\n".$row2[2]."$$\n\n");
  317. fwrite($handle,"DELIMITER ;\n\n");
  318. }
  319. }
  320. */
  321. /* Backup Procedure structure*/
  322. // Write the footer (restore the previous database settings)
  323. $sqlfooter="\n\n";
  324. if (GETPOST("nobin_use_transaction")) $sqlfooter .= "COMMIT;\n";
  325. if (GETPOST("nobin_disable_fk")) $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
  326. $sqlfooter.="\n\n-- Dump completed on ".date('Y-m-d G-i-s');
  327. fwrite($handle, $sqlfooter);
  328. fclose($handle);
  329. return 1;
  330. }