upgrade.php 18 KB

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