index.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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. // Other included/scanned files
  163. if ($sFileList = php_ini_scanned_files())
  164. {
  165. if (strlen($sFileList) > 0)
  166. {
  167. $aFiles = explode(',', $sFileList);
  168. foreach ($aFiles as $sFile)
  169. {
  170. $sPhpIniFile .= ', '.trim($sFile);
  171. }
  172. }
  173. }
  174. $oP->log("Info - php.ini file(s): '$sPhpIniFile'");
  175. }
  176. else
  177. {
  178. $sPhpIniFile = 'php.ini';
  179. }
  180. if (!ini_get('file_uploads'))
  181. {
  182. $oP->error("Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  183. $bResult = false;
  184. }
  185. $sUploadTmpDir = GetUploadTmpDir();
  186. if (empty($sUploadTmpDir))
  187. {
  188. $sUploadTmpDir = '/tmp';
  189. $oP->warning("Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.");
  190. }
  191. // check that the upload directory is indeed writable from PHP
  192. if (!empty($sUploadTmpDir))
  193. {
  194. if (!file_exists($sUploadTmpDir))
  195. {
  196. $oP->error("Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.");
  197. $bResult = false;
  198. }
  199. else if (!is_writable($sUploadTmpDir))
  200. {
  201. $oP->error("Temporary directory for files upload ($sUploadTmpDir) is not writable.");
  202. $bResult = false;
  203. }
  204. else
  205. {
  206. $oP->log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
  207. }
  208. }
  209. if (!ini_get('upload_max_filesize'))
  210. {
  211. $oP->error("File upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  212. }
  213. $iMaxFileUploads = ini_get('max_file_uploads');
  214. if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
  215. {
  216. $oP->error("File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").");
  217. $bResult = false;
  218. }
  219. $oP->log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
  220. $oP->log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
  221. // Check some more ini settings here, needed for file upload
  222. if (get_magic_quotes_gpc())
  223. {
  224. $oP->error("'magic_quotes_gpc' is set to On. Please turn it Off before continuing. You may want to check the PHP configuration file(s): '$sPhpIniFile'. Be aware that this setting can also be overridden in the apache configuration.");
  225. $bResult = false;
  226. }
  227. $bResult = $bResult & CheckMemoryLimit($oP, MIN_MEMORY_LIMIT);
  228. return $bResult;
  229. }
  230. /**
  231. * Helper function check the connection to the database and (if connected) to enumerate
  232. * the existing databases
  233. * @return Array The list of databases found in the server
  234. */
  235. function CheckServerConnection(SetupWebPage $oP, $sDBServer, $sDBUser, $sDBPwd)
  236. {
  237. $aResult = array();
  238. $oP->log('Info - CheckServerConnection');
  239. try
  240. {
  241. $oDBSource = new CMDBSource;
  242. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  243. $oP->ok("Connection to '$sDBServer' as '$sDBUser' successful.");
  244. $oP->log("Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  245. $sDBVersion = $oDBSource->GetDBVersion();
  246. if (version_compare($sDBVersion, MYSQL_MIN_VERSION, '>='))
  247. {
  248. $oP->ok("Current MySQL version ($sDBVersion), greater than minimum required version (".MYSQL_MIN_VERSION.")");
  249. // Check some server variables
  250. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  251. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  252. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  253. {
  254. $oP->ok("MySQL server's max_allowed_packet is big enough.");
  255. }
  256. else if($iMaxAllowedPacket < $iMaxUploadSize)
  257. {
  258. $oP->warning("MySQL server's max_allowed_packet ($iMaxAllowedPacket) is not big enough. Please, consider setting it to at least ".(500 + $iMaxUploadSize).".");
  259. }
  260. $oP->log("Info - MySQL max_allowed_packet: $iMaxAllowedPacket");
  261. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  262. if ($iMaxConnections < 5)
  263. {
  264. $oP->warning("MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  265. }
  266. $oP->log("Info - MySQL max_connections: ".($oDBSource->GetServerVariable('max_connections')));
  267. }
  268. else
  269. {
  270. $oP->error("Error: Current MySQL version is ($sDBVersion), minimum required version (".MYSQL_MIN_VERSION.")");
  271. return false;
  272. }
  273. try
  274. {
  275. $aResult = $oDBSource->ListDB();
  276. }
  277. catch(Exception $e)
  278. {
  279. $oP->warning("Warning: unable to enumerate the current databases.");
  280. $aResult = true; // Not an array to differentiate with an empty array
  281. }
  282. }
  283. catch(Exception $e)
  284. {
  285. $oP->error("Error: Connection to '$sDBServer' as '$sDBUser' failed.");
  286. $oP->p($e->GetHtmlDesc());
  287. $aResult = false;
  288. }
  289. return $aResult;
  290. }
  291. /**
  292. * Helper function to initialize the ORM and load the data model
  293. * from the given file
  294. * @param $sConfigFileName string The name of the configuration file to load
  295. * @param $bAllowMissingDatabase boolean Whether or not to allow loading a data model with no corresponding DB
  296. * @return none
  297. */
  298. function InitDataModel(SetupWebPage $oP, $sConfigFileName, $bAllowMissingDatabase = true)
  299. {
  300. require_once('../core/log.class.inc.php');
  301. require_once('../core/coreexception.class.inc.php');
  302. require_once('../core/attributedef.class.inc.php');
  303. require_once('../core/filterdef.class.inc.php');
  304. require_once('../core/stimulus.class.inc.php');
  305. require_once('../core/MyHelpers.class.inc.php');
  306. require_once('../core/expression.class.inc.php');
  307. require_once('../core/cmdbsource.class.inc.php');
  308. require_once('../core/sqlquery.class.inc.php');
  309. require_once('../core/dbobject.class.php');
  310. require_once('../core/dbobjectsearch.class.php');
  311. require_once('../core/dbobjectset.class.php');
  312. require_once('../core/userrights.class.inc.php');
  313. $oP->log("Info - MetaModel::Startup from file '$sConfigFileName' (AllowMissingDB = $bAllowMissingDatabase)");
  314. MetaModel::Startup($sConfigFileName, $bAllowMissingDatabase);
  315. }
  316. /**
  317. * Helper function to create the database structure
  318. * @return boolean true on success, false otherwise
  319. */
  320. function CreateDatabaseStructure(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix)
  321. {
  322. InitDataModel($oP, TMP_CONFIG_FILE, true); // Allow the DB to NOT exist since we're about to create it !
  323. $oP->log('Info - CreateDatabaseStructure');
  324. if (strlen($sDBPrefix) > 0)
  325. {
  326. $oP->info("Creating the structure in '$sDBName' (table names prefixed by '$sDBPrefix').");
  327. }
  328. else
  329. {
  330. $oP->info("Creating the structure in '$sDBName'.");
  331. }
  332. //MetaModel::CheckDefinitions();
  333. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  334. {
  335. MetaModel::DBCreate();
  336. $oP->ok("Database structure successfuly created.");
  337. }
  338. else
  339. {
  340. if (strlen($sDBPrefix) > 0)
  341. {
  342. $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.");
  343. }
  344. else
  345. {
  346. $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.");
  347. }
  348. return false;
  349. }
  350. return true;
  351. }
  352. /**
  353. * Helper function to create and administrator account for iTop
  354. * @return boolean true on success, false otherwise
  355. */
  356. function CreateAdminAccount(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd)
  357. {
  358. $oP->log('Info - CreateAdminAccount');
  359. InitDataModel($oP, TMP_CONFIG_FILE, true); // allow missing DB
  360. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd))
  361. {
  362. $oP->ok("Administrator account '$sAdminUser' created.");
  363. return true;
  364. }
  365. else
  366. {
  367. $oP->error("Failed to create the administrator account '$sAdminUser'.");
  368. return false;
  369. }
  370. }
  371. //aFilesToLoad[aFilesToLoad.length] = './menus.xml'; // First load the menus
  372. function ListDataFiles($sDirectory, SetupWebPage $oP)
  373. {
  374. $aFilesToLoad = array();
  375. if ($hDir = @opendir($sDirectory))
  376. {
  377. // This is the correct way to loop over the directory. (according to the documentation)
  378. while (($sFile = readdir($hDir)) !== false)
  379. {
  380. $sExtension = pathinfo($sFile, PATHINFO_EXTENSION );
  381. if (strcasecmp($sExtension, 'xml') == 0)
  382. {
  383. $aFilesToLoad[] = $sDirectory.'/'.$sFile;
  384. }
  385. }
  386. closedir($hDir);
  387. // Load order is important we expect the files to be ordered
  388. // like numbered 1.Organizations.xml 2.Locations.xml , etc.
  389. asort($aFilesToLoad);
  390. }
  391. else
  392. {
  393. $oP->error("Data directory (".$sDirectory.") not found or not readable.");
  394. }
  395. return $aFilesToLoad;
  396. }
  397. /**
  398. * Scans the ./data directory for XML files and output them as a Javascript array
  399. */
  400. function PopulateDataFilesList(SetupWebPage $oP)
  401. {
  402. $oP->add("<script type=\"text/javascript\">\n");
  403. $oP->add("function PopulateDataFilesList()\n");
  404. $oP->add("{\n");
  405. // Structure data
  406. //
  407. $aStructureDataFiles = ListDataFiles(SETUP_STRUCTURE_DATA_DIR, $oP);
  408. foreach($aStructureDataFiles as $sFile)
  409. {
  410. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  411. }
  412. // Sample data - loaded IIF wished by the user
  413. //
  414. $oP->add("if (($(\"#sample_data:checked\").length == 1))");
  415. $oP->add("{");
  416. $aSampleDataFiles = ListDataFiles(SETUP_SAMPLE_DATA_DIR, $oP);
  417. foreach($aSampleDataFiles as $sFile)
  418. {
  419. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  420. }
  421. $oP->add("}\n");
  422. $oP->add("}\n");
  423. $oP->add("</script>\n");
  424. }
  425. /**
  426. * Display the form for the first step of the configuration wizard
  427. * which consists in the database server selection
  428. */
  429. function DisplayStep1(SetupWebPage $oP)
  430. {
  431. $sNextOperation = 'step2';
  432. $oP->add("<h1>iTop configuration wizard</h1>\n");
  433. $oP->add("<h2>Checking prerequisites</h2>\n");
  434. if (CheckPHPVersion($oP))
  435. {
  436. $sRedStar = '<span class="hilite">*</span>';
  437. $oP->add("<h2>Step 1: Configuration of the database connection</h2>\n");
  438. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Connection to the database...', 1)\">\n");
  439. // Form goes here
  440. $oP->add("<fieldset><legend>Database connection</legend>\n");
  441. $aForm = array();
  442. $aForm[] = array('label' => "Server name$sRedStar:", 'input' => "<input id=\"db_server\" type=\"text\" name=\"db_server\" value=\"\">",
  443. 'help' => 'E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"');
  444. $aForm[] = array('label' => "User name$sRedStar:", 'input' => "<input id=\"db_user\" type=\"text\" name=\"db_user\" value=\"\">",
  445. 'help' => 'The account must have the following privileges: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER');
  446. $aForm[] = array('label' => 'Password:', 'input' => "<input id=\"db_pwd\" type=\"password\" name=\"db_pwd\" value=\"\">");
  447. $oP->form($aForm);
  448. $oP->add("</fieldset>\n");
  449. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  450. $oP->add("<button type=\"submit\">Next >></button>\n");
  451. $oP->add("</form>\n");
  452. }
  453. }
  454. /**
  455. * Display the form for the second step of the configuration wizard
  456. * which consists in
  457. * 1) Validating the parameters by connecting to the database server
  458. * 2) Prompting to select an existing database or to create a new one
  459. */
  460. function DisplayStep2(SetupWebPage $oP, Config $oConfig, $sDBServer, $sDBUser, $sDBPwd)
  461. {
  462. $sNextOperation = 'step3';
  463. $oP->add("<h1>iTop configuration wizard</h1>\n");
  464. $oP->add("<h2>Step 2: Database selection</h2>\n");
  465. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Creating database structure...', 2);\">\n");
  466. $aDatabases = CheckServerConnection($oP, $sDBServer, $sDBUser, $sDBPwd);
  467. if ($aDatabases === false)
  468. {
  469. // Connection failed, invalid credentials ? Go back
  470. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  471. }
  472. else
  473. {
  474. // Connection is Ok, save it and continue the setup wizard
  475. $oConfig->SetDBHost($sDBServer);
  476. $oConfig->SetDBUser($sDBUser);
  477. $oConfig->SetDBPwd($sDBPwd);
  478. $oConfig->WriteToFile();
  479. $oP->add("<fieldset><legend>Specify a database<span class=\"hilite\">*</span></legend>\n");
  480. $aForm = array();
  481. if (is_array($aDatabases))
  482. {
  483. foreach($aDatabases as $sDBName)
  484. {
  485. $aForm[] = array('label' => "<input id=\"db_$sDBName\" type=\"radio\" name=\"db_name\" value=\"$sDBName\" /><label for=\"db_$sDBName\"> $sDBName</label>");
  486. }
  487. }
  488. else
  489. {
  490. $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\"/>");
  491. $oP->add_ready_script("$('#current_db_name').click( function() { $('#current_db').attr('checked', true); });");
  492. }
  493. $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\"/>");
  494. $oP->form($aForm);
  495. $oP->add_ready_script("$('#new_db_name').click( function() { $('#new_db').attr('checked', true); })");
  496. $oP->add("</fieldset>\n");
  497. $aForm = array();
  498. $aForm[] = array('label' => "Add a prefix to all the tables: <input id=\"db_prefix\" type=\"text\" name=\"db_prefix\" value=\"\" maxlength=\"32\"/>");
  499. $oP->form($aForm);
  500. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  501. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  502. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  503. $oP->add("<button type=\"submit\">Next >></button>\n");
  504. }
  505. $oP->add("</form>\n");
  506. }
  507. /**
  508. * Display the form for the third step of the configuration wizard
  509. * which consists in
  510. * 1) Validating the parameters by connecting to the database server & selecting the database
  511. * 2) Creating the database structure
  512. * 3) Prompting for the admin account to be created
  513. */
  514. function DisplayStep3(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix)
  515. {
  516. $sNextOperation = 'step4';
  517. $oP->add("<h1>iTop configuration wizard</h1>\n");
  518. $oP->add("<h2>Creation of the database structure</h2>\n");
  519. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Creating user and profiles...', 3);\">\n");
  520. $oConfig->SetDBName($sDBName);
  521. $oConfig->SetDBSubname($sDBPrefix);
  522. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  523. if (CreateDatabaseStructure($oP, $oConfig, $sDBName, $sDBPrefix))
  524. {
  525. $sRedStar = "<span class=\"hilite\">*</span>";
  526. $oP->add("<h2>Step 3: Definition of the administrator account</h2>\n");
  527. // Database created, continue with admin creation
  528. $oP->add("<fieldset><legend>Administrator account</legend>\n");
  529. $aForm = array();
  530. $aForm[] = array('label' => "Login$sRedStar:", 'input' => "<input id=\"auth_user\" type=\"text\" name=\"auth_user\" value=\"\">");
  531. $aForm[] = array('label' => "Password$sRedStar:", 'input' => "<input id=\"auth_pwd\" type=\"password\" name=\"auth_pwd\" value=\"\">");
  532. $aForm[] = array('label' => "Retype password$sRedStar:", 'input' => "<input id=\"auth_pwd2\" type=\"password\" name=\"auth_pwd2\" value=\"\">");
  533. $oP->form($aForm);
  534. $oP->add("</fieldset>\n");
  535. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  536. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  537. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  538. $oP->add("<button type=\"submit\">Next >></button>\n");
  539. }
  540. else
  541. {
  542. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  543. }
  544. // Form goes here
  545. $oP->add("</form>\n");
  546. }
  547. /**
  548. * Display the form for the fourth step of the configuration wizard
  549. * which consists in
  550. * 1) Creating the admin user account
  551. * 2) Prompting to load some sample data
  552. */
  553. function DisplayStep4(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd)
  554. {
  555. $sNextOperation = 'step5';
  556. $oP->add("<h1>iTop configuration wizard</h1>\n");
  557. $oP->add("<h2>Creation of the administrator account</h2>\n");
  558. $oP->add("<form method=\"post\"\">\n");
  559. if (CreateAdminAccount($oP, $oConfig, $sAdminUser, $sAdminPwd) && UserRights::Setup())
  560. {
  561. $oP->add("<h2>Step 4: Loading of sample data</h2>\n");
  562. $oP->p("<fieldset><legend> Do you want to load sample data into the database ? </legend>\n");
  563. $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");
  564. $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");
  565. $oP->p("</fieldset>\n");
  566. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  567. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  568. $oP->add("<button onclick=\"DoSubmit('Finalizing configuration and loading data...', 4);\">Finish</button>\n");
  569. }
  570. else
  571. {
  572. // Creation failed
  573. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  574. }
  575. // End of visible form
  576. $oP->add("</form>\n");
  577. // Hidden form
  578. $oP->add("<form id=\"GoToNextStep\" method=\"post\">\n");
  579. $oP->add("<input type=\"hidden\" name=\"auth_user\" value=\"$sAdminUser\">\n"); // To be compatible with login page
  580. $oP->add("<input type=\"hidden\" name=\"auth_pwd\" value=\"$sAdminPwd\">\n"); // To be compatible with login page
  581. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  582. $oP->add("</form>\n");
  583. $oP->add("<div id=\"log\" style=\"color:#F00;\"></div>\n");
  584. $oP->add_linked_script('./jquery.progression.js');
  585. PopulateDataFilesList($oP);
  586. }
  587. /**
  588. * Display the form for the fifth (and final) step of the configuration wizard
  589. * which consists in
  590. * 1) Creating the final configuration file
  591. * 2) Prompting the user to make the file read-only
  592. */
  593. function DisplayStep5(SetupWebPage $oP, Config $oConfig, $sAuthUser, $sAuthPwd)
  594. {
  595. try
  596. {
  597. session_start();
  598. // Write the final configuration file
  599. $oConfig->WriteToFile(FINAL_CONFIG_FILE);
  600. // Start the application
  601. InitDataModel($oP, FINAL_CONFIG_FILE, false); // DO NOT allow missing DB
  602. if (UserRights::Login($sAuthUser, $sAuthPwd))
  603. {
  604. $_SESSION['auth_user'] = $sAuthUser;
  605. $_SESSION['auth_pwd'] = $sAuthPwd;
  606. // remove the tmp config file
  607. @unlink(TMP_CONFIG_FILE);
  608. // try to make the final config file read-only
  609. @chmod(FINAL_CONFIG_FILE, 0440); // Read-only for owner and group, nothing for others
  610. $oP->add("<h1>iTop configuration wizard</h1>\n");
  611. $oP->add("<h2>Configuration completed</h2>\n");
  612. $oP->add("<form method=\"get\" action=\"../index.php\">\n");
  613. $oP->ok("The initialization completed successfully.");
  614. // Form goes here
  615. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  616. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  617. $oP->add("<button type=\"submit\">Enter iTop</button>\n");
  618. $oP->add("</form>\n");
  619. }
  620. else
  621. {
  622. $oP->add("<h1>iTop configuration wizard</h1>\n");
  623. $oP->add("<h2>Step 5: Configuration completed</h2>\n");
  624. @unlink(FINAL_CONFIG_FILE); // remove the aborted config
  625. $oP->error("Error: Failed to login for user: '$sAuthUser'\n");
  626. $oP->add("<form method=\"get\" action=\"../index.php\">\n");
  627. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  628. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  629. $oP->add("</form>\n");
  630. }
  631. }
  632. catch(Exception $e)
  633. {
  634. $oP->error("Error: unable to create the configuration file.");
  635. $oP->p($e->getHtmlDesc());
  636. $oP->p("Did you forget to remove the previous (read-only) configuration file ?");
  637. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  638. }
  639. }
  640. /**
  641. * Main program
  642. */
  643. clearstatcache(); // Make sure we know what we are doing !
  644. if (file_exists(FINAL_CONFIG_FILE))
  645. {
  646. // The configuration file already exists
  647. if (is_writable(FINAL_CONFIG_FILE))
  648. {
  649. $oP->warning("<b>Warning:</b> a configuration file '".FINAL_CONFIG_FILE."' already exists, and will be overwritten.");
  650. }
  651. else
  652. {
  653. $oP->add("<h1>iTop configuration wizard</h1>\n");
  654. $oP->add("<h2>Fatal error</h2>\n");
  655. $oP->error("<b>Error:</b> the configuration file '".FINAL_CONFIG_FILE."' already exists and cannot be overwritten.");
  656. $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.");
  657. $oP->output();
  658. exit;
  659. }
  660. }
  661. else
  662. {
  663. // No configuration file yet
  664. // Check that the wizard can write into the root dir to create the configuration file
  665. if (!is_writable(dirname(FINAL_CONFIG_FILE)))
  666. {
  667. $oP->add("<h1>iTop configuration wizard</h1>\n");
  668. $oP->add("<h2>Fatal error</h2>\n");
  669. $oP->error("<b>Error:</b> the directory where to store the configuration file is not writable.");
  670. $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.");
  671. $oP->output();
  672. exit;
  673. }
  674. }
  675. try
  676. {
  677. $oConfig = new Config(TMP_CONFIG_FILE);
  678. }
  679. catch(Exception $e)
  680. {
  681. // We'll end here when the tmp config file does not exist. It's normal
  682. $oConfig = new Config(TMP_CONFIG_FILE, false /* Don't try to load it */);
  683. }
  684. try
  685. {
  686. switch($sOperation)
  687. {
  688. case 'step1':
  689. $oP->log("Info - ========= Wizard step 1 ========");
  690. DisplayStep1($oP);
  691. break;
  692. case 'step2':
  693. $oP->no_cache();
  694. $oP->log("Info - ========= Wizard step 2 ========");
  695. $sDBServer = Utils::ReadParam('db_server');
  696. $sDBUser = Utils::ReadParam('db_user');
  697. $sDBPwd = Utils::ReadParam('db_pwd');
  698. DisplayStep2($oP, $oConfig, $sDBServer, $sDBUser, $sDBPwd);
  699. break;
  700. case 'step3':
  701. $oP->no_cache();
  702. $oP->log("Info - ========= Wizard step 3 ========");
  703. $sDBName = Utils::ReadParam('db_name');
  704. if (empty($sDBName))
  705. {
  706. $sDBName = Utils::ReadParam('new_db_name');
  707. }
  708. $sDBPrefix = Utils::ReadParam('db_prefix');
  709. DisplayStep3($oP, $oConfig, $sDBName, $sDBPrefix);
  710. break;
  711. case 'step4':
  712. $oP->no_cache();
  713. $oP->log("Info - ========= Wizard step 4 ========");
  714. $sAdminUser = Utils::ReadParam('auth_user');
  715. $sAdminPwd = Utils::ReadParam('auth_pwd');
  716. DisplayStep4($oP, $oConfig, $sAdminUser, $sAdminPwd);
  717. break;
  718. case 'step5':
  719. $oP->no_cache();
  720. $oP->log("Info - ========= Wizard step 5 ========");
  721. $sAdminUser = Utils::ReadParam('auth_user');
  722. $sAdminPwd = Utils::ReadParam('auth_pwd');
  723. DisplayStep5($oP, $oConfig, $sAdminUser, $sAdminPwd);
  724. break;
  725. default:
  726. $oP->error("Error: unsupported operation '$sOperation'");
  727. }
  728. }
  729. catch(Exception $e)
  730. {
  731. $oP->error("Error: '".$e->getMessage()."'");
  732. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  733. }
  734. catch(CoreException $e)
  735. {
  736. $oP->error("Error: '".$e->getHtmlDesc()."'");
  737. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  738. }
  739. $oP->output();
  740. ?>