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