runtimeenv.class.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. * Web page used for displaying the login form
  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."setup/modulediscovery.class.inc.php");
  25. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  26. require_once(APPROOT.'setup/compiler.class.inc.php');
  27. require_once(APPROOT.'core/metamodel.class.php');
  28. define ('MODULE_ACTION_OPTIONAL', 1);
  29. define ('MODULE_ACTION_MANDATORY', 2);
  30. define ('MODULE_ACTION_IMPOSSIBLE', 3);
  31. define ('ROOT_MODULE', '_Root_'); // Convention to store IN MEMORY the name/version of the root module i.e. application
  32. define ('DATAMODEL_MODULE', 'datamodel'); // Convention to store the version of the datamodel
  33. class RunTimeEnvironment
  34. {
  35. protected $sTargetEnv;
  36. public function __construct($sEnvironment = 'production')
  37. {
  38. $this->sTargetEnv = $sEnvironment;
  39. }
  40. /**
  41. * Helper function to initialize the ORM and load the data model
  42. * from the given file
  43. * @param $oConfig object The configuration (volatile, not necessarily already on disk)
  44. * @param $bModelOnly boolean Whether or not to allow loading a data model with no corresponding DB
  45. * @return none
  46. */
  47. public function InitDataModel($oConfig, $bModelOnly = true, $bUseCache = false)
  48. {
  49. require_once(APPROOT.'/core/log.class.inc.php');
  50. require_once(APPROOT.'/core/kpi.class.inc.php');
  51. require_once(APPROOT.'/core/coreexception.class.inc.php');
  52. require_once(APPROOT.'/core/dict.class.inc.php');
  53. require_once(APPROOT.'/core/attributedef.class.inc.php');
  54. require_once(APPROOT.'/core/filterdef.class.inc.php');
  55. require_once(APPROOT.'/core/stimulus.class.inc.php');
  56. require_once(APPROOT.'/core/MyHelpers.class.inc.php');
  57. require_once(APPROOT.'/core/expression.class.inc.php');
  58. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  59. require_once(APPROOT.'/core/sqlquery.class.inc.php');
  60. require_once(APPROOT.'/core/dbobject.class.php');
  61. require_once(APPROOT.'/core/dbobjectsearch.class.php');
  62. require_once(APPROOT.'/core/dbobjectset.class.php');
  63. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  64. require_once(APPROOT.'/core/userrights.class.inc.php');
  65. require_once(APPROOT.'/setup/moduleinstallation.class.inc.php');
  66. $sConfigFile = $oConfig->GetLoadedFile();
  67. if (strlen($sConfigFile) > 0)
  68. {
  69. $this->log_info("MetaModel::Startup from $sConfigFile (ModelOnly = $bModelOnly)");
  70. }
  71. else
  72. {
  73. $this->log_info("MetaModel::Startup (ModelOnly = $bModelOnly)");
  74. }
  75. if (!$bUseCache)
  76. {
  77. // Reset the cache for the first use !
  78. MetaModel::ResetCache($this->sTargetEnv);
  79. }
  80. MetaModel::Startup($oConfig, $bModelOnly, $bUseCache);
  81. }
  82. /**
  83. * Analyzes the current installation and the possibilities
  84. *
  85. * @param Config $oConfig Defines the target environment (DB)
  86. * @param mixed $modulesPath Either a single string or an array of absolute paths
  87. * @return hash Array with the following format:
  88. * array =>
  89. * 'iTop' => array(
  90. * 'version_db' => ... (could be empty in case of a fresh install)
  91. * 'version_code => ...
  92. * )
  93. * <module_name> => array(
  94. * 'version_db' => ...
  95. * 'version_code' => ...
  96. * 'install' => array(
  97. * 'flag' => SETUP_NEVER | SETUP_OPTIONAL | SETUP_MANDATORY
  98. * 'message' => ...
  99. * )
  100. * 'uninstall' => array(
  101. * 'flag' => SETUP_NEVER | SETUP_OPTIONAL | SETUP_MANDATORY
  102. * 'message' => ...
  103. * )
  104. * 'label' => ...
  105. * 'dependencies' => array(<module1>, <module2>, ...)
  106. * 'visible' => true | false
  107. * )
  108. * )
  109. */
  110. public function AnalyzeInstallation($oConfig, $modulesPath)
  111. {
  112. $aRes = array(
  113. ROOT_MODULE => array(
  114. 'version_db' => '',
  115. 'name_db' => '',
  116. 'version_code' => ITOP_VERSION.'.'.ITOP_REVISION,
  117. 'name_code' => ITOP_APPLICATION,
  118. )
  119. );
  120. $aDirs = is_array($modulesPath) ? $modulesPath : array($modulesPath);
  121. $aModules = ModuleDiscovery::GetAvailableModules($aDirs);
  122. foreach($aModules as $sModuleId => $aModuleInfo)
  123. {
  124. list($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId);
  125. if ($sModuleName == '')
  126. {
  127. throw new Exception("Missing name for the module: '$sModuleId'");
  128. }
  129. if ($sModuleVersion == '')
  130. {
  131. // The version must not be empty (it will be used as a criteria to determine wether a module has been installed or not)
  132. //throw new Exception("Missing version for the module: '$sModuleId'");
  133. $sModuleVersion = '1.0.0';
  134. }
  135. $sModuleAppVersion = $aModuleInfo['itop_version'];
  136. $aModuleInfo['version_db'] = '';
  137. $aModuleInfo['version_code'] = $sModuleVersion;
  138. if (!in_array($sModuleAppVersion, array('1.0.0', '1.0.1', '1.0.2')))
  139. {
  140. // This module is NOT compatible with the current version
  141. $aModuleInfo['install'] = array(
  142. 'flag' => MODULE_ACTION_IMPOSSIBLE,
  143. 'message' => 'the module is not compatible with the current version of the application'
  144. );
  145. }
  146. elseif ($aModuleInfo['mandatory'])
  147. {
  148. $aModuleInfo['install'] = array(
  149. 'flag' => MODULE_ACTION_MANDATORY,
  150. 'message' => 'the module is part of the application'
  151. );
  152. }
  153. else
  154. {
  155. $aModuleInfo['install'] = array(
  156. 'flag' => MODULE_ACTION_OPTIONAL,
  157. 'message' => ''
  158. );
  159. }
  160. $aRes[$sModuleName] = $aModuleInfo;
  161. }
  162. try
  163. {
  164. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  165. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  166. $aSelectInstall = CMDBSource::QueryToArray("SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install");
  167. }
  168. catch (MySQLException $e)
  169. {
  170. // No database or erroneous information
  171. $aSelectInstall = array();
  172. }
  173. // Build the list of installed module (get the latest installation)
  174. //
  175. $aInstallByModule = array(); // array of <module> => array ('installed' => timestamp, 'version' => <version>)
  176. foreach ($aSelectInstall as $aInstall)
  177. {
  178. //$aInstall['comment']; // unsused
  179. $iInstalled = strtotime($aInstall['installed']);
  180. $sModuleName = $aInstall['name'];
  181. $sModuleVersion = $aInstall['version'];
  182. if ($sModuleVersion == '')
  183. {
  184. // Though the version cannot be empty in iTop 2.0, it used to be possible
  185. // therefore we have to put something here or the module will not be considered
  186. // as being installed
  187. $sModuleVersion = '0.0.0';
  188. }
  189. if ($aInstall['parent_id'] == 0)
  190. {
  191. $sModuleName = ROOT_MODULE;
  192. }
  193. if (array_key_exists($sModuleName, $aInstallByModule))
  194. {
  195. if ($iInstalled < $aInstallByModule[$sModuleName]['installed'])
  196. {
  197. continue;
  198. }
  199. }
  200. if ($aInstall['parent_id'] == 0)
  201. {
  202. $aRes[$sModuleName]['version_db'] = $sModuleVersion;
  203. $aRes[$sModuleName]['name_db'] = $aInstall['name'];
  204. }
  205. $aInstallByModule[$sModuleName]['installed'] = $iInstalled;
  206. $aInstallByModule[$sModuleName]['version'] = $sModuleVersion;
  207. }
  208. // Adjust the list of proposed modules
  209. //
  210. foreach ($aInstallByModule as $sModuleName => $aModuleDB)
  211. {
  212. if ($sModuleName == ROOT_MODULE) continue; // Skip the main module
  213. if (!array_key_exists($sModuleName, $aRes))
  214. {
  215. // A module was installed, it is not proposed in the new build... skip
  216. continue;
  217. }
  218. $aRes[$sModuleName]['version_db'] = $aModuleDB['version'];
  219. if ($aRes[$sModuleName]['install']['flag'] == MODULE_ACTION_MANDATORY)
  220. {
  221. $aRes[$sModuleName]['uninstall'] = array(
  222. 'flag' => MODULE_ACTION_IMPOSSIBLE,
  223. 'message' => 'the module is part of the application'
  224. );
  225. }
  226. else
  227. {
  228. $aRes[$sModuleName]['uninstall'] = array(
  229. 'flag' => MODULE_ACTION_OPTIONAL,
  230. 'message' => ''
  231. );
  232. }
  233. }
  234. return $aRes;
  235. }
  236. public function WriteConfigFileSafe($oConfig)
  237. {
  238. self::MakeDirSafe(APPCONF);
  239. self::MakeDirSafe(APPCONF.$this->sTargetEnv);
  240. $sTargetConfigFile = APPCONF.$this->sTargetEnv.'/'.ITOP_CONFIG_FILE;
  241. // Write the config file
  242. @chmod($sTargetConfigFile, 0770); // In case it exists: RWX for owner and group, nothing for others
  243. $oConfig->WriteToFile($sTargetConfigFile);
  244. @chmod($sTargetConfigFile, 0440); // Read-only for owner and group, nothing for others
  245. }
  246. /**
  247. * Get the installed modules (only the installed ones)
  248. */
  249. protected function GetMFModulesToCompile($sSourceEnv, $sSourceDir)
  250. {
  251. $sSourceDirFull = APPROOT.$sSourceDir;
  252. if (!is_dir($sSourceDirFull))
  253. {
  254. throw new Exception("The source directory '$sSourceDir' does not exist (or could not be read)");
  255. }
  256. $aRet = array();
  257. // Determine the installed modules
  258. //
  259. $oSourceConfig = new Config(APPCONF.$sSourceEnv.'/'.ITOP_CONFIG_FILE);
  260. $oSourceEnv = new RunTimeEnvironment($sSourceEnv);
  261. $aAvailableModules = $oSourceEnv->AnalyzeInstallation($oSourceConfig, $sSourceDir); //TODO: use an absolute PATH
  262. // Do load the required modules
  263. //
  264. $oFactory = new ModelFactory($sSourceDirFull);
  265. $aModules = $oFactory->FindModules();
  266. foreach($aModules as $foo => $oModule)
  267. {
  268. $sModule = $oModule->GetName();
  269. if (array_key_exists($sModule, $aAvailableModules))
  270. {
  271. if ($aAvailableModules[$sModule]['version_db'] != '')
  272. {
  273. $aRet[] = $oModule;
  274. }
  275. }
  276. }
  277. return $aRet;
  278. }
  279. public function CompileFrom($sSourceEnv, $sSourceDir = null)
  280. {
  281. if (is_null($sSourceDir))
  282. {
  283. $oSourceConfig = new Config(utils::GetConfigFilePath($sSourceEnv));
  284. $sSourceDir = $oSourceConfig->Get('source_dir');
  285. }
  286. $sSourceDirFull = APPROOT.$sSourceDir;
  287. // Do load the required modules
  288. //
  289. $oFactory = new ModelFactory($sSourceDirFull);
  290. foreach($this->GetMFModulesToCompile($sSourceEnv, $sSourceDir) as $oModule)
  291. {
  292. $sModule = $oModule->GetName();
  293. $oFactory->LoadModule($oModule);
  294. if ($oFactory->HasLoadErrors())
  295. {
  296. break;
  297. }
  298. }
  299. if ($oFactory->HasLoadErrors())
  300. {
  301. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  302. {
  303. echo "<h3>Module: ".$sModuleId."</h3>\n";
  304. foreach($aErrors as $oXmlError)
  305. {
  306. echo "<p>File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message."</p>\n";
  307. }
  308. }
  309. }
  310. else
  311. {
  312. $oFactory->ApplyChanges();
  313. //$oFactory->Dump();
  314. $sTargetDir = APPROOT.'env-'.$this->sTargetEnv;
  315. self::MakeDirSafe($sTargetDir);
  316. $oMFCompiler = new MFCompiler($oFactory, $sSourceDirFull);
  317. $oMFCompiler->Compile($sTargetDir);
  318. MetaModel::ResetCache($this->sTargetEnv);
  319. }
  320. }
  321. /**
  322. * Helper function to create the database structure
  323. * @return boolean true on success, false otherwise
  324. */
  325. public function CreateDatabaseStructure(Config $oConfig, $sMode)
  326. {
  327. if (strlen($oConfig->GetDBSubname()) > 0)
  328. {
  329. $this->log_info("Creating the structure in '".$oConfig->GetDBName()."' (table names prefixed by '".$oConfig->GetDBSubname()."').");
  330. }
  331. else
  332. {
  333. $this->log_info("Creating the structure in '".$oConfig->GetDBSubname()."'.");
  334. }
  335. //MetaModel::CheckDefinitions();
  336. if ($sMode == 'install')
  337. {
  338. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  339. {
  340. MetaModel::DBCreate();
  341. $this->log_ok("Database structure successfully created.");
  342. }
  343. else
  344. {
  345. if (strlen($oConfig->GetDBSubname()) > 0)
  346. {
  347. throw new Exception("Error: found iTop tables into the database '".$oConfig->GetDBName()."' (prefix: '".$oConfig->GetDBSubname()."'). Please, try selecting another database instance or specify another prefix to prevent conflicting table names.");
  348. }
  349. else
  350. {
  351. throw new Exception("Error: found iTop tables into the database '".$oConfig->GetDBName()."'. Please, try selecting another database instance or specify a prefix to prevent conflicting table names.");
  352. }
  353. }
  354. }
  355. else
  356. {
  357. if (MetaModel::DBExists(/* bMustBeComplete */ false))
  358. {
  359. MetaModel::DBCreate();
  360. $this->log_ok("Database structure successfully updated.");
  361. // Check (and update only if it seems needed) the hierarchical keys
  362. ob_start();
  363. MetaModel::CheckHKeys(false /* bDiagnosticsOnly */, true /* bVerbose*/, true /* bForceUpdate */); // Since in 1.2-beta the detection was buggy, let's force the rebuilding of HKeys
  364. $sFeedback = ob_get_clean();
  365. $this->log_ok("Hierchical keys rebuilt: $sFeedback");
  366. // Check (and fix) data sync configuration
  367. ob_start();
  368. MetaModel::CheckDataSources(false /*$bDiagnostics*/, true/*$bVerbose*/);
  369. $sFeedback = ob_get_clean();
  370. $this->log_ok("Data sources checked: $sFeedback");
  371. }
  372. else
  373. {
  374. if (strlen($oConfig->GetDBSubname()) > 0)
  375. {
  376. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."' (prefix: '".$oConfig->GetDBSubname()."'). Please, try selecting another database instance.");
  377. }
  378. else
  379. {
  380. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."'. Please, try selecting another database instance.");
  381. }
  382. }
  383. }
  384. return true;
  385. }
  386. public function RecordInstallation(Config $oConfig, $sDataModelVersion, $aSelectedModules, $sModulesRelativePath)
  387. {
  388. // Record datamodel version
  389. $aData = array(
  390. 'source_dir' => $oConfig->Get('source_dir'),
  391. );
  392. $oInstallRec = new ModuleInstallation();
  393. $oInstallRec->Set('name', DATAMODEL_MODULE);
  394. $oInstallRec->Set('version', $sDataModelVersion);
  395. $oInstallRec->Set('comment', json_encode($aData));
  396. $oInstallRec->Set('parent_id', 0); // root module
  397. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  398. // Record main installation
  399. $oInstallRec = new ModuleInstallation();
  400. $oInstallRec->Set('name', ITOP_APPLICATION);
  401. $oInstallRec->Set('version', ITOP_VERSION.'.'.ITOP_REVISION);
  402. $oInstallRec->Set('comment', "Done by the setup program\nBuilt on ".ITOP_BUILD_DATE);
  403. $oInstallRec->Set('parent_id', 0); // root module
  404. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  405. // Record installed modules
  406. //
  407. $aAvailableModules = $this->AnalyzeInstallation($oConfig, APPROOT.$sModulesRelativePath);
  408. foreach($aSelectedModules as $sModuleId)
  409. {
  410. $aModuleData = $aAvailableModules[$sModuleId];
  411. $sName = $sModuleId;
  412. $sVersion = $aModuleData['version_code'];
  413. $aComments = array();
  414. $aComments[] = 'Done by the setup program';
  415. if ($aModuleData['mandatory'])
  416. {
  417. $aComments[] = 'Mandatory';
  418. }
  419. else
  420. {
  421. $aComments[] = 'Optional';
  422. }
  423. if ($aModuleData['visible'])
  424. {
  425. $aComments[] = 'Visible (during the setup)';
  426. }
  427. else
  428. {
  429. $aComments[] = 'Hidden (selected automatically)';
  430. }
  431. foreach ($aModuleData['dependencies'] as $sDependOn)
  432. {
  433. $aComments[] = "Depends on module: $sDependOn";
  434. }
  435. $sComment = implode("\n", $aComments);
  436. $oInstallRec = new ModuleInstallation();
  437. $oInstallRec->Set('name', $sName);
  438. $oInstallRec->Set('version', $sVersion);
  439. $oInstallRec->Set('comment', $sComment);
  440. $oInstallRec->Set('parent_id', $iMainItopRecord);
  441. $oInstallRec->DBInsertNoReload();
  442. }
  443. // Database is created, installation has been tracked into it
  444. return true;
  445. }
  446. public function GetApplicationVersion(Config $oConfig)
  447. {
  448. $aResult = false;
  449. try
  450. {
  451. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  452. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  453. $aSelectInstall = CMDBSource::QueryToArray("SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install");
  454. }
  455. catch (MySQLException $e)
  456. {
  457. // No database or erroneous information
  458. return false;
  459. }
  460. // Scan the list of installed modules to get the version of the 'ROOT' module which holds the main application version
  461. foreach ($aSelectInstall as $aInstall)
  462. {
  463. $sModuleVersion = $aInstall['version'];
  464. if ($sModuleVersion == '')
  465. {
  466. // Though the version cannot be empty in iTop 2.0, it used to be possible
  467. // therefore we have to put something here or the module will not be considered
  468. // as being installed
  469. $sModuleVersion = '0.0.0';
  470. }
  471. if ($aInstall['parent_id'] == 0)
  472. {
  473. if ($aInstall['name'] == DATAMODEL_MODULE)
  474. {
  475. $aResult['datamodel_version'] = $sModuleVersion;
  476. $aComments = json_decode($aInstall['comment'], true);
  477. if (is_array($aComments))
  478. {
  479. $aResult = array_merge($aResult, $aComments);
  480. }
  481. }
  482. else
  483. {
  484. $aResult['product_name'] = $aInstall['name'];
  485. $aResult['product_version'] = $sModuleVersion;
  486. }
  487. }
  488. }
  489. if (!array_key_exists('datamodel_version', $aResult))
  490. {
  491. // Versions prior to 2.0 did not record the version of the datamodel
  492. // so assume that the datamodel version is equal to the application version
  493. $aResult['datamodel_version'] = $aResult['product_version'];
  494. }
  495. return $aResult;
  496. }
  497. public static function MakeDirSafe($sDir)
  498. {
  499. if (!is_dir($sDir))
  500. {
  501. @mkdir($sDir);
  502. }
  503. @chmod($sDir, 0770); // RWX for owner and group, nothing for others
  504. }
  505. /**
  506. * Wrappers for logging into the setup log files
  507. */
  508. protected function log_error($sText)
  509. {
  510. SetupPage::log_error($sText);
  511. }
  512. protected function log_warning($sText)
  513. {
  514. SetupPage::log_warning($sText);
  515. }
  516. protected function log_info($sText)
  517. {
  518. SetupPage::log_info($sText);
  519. }
  520. protected function log_ok($sText)
  521. {
  522. SetupPage::log_ok($sText);
  523. }
  524. } // End of class