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