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