index.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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');
  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. InitDataModel($oP, TMP_CONFIG_FILE, false); // load data model and connect to the database
  486. if (!UserRights::Setup())
  487. {
  488. return false;
  489. }
  490. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  491. {
  492. $oP->ok("Administrator account '$sAdminUser' created.");
  493. return true;
  494. }
  495. else
  496. {
  497. $oP->error("Failed to create the administrator account '$sAdminUser'.");
  498. return false;
  499. }
  500. }
  501. function ListModuleFiles($sRelDir, SetupWebPage $oP)
  502. {
  503. $sDirectory = APPROOT.'/'.$sRelDir;
  504. //echo "<p>$sDirectory</p>\n";
  505. if ($hDir = opendir($sDirectory))
  506. {
  507. // This is the correct way to loop over the directory. (according to the documentation)
  508. while (($sFile = readdir($hDir)) !== false)
  509. {
  510. $aMatches = array();
  511. if (is_dir($sDirectory.'/'.$sFile))
  512. {
  513. if (($sFile != '.') && ($sFile != '..') && ($sFile != '.svn'))
  514. {
  515. ListModuleFiles($sRelDir.'/'.$sFile, $oP);
  516. }
  517. }
  518. else if (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches))
  519. {
  520. $oP->SetModulePath($sRelDir);
  521. try
  522. {
  523. //echo "<p>Loading: $sDirectory/$sFile...</p>\n";
  524. require_once($sDirectory.'/'.$sFile);
  525. //echo "<p>Done.</p>\n";
  526. }
  527. catch(Exception $e)
  528. {
  529. // Continue...
  530. }
  531. }
  532. }
  533. closedir($hDir);
  534. }
  535. else
  536. {
  537. $oP->error("Data directory (".$sDirectory.") not found or not readable.");
  538. }
  539. }
  540. /**
  541. * Scans the ./data directory for XML files and output them as a Javascript array
  542. */
  543. function PopulateDataFilesList(SetupWebPage $oP, $aParamValues)
  544. {
  545. $oP->add("<script type=\"text/javascript\">\n");
  546. $oP->add("function PopulateDataFilesList()\n");
  547. $oP->add("{\n");
  548. $oP->add("if (aFilesToLoad.length > 0) return;"); // Populate the list only once...
  549. $aAvailableModules = GetAvailableModules($oP);
  550. $aStructureDataFiles = array();
  551. $aSampleDataFiles = array();
  552. foreach($aParamValues['module'] as $sModuleId)
  553. {
  554. $aModuleStruct = $aAvailableModules[$sModuleId]['data.struct'];
  555. $aModuleSamples = $aAvailableModules[$sModuleId]['data.sample'];
  556. $aStructureDataFiles = array_merge($aStructureDataFiles, $aModuleStruct);
  557. $aSampleDataFiles = array_merge($aSampleDataFiles, $aModuleSamples);
  558. }
  559. // Structure data
  560. //
  561. foreach($aStructureDataFiles as $sFile)
  562. {
  563. // Under Windows, it is a must to escape backslashes (not an issue until a folder name starts with t or n, etc...)
  564. $sFile = APPROOT.$sFile;
  565. $sFile = str_replace('\\', '\\\\', $sFile);
  566. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  567. }
  568. // Sample data - loaded IIF wished by the user
  569. //
  570. $oP->add("if (($(\"#sample_data:checked\").length == 1))");
  571. $oP->add("{");
  572. foreach($aSampleDataFiles as $sFile)
  573. {
  574. // Under Windows, it is a must to escape backslashes (not an issue until a folder name starts with t or n, etc...)
  575. $sFile = APPROOT.$sFile;
  576. $sFile = str_replace('\\', '\\\\', $sFile);
  577. $oP->add("aFilesToLoad[aFilesToLoad.length] = '$sFile';\n");
  578. }
  579. $oP->add("}\n");
  580. $oP->add("}\n");
  581. $oP->add("</script>\n");
  582. }
  583. /**
  584. * Add some parameters as hidden inputs into a form
  585. * @param SetupWebpage $oP The page to insert the form elements into
  586. * @param Hash $aParamValues The pairs name/value to be stored in the form
  587. * @param Array $aExcludeParams A list of parameters to exclude from the previous hash
  588. */
  589. function AddParamsToForm(SetupWebpage $oP, $aParamValues, $aExcludeParams = array())
  590. {
  591. foreach($aParamValues as $sName => $value)
  592. {
  593. if(!in_array($sName, $aExcludeParams))
  594. {
  595. if (is_array($value))
  596. {
  597. foreach($value as $sKey => $sItem)
  598. {
  599. $oP->add('<input type="hidden" name="'.$sName.'['.$sKey.']'.'" value="'.$sItem.'">');
  600. }
  601. }
  602. else
  603. {
  604. $oP->add('<input type="hidden" name="'.$sName.'" value="'.$value.'">');
  605. }
  606. }
  607. }
  608. }
  609. /**
  610. * Search (on the disk) for all defined iTop modules, load them and returns the list (as an array)
  611. * of the possible iTop modules to install
  612. * @param none
  613. * @return Hash A big array moduleID => ModuleData
  614. */
  615. function GetAvailableModules(SetupWebpage $oP)
  616. {
  617. clearstatcache();
  618. ListModuleFiles('modules', $oP);
  619. return $oP->GetModules();
  620. }
  621. /**
  622. * Build the config file from the parameters (especially the selected modules)
  623. */
  624. function BuildConfig(SetupWebpage $oP, Config &$oConfig, $aParamValues, $aAvailableModules)
  625. {
  626. // Initialize the arrays below with default values for the application...
  627. $aAddOns = $oConfig->GetAddOns();
  628. $aAppModules = $oConfig->GetAppModules();
  629. $aDataModels = $oConfig->GetDataModels();
  630. $aWebServiceCategories = $oConfig->GetWebServiceCategories();
  631. $aDictionaries = $oConfig->GetDictionaries();
  632. // Merge the values with the ones provided by the modules
  633. // Make sure when don't load the same file twice...
  634. foreach($aParamValues['module'] as $sModuleId)
  635. {
  636. $oP->log('Installed iTop module: '. $sModuleId);
  637. if (isset($aAvailableModules[$sModuleId]['datamodel']))
  638. {
  639. $aDataModels = array_unique(array_merge($aDataModels, $aAvailableModules[$sModuleId]['datamodel']));
  640. }
  641. if (isset($aAvailableModules[$sModuleId]['webservice']))
  642. {
  643. $aWebServiceCategories = array_unique(array_merge($aWebServiceCategories, $aAvailableModules[$sModuleId]['webservice']));
  644. }
  645. if (isset($aAvailableModules[$sModuleId]['dictionary']))
  646. {
  647. $aDictionaries = array_unique(array_merge($aDictionaries, $aAvailableModules[$sModuleId]['dictionary']));
  648. }
  649. if (isset($aAvailableModules[$sModuleId]['settings']))
  650. {
  651. foreach($aAvailableModules[$sModuleId]['settings'] as $sProperty => $value)
  652. {
  653. list($sName, $sVersion) = GetModuleName($sModuleId);
  654. $oConfig->SetModuleSetting($sName, $sProperty, $value);
  655. }
  656. }
  657. if (isset($aAvailableModules[$sModuleId]['installer']))
  658. {
  659. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  660. if (!class_exists($sModuleInstallerClass))
  661. {
  662. throw new Exception("Wrong installer class: '$sModuleInstallerClass' is not a PHP class - Module: ".$aAvailableModules[$sModuleId]['label']);
  663. }
  664. if (!is_subclass_of($sModuleInstallerClass, 'ModuleInstallerAPI'))
  665. {
  666. throw new Exception("Wrong installer class: '$sModuleInstallerClass' is not derived from 'ModuleInstallerAPI' - Module: ".$aAvailableModules[$sModuleId]['label']);
  667. }
  668. $aCallSpec = array($sModuleInstallerClass, 'BeforeWritingConfig');
  669. $oConfig = call_user_func_array($aCallSpec, array($oConfig));
  670. }
  671. }
  672. $oConfig->SetAddOns($aAddOns);
  673. $oConfig->SetAppModules($aAppModules);
  674. $oConfig->SetDataModels($aDataModels);
  675. $oConfig->SetWebServiceCategories($aWebServiceCategories);
  676. $oConfig->SetDictionaries($aDictionaries);
  677. }
  678. /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  679. // Handling of the different steps of the setup wizard
  680. /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  681. /**
  682. * Displays the welcome screen and check some basic prerequisites
  683. */
  684. function WelcomeAndCheckPrerequisites(SetupWebPage $oP, $aParamValues, $iCurrentStep)
  685. {
  686. $sNextOperation = 'step'.($iCurrentStep+1);
  687. $oP->add("<h1>iTop configuration wizard</h1>\n");
  688. $sVersionStringShort = GetITopVersion(true);
  689. $sVersionStringLong = GetITopVersion(false);
  690. $oP->set_title('Welcome to '.$sVersionStringShort);
  691. $oP->log($sVersionStringLong);
  692. $oP->add("<h2>Checking prerequisites</h2>\n");
  693. if (CheckPHPVersion($oP))
  694. {
  695. $oP->add("<h2 class=\"next\">Next: Licence agreement</h2>\n");
  696. $oP->add("<form id=\"theForm\" method=\"post\" onSubmit=\"return DoSubmit('', 0)\">\n");
  697. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  698. AddParamsToForm($oP, $aParamValues);
  699. $oP->add("<table style=\"width:100%\"><tr>\n");
  700. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" type=\"submit\">Next >></button></td>\n");
  701. $oP->add("</tr></table>\n");
  702. $oP->add("</form>\n");
  703. }
  704. }
  705. function LicenceAcknowledgement($oP, $aParamValues, $iCurrentStep)
  706. {
  707. $sNextOperation = 'step'.($iCurrentStep+1);
  708. $oP->set_title('License agreement');
  709. $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>');
  710. $oP->add("<iframe style=\"width: 100%; height: 350px; overflow-y:auto; font-size:0.8em;\" src=\"./licence.html\">Next: Database server selection</iframe>\n");
  711. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  712. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  713. AddParamsToForm($oP, $aParamValues, array('licence_ok'));
  714. $sChecked = $aParamValues['licence_ok'] == 1 ? 'checked' : '';
  715. $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");
  716. $oP->add("<h2 class=\"next\">Next: Database server selection</h2>\n");
  717. $oP->add("<table style=\"width:100%\"><tr>\n");
  718. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  719. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('', $iCurrentStep)\">Next >></button></td>\n");
  720. $oP->add("</tr></table>\n");
  721. $oP->add("</form>\n");
  722. }
  723. /**
  724. * Display the form for the first step of the configuration wizard
  725. * which consists in the database server selection
  726. */
  727. function DatabaseServerSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep)
  728. {
  729. $sNextOperation = 'step'.($iCurrentStep+1);
  730. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  731. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  732. AddParamsToForm($oP, $aParamValues, array('db_server', 'db_user', 'db_pwd'));
  733. if ($aParamValues['licence_ok'] == 1)
  734. {
  735. $sRedStar = '<span class="hilite">*</span>';
  736. $oP->set_title("Database server selection\n");
  737. $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");
  738. // Form goes here
  739. $oP->add("<fieldset><legend>Database connection</legend>\n");
  740. $aForm = array();
  741. $aForm[] = array('label' => "Server name$sRedStar:", 'input' => "<input id=\"db_server\" type=\"text\" name=\"db_server\" value=\"{$aParamValues['db_server']}\">",
  742. 'help' => 'E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"');
  743. $aForm[] = array('label' => "User name$sRedStar:", 'input' => "<input id=\"db_user\" type=\"text\" name=\"db_user\" value=\"{$aParamValues['db_user']}\">",
  744. 'help' => 'The account must have the following privileges: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER');
  745. $aForm[] = array('label' => 'Password:', 'input' => "<input id=\"db_pwd\" type=\"password\" name=\"db_pwd\" value=\"{$aParamValues['db_pwd']}\">");
  746. $oP->form($aForm);
  747. $oP->add("</fieldset>\n");
  748. $oP->add("<h2 class=\"next\">Next: Database instance Selection</h2>\n");
  749. $oP->add("<table style=\"width:100%\"><tr>\n");
  750. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  751. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Connecting to the database...', $iCurrentStep);\">Next >></button></td>\n");
  752. $oP->add("</tr></table>\n");
  753. }
  754. else
  755. {
  756. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  757. }
  758. $oP->add("</form>\n");
  759. }
  760. /**
  761. * Display the form for the second step of the configuration wizard
  762. * which consists in
  763. * 1) Validating the parameters by connecting to the database server
  764. * 2) Prompting to select an existing database or to create a new one
  765. */
  766. function DatabaseInstanceSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep, $oConfig)
  767. {
  768. $sNextOperation = 'step'.($iCurrentStep+1);
  769. $oP->set_title("Database instance selection\n");
  770. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  771. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  772. AddParamsToForm($oP, $aParamValues, array('db_name', 'db_prefix', 'new_db_name'));
  773. $sDBServer = $aParamValues['db_server'];
  774. $sDBUser = $aParamValues['db_user'];
  775. $sDBPwd = $aParamValues['db_pwd'];
  776. $aDatabases = CheckServerConnection($oP, $sDBServer, $sDBUser, $sDBPwd);
  777. if ($aDatabases === false)
  778. {
  779. // Connection failed, invalid credentials ? Go back
  780. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  781. }
  782. else
  783. {
  784. // Connection is Ok, save it and continue the setup wizard
  785. $oConfig->SetDBHost($sDBServer);
  786. $oConfig->SetDBUser($sDBUser);
  787. $oConfig->SetDBPwd($sDBPwd);
  788. $oConfig->WriteToFile();
  789. $oP->add("<fieldset><legend>Select the database instance to use for iTop<span class=\"hilite\">*</span></legend>\n");
  790. $aForm = array();
  791. $bExistingChecked = false;
  792. if (is_array($aDatabases))
  793. {
  794. foreach($aDatabases as $sDBName)
  795. {
  796. $sChecked = '';
  797. if ($aParamValues['db_name'] == $sDBName)
  798. {
  799. $sChecked = 'checked';
  800. $bExistingChecked = true;
  801. }
  802. $aForm[] = array('label' => "<input id=\"db_$sDBName\" type=\"radio\" name=\"db_name\" value=\"$sDBName\" $sChecked/><label for=\"db_$sDBName\"> $sDBName</label>");
  803. }
  804. }
  805. else
  806. {
  807. $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\"/>");
  808. $oP->add_ready_script("$('#current_db_name').click( function() { $('#current_db').attr('checked', true); });");
  809. }
  810. $sChecked = '';
  811. $sDBName = '';
  812. // If the 'Create Database' option was checked... and the database still does not exist
  813. if (!$bExistingChecked && !empty($aParamValues['new_db_name']))
  814. {
  815. $sChecked = 'checked';
  816. $sDBName = $aParamValues['new_db_name'];
  817. }
  818. $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\"/>");
  819. $oP->form($aForm);
  820. $oP->add_ready_script("$('#new_db_name').click( function() { $('#new_db').attr('checked', true); })");
  821. $oP->add("</fieldset>\n");
  822. $aForm = array();
  823. $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\"/>");
  824. $oP->form($aForm);
  825. $oP->add("<h2 class=\"next\">Next: iTop modules selection</h2>\n");
  826. $oP->add("<table style=\"width:100%\"><tr>\n");
  827. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  828. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('', $iCurrentStep);\">Next >></button></td>\n");
  829. $oP->add("</tr></table>\n");
  830. }
  831. $oP->add("</form>\n");
  832. }
  833. /**
  834. * Display the form to select the iTop modules to be installed
  835. */
  836. function ModulesSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep, $oConfig)
  837. {
  838. $sNextOperation = 'step'.($iCurrentStep+1);
  839. $sPrevOperation = 'step'.($iCurrentStep-1);
  840. $sDBName = $aParamValues['db_name'];
  841. if ($sDBName == '')
  842. {
  843. $sDBName = $aParamValues['new_db_name'];
  844. }
  845. $sDBPrefix = $aParamValues['db_prefix'];
  846. $oConfig->SetDBName($sDBName);
  847. $oConfig->SetDBSubname($sDBPrefix);
  848. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  849. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  850. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  851. AddParamsToForm($oP, $aParamValues, array('module'));
  852. $sRedStar = '<span class="hilite">*</span>';
  853. $oP->set_title("iTop modules selection");
  854. $oP->add("<h2>Customize your iTop installation to fit your needs</h2>\n");
  855. $aAvailableModules = GetAvailableModules($oP);
  856. // Form goes here
  857. $oP->add("<fieldset><legend>Select the iTop modules you want to install:</legend>\n");
  858. $oP->add("<div style=\"border: 0;width:100%; height: 350px; overflow-y:auto;\">");
  859. $sRedStar = '<span class="hilite">*</span>';
  860. $index = 0;
  861. $aSelectedModules = $aParamValues['module'];
  862. if ($aSelectedModules == '')
  863. {
  864. // Make sure it gets initialized as an array, default value: all modules selected !
  865. $aSelectedModules = array();
  866. foreach($aAvailableModules as $sModuleId => $aModule)
  867. {
  868. $aSelectedModules[] = $sModuleId;
  869. }
  870. }
  871. foreach($aAvailableModules as $sModuleId => $aModule)
  872. {
  873. $sModuleLabel = $aModule['label'];
  874. $sModuleHelp = $aModule['doc.more_information'];
  875. $sClass = ($aModule['mandatory']) ? 'class="read-only"' : '';
  876. $sChecked = ($aModule['mandatory'] || in_array($sModuleId, $aSelectedModules) ) ? 'checked' : '';
  877. $sMoreInfo = (!empty($aModule['doc.more_information'])) ? "<a href=\"..{$aModule['doc.more_information']}\" target=\"_blank\">more info</a>": '';
  878. if ($aModule['category'] == 'authentication')
  879. {
  880. // For now authentication modules are always on and hidden
  881. $oP->add("<input type=\"hidden\" id=\"module[$index]\" name=\"module[$index]\" value=\"$sModuleId\">\n");
  882. $index++;
  883. }
  884. elseif ($aModule['visible'])
  885. {
  886. $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");
  887. $index++;
  888. }
  889. else
  890. {
  891. // For now hidden modules are always on !
  892. $oP->add("<input type=\"hidden\" id=\"module[$index]\" name=\"module[$index]\" value=\"$sModuleId\">\n");
  893. $index++;
  894. }
  895. }
  896. $oP->add("</div>");
  897. $oP->add("</fieldset>\n");
  898. $oP->add("<h2 class=\"next\">Next: Administrator account creation</h2>\n");
  899. $oP->add("<table style=\"width:100%\"><tr>\n");
  900. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  901. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Creating the database structure...', $iCurrentStep);\">Next >></button></td>\n");
  902. $oP->add("</tr></table>\n");
  903. $oP->add("</form>\n");
  904. $oP->add_ready_script("$('.read-only').click( function() { $(this).attr('checked','checked'); } );");
  905. }
  906. /**
  907. * Display the form for the third step of the configuration wizard
  908. * which consists in
  909. * 1) Validating the parameters by connecting to the database server & selecting the database
  910. * 2) Creating the database structure
  911. * 3) Prompting for the admin account to be created
  912. */
  913. function AdminAccountDefinition(SetupWebPage $oP, $aParamValues, $iCurrentStep, Config $oConfig)
  914. {
  915. $sNextOperation = 'step'.($iCurrentStep+1);
  916. $oP->set_title("Administrator account creation");
  917. $oP->add("<h2>Creation of the database structure</h2>");
  918. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  919. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  920. AddParamsToForm($oP, $aParamValues, array('auth_user', 'auth_pwd', 'language'));
  921. $sDBName = $aParamValues['db_name'];
  922. if ($sDBName == '')
  923. {
  924. $sDBName = $aParamValues['new_db_name'];
  925. }
  926. $sDBPrefix = $aParamValues['db_prefix'];
  927. $oConfig->SetDBName($sDBName);
  928. $oConfig->SetDBSubname($sDBPrefix);
  929. $aAvailableModules = GetAvailableModules($oP);
  930. BuildConfig($oP, $oConfig, $aParamValues, $aAvailableModules); // Load all the includes based on the modules selected
  931. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  932. if (CreateDatabaseStructure($oP, $oConfig, $sDBName, $sDBPrefix, $aParamValues['module']))
  933. {
  934. foreach($aParamValues['module'] as $sModuleId)
  935. {
  936. if (isset($aAvailableModules[$sModuleId]['installer']))
  937. {
  938. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  939. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  940. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  941. call_user_func_array($aCallSpec, array($oConfig));
  942. }
  943. }
  944. $sRedStar = "<span class=\"hilite\">*</span>";
  945. $oP->add("<h2>Default language for the application:</h2>\n");
  946. // Possible languages (depends on the dictionaries loaded in the config)
  947. $aForm = array();
  948. $aAvailableLanguages = Dict::GetLanguages();
  949. $sLanguages = '';
  950. $sDefaultCode = $oConfig->GetDefaultLanguage();
  951. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  952. {
  953. $sSelected = ($sLangCode == $sDefaultCode ) ? 'selected ' : '';
  954. $sLanguages.="<option value=\"{$sLangCode}\">{$aInfo['description']} ({$aInfo['localized_description']})</option>";
  955. }
  956. $aForm[] = array('label' => "Default Language$sRedStar:", 'input' => "<select id=\"language\" name=\"language\">$sLanguages</option>");
  957. $oP->form($aForm);
  958. $oP->add("<h2>Definition of the administrator account</h2>\n");
  959. // Database created, continue with admin creation
  960. $oP->add("<fieldset><legend>Administrator account</legend>\n");
  961. $aForm = array();
  962. $aForm[] = array('label' => "Login$sRedStar:", 'input' => "<input id=\"auth_user\" type=\"text\" name=\"auth_user\" value=\"{$aParamValues['auth_user']}\">");
  963. $aForm[] = array('label' => "Password$sRedStar:", 'input' => "<input id=\"auth_pwd\" type=\"password\" name=\"auth_pwd\" value=\"{$aParamValues['auth_pwd']}\">");
  964. $aForm[] = array('label' => "Retype password$sRedStar:", 'input' => "<input id=\"auth_pwd2\" type=\"password\" name=\"auth_pwd2\" value=\"{$aParamValues['auth_pwd']}\">");
  965. $oP->form($aForm);
  966. $oP->add("</fieldset>\n");
  967. $oP->add("<h2 class=\"next\">Next: Application initialization</h2>\n");
  968. $oP->add("<table style=\"width:100%\"><tr>\n");
  969. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  970. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Creating the admin account and profiles...', $iCurrentStep);\">Next >></button></td>\n");
  971. $oP->add("</tr></table>\n");
  972. }
  973. else
  974. {
  975. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button>\n");
  976. }
  977. // Form goes here
  978. $oP->add("</form>\n");
  979. }
  980. /**
  981. * Display the form for the fourth step of the configuration wizard
  982. * which consists in
  983. * 1) Creating the admin user account
  984. * 2) Prompting to load some sample data
  985. */
  986. function SampleDataSelection(SetupWebPage $oP, $aParamValues, $iCurrentStep, Config $oConfig)
  987. {
  988. $sNextOperation = 'step'.($iCurrentStep+1);
  989. $oP->set_title("Application initialization");
  990. $sAdminUser = $aParamValues['auth_user'];
  991. $sAdminPwd = $aParamValues['auth_pwd'];
  992. $sLanguage = $aParamValues['language'];
  993. $oConfig->SetDefaultLanguage($aParamValues['language']);
  994. $oConfig->WriteToFile(TMP_CONFIG_FILE);
  995. $oP->add("<form id=\"theForm\" method=\"post\"\">\n");
  996. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  997. AddParamsToForm($oP, $aParamValues, array('sample_data'));
  998. if (CreateAdminAccount($oP, $oConfig, $sAdminUser, $sAdminPwd, $sLanguage))
  999. {
  1000. $oP->add("<h2>Loading of sample data</h2>\n");
  1001. $oP->p("<fieldset><legend> Do you want to load sample data into the database ? </legend>\n");
  1002. $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");
  1003. $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");
  1004. $oP->p("</fieldset>\n");
  1005. $oP->add("<h2 class=\"next\">Next: Setup complete</h2>\n");
  1006. $oP->add("<table style=\"width:100%\"><tr>\n");
  1007. $oP->add("<td style=\"text-align:left;\"><button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button></td>\n");
  1008. $oP->add("<td style=\"text-align:right;\"><button type=\"submit\" onClick=\"return DoSubmit('Finalizing configuration and loading data...', $iCurrentStep)\">Next >></button></td>\n");
  1009. $oP->add("</tr></table>\n");
  1010. }
  1011. else
  1012. {
  1013. // Creation failed
  1014. $oP->error("Internal error: Failed to create the admin account or to setup the user rights");
  1015. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep)\"><< Back</button>\n");
  1016. }
  1017. // End of visible form
  1018. $oP->add("</form>\n");
  1019. // Hidden form submitted when moving on to the next page, once all the data files
  1020. // have been processed
  1021. $oP->add("<form id=\"GoToNextStep\" method=\"post\">\n");
  1022. AddParamsToForm($oP, $aParamValues, array('sample_data'));
  1023. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sNextOperation\">\n");
  1024. $oP->add("</form>\n");
  1025. $oP->add("<div id=\"log\" style=\"color:#F00;\"></div>\n");
  1026. $oP->add_linked_script('./jquery.progression.js');
  1027. PopulateDataFilesList($oP, $aParamValues);
  1028. }
  1029. /**
  1030. * Display the form for the fifth (and final) step of the configuration wizard
  1031. * which consists in
  1032. * 1) Creating the final configuration file
  1033. * 2) Prompting the user to make the file read-only
  1034. */
  1035. function SetupFinished(SetupWebPage $oP, $aParamValues, $iCurrentStep, Config $oConfig)
  1036. {
  1037. $sAuthUser = $aParamValues['auth_user'];
  1038. $sAuthPwd = $aParamValues['auth_pwd'];
  1039. try
  1040. {
  1041. $sSessionName = sprintf('iTop-%x', rand());
  1042. $oConfig->Set('session_name', $sSessionName);
  1043. session_name($sSessionName);
  1044. session_start();
  1045. // Write the final configuration file
  1046. $oConfig->WriteToFile(FINAL_CONFIG_FILE);
  1047. // Start the application
  1048. InitDataModel($oP, FINAL_CONFIG_FILE, false); // Load model and startup DB
  1049. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  1050. {
  1051. UserRights::Login($sAuthUser);
  1052. $_SESSION['auth_user'] = $sAuthUser;
  1053. $_SESSION['login_mode'] = 'form'; // Will enable the "log-off button"
  1054. // remove the tmp config file
  1055. @unlink(TMP_CONFIG_FILE);
  1056. // try to make the final config file read-only
  1057. @chmod(FINAL_CONFIG_FILE, 0440); // Read-only for owner and group, nothing for others
  1058. $oP->set_title("Setup complete");
  1059. $oP->add("<form id=\"theForm\" method=\"get\" action=\"../index.php\">\n");
  1060. // Check if there are some manual steps required:
  1061. $aAvailableModules = GetAvailableModules($oP);
  1062. $aManualSteps = array();
  1063. foreach($aParamValues['module'] as $sModuleId)
  1064. {
  1065. if (!empty($aAvailableModules[$sModuleId]['doc.manual_setup']))
  1066. {
  1067. $aManualSteps[$aAvailableModules[$sModuleId]['label']] = $aAvailableModules[$sModuleId]['doc.manual_setup'];
  1068. }
  1069. }
  1070. if (count($aManualSteps) > 0)
  1071. {
  1072. $oP->add("<h2>Manual operations required</h2>");
  1073. $oP->p("In order to complete the installation, the following manual operations are required:");
  1074. foreach($aManualSteps as $sModuleLabel => $sUrl)
  1075. {
  1076. $oP->p("<a href=\"$sUrl\" target=\"_blank\">Manual instructions for $sModuleLabel</a>");
  1077. }
  1078. }
  1079. else
  1080. {
  1081. $oP->add("<h2>Congratulations for installing iTop</h2>");
  1082. $oP->ok("The initialization completed successfully.");
  1083. }
  1084. // Form goes here.. No back button since the job is done !
  1085. $oP->add('<table style="width:600px;border:0;padding:0;"><tr>');
  1086. $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>");
  1087. $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>");
  1088. $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>");
  1089. $oP->add('</tr></table>');
  1090. $oP->add("<p style=\"text-align:center;width:100%\"><button type=\"submit\">Enter iTop</button></p>\n");
  1091. $oP->add("</form>\n");
  1092. }
  1093. else
  1094. {
  1095. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1096. $oP->add("<h2>Step 5: Configuration completed</h2>\n");
  1097. @unlink(FINAL_CONFIG_FILE); // remove the aborted config
  1098. $oP->error("Error: Failed to login for user: '$sAuthUser'\n");
  1099. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  1100. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  1101. AddParamsToForm($oP, $aParamValues);
  1102. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"step0\">\n");
  1103. $oP->add("</form>\n");
  1104. }
  1105. }
  1106. catch(Exception $e)
  1107. {
  1108. $oP->error("Error: unable to create the configuration file.");
  1109. $oP->p($e->getHtmlDesc());
  1110. $oP->p("Did you forget to remove the previous (read-only) configuration file ?");
  1111. $oP->add("<form id=\"theForm\" method=\"post\">\n");
  1112. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"step0\">\n");
  1113. AddParamsToForm($oP, $aParamValues);
  1114. $oP->add("<button type=\"button\" onClick=\"return DoGoBack($iCurrentStep);\"><< Back</button>\n");
  1115. $oP->add("</form>\n");
  1116. }
  1117. }
  1118. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1119. // Main program
  1120. ///////////////////////////////////////////////////////////////////////////////////////////////////
  1121. clearstatcache(); // Make sure we know what we are doing !
  1122. if (file_exists(FINAL_CONFIG_FILE))
  1123. {
  1124. Utils::SpecifyConfigFile(FINAL_CONFIG_FILE);
  1125. // The configuration file already exists
  1126. if (is_writable(FINAL_CONFIG_FILE))
  1127. {
  1128. $oP->warning("<b>Warning:</b> a configuration file '".FINAL_CONFIG_FILE."' already exists, and will be overwritten.");
  1129. }
  1130. else
  1131. {
  1132. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1133. $oP->add("<h2>Fatal error</h2>\n");
  1134. $oP->error("<b>Error:</b> the configuration file '".FINAL_CONFIG_FILE."' already exists and cannot be overwritten.");
  1135. $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.");
  1136. $oP->output();
  1137. exit;
  1138. }
  1139. }
  1140. else
  1141. {
  1142. Utils::SpecifyConfigFile(TMP_CONFIG_FILE);
  1143. // No configuration file yet
  1144. // Check that the wizard can write into the root dir to create the configuration file
  1145. if (!is_writable(dirname(FINAL_CONFIG_FILE)))
  1146. {
  1147. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1148. $oP->add("<h2>Fatal error</h2>\n");
  1149. $oP->error("<b>Error:</b> the directory where to store the configuration file is not writable.");
  1150. $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.");
  1151. $oP->output();
  1152. exit;
  1153. }
  1154. if (!is_writable(dirname(FINAL_CONFIG_FILE).'/setup'))
  1155. {
  1156. $oP->add("<h1>iTop configuration wizard</h1>\n");
  1157. $oP->add("<h2>Fatal error</h2>\n");
  1158. $oP->error("<b>Error:</b> the directory where to store temporary setup files is not writable.");
  1159. $oP->p("The wizard cannot create operate. Please make sure that the directory '<b>".realpath(dirname(FINAL_CONFIG_FILE))."/setup</b>' is writable for the web server.");
  1160. $oP->output();
  1161. exit;
  1162. }
  1163. }
  1164. try
  1165. {
  1166. $oConfig = new Config(TMP_CONFIG_FILE);
  1167. }
  1168. catch(Exception $e)
  1169. {
  1170. // We'll end here when the tmp config file does not exist. It's normal
  1171. $oConfig = new Config(TMP_CONFIG_FILE, false /* Don't try to load it */);
  1172. }
  1173. try
  1174. {
  1175. $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');
  1176. foreach($aParams as $sName)
  1177. {
  1178. $aParamValues[$sName] = utils::ReadParam($sName, '');
  1179. }
  1180. switch($sOperation)
  1181. {
  1182. case 'step0':
  1183. $oP->no_cache();
  1184. $oP->log("Info - ========= Wizard step 0 ========");
  1185. WelcomeAndCheckPrerequisites($oP, $aParamValues, 0);
  1186. break;
  1187. case 'step1':
  1188. $oP->no_cache();
  1189. $oP->log("Info - ========= Wizard step 1 ========");
  1190. LicenceAcknowledgement($oP, $aParamValues, 1);
  1191. break;
  1192. case 'step2':
  1193. $oP->log("Info - ========= Wizard step 2 ========");
  1194. DatabaseServerSelection($oP, $aParamValues, 2);
  1195. break;
  1196. case 'step3':
  1197. $oP->no_cache();
  1198. $oP->log("Info - ========= Wizard step 3 ========");
  1199. DatabaseInstanceSelection($oP, $aParamValues, 3, $oConfig);
  1200. break;
  1201. case 'step4':
  1202. $oP->no_cache();
  1203. $oP->log("Info - ========= Wizard step 4 ========");
  1204. ModulesSelection($oP, $aParamValues, 4, $oConfig);
  1205. break;
  1206. case 'step5':
  1207. $oP->no_cache();
  1208. $oP->log("Info - ========= Wizard step 5 ========");
  1209. AdminAccountDefinition($oP, $aParamValues, 5, $oConfig);
  1210. break;
  1211. case 'step6':
  1212. $oP->no_cache();
  1213. $oP->log("Info - ========= Wizard step 6 ========");
  1214. SampleDataSelection($oP, $aParamValues, 6, $oConfig);
  1215. break;
  1216. case 'step7':
  1217. $oP->no_cache();
  1218. $oP->log("Info - ========= Wizard step 7 ========");
  1219. SetupFinished($oP, $aParamValues, 7, $oConfig);
  1220. break;
  1221. default:
  1222. $oP->error("Error: unsupported operation '$sOperation'");
  1223. }
  1224. }
  1225. catch(Exception $e)
  1226. {
  1227. $oP->error("Error: '".$e->getMessage()."'");
  1228. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  1229. }
  1230. catch(CoreException $e)
  1231. {
  1232. $oP->error("Error: '".$e->getHtmlDesc()."'");
  1233. $oP->add("<button type=\"button\" onClick=\"window.history.back();\"><< Back</button>\n");
  1234. }
  1235. $oP->output();
  1236. ?>