upgrade.php 17 KB

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