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