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