index.php 51 KB

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