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