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