index.php 26 KB

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