index.php 28 KB

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