runtimeenv.class.inc.php 15 KB

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