upgrade.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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, '', 'main-inside main-inside-borderbottom');
  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"><span class="opacitymedium messagebepatient">'.$langs->trans("PleaseBePatient").'</span></td></tr>';
  207. print '</table>';
  208. flush();
  209. print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
  210. }
  211. /*
  212. * Remove deprecated indexes and constraints for Mysql
  213. */
  214. if ($ok && preg_match('/mysql/', $db->type)) {
  215. $versioncommande = array(4, 0, 0);
  216. if (count($versioncommande) && count($versionarray)
  217. && versioncompare($versioncommande, $versionarray) <= 0) { // Si mysql >= 4.0
  218. dolibarr_install_syslog("Clean database from bad named constraints");
  219. // Suppression vieilles contraintes sans noms et en doubles
  220. // Les contraintes indesirables ont un nom qui commence par 0_ ou se termine par ibfk_999
  221. $listtables = array(
  222. MAIN_DB_PREFIX.'adherent_options',
  223. MAIN_DB_PREFIX.'bank_class',
  224. MAIN_DB_PREFIX.'c_ecotaxe',
  225. MAIN_DB_PREFIX.'c_methode_commande_fournisseur', // table renamed
  226. MAIN_DB_PREFIX.'c_input_method'
  227. );
  228. $listtables = $db->DDLListTables($conf->db->name, '');
  229. foreach ($listtables as $val) {
  230. // Database prefix filter
  231. if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val)) {
  232. //print "x".$val."<br>";
  233. $sql = "SHOW CREATE TABLE ".$val;
  234. $resql = $db->query($sql);
  235. if ($resql) {
  236. $values = $db->fetch_array($resql);
  237. $i = 0;
  238. $createsql = $values[1];
  239. $reg = array();
  240. while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100) {
  241. $sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1];
  242. $resqldrop = $db->query($sqldrop);
  243. if ($resqldrop) {
  244. print '<tr><td colspan="2">'.$sqldrop.";</td></tr>\n";
  245. }
  246. $createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql);
  247. $i++;
  248. }
  249. $db->free($resql);
  250. } else {
  251. if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE') {
  252. print '<tr><td colspan="2"><span class="error">'.dol_escape_htmltag($sql).' : '.dol_escape_htmltag($db->lasterror())."</span></td></tr>\n";
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }
  259. /*
  260. * Load sql files
  261. */
  262. if ($ok) {
  263. $dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver
  264. if (!empty($dirmodule)) {
  265. $dir = dol_buildpath('/'.$dirmodule.'/sql/', 0);
  266. }
  267. dolibarr_install_syslog("Scan sql files for migration files in ".$dir);
  268. // Clean last part to exclude minor version x.y.z -> x.y
  269. $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.0', $versionfrom);
  270. $newversionto = preg_replace('/(\.[0-9]+)$/i', '.0', $versionto);
  271. $filelist = array();
  272. $i = 0;
  273. $ok = 0;
  274. $from = '^'.preg_quote($newversionfrom, '/');
  275. $to = preg_quote($newversionto.'.sql', '/').'$';
  276. // Get files list
  277. $filesindir = array();
  278. $handle = opendir($dir);
  279. if (is_resource($handle)) {
  280. while (($file = readdir($handle)) !== false) {
  281. if (preg_match('/\.sql$/i', $file)) {
  282. $filesindir[] = $file;
  283. }
  284. }
  285. sort($filesindir);
  286. } else {
  287. print '<div class="error">'.$langs->trans("ErrorCanNotReadDir", $dir).'</div>';
  288. }
  289. // Define which file to run
  290. foreach ($filesindir as $file) {
  291. if (preg_match('/'.$from.'\-/i', $file)) {
  292. $filelist[] = $file;
  293. } elseif (preg_match('/\-'.$to.'/i', $file)) { // First test may be false if we migrate from x.y.* to x.y.*
  294. $filelist[] = $file;
  295. }
  296. }
  297. if (count($filelist) == 0) {
  298. print '<div class="error">'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'</div>';
  299. } else {
  300. $listoffileprocessed = array(); // Protection to avoid to process twice the same file
  301. // Loop on each migrate files
  302. foreach ($filelist as $file) {
  303. if (in_array($dir.$file, $listoffileprocessed)) {
  304. continue;
  305. }
  306. print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>';
  307. print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").'</td><td class="right">'.$file.'</td></tr>'."\n";
  308. // Run sql script
  309. $ok = run_sql($dir.$file, 0, '', 1, '', 'default', 32768, 0, 0, 2);
  310. $listoffileprocessed[$dir.$file] = $dir.$file;
  311. // Scan if there is migration scripts that depends of Dolibarr version
  312. // for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql" or "dolibarr_always.sql")
  313. $modulesfile = array();
  314. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  315. $handlemodule = @opendir($dirroot); // $dirroot may be '..'
  316. if (is_resource($handlemodule)) {
  317. while (($filemodule = readdir($handlemodule)) !== false) {
  318. if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) { // We exclude filemodule that contains . (are not directories) and are not directories.
  319. //print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file;
  320. if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file)) {
  321. $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file;
  322. }
  323. if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_allversions.sql')) {
  324. $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_allversions.sql'] = '/'.$filemodule.'/sql/dolibarr_allversions.sql';
  325. }
  326. }
  327. }
  328. closedir($handlemodule);
  329. }
  330. }
  331. if (count($modulesfile)) {
  332. print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>';
  333. foreach ($modulesfile as $modulefilelong => $modulefileshort) {
  334. if (in_array($modulefilelong, $listoffileprocessed)) {
  335. continue;
  336. }
  337. print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").' (external modules)</td><td class="right">'.$modulefileshort.'</td></tr>'."\n";
  338. // Run sql script
  339. $okmodule = run_sql($modulefilelong, 0, '', 1); // Note: Result of migration of external module should not decide if we continue migration of Dolibarr or not.
  340. $listoffileprocessed[$modulefilelong] = $modulefilelong;
  341. }
  342. }
  343. }
  344. }
  345. }
  346. print '</table>';
  347. if ($db->connected) {
  348. $db->close();
  349. }
  350. }
  351. if (empty($actiondone)) {
  352. print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
  353. }
  354. $ret = 0;
  355. if (!$ok && isset($argv[1])) {
  356. $ret = 1;
  357. }
  358. dolibarr_install_syslog("Exit ".$ret);
  359. dolibarr_install_syslog("--- upgrade: end ".((!$ok && empty($_GET["ignoreerrors"])) || $dirmodule));
  360. $nonext = (!$ok && empty($_GET["ignoreerrors"])) ? 2 : 0;
  361. if ($dirmodule) {
  362. $nonext = 1;
  363. }
  364. pFooter($nonext, $setuplang);
  365. if ($db->connected) {
  366. $db->close();
  367. }
  368. // Return code if ran from command line
  369. if ($ret) {
  370. exit($ret);
  371. }