index.php 29 KB

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