upgrade.php 16 KB

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