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