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