index.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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('../approot.inc.php');
  25. require_once(APPROOT.'/application/utils.inc.php');
  26. require_once(APPROOT.'/core/config.class.inc.php');
  27. require_once(APPROOT.'/core/log.class.inc.php');
  28. require_once(APPROOT.'/core/kpi.class.inc.php');
  29. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  30. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  31. define('TMP_CONFIG_FILE', APPROOT.'/tmp-config-itop.php');
  32. define('FINAL_CONFIG_FILE', APPROOT.'/config-itop.php');
  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', 'step0');
  37. $oP = new SetupWebPage('iTop configuration wizard');
  38. ///////////////////////////////////////////////////////////////////////////////////////////////////
  39. // Various helper function
  40. ///////////////////////////////////////////////////////////////////////////////////////////////////
  41. /**
  42. * Get a nicely formatted version string
  43. */
  44. function GetITopVersion($bShort = true)
  45. {
  46. $sVersionString = '';
  47. if ($bShort)
  48. {
  49. $sVersionString = "iTop Version ".ITOP_VERSION;
  50. }
  51. else
  52. {
  53. if (ITOP_REVISION == '$WCREV$')
  54. {
  55. // This is NOT a version built using the buil system, just display the main version
  56. $sVersionString = "iTop Version ".ITOP_VERSION;
  57. }
  58. else
  59. {
  60. // This is a build made from SVN, let display the full information
  61. $sVersionString = "iTop Version ".ITOP_VERSION." revision ".ITOP_REVISION.", built on: ".ITOP_BUILD_DATE;
  62. }
  63. }
  64. return $sVersionString;
  65. }
  66. /**
  67. * Helper function to retrieve the system's temporary directory
  68. * Emulates sys_get_temp_dir if neeed (PHP < 5.2.1)
  69. * @return string Path to the system's temp directory
  70. */
  71. function GetTmpDir()
  72. {
  73. // try to figure out what is the temporary directory
  74. // prior to PHP 5.2.1 the function sys_get_temp_dir
  75. // did not exist
  76. if ( !function_exists('sys_get_temp_dir'))
  77. {
  78. if( $temp=getenv('TMP') ) return realpath($temp);
  79. if( $temp=getenv('TEMP') ) return realpath($temp);
  80. if( $temp=getenv('TMPDIR') ) return realpath($temp);
  81. $temp=tempnam(__FILE__,'');
  82. if (file_exists($temp))
  83. {
  84. unlink($temp);
  85. return realpath(dirname($temp));
  86. }
  87. return null;
  88. }
  89. else
  90. {
  91. return realpath(sys_get_temp_dir());
  92. }
  93. }
  94. /**
  95. * Check the value of the PHP setting 'memory_limit'
  96. * against the minimum recommended value
  97. * @param SetpWebPage $oP The current web page
  98. * @param integer $iMinMemoryRequired The minimum memory for the test to pass
  99. * @return boolean Whether or not it's Ok to continue
  100. */
  101. function CheckMemoryLimit(SetupWebPage $oP, $iMinMemoryRequired)
  102. {
  103. $sMemoryLimit = trim(ini_get('memory_limit'));
  104. $bResult = true;
  105. if (empty($sMemoryLimit))
  106. {
  107. // On some PHP installations, memory_limit does not exist as a PHP setting!
  108. // (encountered on a 5.2.0 under Windows)
  109. // In that case, ini_set will not work, let's keep track of this and proceed anyway
  110. $oP->warning("No memory limit has been defined in this instance of PHP");
  111. }
  112. else
  113. {
  114. // Check that the limit will allow us to load the data
  115. //
  116. $iMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
  117. if ($iMemoryLimit < $iMinMemoryRequired)
  118. {
  119. $oP->error("memory_limit ($iMemoryLimit) is too small, the minimum value to run iTop is $iMinMemoryRequired.");
  120. $bResult = false;
  121. }
  122. else
  123. {
  124. $oP->log_info("memory_limit is $iMemoryLimit, ok.");
  125. }
  126. }
  127. return $bResult;
  128. }
  129. /**
  130. * Helper function to retrieve the directory where files are to be uploaded
  131. * @return string Path to the temp directory used for uploading files
  132. */
  133. function GetUploadTmpDir()
  134. {
  135. $sPath = ini_get('upload_tmp_dir');
  136. if (empty($sPath))
  137. {
  138. $sPath = GetTmpDir();
  139. }
  140. return $sPath;
  141. }
  142. /**
  143. * Helper function to check if the current version of PHP
  144. * is compatible with the application
  145. * @return boolean true if this is Ok, false otherwise
  146. */
  147. function CheckPHPVersion(SetupWebPage $oP)
  148. {
  149. $bResult = true;
  150. $oP->log('Info - CheckPHPVersion');
  151. if (version_compare(phpversion(), PHP_MIN_VERSION, '>='))
  152. {
  153. $oP->ok("The current PHP Version (".phpversion().") is greater than the minimum required version (".PHP_MIN_VERSION.")");
  154. }
  155. else
  156. {
  157. $oP->error("Error: The current PHP Version (".phpversion().") is lower than the minimum required version (".PHP_MIN_VERSION.")");
  158. return false;
  159. }
  160. $aMandatoryExtensions = array('mysql', 'iconv', 'simplexml', 'soap', 'hash', 'json', 'session', 'pcre');
  161. $aOptionalExtensions = array('mcrypt' => 'Strong encryption will not be used.',
  162. 'ldap' => 'LDAP authentication will be disabled.');
  163. asort($aMandatoryExtensions); // Sort the list to look clean !
  164. ksort($aOptionalExtensions); // Sort the list to look clean !
  165. $aExtensionsOk = array();
  166. $aMissingExtensions = array();
  167. $aMissingExtensionsLinks = array();
  168. // First check the mandatory extensions
  169. foreach($aMandatoryExtensions as $sExtension)
  170. {
  171. if (extension_loaded($sExtension))
  172. {
  173. $aExtensionsOk[] = $sExtension;
  174. }
  175. else
  176. {
  177. $aMissingExtensions[] = $sExtension;
  178. $aMissingExtensionsLinks[] = "<a href=\"http://www.php.net/manual/en/book.$sExtension.php\" target=\"_blank\">$sExtension</a>";
  179. }
  180. }
  181. if (count($aExtensionsOk) > 0)
  182. {
  183. $oP->ok("Required PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  184. }
  185. if (count($aMissingExtensions) > 0)
  186. {
  187. $oP->error("Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".");
  188. $bResult = false;
  189. }
  190. // Next check the optional extensions
  191. $aExtensionsOk = array();
  192. $aMissingExtensions = array();
  193. foreach($aOptionalExtensions as $sExtension => $sMessage)
  194. {
  195. if (extension_loaded($sExtension))
  196. {
  197. $aExtensionsOk[] = $sExtension;
  198. }
  199. else
  200. {
  201. $aMissingExtensions[$sExtension] = $sMessage;
  202. }
  203. }
  204. if (count($aExtensionsOk) > 0)
  205. {
  206. $oP->ok("Optional PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  207. }
  208. if (count($aMissingExtensions) > 0)
  209. {
  210. foreach($aMissingExtensions as $sExtension => $sMessage)
  211. {
  212. $oP->warning("Missing optional PHP extension: $sExtension. ".$sMessage);
  213. }
  214. }
  215. // Check some ini settings here
  216. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  217. {
  218. $sPhpIniFile = php_ini_loaded_file();
  219. // Other included/scanned files
  220. if ($sFileList = php_ini_scanned_files())
  221. {
  222. if (strlen($sFileList) > 0)
  223. {
  224. $aFiles = explode(',', $sFileList);
  225. foreach ($aFiles as $sFile)
  226. {
  227. $sPhpIniFile .= ', '.trim($sFile);
  228. }
  229. }
  230. }
  231. $oP->log("Info - php.ini file(s): '$sPhpIniFile'");
  232. }
  233. else
  234. {
  235. $sPhpIniFile = 'php.ini';
  236. }
  237. if (!ini_get('file_uploads'))
  238. {
  239. $oP->error("Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  240. $bResult = false;
  241. }
  242. $sUploadTmpDir = GetUploadTmpDir();
  243. if (empty($sUploadTmpDir))
  244. {
  245. $sUploadTmpDir = '/tmp';
  246. $oP->warning("Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.");
  247. }
  248. // check that the upload directory is indeed writable from PHP
  249. if (!empty($sUploadTmpDir))
  250. {
  251. if (!file_exists($sUploadTmpDir))
  252. {
  253. $oP->error("Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.");
  254. $bResult = false;
  255. }
  256. else if (!is_writable($sUploadTmpDir))
  257. {
  258. $oP->error("Temporary directory for files upload ($sUploadTmpDir) is not writable.");
  259. $bResult = false;
  260. }
  261. else
  262. {
  263. $oP->log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
  264. }
  265. }
  266. if (!ini_get('upload_max_filesize'))
  267. {
  268. $oP->error("File upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  269. }
  270. $iMaxFileUploads = ini_get('max_file_uploads');
  271. if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
  272. {
  273. $oP->error("File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").");
  274. $bResult = false;
  275. }
  276. $oP->log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
  277. $oP->log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
  278. // Check some more ini settings here, needed for file upload
  279. if (get_magic_quotes_gpc())
  280. {
  281. $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.");
  282. $bResult = false;
  283. }
  284. $bResult = $bResult & CheckMemoryLimit($oP, MIN_MEMORY_LIMIT);
  285. return $bResult;
  286. }
  287. /**
  288. * Helper function check the connection to the database and (if connected) to enumerate
  289. * the existing databases
  290. * @return Array The list of databases found in the server
  291. */
  292. function CheckServerConnection(SetupWebPage $oP, $sDBServer, $sDBUser, $sDBPwd)
  293. {
  294. $aResult = array();
  295. $oP->log('Info - CheckServerConnection');
  296. try
  297. {
  298. $oDBSource = new CMDBSource;
  299. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  300. $oP->ok("Connection to '$sDBServer' as '$sDBUser' successful.");
  301. $oP->log("Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  302. $sDBVersion = $oDBSource->GetDBVersion();
  303. if (version_compare($sDBVersion, MYSQL_MIN_VERSION, '>='))
  304. {
  305. $oP->ok("Current MySQL version ($sDBVersion), greater than minimum required version (".MYSQL_MIN_VERSION.")");
  306. // Check some server variables
  307. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  308. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  309. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  310. {
  311. $oP->ok("MySQL server's max_allowed_packet is big enough.");
  312. }
  313. else if($iMaxAllowedPacket < $iMaxUploadSize)
  314. {
  315. $oP->warning("MySQL server's max_allowed_packet ($iMaxAllowedPacket) is not big enough. Please, consider setting it to at least ".(500 + $iMaxUploadSize).".");
  316. }
  317. $oP->log("Info - MySQL max_allowed_packet: $iMaxAllowedPacket");
  318. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  319. if ($iMaxConnections < 5)
  320. {
  321. $oP->warning("MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  322. }
  323. $oP->log("Info - MySQL max_connections: ".($oDBSource->GetServerVariable('max_connections')));
  324. }
  325. else
  326. {
  327. $oP->error("Error: Current MySQL version is ($sDBVersion), minimum required version (".MYSQL_MIN_VERSION.")");
  328. return false;
  329. }
  330. try
  331. {
  332. $aResult = $oDBSource->ListDB();
  333. }
  334. catch(Exception $e)
  335. {
  336. $oP->warning("Warning: unable to enumerate the current databases.");
  337. $aResult = true; // Not an array to differentiate with an empty array
  338. }
  339. }
  340. catch(Exception $e)
  341. {
  342. $oP->error("Error: Connection to '$sDBServer' as '$sDBUser' failed.");
  343. $oP->p($e->GetHtmlDesc());
  344. $aResult = false;
  345. }
  346. return $aResult;
  347. }
  348. /**
  349. * Helper function to interpret the name of a module
  350. * @param $sModuleId string Identifier of the module, in the form 'name/version'
  351. * @return array(name, version)
  352. */
  353. function GetModuleName($sModuleId)
  354. {
  355. if (preg_match('!^(.*)/(.*)$!', $sModuleId, $aMatches))
  356. {
  357. $sName = $aMatches[1];
  358. $sVersion = $aMatches[2];
  359. }
  360. else
  361. {
  362. $sName = $sModuleId;
  363. $sVersion = "";
  364. }
  365. return array($sName, $sVersion);
  366. }
  367. /**
  368. * Helper function to initialize the ORM and load the data model
  369. * from the given file
  370. * @param $sConfigFileName string The name of the configuration file to load
  371. * @param $bModelOnly boolean Whether or not to allow loading a data model with no corresponding DB
  372. * @return none
  373. */
  374. function InitDataModel(SetupWebPage $oP, $sConfigFileName, $bModelOnly = true)
  375. {
  376. require_once(APPROOT.'/core/log.class.inc.php');
  377. require_once(APPROOT.'/core/kpi.class.inc.php');
  378. require_once(APPROOT.'/core/coreexception.class.inc.php');
  379. require_once(APPROOT.'/core/dict.class.inc.php');
  380. require_once(APPROOT.'/core/attributedef.class.inc.php');
  381. require_once(APPROOT.'/core/filterdef.class.inc.php');
  382. require_once(APPROOT.'/core/stimulus.class.inc.php');
  383. require_once(APPROOT.'/core/MyHelpers.class.inc.php');
  384. require_once(APPROOT.'/core/expression.class.inc.php');
  385. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  386. require_once(APPROOT.'/core/sqlquery.class.inc.php');
  387. require_once(APPROOT.'/core/dbobject.class.php');
  388. require_once(APPROOT.'/core/dbobjectsearch.class.php');
  389. require_once(APPROOT.'/core/dbobjectset.class.php');
  390. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  391. require_once(APPROOT.'/core/userrights.class.inc.php');
  392. require_once(APPROOT.'/setup/moduleinstallation.class.inc.php');
  393. $oP->log("Info - MetaModel::Startup from file '$sConfigFileName' (ModelOnly = $bModelOnly)");
  394. MetaModel::Startup($sConfigFileName, $bModelOnly);
  395. }
  396. /**
  397. * Helper function to create the database structure
  398. * @return boolean true on success, false otherwise
  399. */
  400. function CreateDatabaseStructure(SetupWebPage $oP, Config $oConfig, $sDBName, $sDBPrefix, $aSelectedModules)
  401. {
  402. InitDataModel($oP, TMP_CONFIG_FILE, true); // Allow the DB to NOT exist since we're about to create it !
  403. $oP->log('Info - CreateDatabaseStructure');
  404. if (strlen($sDBPrefix) > 0)
  405. {
  406. $oP->info("Creating the structure in '$sDBName' (table names prefixed by '$sDBPrefix').");
  407. }
  408. else
  409. {
  410. $oP->info("Creating the structure in '$sDBName'.");
  411. }
  412. //MetaModel::CheckDefinitions();
  413. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  414. {
  415. MetaModel::DBCreate();
  416. $oP->ok("Database structure successfully created.");
  417. }
  418. else
  419. {
  420. if (strlen($sDBPrefix) > 0)
  421. {
  422. $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.");
  423. }
  424. else
  425. {
  426. $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.");
  427. }
  428. return false;
  429. }
  430. // Record main installation
  431. $oInstallRec = new ModuleInstallation();
  432. $oInstallRec->Set('name', 'itop');
  433. $oInstallRec->Set('version', ITOP_VERSION.'.'.ITOP_REVISION);
  434. $oInstallRec->Set('comment', "Done by the setup program\nBuilt on ".ITOP_BUILD_DATE);
  435. $oInstallRec->Set('parent_id', 0); // root module
  436. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  437. // Record installed modules
  438. //
  439. $aAvailableModules = GetAvailableModules($oP);
  440. foreach($aSelectedModules as $sModuleId)
  441. {
  442. $aModuleData = $aAvailableModules[$sModuleId];
  443. list($sName, $sVersion) = GetModuleName($sModuleId);
  444. $aComments = array();
  445. $aComments[] = 'Done by the setup program';
  446. if ($aModuleData['mandatory'])
  447. {
  448. $aComments[] = 'Mandatory';
  449. }
  450. else
  451. {
  452. $aComments[] = 'Optional';
  453. }
  454. if ($aModuleData['visible'])
  455. {
  456. $aComments[] = 'Visible (during the setup)';
  457. }
  458. else
  459. {
  460. $aComments[] = 'Hidden (selected automatically)';
  461. }
  462. foreach ($aModuleData['dependencies'] as $sDependOn)
  463. {
  464. $aComments[] = "Depends on module: $sDependOn";
  465. }
  466. $sComment = implode("\n", $aComments);
  467. $oInstallRec = new ModuleInstallation();
  468. $oInstallRec->Set('name', $sName);
  469. $oInstallRec->Set('version', $sVersion);
  470. $oInstallRec->Set('comment', $sComment);
  471. $oInstallRec->Set('parent_id', $iMainItopRecord);
  472. $oInstallRec->DBInsertNoReload();
  473. }
  474. // Database is created, installation has been tracked into it
  475. return true;
  476. }
  477. /**
  478. * Helper function to create and administrator account for iTop
  479. * @return boolean true on success, false otherwise
  480. */
  481. function CreateAdminAccount(SetupWebPage $oP, Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  482. {
  483. $oP->log('Info - CreateAdminAccount');
  484. InitDataModel($oP, TMP_CONFIG_FILE, false); // load data model and connect to the database
  485. if (!UserRights::Setup())
  486. {
  487. return false;
  488. }
  489. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  490. {
  491. $oP->ok("Administrator account '$sAdminUser' created.");
  492. return true;
  493. }
  494. else
  495. {
  496. $oP->error("Failed to create the administrator account '$sAdminUser'.");
  497. return false;
  498. }
  499. }
  500. function ListModuleFiles($sRelDir, SetupWebPage $oP)
  501. {
  502. $sDirectory = APPROOT.'/'.$sRelDir;
  503. //echo "<p>$sDirectory</p>\n";
  504. if ($hDir = opendir($sDirectory))
  505. {
  506. // This is the correct way to loop over the directory. (according to the documentation)
  507. while (($sFile = readdir($hDir)) !== false)
  508. {
  509. $aMatches = array();
  510. if (is_dir($sDirectory.'/'.$sFile))
  511. {
  512. if (($sFile != '.') && ($sFile != '..') && ($sFile != '.svn'))
  513. {
  514. ListModuleFiles($sRelDir.'/'.$sFile, $oP);
  515. }
  516. }
  517. else if (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches))
  518. {
  519. $oP->SetModulePath($sRelDir);
  520. try
  521. {
  522. //echo "<p>Loading: $sDirectory/$sFile...</p>\n";
  523. require_once($sDirectory.'/'.$sFile);
  524. //echo "<p>Done.</p>\n";
  525. }
  526. catch(Exception $e)
  527. {
  528. // Continue...
  529. }
  530. }
  531. }
  532. closedir($hDir);
  533. }
  534. else
  535. {
  536. $oP->error("Data directory (".$sDirectory.") not found or not readable.");
  537. }
  538. }
  539. /**
  540. * Scans the ./data directory for XML files and output them as a Javascript array
  541. */
  542. function PopulateDataFilesList(SetupWebPage $oP, $aParamValues)
  543. {
  544. $oP->add("<script type=\"text/javascript\">\n");
  545. $oP->add("function PopulateDataFilesList()\n");
  546. $oP->add("{\n");
  547. $oP->add("if (aFilesToLoad.length > 0) return;"); // Populate the list only once...
  548. $aAvailableModules = GetAvailableModules($oP);
  549. $aStructureDataFiles = array();
  550. $aSampleDataFiles = array();
  551. foreach($aParamValues['module'] as $sModuleId)
  552. {
  553. $aModuleStruct = $aAvailableModules[$sModuleId]['data.struct'];
  554. $aModuleSamples = $aAvailableModules[$sModuleId]['data.sample'];
  555. $aStructureDataFiles = array_merge($aStructureDataFiles, $aModuleStruct);
  556. $aSampleDataFiles = array_merge($aSampleDataFiles, $aModuleSamples);
  557. }
  558. // Structure data
  559. //
  560. foreach($aStructureDataFiles as $sFile)
  561. {
  562. // Under Windows, it is a must to escape backslashes (not an issue until a folder name starts with t or n, etc...)
  563. $sFile = APPROOT.$sFile;
  564. $sFile = str_replace('\\', '\\\\', $sFile);
  565. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  566. }
  567. // Sample data - loaded IIF wished by the user
  568. //
  569. $oP->add("if (($(\"#sample_data:checked\").length == 1))");
  570. $oP->add("{");
  571. foreach($aSampleDataFiles as $sFile)
  572. {
  573. // Under Windows, it is a must to escape backslashes (not an issue until a folder name starts with t or n, etc...)
  574. $sFile = APPROOT.$sFile;
  575. $sFile = str_replace('\\', '\\\\', $sFile);
  576. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  577. }
  578. $oP->add("}\n");
  579. $oP->add("}\n");
  580. $oP->add("</script>\n");
  581. }
  582. /**
  583. * Add some parameters as hidden inputs into a form
  584. * @param SetupWebpage $oP The page to insert the form elements into
  585. * @param Hash $aParamValues The pairs name/value to be stored in the form
  586. * @param Array $aExcludeParams A list of parameters to exclude from the previous hash
  587. */
  588. function AddParamsToForm(SetupWebpage $oP, $aParamValues, $aExcludeParams = array())
  589. {
  590. foreach($aParamValues as $sName => $value)
  591. {
  592. if(!in_array($sName, $aExcludeParams))
  593. {
  594. if (is_array($value))
  595. {
  596. foreach($value as $sKey => $sItem)
  597. {
  598. $oP->add('<input type="hidden" name="'.$sName.'['.$sKey.']'.'" value="'.$sItem.'">');
  599. }
  600. }
  601. else
  602. {
  603. $oP->add('<input type="hidden" name="'.$sName.'" value="'.$value.'">');
  604. }
  605. }
  606. }
  607. }
  608. /**
  609. * Search (on the disk) for all defined iTop modules, load them and returns the list (as an array)
  610. * of the possible iTop modules to install
  611. * @param none
  612. * @return Hash A big array moduleID => ModuleData
  613. */
  614. function GetAvailableModules(SetupWebpage $oP)
  615. {
  616. clearstatcache();
  617. ListModuleFiles('modules', $oP);
  618. return $oP->GetModules();
  619. }
  620. /**
  621. * Build the config file from the parameters (especially the selected modules)
  622. */
  623. function BuildConfig(SetupWebpage $oP, Config &$oConfig, $aParamValues)
  624. {
  625. $aAvailableModules = GetAvailableModules($oP);
  626. // Initialize the arrays below with default values for the application...
  627. $aAddOns = $oConfig->GetAddOns();
  628. $aAppModules = $oConfig->GetAppModules();
  629. $aDataModels = $oConfig->GetDataModels();
  630. $aWebServiceCategories = $oConfig->GetWebServiceCategories();
  631. $aDictionaries = $oConfig->GetDictionaries();
  632. // Merge the values with the ones provided by the modules
  633. // Make sure when don't load the same file twice...
  634. foreach($aParamValues['module'] as $sModuleId)
  635. {
  636. $oP->log('Installed iTop module: '. $sModuleId);
  637. if (isset($aAvailableModules[$sModuleId]['datamodel']))
  638. {
  639. $aDataModels = array_unique(array_merge($aDataModels, $aAvailableModules[$sModuleId]['datamodel']));
  640. }
  641. if (isset($aAvailableModules[$sModuleId]['webservice']))
  642. {
  643. $aWebServiceCategories = array_unique(array_merge($aWebServiceCategories, $aAvailableModules[$sModuleId]['webservice']));
  644. }
  645. if (isset($aAvailableModules[$sModuleId]['dictionary']))
  646. {
  647. $aDictionaries = array_unique(array_merge($aDictionaries, $aAvailableModules[$sModuleId]['dictionary']));
  648. }
  649. if (isset($aAvailableModules[$sModuleId]['settings']))
  650. {
  651. foreach($aAvailableModules[$sModuleId]['settings'] as $sProperty => $value)
  652. {
  653. list($sName, $sVersion) = GetModuleName($sModuleId);
  654. $oConfig->SetModuleSetting($sName, $sProperty, $value);
  655. }
  656. }
  657. }
  658. $oConfig->SetAddOns($aAddOns);
  659. $oConfig->SetAppModules($aAppModules);
  660. $oConfig->SetDataModels($aDataModels);
  661. $oConfig->SetWebServiceCategories($aWebServiceCategories);
  662. $oConfig->SetDictionaries($aDictionaries);
  663. }
  664. /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  665. // Handling of the different steps of the setup wizard
  666. /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  667. /**
  668. * Displays the welcome screen and check some basic prerequisites
  669. */
  670. function WelcomeAndCheckPrerequisites(SetupWebPage $oP, $aParamValues, $iCurrentStep)
  671. {
  672. $sNextOperation = 'step'.($iCurrentStep+1);
  673. $oP->add("<h1>iTop configuration wizard</h1>\n");
  674. $sVersionStringShort = GetITopVersion(true);
  675. $sVersionStringLong = GetITopVersion(false);
  676. $oP->set_title('Welcome to '.$sVersionStringShort);
  677. $oP->log($sVersionStringLong);
  678. $oP->add("<h2>Checking prerequisites</h2>\n");
  679. if (CheckPHPVersion($oP))
  680. {
  681. $oP->add("<h2 class=\"next\">Next: Licence agreement</h2>\n");
  682. $oP->add("<form id=\"theForm\" method=\"post\" onSubmit=\"return DoSubmit('', 0)\">\n");
  683. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  684. AddParamsToForm($oP, $aParamValues);
  685. $oP->add("<table style=\"width:100%\"><tr>\n");
  686. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" type=\"submit\">Next >></button></td>\n");
  687. $oP->add("</tr></table>\n");
  688. $oP->add("</form>\n");
  689. }
  690. }
  691. function LicenceAcknowledgement($oP, $aParamValues, $iCurrentStep)
  692. {
  693. $sNextOperation = 'step'.($iCurrentStep+1);
  694. $oP->set_title('License agreement');
  695. $oP->add('<h2>iTop is released by <a href="http://www.combodo.com" target="_blank">Combodo SARL</a> under the terms of the GPL V3 license. In order to use iTop you must accept the terms of this license.</h2>');
  696. $oP->add("<iframe style=\"width: 100%; height: 350px; overflow-y:auto; font-size:0.8em;\" src=\"./licence.html\">Next: Database server selection</iframe>\n");
  697. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  698. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  699. AddParamsToForm($oP, $aParamValues, array('licence_ok'));
  700. $sChecked = $aParamValues['licence_ok'] == 1 ? 'checked' : '';
  701. $oP->add("<h2><input id=\"licence_ok\" type=\"checkbox\" name=\"licence_ok\" value=\"1\" $sChecked><label for=\"licence_ok\">I accept the terms of this licence agreement</label></h2>\n");
  702. $oP->add("<h2 class=\"next\">Next: Database server selection</h2>\n");
  703. $oP->add("<table style=\"width:100%\"><tr>\n");
  704. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  705. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('', $iCurrentStep)\">Next >></button></td>\n");
  706. $oP->add("</tr></table>\n");
  707. $oP->add("</form>\n");
  708. }
  709. /**
  710. * Display the form for the first step of the configuration wizard
  711. * which consists in the database server selection
  712. */
  713. function DatabaseServerSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep)
  714. {
  715. $sNextOperation = 'step'.($iCurrentStep+1);
  716. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  717. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  718. AddParamsToForm($oP, $aParamValues, array('db_server', 'db_user', 'db_pwd'));
  719. if ($aParamValues['licence_ok'] == 1)
  720. {
  721. $sRedStar = '<span class="hilite">*</span>';
  722. $oP->set_title("Database server selection\n");
  723. $oP->add("<h2>Please enter the name of the MySQL database server you want to use for iTop and supply valid credentials to connect to it</h2>\n");
  724. // Form goes here
  725. $oP->add("<fieldset><legend>Database connection</legend>\n");
  726. $aForm = array();
  727. $aForm[] = array('label' => "Server name$sRedStar:", 'input' => "<input id=\"db_server\" type=\"text\" name=\"db_server\" value=\"{$aParamValues['db_server']}\">",
  728. 'help' => 'E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"');
  729. $aForm[] = array('label' => "User name$sRedStar:", 'input' => "<input id=\"db_user\" type=\"text\" name=\"db_user\" value=\"{$aParamValues['db_user']}\">",
  730. 'help' => 'The account must have the following privileges: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER');
  731. $aForm[] = array('label' => 'Password:', 'input' => "<input id=\"db_pwd\" type=\"password\" name=\"db_pwd\" value=\"{$aParamValues['db_pwd']}\">");
  732. $oP->form($aForm);
  733. $oP->add("</fieldset>\n");
  734. $oP->add("<h2 class=\"next\">Next: Database instance Selection</h2>\n");
  735. $oP->add("<table style=\"width:100%\"><tr>\n");
  736. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  737. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Connecting to the database...', $iCurrentStep);\">Next >></button></td>\n");
  738. $oP->add("</tr></table>\n");
  739. }
  740. else
  741. {
  742. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  743. }
  744. $oP->add("</form>\n");
  745. }
  746. /**
  747. * Display the form for the second step of the configuration wizard
  748. * which consists in
  749. * 1) Validating the parameters by connecting to the database server
  750. * 2) Prompting to select an existing database or to create a new one
  751. */
  752. function DatabaseInstanceSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep, $oConfig)
  753. {
  754. $sNextOperation = 'step'.($iCurrentStep+1);
  755. $oP->set_title("Database instance selection\n");
  756. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  757. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  758. AddParamsToForm($oP, $aParamValues, array('db_name', 'db_prefix', 'new_db_name'));
  759. $sDBServer = $aParamValues['db_server'];
  760. $sDBUser = $aParamValues['db_user'];
  761. $sDBPwd = $aParamValues['db_pwd'];
  762. $aDatabases = CheckServerConnection($oP, $sDBServer, $sDBUser, $sDBPwd);
  763. if ($aDatabases === false)
  764. {
  765. // Connection failed, invalid credentials ? Go back
  766. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  767. }
  768. else
  769. {
  770. // Connection is Ok, save it and continue the setup wizard
  771. $oConfig->SetDBHost($sDBServer);
  772. $oConfig->SetDBUser($sDBUser);
  773. $oConfig->SetDBPwd($sDBPwd);
  774. $oConfig->WriteToFile();
  775. $oP->add("<fieldset><legend>Select the database instance to use for iTop<span class=\"hilite\">*</span></legend>\n");
  776. $aForm = array();
  777. $bExistingChecked = false;
  778. if (is_array($aDatabases))
  779. {
  780. foreach($aDatabases as $sDBName)
  781. {
  782. $sChecked = '';
  783. if ($aParamValues['db_name'] == $sDBName)
  784. {
  785. $sChecked = 'checked';
  786. $bExistingChecked = true;
  787. }
  788. $aForm[] = array('label' => "<input id=\"db_$sDBName\" type=\"radio\" name=\"db_name\" value=\"$sDBName\" $sChecked/><label for=\"db_$sDBName\"> $sDBName</label>");
  789. }
  790. }
  791. else
  792. {
  793. $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\"/>");
  794. $oP->add_ready_script("$('#current_db_name').click( function() { $('#current_db').attr('checked', true); });");
  795. }
  796. $sChecked = '';
  797. $sDBName = '';
  798. // If the 'Create Database' option was checked... and the database still does not exist
  799. if (!$bExistingChecked && !empty($aParamValues['new_db_name']))
  800. {
  801. $sChecked = 'checked';
  802. $sDBName = $aParamValues['new_db_name'];
  803. }
  804. $aForm[] = array('label' => "<input id=\"new_db\" type=\"radio\" name=\"db_name\" value=\"\" $sChecked/><label for=\"new_db\"> Create a new database:</label> <input type=\"text\" id=\"new_db_name\" name=\"new_db_name\" value=\"$sDBName\" maxlength=\"32\"/>");
  805. $oP->form($aForm);
  806. $oP->add_ready_script("$('#new_db_name').click( function() { $('#new_db').attr('checked', true); })");
  807. $oP->add("</fieldset>\n");
  808. $aForm = array();
  809. $aForm[] = array('label' => "Add a prefix to all the tables: <input id=\"db_prefix\" type=\"text\" name=\"db_prefix\" value=\"{$aParamValues['db_prefix']}\" maxlength=\"32\"/>");
  810. $oP->form($aForm);
  811. $oP->add("<h2 class=\"next\">Next: iTop modules selection</h2>\n");
  812. $oP->add("<table style=\"width:100%\"><tr>\n");
  813. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  814. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('', $iCurrentStep);\">Next >></button></td>\n");
  815. $oP->add("</tr></table>\n");
  816. }
  817. $oP->add("</form>\n");
  818. }
  819. /**
  820. * Display the form to select the iTop modules to be installed
  821. */
  822. function ModulesSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep, $oConfig)
  823. {
  824. $sNextOperation = 'step'.($iCurrentStep+1);
  825. $sPrevOperation = 'step'.($iCurrentStep-1);
  826. $sDBName = $aParamValues['db_name'];
  827. if ($sDBName == '')
  828. {
  829. $sDBName = $aParamValues['new_db_name'];
  830. }
  831. $sDBPrefix = $aParamValues['db_prefix'];
  832. $oConfig->SetDBName($sDBName);
  833. $oConfig->SetDBSubname($sDBPrefix);
  834. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  835. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  836. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  837. AddParamsToForm($oP, $aParamValues, array('module'));
  838. $sRedStar = '<span class="hilite">*</span>';
  839. $oP->set_title("iTop modules selection");
  840. $oP->add("<h2>Customize your iTop installation to fit your needs</h2>\n");
  841. $aAvailableModules = GetAvailableModules($oP);
  842. // Form goes here
  843. $oP->add("<fieldset><legend>Select the iTop modules you want to install:</legend>\n");
  844. $oP->add("<div style=\"border: 0;width:100%; height: 350px; overflow-y:auto;\">");
  845. $sRedStar = '<span class="hilite">*</span>';
  846. $index = 0;
  847. $aSelectedModules = $aParamValues['module'];
  848. if ($aSelectedModules == '')
  849. {
  850. // Make sure it gets initialized as an array, default value: all modules selected !
  851. $aSelectedModules = array();
  852. foreach($aAvailableModules as $sModuleId => $aModule)
  853. {
  854. $aSelectedModules[] = $sModuleId;
  855. }
  856. }
  857. foreach($aAvailableModules as $sModuleId => $aModule)
  858. {
  859. $sModuleLabel = $aModule['label'];
  860. $sModuleHelp = $aModule['doc.more_information'];
  861. $sClass = ($aModule['mandatory']) ? 'class="read-only"' : '';
  862. $sChecked = ($aModule['mandatory'] || in_array($sModuleId, $aSelectedModules) ) ? 'checked' : '';
  863. $sMoreInfo = (!empty($aModule['doc.more_information'])) ? "<a href=\"..{$aModule['doc.more_information']}\" target=\"_blank\">more info</a>": '';
  864. if ($aModule['category'] == 'authentication')
  865. {
  866. // For now authentication modules are always on and hidden
  867. $oP->add("<input type=\"hidden\" id=\"module[$index]\" name=\"module[$index]\" value=\"$sModuleId\">\n");
  868. $index++;
  869. }
  870. elseif ($aModule['visible'])
  871. {
  872. $oP->add("<p><input type=\"checkbox\" $sClass $sChecked id=\"module[$index]\" name=\"module[$index]\" value=\"$sModuleId\"><label $sClass for=\"module[$index]\"> {$aModule['label']}</label> $sMoreInfo</p>\n");
  873. $index++;
  874. }
  875. else
  876. {
  877. // For now hidden modules are always on !
  878. $oP->add("<input type=\"hidden\" id=\"module[$index]\" name=\"module[$index]\" value=\"$sModuleId\">\n");
  879. $index++;
  880. }
  881. }
  882. $oP->add("</div>");
  883. $oP->add("</fieldset>\n");
  884. $oP->add("<h2 class=\"next\">Next: Administrator account creation</h2>\n");
  885. $oP->add("<table style=\"width:100%\"><tr>\n");
  886. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  887. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Creating the database structure...', $iCurrentStep);\">Next >></button></td>\n");
  888. $oP->add("</tr></table>\n");
  889. $oP->add("</form>\n");
  890. $oP->add_ready_script("$('.read-only').click( function() { $(this).attr('checked','checked'); } );");
  891. }
  892. /**
  893. * Display the form for the third step of the configuration wizard
  894. * which consists in
  895. * 1) Validating the parameters by connecting to the database server & selecting the database
  896. * 2) Creating the database structure
  897. * 3) Prompting for the admin account to be created
  898. */
  899. function AdminAccountDefinition(SetupWebPage $oP, $aParamValues, $iCurrentStep, Config $oConfig)
  900. {
  901. $sNextOperation = 'step'.($iCurrentStep+1);
  902. $oP->set_title("Administrator account creation");
  903. $oP->add("<h2>Creation of the database structure</h2>");
  904. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  905. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  906. AddParamsToForm($oP, $aParamValues, array('auth_user', 'auth_pwd', 'language'));
  907. $sDBName = $aParamValues['db_name'];
  908. if ($sDBName == '')
  909. {
  910. $sDBName = $aParamValues['new_db_name'];
  911. }
  912. $sDBPrefix = $aParamValues['db_prefix'];
  913. $oConfig->SetDBName($sDBName);
  914. $oConfig->SetDBSubname($sDBPrefix);
  915. BuildConfig($oP, $oConfig, $aParamValues); // Load all the includes based on the modules selected
  916. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  917. if (CreateDatabaseStructure($oP, $oConfig, $sDBName, $sDBPrefix, $aParamValues['module']))
  918. {
  919. $sRedStar = "<span class=\"hilite\">*</span>";
  920. $oP->add("<h2>Default language for the application:</h2>\n");
  921. // Possible languages (depends on the dictionaries loaded in the config)
  922. $aForm = array();
  923. $aAvailableLanguages = Dict::GetLanguages();
  924. $sLanguages = '';
  925. $sDefaultCode = $oConfig->GetDefaultLanguage();
  926. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  927. {
  928. $sSelected = ($sLangCode == $sDefaultCode ) ? 'selected ' : '';
  929. $sLanguages.="<option value=\"{$sLangCode}\">{$aInfo['description']} ({$aInfo['localized_description']})</option>";
  930. }
  931. $aForm[] = array('label' => "Default Language$sRedStar:", 'input' => "<select id=\"language\" name=\"language\">$sLanguages</option>");
  932. $oP->form($aForm);
  933. $oP->add("<h2>Definition of the administrator account</h2>\n");
  934. // Database created, continue with admin creation
  935. $oP->add("<fieldset><legend>Administrator account</legend>\n");
  936. $aForm = array();
  937. $aForm[] = array('label' => "Login$sRedStar:", 'input' => "<input id=\"auth_user\" type=\"text\" name=\"auth_user\" value=\"{$aParamValues['auth_user']}\">");
  938. $aForm[] = array('label' => "Password$sRedStar:", 'input' => "<input id=\"auth_pwd\" type=\"password\" name=\"auth_pwd\" value=\"{$aParamValues['auth_pwd']}\">");
  939. $aForm[] = array('label' => "Retype password$sRedStar:", 'input' => "<input id=\"auth_pwd2\" type=\"password\" name=\"auth_pwd2\" value=\"{$aParamValues['auth_pwd']}\">");
  940. $oP->form($aForm);
  941. $oP->add("</fieldset>\n");
  942. $oP->add("<h2 class=\"next\">Next: Application initialization</h2>\n");
  943. $oP->add("<table style=\"width:100%\"><tr>\n");
  944. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  945. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Creating the admin account and profiles...', $iCurrentStep);\">Next >></button></td>\n");
  946. $oP->add("</tr></table>\n");
  947. }
  948. else
  949. {
  950. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button>\n");
  951. }
  952. // Form goes here
  953. $oP->add("</form>\n");
  954. }
  955. /**
  956. * Display the form for the fourth step of the configuration wizard
  957. * which consists in
  958. * 1) Creating the admin user account
  959. * 2) Prompting to load some sample data
  960. */
  961. function SampleDataSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep, Config $oConfig)
  962. {
  963. $sNextOperation = 'step'.($iCurrentStep+1);
  964. $oP->set_title("Application initialization");
  965. $sAdminUser = $aParamValues['auth_user'];
  966. $sAdminPwd = $aParamValues['auth_pwd'];
  967. $sLanguage = $aParamValues['language'];
  968. $oConfig->SetDefaultLanguage($aParamValues['language']);
  969. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  970. $oP->add("<form id=\"theForm\" method=\"post\"\">\n");
  971. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  972. AddParamsToForm($oP, $aParamValues, array('sample_data'));
  973. if (CreateAdminAccount($oP, $oConfig, $sAdminUser, $sAdminPwd, $sLanguage))
  974. {
  975. $oP->add("<h2>Loading of sample data</h2>\n");
  976. $oP->p("<fieldset><legend> Do you want to load sample data into the database ? </legend>\n");
  977. $oP->p("<input type=\"radio\" id=\"sample_data\" name=\"sample_data\" id=\"sample_data_no\" checked value=\"yes\"><label for=\"sample_data_yes\"> Yes, for testing purposes, populate the database with sample data.</label>\n");
  978. $oP->p("<input type=\"radio\" name=\"sample_data\" unchecked id=\"sample_data_no\" value=\"no\"><label for=\"sample_data_no\"> No, this is a production system, load only the data required by the application.</label>\n");
  979. $oP->p("</fieldset>\n");
  980. $oP->add("<h2 class=\"next\">Next: Setup complete</h2>\n");
  981. $oP->add("<table style=\"width:100%\"><tr>\n");
  982. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  983. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Finalizing configuration and loading data...', $iCurrentStep)\">Next >></button></td>\n");
  984. $oP->add("</tr></table>\n");
  985. }
  986. else
  987. {
  988. // Creation failed
  989. $oP->error("Internal error: Failed to create the admin account or to setup the user rights");
  990. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button>\n");
  991. }
  992. // End of visible form
  993. $oP->add("</form>\n");
  994. // Hidden form submitted when moving on to the next page, once all the data files
  995. // have been processed
  996. $oP->add("<form id=\"GoToNextStep\" method=\"post\">\n");
  997. AddParamsToForm($oP, $aParamValues, array('sample_data'));
  998. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  999. $oP->add("</form>\n");
  1000. $oP->add("<div id=\"log\" style=\"color:#F00;\"></div>\n");
  1001. $oP->add_linked_script('./jquery.progression.js');
  1002. PopulateDataFilesList($oP, $aParamValues);
  1003. }
  1004. /**
  1005. * Display the form for the fifth (and final) step of the configuration wizard
  1006. * which consists in
  1007. * 1) Creating the final configuration file
  1008. * 2) Prompting the user to make the file read-only
  1009. */
  1010. function SetupFinished(SetupWebPage $oP, $aParamValues, $iCurrentStep, Config $oConfig)
  1011. {
  1012. $sAuthUser = $aParamValues['auth_user'];
  1013. $sAuthPwd = $aParamValues['auth_pwd'];
  1014. try
  1015. {
  1016. $sSessionName = sprintf('iTop-%x', rand());
  1017. $oConfig->Set('session_name', $sSessionName);
  1018. session_name($sSessionName);
  1019. session_start();
  1020. // Write the final configuration file
  1021. $oConfig->WriteToFile(FINAL_CONFIG_FILE);
  1022. // Start the application
  1023. InitDataModel($oP, FINAL_CONFIG_FILE, false); // Load model and startup DB
  1024. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  1025. {
  1026. UserRights::Login($sAuthUser);
  1027. $_SESSION['auth_user'] = $sAuthUser;
  1028. $_SESSION['login_mode'] = 'form'; // Will enable the "log-off button"
  1029. // remove the tmp config file
  1030. @unlink(TMP_CONFIG_FILE);
  1031. // try to make the final config file read-only
  1032. @chmod(FINAL_CONFIG_FILE, 0440); // Read-only for owner and group, nothing for others
  1033. $oP->set_title("Setup complete");
  1034. $oP->add("<form id=\"theForm\" method=\"get\" action=\"../index.php\">\n");
  1035. // Check if there are some manual steps required:
  1036. $aAvailableModules = GetAvailableModules($oP);
  1037. $aManualSteps = array();
  1038. foreach($aParamValues['module'] as $sModuleId)
  1039. {
  1040. if (!empty($aAvailableModules[$sModuleId]['doc.manual_setup']))
  1041. {
  1042. $aManualSteps[$aAvailableModules[$sModuleId]['label']] = $aAvailableModules[$sModuleId]['doc.manual_setup'];
  1043. }
  1044. }
  1045. if (count($aManualSteps) > 0)
  1046. {
  1047. $oP->add("<h2>Manual operations required</h2>");
  1048. $oP->p("In order to complete the installation, the following manual operations are required:");
  1049. foreach($aManualSteps as $sModuleLabel => $sUrl)
  1050. {
  1051. $oP->p("<a href=\"$sUrl\" target=\"_blank\">Manual instructions for $sModuleLabel</a>");
  1052. }
  1053. }
  1054. else
  1055. {
  1056. $oP->add("<h2>Congratulations for installing iTop</h2>");
  1057. $oP->ok("The initialization completed successfully.");
  1058. }
  1059. // Form goes here.. No back button since the job is done !
  1060. $oP->add('<table style="width:600px;border:0;padding:0;"><tr>');
  1061. $oP->add("<td><a style=\"background:transparent;padding:0;\" title=\"Free: Register your iTop version.\" href=\"http://www.combodo.com/register?product=iTop&version=".urlencode(ITOP_VERSION." revision ".ITOP_REVISION)."\" target=\"_blank\"><img style=\"border:0\" src=\"../images/setup-register.gif\"/></td></a>");
  1062. $oP->add("<td><a style=\"background:transparent;padding:0;\" title=\"Get Professional Support from Combodo\" href=\"http://www.combodo.com/itopsupport\" target=\"_blank\"><img style=\"border:0\" src=\"../images/setup-support.gif\"/></td></a>");
  1063. $oP->add("<td><a style=\"background:transparent;padding:0;\" title=\"Get Professional Training from Combodo\" href=\"http://www.combodo.com/itoptraining\" target=\"_blank\"><img style=\"border:0\" src=\"../images/setup-training.gif\"/></td></a>");
  1064. $oP->add('</tr></table>');
  1065. $oP->add("<p style=\"text-align:center;width:100%\"><button type=\"submit\">Enter iTop</button></p>\n");
  1066. $oP->add("</form>\n");
  1067. }
  1068. else
  1069. {
  1070. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1071. $oP->add("<h2>Step 5: Configuration completed</h2>\n");
  1072. @unlink(FINAL_CONFIG_FILE); // remove the aborted config
  1073. $oP->error("Error: Failed to login for user: '$sAuthUser'\n");
  1074. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  1075. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  1076. AddParamsToForm($oP, $aParamValues);
  1077. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"step0\">\n");
  1078. $oP->add("</form>\n");
  1079. }
  1080. }
  1081. catch(Exception $e)
  1082. {
  1083. $oP->error("Error: unable to create the configuration file.");
  1084. $oP->p($e->getHtmlDesc());
  1085. $oP->p("Did you forget to remove the previous (read-only) configuration file ?");
  1086. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  1087. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"step0\">\n");
  1088. AddParamsToForm($oP, $aParamValues);
  1089. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  1090. $oP->add("</form>\n");
  1091. }
  1092. }
  1093. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1094. // Main program
  1095. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1096. clearstatcache(); // Make sure we know what we are doing !
  1097. if (file_exists(FINAL_CONFIG_FILE))
  1098. {
  1099. Utils::SpecifyConfigFile(FINAL_CONFIG_FILE);
  1100. // The configuration file already exists
  1101. if (is_writable(FINAL_CONFIG_FILE))
  1102. {
  1103. $oP->warning("<b>Warning:</b> a configuration file '".FINAL_CONFIG_FILE."' already exists, and will be overwritten.");
  1104. }
  1105. else
  1106. {
  1107. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1108. $oP->add("<h2>Fatal error</h2>\n");
  1109. $oP->error("<b>Error:</b> the configuration file '".FINAL_CONFIG_FILE."' already exists and cannot be overwritten.");
  1110. $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.");
  1111. $oP->output();
  1112. exit;
  1113. }
  1114. }
  1115. else
  1116. {
  1117. Utils::SpecifyConfigFile(TMP_CONFIG_FILE);
  1118. // No configuration file yet
  1119. // Check that the wizard can write into the root dir to create the configuration file
  1120. if (!is_writable(dirname(FINAL_CONFIG_FILE)))
  1121. {
  1122. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1123. $oP->add("<h2>Fatal error</h2>\n");
  1124. $oP->error("<b>Error:</b> the directory where to store the configuration file is not writable.");
  1125. $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.");
  1126. $oP->output();
  1127. exit;
  1128. }
  1129. if (!is_writable(dirname(FINAL_CONFIG_FILE).'/setup'))
  1130. {
  1131. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1132. $oP->add("<h2>Fatal error</h2>\n");
  1133. $oP->error("<b>Error:</b> the directory where to store temporary setup files is not writable.");
  1134. $oP->p("The wizard cannot create operate. Please make sure that the directory '<b>".realpath(dirname(FINAL_CONFIG_FILE))."/setup</b>' is writable for the web server.");
  1135. $oP->output();
  1136. exit;
  1137. }
  1138. }
  1139. try
  1140. {
  1141. $oConfig = new Config(TMP_CONFIG_FILE);
  1142. }
  1143. catch(Exception $e)
  1144. {
  1145. // We'll end here when the tmp config file does not exist. It's normal
  1146. $oConfig = new Config(TMP_CONFIG_FILE, false /* Don't try to load it */);
  1147. }
  1148. try
  1149. {
  1150. $aParams = array('licence_ok', 'db_server', 'db_user', 'db_pwd','db_name', 'new_db_name', 'db_prefix', 'module', 'sample_data', 'auth_user', 'auth_pwd', 'language');
  1151. foreach($aParams as $sName)
  1152. {
  1153. $aParamValues[$sName] = utils::ReadParam($sName, '');
  1154. }
  1155. switch($sOperation)
  1156. {
  1157. case 'step0':
  1158. $oP->no_cache();
  1159. $oP->log("Info - ========= Wizard step 0 ========");
  1160. WelcomeAndCheckPrerequisites($oP, $aParamValues, 0);
  1161. break;
  1162. case 'step1':
  1163. $oP->no_cache();
  1164. $oP->log("Info - ========= Wizard step 1 ========");
  1165. LicenceAcknowledgement($oP, $aParamValues, 1);
  1166. break;
  1167. case 'step2':
  1168. $oP->log("Info - ========= Wizard step 2 ========");
  1169. DatabaseServerSelection($oP, $aParamValues, 2);
  1170. break;
  1171. case 'step3':
  1172. $oP->no_cache();
  1173. $oP->log("Info - ========= Wizard step 3 ========");
  1174. DatabaseInstanceSelection($oP, $aParamValues, 3, $oConfig);
  1175. break;
  1176. case 'step4':
  1177. $oP->no_cache();
  1178. $oP->log("Info - ========= Wizard step 4 ========");
  1179. ModulesSelection($oP, $aParamValues, 4, $oConfig);
  1180. break;
  1181. case 'step5':
  1182. $oP->no_cache();
  1183. $oP->log("Info - ========= Wizard step 5 ========");
  1184. AdminAccountDefinition($oP, $aParamValues, 5, $oConfig);
  1185. break;
  1186. case 'step6':
  1187. $oP->no_cache();
  1188. $oP->log("Info - ========= Wizard step 6 ========");
  1189. SampleDataSelection($oP, $aParamValues, 6, $oConfig);
  1190. break;
  1191. case 'step7':
  1192. $oP->no_cache();
  1193. $oP->log("Info - ========= Wizard step 7 ========");
  1194. SetupFinished($oP, $aParamValues, 7, $oConfig);
  1195. break;
  1196. default:
  1197. $oP->error("Error: unsupported operation '$sOperation'");
  1198. }
  1199. }
  1200. catch(Exception $e)
  1201. {
  1202. $oP->error("Error: '".$e->getMessage()."'");
  1203. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  1204. }
  1205. catch(CoreException $e)
  1206. {
  1207. $oP->error("Error: '".$e->getHtmlDesc()."'");
  1208. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  1209. }
  1210. $oP->output();
  1211. ?>