index.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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/dict.class.inc.php');
  321. require_once('../core/attributedef.class.inc.php');
  322. require_once('../core/filterdef.class.inc.php');
  323. require_once('../core/stimulus.class.inc.php');
  324. require_once('../core/MyHelpers.class.inc.php');
  325. require_once('../core/expression.class.inc.php');
  326. require_once('../core/cmdbsource.class.inc.php');
  327. require_once('../core/sqlquery.class.inc.php');
  328. require_once('../core/dbobject.class.php');
  329. require_once('../core/dbobjectsearch.class.php');
  330. require_once('../core/dbobjectset.class.php');
  331. require_once('../core/userrights.class.inc.php');
  332. $oP->log("Info - MetaModel::Startup from file '$sConfigFileName' (AllowMissingDB = $bAllowMissingDatabase)");
  333. MetaModel::Startup($sConfigFileName, $bAllowMissingDatabase);
  334. }
  335. /**
  336. * Helper function to create the database structure
  337. * @return boolean true on success, false otherwise
  338. */
  339. function CreateDatabaseStructure(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix)
  340. {
  341. InitDataModel($oP, TMP_CONFIG_FILE, true); // Allow the DB to NOT exist since we're about to create it !
  342. $oP->log('Info - CreateDatabaseStructure');
  343. if (strlen($sDBPrefix) > 0)
  344. {
  345. $oP->info("Creating the structure in '$sDBName' (table names prefixed by '$sDBPrefix').");
  346. }
  347. else
  348. {
  349. $oP->info("Creating the structure in '$sDBName'.");
  350. }
  351. //MetaModel::CheckDefinitions();
  352. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  353. {
  354. MetaModel::DBCreate();
  355. $oP->ok("Database structure successfuly created.");
  356. }
  357. else
  358. {
  359. if (strlen($sDBPrefix) > 0)
  360. {
  361. $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.");
  362. }
  363. else
  364. {
  365. $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.");
  366. }
  367. return false;
  368. }
  369. return true;
  370. }
  371. /**
  372. * Helper function to create and administrator account for iTop
  373. * @return boolean true on success, false otherwise
  374. */
  375. function CreateAdminAccount(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd)
  376. {
  377. $oP->log('Info - CreateAdminAccount');
  378. InitDataModel($oP, TMP_CONFIG_FILE, true); // allow missing DB
  379. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd))
  380. {
  381. $oP->ok("Administrator account '$sAdminUser' created.");
  382. return true;
  383. }
  384. else
  385. {
  386. $oP->error("Failed to create the administrator account '$sAdminUser'.");
  387. return false;
  388. }
  389. }
  390. //aFilesToLoad[aFilesToLoad.length] = './menus.xml'; // First load the menus
  391. function ListDataFiles($sDirectory, SetupWebPage $oP)
  392. {
  393. $aFilesToLoad = array();
  394. if ($hDir = @opendir($sDirectory))
  395. {
  396. // This is the correct way to loop over the directory. (according to the documentation)
  397. while (($sFile = readdir($hDir)) !== false)
  398. {
  399. $sExtension = pathinfo($sFile, PATHINFO_EXTENSION );
  400. if (strcasecmp($sExtension, 'xml') == 0)
  401. {
  402. $aFilesToLoad[] = $sDirectory.'/'.$sFile;
  403. }
  404. }
  405. closedir($hDir);
  406. // Load order is important we expect the files to be ordered
  407. // like numbered 1.Organizations.xml 2.Locations.xml , etc.
  408. asort($aFilesToLoad);
  409. }
  410. else
  411. {
  412. $oP->error("Data directory (".$sDirectory.") not found or not readable.");
  413. }
  414. return $aFilesToLoad;
  415. }
  416. /**
  417. * Scans the ./data directory for XML files and output them as a Javascript array
  418. */
  419. function PopulateDataFilesList(SetupWebPage $oP)
  420. {
  421. $oP->add("<script type=\"text/javascript\">\n");
  422. $oP->add("function PopulateDataFilesList()\n");
  423. $oP->add("{\n");
  424. // Structure data
  425. //
  426. $aStructureDataFiles = ListDataFiles(SETUP_STRUCTURE_DATA_DIR, $oP);
  427. foreach($aStructureDataFiles as $sFile)
  428. {
  429. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  430. }
  431. // Sample data - loaded IIF wished by the user
  432. //
  433. $oP->add("if (($(\"#sample_data:checked\").length == 1))");
  434. $oP->add("{");
  435. $aSampleDataFiles = ListDataFiles(SETUP_SAMPLE_DATA_DIR, $oP);
  436. foreach($aSampleDataFiles as $sFile)
  437. {
  438. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  439. }
  440. $oP->add("}\n");
  441. $oP->add("}\n");
  442. $oP->add("</script>\n");
  443. }
  444. /**
  445. * Display the form for the first step of the configuration wizard
  446. * which consists in the database server selection
  447. */
  448. function DisplayStep1(SetupWebPage $oP)
  449. {
  450. $sNextOperation = 'step2';
  451. $sVersionString = GetITopVersion();
  452. $oP->add("<h1>iTop configuration wizard</h1>\n");
  453. $oP->p($sVersionString);
  454. $oP->log($sVersionString);
  455. $oP->add("<h2>Checking prerequisites</h2>\n");
  456. if (CheckPHPVersion($oP))
  457. {
  458. $sRedStar = '<span class="hilite">*</span>';
  459. $oP->add("<h2>Step 1: Configuration of the database connection</h2>\n");
  460. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Connection to the database...', 1)\">\n");
  461. // Form goes here
  462. $oP->add("<fieldset><legend>Database connection</legend>\n");
  463. $aForm = array();
  464. $aForm[] = array('label' => "Server name$sRedStar:", 'input' => "<input id=\"db_server\" type=\"text\" name=\"db_server\" value=\"\">",
  465. 'help' => 'E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"');
  466. $aForm[] = array('label' => "User name$sRedStar:", 'input' => "<input id=\"db_user\" type=\"text\" name=\"db_user\" value=\"\">",
  467. 'help' => 'The account must have the following privileges: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER');
  468. $aForm[] = array('label' => 'Password:', 'input' => "<input id=\"db_pwd\" type=\"password\" name=\"db_pwd\" value=\"\">");
  469. $oP->form($aForm);
  470. $oP->add("</fieldset>\n");
  471. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  472. $oP->add("<button type=\"submit\">Next >></button>\n");
  473. $oP->add("</form>\n");
  474. }
  475. }
  476. /**
  477. * Display the form for the second step of the configuration wizard
  478. * which consists in
  479. * 1) Validating the parameters by connecting to the database server
  480. * 2) Prompting to select an existing database or to create a new one
  481. */
  482. function DisplayStep2(SetupWebPage $oP, Config $oConfig, $sDBServer, $sDBUser, $sDBPwd)
  483. {
  484. $sNextOperation = 'step3';
  485. $oP->add("<h1>iTop configuration wizard</h1>\n");
  486. $oP->add("<h2>Step 2: Database selection</h2>\n");
  487. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Creating database structure...', 2);\">\n");
  488. $aDatabases = CheckServerConnection($oP, $sDBServer, $sDBUser, $sDBPwd);
  489. if ($aDatabases === false)
  490. {
  491. // Connection failed, invalid credentials ? Go back
  492. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  493. }
  494. else
  495. {
  496. // Connection is Ok, save it and continue the setup wizard
  497. $oConfig->SetDBHost($sDBServer);
  498. $oConfig->SetDBUser($sDBUser);
  499. $oConfig->SetDBPwd($sDBPwd);
  500. $oConfig->WriteToFile();
  501. $oP->add("<fieldset><legend>Specify a database<span class=\"hilite\">*</span></legend>\n");
  502. $aForm = array();
  503. if (is_array($aDatabases))
  504. {
  505. foreach($aDatabases as $sDBName)
  506. {
  507. $aForm[] = array('label' => "<input id=\"db_$sDBName\" type=\"radio\" name=\"db_name\" value=\"$sDBName\" /><label for=\"db_$sDBName\"> $sDBName</label>");
  508. }
  509. }
  510. else
  511. {
  512. $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\"/>");
  513. $oP->add_ready_script("$('#current_db_name').click( function() { $('#current_db').attr('checked', true); });");
  514. }
  515. $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\"/>");
  516. $oP->form($aForm);
  517. $oP->add_ready_script("$('#new_db_name').click( function() { $('#new_db').attr('checked', true); })");
  518. $oP->add("</fieldset>\n");
  519. $aForm = array();
  520. $aForm[] = array('label' => "Add a prefix to all the tables: <input id=\"db_prefix\" type=\"text\" name=\"db_prefix\" value=\"\" maxlength=\"32\"/>");
  521. $oP->form($aForm);
  522. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  523. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  524. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  525. $oP->add("<button type=\"submit\">Next >></button>\n");
  526. }
  527. $oP->add("</form>\n");
  528. }
  529. /**
  530. * Display the form for the third step of the configuration wizard
  531. * which consists in
  532. * 1) Validating the parameters by connecting to the database server & selecting the database
  533. * 2) Creating the database structure
  534. * 3) Prompting for the admin account to be created
  535. */
  536. function DisplayStep3(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix)
  537. {
  538. $sNextOperation = 'step4';
  539. $oP->add("<h1>iTop configuration wizard</h1>\n");
  540. $oP->add("<h2>Creation of the database structure</h2>\n");
  541. $oP->add("<form method=\"post\" onSubmit=\"return DoSubmit('Creating user and profiles...', 3);\">\n");
  542. $oConfig->SetDBName($sDBName);
  543. $oConfig->SetDBSubname($sDBPrefix);
  544. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  545. if (CreateDatabaseStructure($oP, $oConfig, $sDBName, $sDBPrefix))
  546. {
  547. $sRedStar = "<span class=\"hilite\">*</span>";
  548. $oP->add("<h2>Step 3: Definition of the administrator account</h2>\n");
  549. // Database created, continue with admin creation
  550. $oP->add("<fieldset><legend>Administrator account</legend>\n");
  551. $aForm = array();
  552. $aForm[] = array('label' => "Login$sRedStar:", 'input' => "<input id=\"auth_user\" type=\"text\" name=\"auth_user\" value=\"\">");
  553. $aForm[] = array('label' => "Password$sRedStar:", 'input' => "<input id=\"auth_pwd\" type=\"password\" name=\"auth_pwd\" value=\"\">");
  554. $aForm[] = array('label' => "Retype password$sRedStar:", 'input' => "<input id=\"auth_pwd2\" type=\"password\" name=\"auth_pwd2\" value=\"\">");
  555. $oP->form($aForm);
  556. $oP->add("</fieldset>\n");
  557. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  558. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  559. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  560. $oP->add("<button type=\"submit\">Next >></button>\n");
  561. }
  562. else
  563. {
  564. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  565. }
  566. // Form goes here
  567. $oP->add("</form>\n");
  568. }
  569. /**
  570. * Display the form for the fourth step of the configuration wizard
  571. * which consists in
  572. * 1) Creating the admin user account
  573. * 2) Prompting to load some sample data
  574. */
  575. function DisplayStep4(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd)
  576. {
  577. $sNextOperation = 'step5';
  578. $oP->add("<h1>iTop configuration wizard</h1>\n");
  579. $oP->add("<h2>Creation of the administrator account</h2>\n");
  580. $oP->add("<form method=\"post\"\">\n");
  581. if (CreateAdminAccount($oP, $oConfig, $sAdminUser, $sAdminPwd) && UserRights::Setup())
  582. {
  583. $oP->add("<h2>Step 4: Loading of sample data</h2>\n");
  584. $oP->p("<fieldset><legend> Do you want to load sample data into the database ? </legend>\n");
  585. $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");
  586. $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");
  587. $oP->p("</fieldset>\n");
  588. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  589. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  590. $oP->add("<button onclick=\"return DoSubmit('Finalizing configuration and loading data...', 4);\">Finish</button>\n");
  591. }
  592. else
  593. {
  594. // Creation failed
  595. $oP->error("Failed to create admin account or setup user rights");
  596. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  597. }
  598. // End of visible form
  599. $oP->add("</form>\n");
  600. // Hidden form
  601. $oP->add("<form id=\"GoToNextStep\" method=\"post\">\n");
  602. $oP->add("<input type=\"hidden\" name=\"auth_user\" value=\"$sAdminUser\">\n"); // To be compatible with login page
  603. $oP->add("<input type=\"hidden\" name=\"auth_pwd\" value=\"$sAdminPwd\">\n"); // To be compatible with login page
  604. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  605. $oP->add("</form>\n");
  606. $oP->add("<div id=\"log\" style=\"color:#F00;\"></div>\n");
  607. $oP->add_linked_script('./jquery.progression.js');
  608. PopulateDataFilesList($oP);
  609. }
  610. /**
  611. * Display the form for the fifth (and final) step of the configuration wizard
  612. * which consists in
  613. * 1) Creating the final configuration file
  614. * 2) Prompting the user to make the file read-only
  615. */
  616. function DisplayStep5(SetupWebPage $oP, Config $oConfig, $sAuthUser, $sAuthPwd)
  617. {
  618. try
  619. {
  620. session_start();
  621. // Write the final configuration file
  622. $oConfig->WriteToFile(FINAL_CONFIG_FILE);
  623. // Start the application
  624. InitDataModel($oP, FINAL_CONFIG_FILE, false); // DO NOT allow missing DB
  625. if (UserRights::Login($sAuthUser, $sAuthPwd))
  626. {
  627. $_SESSION['auth_user'] = $sAuthUser;
  628. $_SESSION['auth_pwd'] = $sAuthPwd;
  629. // remove the tmp config file
  630. @unlink(TMP_CONFIG_FILE);
  631. // try to make the final config file read-only
  632. @chmod(FINAL_CONFIG_FILE, 0440); // Read-only for owner and group, nothing for others
  633. $oP->add("<h1>iTop configuration wizard</h1>\n");
  634. $oP->add("<h2>Configuration completed</h2>\n");
  635. $oP->add("<form method=\"get\" action=\"../index.php\">\n");
  636. $oP->ok("The initialization completed successfully.");
  637. // Form goes here
  638. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  639. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  640. $oP->add("<button type=\"submit\">Enter iTop</button>\n");
  641. $oP->add("</form>\n");
  642. }
  643. else
  644. {
  645. $oP->add("<h1>iTop configuration wizard</h1>\n");
  646. $oP->add("<h2>Step 5: Configuration completed</h2>\n");
  647. @unlink(FINAL_CONFIG_FILE); // remove the aborted config
  648. $oP->error("Error: Failed to login for user: '$sAuthUser'\n");
  649. $oP->add("<form method=\"get\" action=\"../index.php\">\n");
  650. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  651. $oP->add("&nbsp;&nbsp;&nbsp;&nbsp;\n");
  652. $oP->add("</form>\n");
  653. }
  654. }
  655. catch(Exception $e)
  656. {
  657. $oP->error("Error: unable to create the configuration file.");
  658. $oP->p($e->getHtmlDesc());
  659. $oP->p("Did you forget to remove the previous (read-only) configuration file ?");
  660. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  661. }
  662. }
  663. /**
  664. * Main program
  665. */
  666. clearstatcache(); // Make sure we know what we are doing !
  667. if (file_exists(FINAL_CONFIG_FILE))
  668. {
  669. // The configuration file already exists
  670. if (is_writable(FINAL_CONFIG_FILE))
  671. {
  672. $oP->warning("<b>Warning:</b> a configuration file '".FINAL_CONFIG_FILE."' already exists, and will be overwritten.");
  673. }
  674. else
  675. {
  676. $oP->add("<h1>iTop configuration wizard</h1>\n");
  677. $oP->add("<h2>Fatal error</h2>\n");
  678. $oP->error("<b>Error:</b> the configuration file '".FINAL_CONFIG_FILE."' already exists and cannot be overwritten.");
  679. $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.");
  680. $oP->output();
  681. exit;
  682. }
  683. }
  684. else
  685. {
  686. // No configuration file yet
  687. // Check that the wizard can write into the root dir to create the configuration file
  688. if (!is_writable(dirname(FINAL_CONFIG_FILE)))
  689. {
  690. $oP->add("<h1>iTop configuration wizard</h1>\n");
  691. $oP->add("<h2>Fatal error</h2>\n");
  692. $oP->error("<b>Error:</b> the directory where to store the configuration file is not writable.");
  693. $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.");
  694. $oP->output();
  695. exit;
  696. }
  697. }
  698. try
  699. {
  700. $oConfig = new Config(TMP_CONFIG_FILE);
  701. }
  702. catch(Exception $e)
  703. {
  704. // We'll end here when the tmp config file does not exist. It's normal
  705. $oConfig = new Config(TMP_CONFIG_FILE, false /* Don't try to load it */);
  706. }
  707. try
  708. {
  709. switch($sOperation)
  710. {
  711. case 'step1':
  712. $oP->log("Info - ========= Wizard step 1 ========");
  713. DisplayStep1($oP);
  714. break;
  715. case 'step2':
  716. $oP->no_cache();
  717. $oP->log("Info - ========= Wizard step 2 ========");
  718. $sDBServer = Utils::ReadParam('db_server');
  719. $sDBUser = Utils::ReadParam('db_user');
  720. $sDBPwd = Utils::ReadParam('db_pwd');
  721. DisplayStep2($oP, $oConfig, $sDBServer, $sDBUser, $sDBPwd);
  722. break;
  723. case 'step3':
  724. $oP->no_cache();
  725. $oP->log("Info - ========= Wizard step 3 ========");
  726. $sDBName = Utils::ReadParam('db_name');
  727. if (empty($sDBName))
  728. {
  729. $sDBName = Utils::ReadParam('new_db_name');
  730. }
  731. $sDBPrefix = Utils::ReadParam('db_prefix');
  732. DisplayStep3($oP, $oConfig, $sDBName, $sDBPrefix);
  733. break;
  734. case 'step4':
  735. $oP->no_cache();
  736. $oP->log("Info - ========= Wizard step 4 ========");
  737. $sAdminUser = Utils::ReadParam('auth_user');
  738. $sAdminPwd = Utils::ReadParam('auth_pwd');
  739. DisplayStep4($oP, $oConfig, $sAdminUser, $sAdminPwd);
  740. break;
  741. case 'step5':
  742. $oP->no_cache();
  743. $oP->log("Info - ========= Wizard step 5 ========");
  744. $sAdminUser = Utils::ReadParam('auth_user');
  745. $sAdminPwd = Utils::ReadParam('auth_pwd');
  746. DisplayStep5($oP, $oConfig, $sAdminUser, $sAdminPwd);
  747. break;
  748. default:
  749. $oP->error("Error: unsupported operation '$sOperation'");
  750. }
  751. }
  752. catch(Exception $e)
  753. {
  754. $oP->error("Error: '".$e->getMessage()."'");
  755. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  756. }
  757. catch(CoreException $e)
  758. {
  759. $oP->error("Error: '".$e->getHtmlDesc()."'");
  760. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  761. }
  762. $oP->output();
  763. ?>