index.php 48 KB

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