index.php 27 KB

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