index.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. <?php
  2. /**
  3. * Wizard to configure and initialize the iTop application
  4. */
  5. require_once('../application/utils.inc.php');
  6. require_once('../core/config.class.inc.php');
  7. require_once('../core/log.class.inc.php');
  8. require_once('../core/cmdbsource.class.inc.php');
  9. require_once('./setuppage.class.inc.php');
  10. define('TMP_CONFIG_FILE', '../tmp-config-itop.php');
  11. define('FINAL_CONFIG_FILE', '../config-itop.php');
  12. define('SETUP_STRUCTURE_DATA_DIR', './data/structure');
  13. define('SETUP_SAMPLE_DATA_DIR', './data');
  14. define('PHP_MIN_VERSION', '5.2.0');
  15. define('MYSQL_MIN_VERSION', '5.0.0');
  16. $sOperation = Utils::ReadParam('operation', 'step1');
  17. $oP = new SetupWebPage('iTop configuration wizard');
  18. /**
  19. * Helper function to retrieve the system's temporary directory
  20. * Emulates sys_get_temp_dir if neeed (PHP < 5.2.1)
  21. * @return string Path to the system's temp directory
  22. */
  23. function GetTmpDir()
  24. {
  25. // try to figure out what is the temporary directory
  26. // prior to PHP 5.2.1 the function sys_get_temp_dir
  27. // did not exist
  28. if ( !function_exists('sys_get_temp_dir'))
  29. {
  30. if( $temp=getenv('TMP') ) return realpath($temp);
  31. if( $temp=getenv('TEMP') ) return realpath($temp);
  32. if( $temp=getenv('TMPDIR') ) return realpath($temp);
  33. $temp=tempnam(__FILE__,'');
  34. if (file_exists($temp))
  35. {
  36. unlink($temp);
  37. return realpath(dirname($temp));
  38. }
  39. return null;
  40. }
  41. else
  42. {
  43. return realpath(sys_get_temp_dir());
  44. }
  45. }
  46. /**
  47. * Helper function to retrieve the directory where files are to be uploaded
  48. * @return string Path to the temp directory used for uploading files
  49. */
  50. function GetUploadTmpDir()
  51. {
  52. $sPath = ini_get('upload_tmp_dir');
  53. if (empty($sPath))
  54. {
  55. $sPath = GetTmpDir();
  56. }
  57. return $sPath;
  58. }
  59. /**
  60. * Helper function to check if the current version of PHP
  61. * is compatible with the application
  62. * @return boolean true if this is Ok, false otherwise
  63. */
  64. function CheckPHPVersion(SetupWebPage $oP)
  65. {
  66. $bResult = true;
  67. $oP->log('Info - CheckPHPVersion');
  68. if (version_compare(phpversion(), PHP_MIN_VERSION, '>='))
  69. {
  70. $oP->ok("The current PHP Version (".phpversion().") is greater than the minimum required version (".PHP_MIN_VERSION.")");
  71. }
  72. else
  73. {
  74. $oP->error("Error: The current PHP Version (".phpversion().") is lower than the minimum required version (".PHP_MIN_VERSION.")");
  75. return false;
  76. }
  77. $aMandatoryExtensions = array('mysql', 'iconv', 'simplexml', 'soap');
  78. asort($aMandatoryExtensions); // Sort the list to look clean !
  79. $aExtensionsOk = array();
  80. $aMissingExtensions = array();
  81. $aMissingExtensionsLinks = array();
  82. foreach($aMandatoryExtensions as $sExtension)
  83. {
  84. if (extension_loaded($sExtension))
  85. {
  86. $aExtensionsOk[] = $sExtension;
  87. }
  88. else
  89. {
  90. $aMissingExtensions[] = $sExtension;
  91. $aMissingExtensionsLinks[] = "<a href=\"http://www.php.net/manual/en/book.$sExtension.php\">$sExtension</a>";
  92. }
  93. }
  94. if (count($aExtensionsOk) > 0)
  95. {
  96. $oP->ok("Required PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  97. }
  98. if (count($aMissingExtensions) > 0)
  99. {
  100. $oP->error("Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".");
  101. $bResult = false;
  102. }
  103. // Check some ini settings here
  104. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  105. {
  106. $sPhpIniFile = php_ini_loaded_file();
  107. $oP->log("Info - php.ini path: '$sPhpIniFile'");
  108. }
  109. else
  110. {
  111. $sPhpIniFile = 'php.ini';
  112. }
  113. if (!ini_get('file_uploads'))
  114. {
  115. $oP->error("Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  116. $bResult = false;
  117. }
  118. $sUploadTmpDir = GetUploadTmpDir();
  119. if (empty($sUploadTmpDir))
  120. {
  121. $sUploadTmpDir = '/tmp';
  122. $oP->warning("Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.");
  123. }
  124. // check that the upload directory is indeed writable from PHP
  125. if (!empty($sUploadTmpDir))
  126. {
  127. if (!file_exists($sUploadTmpDir))
  128. {
  129. $oP->error("Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.");
  130. $bResult = false;
  131. }
  132. else if (!is_writable($sUploadTmpDir))
  133. {
  134. $oP->error("Temporary directory for files upload ($sUploadTmpDir) is not writable.");
  135. $bResult = false;
  136. }
  137. else
  138. {
  139. $oP->log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
  140. }
  141. }
  142. if (!ini_get('upload_max_filesize'))
  143. {
  144. $oP->error("File upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  145. }
  146. $iMaxFileUploads = ini_get('max_file_uploads');
  147. if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
  148. {
  149. $oP->error("File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").");
  150. $bResult = false;
  151. }
  152. $oP->log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
  153. $oP->log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
  154. // Check some more ini settings here, needed for file upload
  155. if (get_magic_quotes_gpc())
  156. {
  157. $oP->error("'magic_quotes_gpc' is set to On in '$sPhpIniFile', please turn if Off before continuing.");
  158. $bResult = false;
  159. }
  160. return $bResult;
  161. }
  162. /**
  163. * Helper function check the connection to the database and (if connected) to enumerate
  164. * the existing databases
  165. * @return Array The list of databases found in the server
  166. */
  167. function CheckServerConnection(SetupWebPage $oP, $sDBServer, $sDBUser, $sDBPwd)
  168. {
  169. $aResult = array();
  170. $oP->log('Info - CheckServerConnection');
  171. try
  172. {
  173. $oDBSource = new CMDBSource;
  174. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  175. $oP->ok("Connection to '$sDBServer' as '$sDBUser' successful.");
  176. $oP->log("Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  177. $sDBVersion = $oDBSource->GetDBVersion();
  178. if (version_compare($sDBVersion, MYSQL_MIN_VERSION, '>='))
  179. {
  180. $oP->ok("Current MySQL version ($sDBVersion), greater than minimum required version (".MYSQL_MIN_VERSION.")");
  181. // Check some server variables
  182. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  183. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  184. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  185. {
  186. $oP->ok("MySQL server's max_allowed_packet is big enough.");
  187. }
  188. else if($iMaxAllowedPacket < $iMaxUploadSize)
  189. {
  190. $oP->warning("MySQL server's max_allowed_packet ($iMaxAllowedPacket) is not big enough. Please, consider setting it to at least ".(500 + $iMaxUploadSize).".");
  191. }
  192. $oP->log("Info - MySQL max_allowed_packet: $iMaxAllowedPacket");
  193. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  194. if ($iMaxConnections < 5)
  195. {
  196. $oP->warning("MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  197. }
  198. $oP->log("Info - MySQL max_connections: ".($oDBSource->GetServerVariable('max_connections')));
  199. }
  200. else
  201. {
  202. $oP->error("Error: Current MySQL version is ($sDBVersion), minimum required version (".MYSQL_MIN_VERSION.")");
  203. return false;
  204. }
  205. try
  206. {
  207. $aResult = $oDBSource->ListDB();
  208. }
  209. catch(Exception $e)
  210. {
  211. $oP->warning("Warning: unable to enumerate the current databases.");
  212. $aResult = true; // Not an array to differentiate with an empty array
  213. }
  214. }
  215. catch(Exception $e)
  216. {
  217. $oP->error("Error: Connection to '$sDBServer' as '$sDBUser' failed.");
  218. $oP->p($e->GetHtmlDesc());
  219. $aResult = false;
  220. }
  221. return $aResult;
  222. }
  223. /**
  224. * Helper function to initialize the ORM and load the data model
  225. * from the given file
  226. * @param $sConfigFileName string The name of the configuration file to load
  227. * @param $bAllowMissingDatabase boolean Whether or not to allow loading a data model with no corresponding DB
  228. * @return none
  229. */
  230. function InitDataModel(SetupWebPage $oP, $sConfigFileName, $bAllowMissingDatabase = true)
  231. {
  232. require_once('../core/log.class.inc.php');
  233. require_once('../core/coreexception.class.inc.php');
  234. require_once('../core/attributedef.class.inc.php');
  235. require_once('../core/filterdef.class.inc.php');
  236. require_once('../core/stimulus.class.inc.php');
  237. require_once('../core/MyHelpers.class.inc.php');
  238. require_once('../core/expression.class.inc.php');
  239. require_once('../core/cmdbsource.class.inc.php');
  240. require_once('../core/sqlquery.class.inc.php');
  241. require_once('../core/dbobject.class.php');
  242. require_once('../core/dbobjectsearch.class.php');
  243. require_once('../core/dbobjectset.class.php');
  244. require_once('../core/userrights.class.inc.php');
  245. $oP->log("Info - MetaModel::Startup from file '$sConfigFileName' (AllowMissingDB = $bAllowMissingDatabase)");
  246. MetaModel::Startup($sConfigFileName, $bAllowMissingDatabase);
  247. }
  248. /**
  249. * Helper function to create the database structure
  250. * @return boolean true on success, false otherwise
  251. */
  252. function CreateDatabaseStructure(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix)
  253. {
  254. InitDataModel($oP, TMP_CONFIG_FILE, true); // Allow the DB to NOT exist since we're about to create it !
  255. $oP->log('Info - CreateDatabaseStructure');
  256. if (strlen($sDBPrefix) > 0)
  257. {
  258. $oP->info("Creating the structure in '$sDBName' (table names prefixed by '$sDBPrefix').");
  259. }
  260. else
  261. {
  262. $oP->info("Creating the structure in '$sDBName'.");
  263. }
  264. //MetaModel::CheckDefinitions();
  265. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  266. {
  267. MetaModel::DBCreate();
  268. $oP->ok("Database structure successfuly created.");
  269. }
  270. else
  271. {
  272. if (strlen($sDBPrefix) > 0)
  273. {
  274. $oP->error("Error: found iTop tables into the database '$sDBName' (prefix: '$sDBPrefix'). Please, try selecting another database instance or specify another prefix to prevent conflicting table names.");
  275. }
  276. else
  277. {
  278. $oP->error("Error: found iTop tables into the database '$sDBName'. Please, try selecting another database instance or specify a prefix to prevent conflicting table names.");
  279. }
  280. return false;
  281. }
  282. return true;
  283. }
  284. /**
  285. * Helper function to create and administrator account for iTop
  286. * @return boolean true on success, false otherwise
  287. */
  288. function CreateAdminAccount(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd)
  289. {
  290. $oP->log('Info - CreateAdminAccount');
  291. InitDataModel($oP, TMP_CONFIG_FILE, true); // allow missing DB
  292. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd))
  293. {
  294. $oP->ok("Administrator account '$sAdminUser' created.");
  295. return true;
  296. }
  297. else
  298. {
  299. $oP->error("Failed to create the administrator account '$sAdminUser'.");
  300. return false;
  301. }
  302. }
  303. //aFilesToLoad[aFilesToLoad.length] = './menus.xml'; // First load the menus
  304. function ListDataFiles($sDirectory, SetupWebPage $oP)
  305. {
  306. $aFilesToLoad = array();
  307. if ($hDir = @opendir($sDirectory))
  308. {
  309. // This is the correct way to loop over the directory. (according to the documentation)
  310. while (($sFile = readdir($hDir)) !== false)
  311. {
  312. $sExtension = pathinfo($sFile, PATHINFO_EXTENSION );
  313. if (strcasecmp($sExtension, 'xml') == 0)
  314. {
  315. $aFilesToLoad[] = $sDirectory.'/'.$sFile;
  316. }
  317. }
  318. closedir($hDir);
  319. // Load order is important we expect the files to be ordered
  320. // like numbered 1.Organizations.xml 2.Locations.xml , etc.
  321. asort($aFilesToLoad);
  322. }
  323. else
  324. {
  325. $oP->error("Data directory (".$sDirectory.") not found or not readable.");
  326. }
  327. return $aFilesToLoad;
  328. }
  329. /**
  330. * Scans the ./data directory for XML files and output them as a Javascript array
  331. */
  332. function PopulateDataFilesList(SetupWebPage $oP)
  333. {
  334. $oP->add("<script type=\"text/javascript\">\n");
  335. $oP->add("function PopulateDataFilesList()\n");
  336. $oP->add("{\n");
  337. // Structure data
  338. //
  339. $aStructureDataFiles = ListDataFiles(SETUP_STRUCTURE_DATA_DIR, $oP);
  340. foreach($aStructureDataFiles as $sFile)
  341. {
  342. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  343. }
  344. // Sample data - loaded IIF wished by the user
  345. //
  346. $oP->add("if (($(\"#sample_data:checked\").length == 1))");
  347. $oP->add("{");
  348. $aSampleDataFiles = ListDataFiles(SETUP_SAMPLE_DATA_DIR, $oP);
  349. foreach($aSampleDataFiles as $sFile)
  350. {
  351. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  352. }
  353. $oP->add("}\n");
  354. $oP->add("}\n");
  355. $oP->add("</script>\n");
  356. }
  357. /**
  358. * Display the form for the first step of the configuration wizard
  359. * which consists in the database server selection
  360. */
  361. function DisplayStep1(SetupWebPage $oP)
  362. {
  363. $sNextOperation = 'step2';
  364. $oP->add("<h1>iTop configuration wizard</h1>\n");
  365. $oP->add("<h2>Checking prerequisites</h2>\n");
  366. if (CheckPHPVersion($oP))
  367. {
  368. $sRedStar = '<span class="hilite">*</span>';
  369. $oP->add("<h2>Step 1: Configuration of the database connection</h2>\n");
  370. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Connection to the database...', 1)\">\n");
  371. // Form goes here
  372. $oP->add("<fieldset><legend>Database connection</legend>\n");
  373. $aForm = array();
  374. $aForm[] = array('label' => "Server name$sRedStar:", 'input' => "<input id=\"db_server\" type=\"text\" name=\"db_server\" value=\"\">",
  375. 'help' => 'E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"');
  376. $aForm[] = array('label' => "User name$sRedStar:", 'input' => "<input id=\"db_user\" type=\"text\" name=\"db_user\" value=\"\">",
  377. 'help' => 'The account must have the following privileges: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER');
  378. $aForm[] = array('label' => 'Password:', 'input' => "<input id=\"db_pwd\" type=\"password\" name=\"db_pwd\" value=\"\">");
  379. $oP->form($aForm);
  380. $oP->add("</fieldset>\n");
  381. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  382. $oP->add("<button type=\"submit\">Next >></button>\n");
  383. $oP->add("</form>\n");
  384. }
  385. }
  386. /**
  387. * Display the form for the second step of the configuration wizard
  388. * which consists in
  389. * 1) Validating the parameters by connecting to the database server
  390. * 2) Prompting to select an existing database or to create a new one
  391. */
  392. function DisplayStep2(SetupWebPage $oP, Config $oConfig, $sDBServer, $sDBUser, $sDBPwd)
  393. {
  394. $sNextOperation = 'step3';
  395. $oP->add("<h1>iTop configuration wizard</h1>\n");
  396. $oP->add("<h2>Step 2: Database selection</h2>\n");
  397. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Creating database structure...', 2);\">\n");
  398. $aDatabases = CheckServerConnection($oP, $sDBServer, $sDBUser, $sDBPwd);
  399. if ($aDatabases === false)
  400. {
  401. // Connection failed, invalid credentials ? Go back
  402. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  403. }
  404. else
  405. {
  406. // Connection is Ok, save it and continue the setup wizard
  407. $oConfig->SetDBHost($sDBServer);
  408. $oConfig->SetDBUser($sDBUser);
  409. $oConfig->SetDBPwd($sDBPwd);
  410. $oConfig->WriteToFile();
  411. $oP->add("<fieldset><legend>Specify a database<span class=\"hilite\">*</span></legend>\n");
  412. $aForm = array();
  413. if (is_array($aDatabases))
  414. {
  415. foreach($aDatabases as $sDBName)
  416. {
  417. $aForm[] = array('label' => "<input id=\"db_$sDBName\" type=\"radio\" name=\"db_name\" value=\"$sDBName\" /><label for=\"db_$sDBName\"> $sDBName</label>");
  418. }
  419. }
  420. else
  421. {
  422. $aForm[] = array('label' => "<input id=\"current_db\" type=\"radio\" name=\"db_name\" value=\"-1\" /><label for=\"current_db\"> Use the existing database:</label> <input type=\"text\" id=\"current_db_name\" name=\"current_db_name\" value=\"\" maxlength=\"32\"/>");
  423. $oP->add_ready_script("$('#current_db_name').click( function() { $('#current_db').attr('checked', true); });");
  424. }
  425. $aForm[] = array('label' => "<input id=\"new_db\" type=\"radio\" name=\"db_name\" value=\"\" /><label for=\"new_db\"> Create a new database:</label> <input type=\"text\" id=\"new_db_name\" name=\"new_db_name\" value=\"\" maxlength=\"32\"/>");
  426. $oP->form($aForm);
  427. $oP->add_ready_script("$('#new_db_name').click( function() { $('#new_db').attr('checked', true); })");
  428. $oP->add("</fieldset>\n");
  429. $aForm = array();
  430. $aForm[] = array('label' => "Add a prefix to all the tables: <input id=\"db_prefix\" type=\"text\" name=\"db_prefix\" value=\"\" maxlength=\"32\"/>");
  431. $oP->form($aForm);
  432. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  433. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  434. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  435. $oP->add("<button type=\"submit\">Next >></button>\n");
  436. }
  437. $oP->add("</form>\n");
  438. }
  439. /**
  440. * Display the form for the third step of the configuration wizard
  441. * which consists in
  442. * 1) Validating the parameters by connecting to the database server & selecting the database
  443. * 2) Creating the database structure
  444. * 3) Prompting for the admin account to be created
  445. */
  446. function DisplayStep3(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix)
  447. {
  448. $sNextOperation = 'step4';
  449. $oP->add("<h1>iTop configuration wizard</h1>\n");
  450. $oP->add("<h2>Creation of the database structure</h2>\n");
  451. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Creating user and profiles...', 3);\">\n");
  452. $oConfig->SetDBName($sDBName);
  453. $oConfig->SetDBSubname($sDBPrefix);
  454. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  455. if (CreateDatabaseStructure($oP, $oConfig, $sDBName, $sDBPrefix))
  456. {
  457. $sRedStar = "<span class=\"hilite\">*</span>";
  458. $oP->add("<h2>Step 3: Definition of the administrator account</h2>\n");
  459. // Database created, continue with admin creation
  460. $oP->add("<fieldset><legend>Administrator account</legend>\n");
  461. $aForm = array();
  462. $aForm[] = array('label' => "Login$sRedStar:", 'input' => "<input id=\"auth_user\" type=\"text\" name=\"auth_user\" value=\"\">");
  463. $aForm[] = array('label' => "Password$sRedStar:", 'input' => "<input id=\"auth_pwd\" type=\"password\" name=\"auth_pwd\" value=\"\">");
  464. $aForm[] = array('label' => "Retype password$sRedStar:", 'input' => "<input id=\"auth_pwd2\" type=\"password\" name=\"auth_pwd2\" value=\"\">");
  465. $oP->form($aForm);
  466. $oP->add("</fieldset>\n");
  467. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  468. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  469. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  470. $oP->add("<button type=\"submit\">Next >></button>\n");
  471. }
  472. else
  473. {
  474. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  475. }
  476. // Form goes here
  477. $oP->add("</form>\n");
  478. }
  479. /**
  480. * Display the form for the fourth step of the configuration wizard
  481. * which consists in
  482. * 1) Creating the admin user account
  483. * 2) Prompting to load some sample data
  484. */
  485. function DisplayStep4(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd)
  486. {
  487. $sNextOperation = 'step5';
  488. $oP->add("<h1>iTop configuration wizard</h1>\n");
  489. $oP->add("<h2>Creation of the administrator account</h2>\n");
  490. $oP->add("<form method=\"post\"\">\n");
  491. if (CreateAdminAccount($oP, $oConfig, $sAdminUser, $sAdminPwd) && UserRights::Setup())
  492. {
  493. $oP->add("<h2>Step 4: Loading of sample data</h2>\n");
  494. $oP->p("<fieldset><legend> Do you want to load sample data into the database ? </legend>\n");
  495. $oP->p("<input type=\"radio\" id=\"sample_data\" name=\"sample_data\" checked value=\"yes\"> Yes, for testing purposes, populate the database with sample data.\n");
  496. $oP->p("<input type=\"radio\" name=\"sample_data\" unchecked value=\"no\"> No, this is a production system, load only the data required by the application.\n");
  497. $oP->p("</fieldset>\n");
  498. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  499. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  500. $oP->add("<button onclick=\"DoSubmit('Finalizing configuration and loading data...', 4);\">Finish</button>\n");
  501. }
  502. else
  503. {
  504. // Creation failed
  505. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  506. }
  507. // End of visible form
  508. $oP->add("</form>\n");
  509. // Hidden form
  510. $oP->add("<form id=\"GoToNextStep\" method=\"post\">\n");
  511. $oP->add("<input type=\"hidden\" name=\"auth_user\" value=\"$sAdminUser\">\n"); // To be compatible with login page
  512. $oP->add("<input type=\"hidden\" name=\"auth_pwd\" value=\"$sAdminPwd\">\n"); // To be compatible with login page
  513. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  514. $oP->add("</form>\n");
  515. $oP->add("<div id=\"log\" style=\"color:#F00;\"></div>\n");
  516. $oP->add_linked_script('./jquery.progression.js');
  517. PopulateDataFilesList($oP);
  518. }
  519. /**
  520. * Display the form for the fifth (and final) step of the configuration wizard
  521. * which consists in
  522. * 1) Creating the final configuration file
  523. * 2) Prompting the user to make the file read-only
  524. */
  525. function DisplayStep5(SetupWebPage $oP, Config $oConfig, $sAuthUser, $sAuthPwd)
  526. {
  527. try
  528. {
  529. session_start();
  530. // Write the final configuration file
  531. $oConfig->WriteToFile(FINAL_CONFIG_FILE);
  532. // Start the application
  533. InitDataModel($oP, FINAL_CONFIG_FILE, false); // DO NOT allow missing DB
  534. if (UserRights::Login($sAuthUser, $sAuthPwd))
  535. {
  536. $_SESSION['auth_user'] = $sAuthUser;
  537. $_SESSION['auth_pwd'] = $sAuthPwd;
  538. // remove the tmp config file
  539. @unlink(TMP_CONFIG_FILE);
  540. // try to make the final config file read-only
  541. @chmod(FINAL_CONFIG_FILE, 0440); // Read-only for owner and group, nothing for others
  542. $oP->add("<h1>iTop configuration wizard</h1>\n");
  543. $oP->add("<h2>Configuration completed</h2>\n");
  544. $oP->add("<form method=\"get\" action=\"../index.php\">\n");
  545. $oP->ok("The initialization completed successfully.");
  546. // Form goes here
  547. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  548. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  549. $oP->add("<button type=\"submit\">Enter iTop</button>\n");
  550. $oP->add("</form>\n");
  551. }
  552. else
  553. {
  554. $oP->add("<h1>iTop configuration wizard</h1>\n");
  555. $oP->add("<h2>Step 5: Configuration completed</h2>\n");
  556. @unlink(FINAL_CONFIG_FILE); // remove the aborted config
  557. $oP->error("Error: Failed to login for user: '$sAuthUser'\n");
  558. $oP->add("<form method=\"get\" action=\"../index.php\">\n");
  559. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  560. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  561. $oP->add("</form>\n");
  562. }
  563. }
  564. catch(Exception $e)
  565. {
  566. $oP->error("Error: unable to create the configuration file.");
  567. $oP->p($e->getHtmlDesc());
  568. $oP->p("Did you forget to remove the previous (read-only) configuration file ?");
  569. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  570. }
  571. }
  572. /**
  573. * Main program
  574. */
  575. clearstatcache(); // Make sure we know what we are doing !
  576. if (file_exists(FINAL_CONFIG_FILE))
  577. {
  578. // The configuration file already exists
  579. if (is_writable(FINAL_CONFIG_FILE))
  580. {
  581. $oP->warning("<b>Warning:</b> a configuration file '".FINAL_CONFIG_FILE."' already exists, and will be overwritten.");
  582. }
  583. else
  584. {
  585. $oP->add("<h1>iTop configuration wizard</h1>\n");
  586. $oP->add("<h2>Fatal error</h2>\n");
  587. $oP->error("<b>Error:</b> the configuration file '".FINAL_CONFIG_FILE."' already exists and cannot be overwritten.");
  588. $oP->p("The wizard cannot create the configuration file for you. Please remove the file '<b>".realpath(FINAL_CONFIG_FILE)."</b>' or change its access-rights/read-only flag before continuing.");
  589. $oP->output();
  590. exit;
  591. }
  592. }
  593. else
  594. {
  595. // No configuration file yet
  596. // Check that the wizard can write into the root dir to create the configuration file
  597. if (!is_writable(dirname(FINAL_CONFIG_FILE)))
  598. {
  599. $oP->add("<h1>iTop configuration wizard</h1>\n");
  600. $oP->add("<h2>Fatal error</h2>\n");
  601. $oP->error("<b>Error:</b> the directory where to store the configuration file is not writable.");
  602. $oP->p("The wizard cannot create the configuration file for you. Please make sure that the directory '<b>".realpath(dirname(FINAL_CONFIG_FILE))."</b>' is writable for the web server.");
  603. $oP->output();
  604. exit;
  605. }
  606. }
  607. try
  608. {
  609. $oConfig = new Config(TMP_CONFIG_FILE);
  610. }
  611. catch(Exception $e)
  612. {
  613. // We'll end here when the tmp config file does not exist. It's normal
  614. $oConfig = new Config(TMP_CONFIG_FILE, false /* Don't try to load it */);
  615. }
  616. try
  617. {
  618. switch($sOperation)
  619. {
  620. case 'step1':
  621. $oP->log("Info - ========= Wizard step 1 ========");
  622. DisplayStep1($oP);
  623. break;
  624. case 'step2':
  625. $oP->no_cache();
  626. $oP->log("Info - ========= Wizard step 2 ========");
  627. $sDBServer = Utils::ReadParam('db_server');
  628. $sDBUser = Utils::ReadParam('db_user');
  629. $sDBPwd = Utils::ReadParam('db_pwd');
  630. DisplayStep2($oP, $oConfig, $sDBServer, $sDBUser, $sDBPwd);
  631. break;
  632. case 'step3':
  633. $oP->no_cache();
  634. $oP->log("Info - ========= Wizard step 3 ========");
  635. $sDBName = Utils::ReadParam('db_name');
  636. if (empty($sDBName))
  637. {
  638. $sDBName = Utils::ReadParam('new_db_name');
  639. }
  640. $sDBPrefix = Utils::ReadParam('db_prefix');
  641. DisplayStep3($oP, $oConfig, $sDBName, $sDBPrefix);
  642. break;
  643. case 'step4':
  644. $oP->no_cache();
  645. $oP->log("Info - ========= Wizard step 4 ========");
  646. $sAdminUser = Utils::ReadParam('auth_user');
  647. $sAdminPwd = Utils::ReadParam('auth_pwd');
  648. DisplayStep4($oP, $oConfig, $sAdminUser, $sAdminPwd);
  649. break;
  650. case 'step5':
  651. $oP->no_cache();
  652. $oP->log("Info - ========= Wizard step 5 ========");
  653. $sAdminUser = Utils::ReadParam('auth_user');
  654. $sAdminPwd = Utils::ReadParam('auth_pwd');
  655. DisplayStep5($oP, $oConfig, $sAdminUser, $sAdminPwd);
  656. break;
  657. default:
  658. $oP->error("Error: unsupported operation '$sOperation'");
  659. }
  660. }
  661. catch(Exception $e)
  662. {
  663. $oP->error("Error: '".$e->getMessage()."'");
  664. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  665. }
  666. catch(CoreException $e)
  667. {
  668. $oP->error("Error: '".$e->getHtmlDesc()."'");
  669. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  670. }
  671. $oP->output();
  672. ?>