index.php 48 KB

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