dolibarr  17.0.4
upgrade.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2015-2016 RaphaĆ«l Doursenaud <rdoursenaud@gpcsolutions.fr>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  *
20  * Upgrade scripts can be ran from command line with syntax:
21  *
22  * cd htdocs/install
23  * php upgrade.php 3.4.0 3.5.0 [dirmodule|ignoredbversion]
24  * php upgrade2.php 3.4.0 3.5.0 [MODULE_NAME1_TO_ENABLE,MODULE_NAME2_TO_ENABLE]
25  *
26  * And for final step:
27  * php step5.php 3.4.0 3.5.0
28  *
29  * Option 'dirmodule' allows to provide a path for an external module, so we migrate from command line using a script from a module.
30  * Option 'ignoredbversion' allows to run migration even if database version does not match start version of migration
31  * Return code is 0 if OK, >0 if error
32  */
33 
39 include_once 'inc.php';
40 if (!file_exists($conffile)) {
41  print 'Error: Dolibarr config file was not found. This may means that Dolibarr is not installed yet. Please call the page "/install/index.php" instead of "/install/upgrade.php").';
42 }
43 require_once $conffile;
44 require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
45 
46 global $langs;
47 
48 $grant_query = '';
49 $step = 2;
50 $ok = 0;
51 
52 
53 // Cette page peut etre longue. On augmente le delai autorise.
54 // Ne fonctionne que si on est pas en safe_mode.
55 $err = error_reporting();
56 error_reporting(0);
57 @set_time_limit(300);
58 error_reporting($err);
59 
60 
61 $setuplang = GETPOST("selectlang", 'aZ09', 3) ? GETPOST("selectlang", 'aZ09', 3) : 'auto';
62 $langs->setDefaultLang($setuplang);
63 $versionfrom = GETPOST("versionfrom", 'alpha', 3) ? GETPOST("versionfrom", 'alpha', 3) : (empty($argv[1]) ? '' : $argv[1]);
64 $versionto = GETPOST("versionto", 'alpha', 3) ? GETPOST("versionto", 'alpha', 3) : (empty($argv[2]) ? '' : $argv[2]);
65 $dirmodule = ((GETPOST("dirmodule", 'alpha', 3) && GETPOST("dirmodule", 'alpha', 3) != 'ignoredbversion')) ? GETPOST("dirmodule", 'alpha', 3) : ((empty($argv[3]) || $argv[3] == 'ignoredbversion') ? '' : $argv[3]);
66 $ignoredbversion = (GETPOST('ignoredbversion', 'alpha', 3) == 'ignoredbversion') ? GETPOST('ignoredbversion', 'alpha', 3) : ((empty($argv[3]) || $argv[3] != 'ignoredbversion') ? '' : $argv[3]);
67 
68 $langs->loadLangs(array("admin", "install", "other", "errors"));
69 
70 if ($dolibarr_main_db_type == "mysqli") {
71  $choix = 1;
72 }
73 if ($dolibarr_main_db_type == "pgsql") {
74  $choix = 2;
75 }
76 if ($dolibarr_main_db_type == "mssql") {
77  $choix = 3;
78 }
79 
80 
81 dolibarr_install_syslog("--- upgrade: Entering upgrade.php page");
82 if (!is_object($conf)) {
83  dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR);
84 }
85 
86 
87 /*
88  * View
89  */
90 
91 if (!$versionfrom && !$versionto) {
92  print 'Error: Parameter versionfrom or versionto missing.'."\n";
93  print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n";
94  // Test if batch mode
95  $sapi_type = php_sapi_name();
96  $script_file = basename(__FILE__);
97  $path = __DIR__.'/';
98  if (substr($sapi_type, 0, 3) == 'cli') {
99  print 'Syntax from command line: '.$script_file." x.y.z a.b.c\n";
100  }
101  exit;
102 }
103 
104 
105 pHeader('', "upgrade2", GETPOST('action', 'aZ09'), 'versionfrom='.$versionfrom.'&versionto='.$versionto, '', 'main-inside main-inside-borderbottom');
106 
107 $actiondone = 0;
108 
109 // Action to launch the migrate script
110 if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) {
111  $actiondone = 1;
112 
113  print '<h3><img class="valignmiddle inline-block paddingright" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> ';
114  print '<span class="inline-block">'.$langs->trans("DatabaseMigration").'</span></h3>';
115 
116  print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
117  $error = 0;
118 
119  // If password is encoded, we decode it
120  if ((!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass)) || !empty($dolibarr_main_db_encrypted_pass)) {
121  require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
122  if (!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass)) {
123  $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
124  $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
125  $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted
126  } else {
127  $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
128  }
129  }
130 
131  // $conf is already instancied inside inc.php
132  $conf->db->type = $dolibarr_main_db_type;
133  $conf->db->host = $dolibarr_main_db_host;
134  $conf->db->port = $dolibarr_main_db_port;
135  $conf->db->name = $dolibarr_main_db_name;
136  $conf->db->user = $dolibarr_main_db_user;
137  $conf->db->pass = $dolibarr_main_db_pass;
138 
139  // Load type and crypt key
140  if (empty($dolibarr_main_db_encryption)) {
141  $dolibarr_main_db_encryption = 0;
142  }
143  $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
144  if (empty($dolibarr_main_db_cryptkey)) {
145  $dolibarr_main_db_cryptkey = '';
146  }
147  $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
148 
149  $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port);
150 
151  // Create the global $hookmanager object
152  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
153  $hookmanager = new HookManager($db);
154 
155  if ($db->connected) {
156  print '<tr><td class="nowrap">';
157  print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.'</td><td class="right"><span class="neutral">'.$langs->trans("OK").'</span></td></tr>'."\n";
158  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerConnection").": $dolibarr_main_db_host ".$langs->transnoentities("OK"));
159  $ok = 1;
160  } else {
161  print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right"><span class="error">'.$langs->transnoentities("Error")."</span></td></tr>\n";
162  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
163  $ok = 0;
164  }
165 
166  if ($ok) {
167  if ($db->database_selected) {
168  print '<tr><td class="nowrap">';
169  print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.'</td><td class="right"><span class="neutral">'.$langs->trans("OK")."</span></td></tr>\n";
170  dolibarr_install_syslog("upgrade: Database connection successful: ".$dolibarr_main_db_name);
171  $ok = 1;
172  } else {
173  print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right"><span class="ok">'.$langs->trans("Error")."</span></td></tr>\n";
174  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
175  $ok = 0;
176  }
177  }
178 
179  // Affiche version
180  if ($ok) {
181  $version = $db->getVersion();
182  $versionarray = $db->getVersionArray();
183  print '<tr><td>'.$langs->trans("ServerVersion").'</td>';
184  print '<td class="right">'.$version.'</td></tr>';
185  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerVersion").": ".$version);
186  if ($db->type == 'mysqli' && function_exists('mysqli_get_charset')) {
187  $tmparray = $db->db->get_charset();
188  print '<tr><td>'.$langs->trans("ClientCharset").'</td>';
189  print '<td class="right">'.$tmparray->charset.'</td></tr>';
190  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCharset").": ".$tmparray->charset);
191  print '<tr><td>'.$langs->trans("ClientSortingCharset").'</td>';
192  print '<td class="right">'.$tmparray->collation.'</td></tr>';
193  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCollation").": ".$tmparray->collation);
194  }
195 
196  // Test database version requirement
197  $versionmindb = explode('.', $db::VERSIONMIN);
198  //print join('.',$versionarray).' - '.join('.',$versionmindb);
199  if (count($versionmindb) && count($versionarray)
200  && versioncompare($versionarray, $versionmindb) < 0) {
201  // Warning: database version too low.
202  print "<tr><td>".$langs->trans("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb)).'</td><td class="right"><span class="error">'.$langs->trans("Error")."</span></td></tr>\n";
203  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb)));
204  $ok = 0;
205  }
206 
207  // Test database version is not forbidden for migration
208  if (empty($ignoredbversion)) {
209  $dbversion_disallowed = array(
210  array('type'=>'mysql', 'version'=>array(5, 5, 40)),
211  array('type'=>'mysqli', 'version'=>array(5, 5, 40)) //,
212  //array('type'=>'mysql','version'=>array(5,5,41)),
213  //array('type'=>'mysqli','version'=>array(5,5,41))
214  );
215  $listofforbiddenversion = '';
216  foreach ($dbversion_disallowed as $dbversion_totest) {
217  if ($dbversion_totest['type'] == $db->type) {
218  $listofforbiddenversion .= ($listofforbiddenversion ? ', ' : '').join('.', $dbversion_totest['version']);
219  }
220  }
221  foreach ($dbversion_disallowed as $dbversion_totest) {
222  //print $db->type.' - '.join('.',$versionarray).' - '.versioncompare($dbversion_totest['version'],$versionarray)."<br>\n";
223  if ($dbversion_totest['type'] == $db->type
224  && (versioncompare($dbversion_totest['version'], $versionarray) == 0 || versioncompare($dbversion_totest['version'], $versionarray) <= -4 || versioncompare($dbversion_totest['version'], $versionarray) >= 4)
225  ) {
226  // Warning: database version too low.
227  print '<tr><td><div class="warning">'.$langs->trans("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)."</div></td><td class=\"right\">".$langs->trans("Error")."</td></tr>\n";
228  dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion));
229  $ok = 0;
230  break;
231  }
232  }
233  }
234  }
235 
236  // Force l'affichage de la progression
237  if ($ok) {
238  print '<tr><td colspan="2"><span class="opacitymedium messagebepatient">'.$langs->trans("PleaseBePatient").'</span></td></tr>';
239  print '</table>';
240 
241  flush();
242 
243  print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
244  }
245 
246 
247  /*
248  * Remove deprecated indexes and constraints for Mysql
249  */
250  if ($ok && preg_match('/mysql/', $db->type)) {
251  $versioncommande = array(4, 0, 0);
252  if (count($versioncommande) && count($versionarray)
253  && versioncompare($versioncommande, $versionarray) <= 0) { // Si mysql >= 4.0
254  dolibarr_install_syslog("Clean database from bad named constraints");
255 
256  // Suppression vieilles contraintes sans noms et en doubles
257  // Les contraintes indesirables ont un nom qui commence par 0_ ou se termine par ibfk_999
258  $listtables = array(
259  MAIN_DB_PREFIX.'adherent_options',
260  MAIN_DB_PREFIX.'bank_class',
261  MAIN_DB_PREFIX.'c_ecotaxe',
262  MAIN_DB_PREFIX.'c_methode_commande_fournisseur', // table renamed
263  MAIN_DB_PREFIX.'c_input_method'
264  );
265 
266  $listtables = $db->DDLListTables($conf->db->name, '');
267 
268  foreach ($listtables as $val) {
269  // Database prefix filter
270  if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val)) {
271  //print "x".$val."<br>";
272  $sql = "SHOW CREATE TABLE ".$val;
273  $resql = $db->query($sql);
274  if ($resql) {
275  $values = $db->fetch_array($resql);
276  $i = 0;
277  $createsql = $values[1];
278  $reg = array();
279  while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100) {
280  $sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1];
281  $resqldrop = $db->query($sqldrop);
282  if ($resqldrop) {
283  print '<tr><td colspan="2">'.$sqldrop.";</td></tr>\n";
284  }
285  $createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql);
286  $i++;
287  }
288  $db->free($resql);
289  } else {
290  if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE') {
291  print '<tr><td colspan="2"><span class="error">'.dol_escape_htmltag($sql).' : '.dol_escape_htmltag($db->lasterror())."</span></td></tr>\n";
292  }
293  }
294  }
295  }
296  }
297  }
298 
299  /*
300  * Load sql files
301  */
302  if ($ok) {
303  $dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver
304  if (!empty($dirmodule)) {
305  $dir = dol_buildpath('/'.$dirmodule.'/sql/', 0);
306  }
307  dolibarr_install_syslog("Scan sql files for migration files in ".$dir);
308 
309  // Clean last part to exclude minor version x.y.z -> x.y
310  $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.0', $versionfrom);
311  $newversionto = preg_replace('/(\.[0-9]+)$/i', '.0', $versionto);
312 
313  $filelist = array();
314  $i = 0;
315  $ok = 0;
316  $from = '^'.preg_quote($newversionfrom, '/');
317  $to = preg_quote($newversionto.'.sql', '/').'$';
318 
319  // Get files list
320  $filesindir = array();
321  $handle = opendir($dir);
322  if (is_resource($handle)) {
323  while (($file = readdir($handle)) !== false) {
324  if (preg_match('/\.sql$/i', $file)) {
325  $filesindir[] = $file;
326  }
327  }
328  sort($filesindir);
329  } else {
330  print '<div class="error">'.$langs->trans("ErrorCanNotReadDir", $dir).'</div>';
331  }
332 
333  // Define which file to run
334  foreach ($filesindir as $file) {
335  if (preg_match('/'.$from.'\-/i', $file)) {
336  $filelist[] = $file;
337  } elseif (preg_match('/\-'.$to.'/i', $file)) { // First test may be false if we migrate from x.y.* to x.y.*
338  $filelist[] = $file;
339  }
340  }
341 
342  if (count($filelist) == 0) {
343  print '<div class="error">'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'</div>';
344  } else {
345  $listoffileprocessed = array(); // Protection to avoid to process twice the same file
346 
347  // Loop on each migrate files
348  foreach ($filelist as $file) {
349  if (in_array($dir.$file, $listoffileprocessed)) {
350  continue;
351  }
352 
353  print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>';
354  print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").'</td><td class="right">'.$file.'</td></tr>'."\n";
355 
356  // Run sql script
357  $ok = run_sql($dir.$file, 0, '', 1, '', 'default', 32768, 0, 0, 2);
358  $listoffileprocessed[$dir.$file] = $dir.$file;
359 
360 
361  // Scan if there is migration scripts that depends of Dolibarr version
362  // for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql" or "dolibarr_always.sql")
363  $modulesfile = array();
364  foreach ($conf->file->dol_document_root as $type => $dirroot) {
365  $handlemodule = @opendir($dirroot); // $dirroot may be '..'
366  if (is_resource($handlemodule)) {
367  while (($filemodule = readdir($handlemodule)) !== false) {
368  if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) { // We exclude filemodule that contains . (are not directories) and are not directories.
369  //print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file;
370  if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file)) {
371  $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file;
372  }
373  if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_allversions.sql')) {
374  $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_allversions.sql'] = '/'.$filemodule.'/sql/dolibarr_allversions.sql';
375  }
376  }
377  }
378  closedir($handlemodule);
379  }
380  }
381 
382  if (count($modulesfile)) {
383  print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>';
384 
385  foreach ($modulesfile as $modulefilelong => $modulefileshort) {
386  if (in_array($modulefilelong, $listoffileprocessed)) {
387  continue;
388  }
389 
390  print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").' (external modules)</td><td class="right">'.$modulefileshort.'</td></tr>'."\n";
391 
392  // Run sql script
393  $okmodule = run_sql($modulefilelong, 0, '', 1); // Note: Result of migration of external module should not decide if we continue migration of Dolibarr or not.
394  $listoffileprocessed[$modulefilelong] = $modulefilelong;
395  }
396  }
397  }
398  }
399  }
400 
401  print '</table>';
402 
403  if ($db->connected) {
404  $db->close();
405  }
406 }
407 
408 
409 if (empty($actiondone)) {
410  print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
411 }
412 
413 $ret = 0;
414 if (!$ok && isset($argv[1])) {
415  $ret = 1;
416 }
417 dolibarr_install_syslog("Exit ".$ret);
418 
419 dolibarr_install_syslog("--- upgrade: end ".((!$ok && empty($_GET["ignoreerrors"])) || $dirmodule));
420 $nonext = (!$ok && empty($_GET["ignoreerrors"])) ? 2 : 0;
421 if ($dirmodule) {
422  $nonext = 1;
423 }
424 pFooter($nonext, $setuplang);
425 
426 if ($db->connected) {
427  $db->close();
428 }
429 
430 // Return code if ran from command line
431 if ($ret) {
432  exit($ret);
433 }
run_sql($sqlfile, $silent=1, $entity='', $usesavepoint=1, $handler='', $okerror='default', $linelengthlimit=32768, $nocommentremoval=0, $offsetforchartofaccount=0, $colspan=0, $onlysqltoimportwebsite=0)
Launch a sql file.
Definition: admin.lib.php:167
versioncompare($versionarray1, $versionarray2)
Compare 2 versions (stored into 2 arrays).
Definition: admin.lib.php:66
Class to manage hooks.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDoliDBInstance($type, $host, $user, $pass, $name, $port)
Return a DoliDB instance (database handler).
pHeader($subtitle, $next, $action='set', $param='', $forcejqueryurl='', $csstable='main-inside')
Show HTML header of install pages.
Definition: inc.php:401
pFooter($nonext=0, $setuplang='', $jscheckfunction='', $withpleasewait=0, $morehtml='')
Print HTML footer of install pages.
Definition: inc.php:490
dolibarr_install_syslog($message, $level=LOG_DEBUG)
Log function for install pages.
Definition: inc.php:551
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.