runtimeenv.class.inc.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Manage a runtime environment
  20. *
  21. * @copyright Copyright (C) 2010-2016 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  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. * Callback function for logging the queries run by the setup.
  42. * According to the documentation the function must be defined before passing it to call_user_func...
  43. * @param string $sQuery
  44. * @param float $fDuration
  45. * @return void
  46. */
  47. public function LogQueryCallback($sQuery, $fDuration)
  48. {
  49. $this->log_info(sprintf('%.3fs - query: %s ', $fDuration, $sQuery));
  50. }
  51. /**
  52. * Helper function to initialize the ORM and load the data model
  53. * from the given file
  54. * @param $oConfig object The configuration (volatile, not necessarily already on disk)
  55. * @param $bModelOnly boolean Whether or not to allow loading a data model with no corresponding DB
  56. * @return none
  57. */
  58. public function InitDataModel($oConfig, $bModelOnly = true, $bUseCache = false)
  59. {
  60. require_once(APPROOT.'/core/log.class.inc.php');
  61. require_once(APPROOT.'/core/kpi.class.inc.php');
  62. require_once(APPROOT.'/core/coreexception.class.inc.php');
  63. require_once(APPROOT.'/core/dict.class.inc.php');
  64. require_once(APPROOT.'/core/attributedef.class.inc.php');
  65. require_once(APPROOT.'/core/filterdef.class.inc.php');
  66. require_once(APPROOT.'/core/stimulus.class.inc.php');
  67. require_once(APPROOT.'/core/MyHelpers.class.inc.php');
  68. require_once(APPROOT.'/core/oql/expression.class.inc.php');
  69. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  70. require_once(APPROOT.'/core/sqlquery.class.inc.php');
  71. require_once(APPROOT.'/core/sqlobjectquery.class.inc.php');
  72. require_once(APPROOT.'/core/sqlunionquery.class.inc.php');
  73. require_once(APPROOT.'/core/dbobject.class.php');
  74. require_once(APPROOT.'/core/dbsearch.class.php');
  75. require_once(APPROOT.'/core/dbobjectset.class.php');
  76. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  77. require_once(APPROOT.'/core/userrights.class.inc.php');
  78. require_once(APPROOT.'/setup/moduleinstallation.class.inc.php');
  79. $sConfigFile = $oConfig->GetLoadedFile();
  80. if (strlen($sConfigFile) > 0)
  81. {
  82. $this->log_info("MetaModel::Startup from $sConfigFile (ModelOnly = $bModelOnly)");
  83. }
  84. else
  85. {
  86. $this->log_info("MetaModel::Startup (ModelOnly = $bModelOnly)");
  87. }
  88. if (!$bUseCache)
  89. {
  90. // Reset the cache for the first use !
  91. MetaModel::ResetCache(md5(APPROOT).'-'.$this->sTargetEnv);
  92. }
  93. MetaModel::Startup($oConfig, $bModelOnly, $bUseCache);
  94. }
  95. /**
  96. * Analyzes the current installation and the possibilities
  97. *
  98. * @param Config $oConfig Defines the target environment (DB)
  99. * @param mixed $modulesPath Either a single string or an array of absolute paths
  100. * @param bool $bAbortOnMissingDependency ...
  101. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  102. * @return hash Array with the following format:
  103. * array =>
  104. * 'iTop' => array(
  105. * 'version_db' => ... (could be empty in case of a fresh install)
  106. * 'version_code => ...
  107. * )
  108. * <module_name> => array(
  109. * 'version_db' => ...
  110. * 'version_code' => ...
  111. * 'install' => array(
  112. * 'flag' => SETUP_NEVER | SETUP_OPTIONAL | SETUP_MANDATORY
  113. * 'message' => ...
  114. * )
  115. * 'uninstall' => array(
  116. * 'flag' => SETUP_NEVER | SETUP_OPTIONAL | SETUP_MANDATORY
  117. * 'message' => ...
  118. * )
  119. * 'label' => ...
  120. * 'dependencies' => array(<module1>, <module2>, ...)
  121. * 'visible' => true | false
  122. * )
  123. * )
  124. */
  125. public function AnalyzeInstallation($oConfig, $modulesPath, $bAbortOnMissingDependency = false, $aModulesToLoad = null)
  126. {
  127. $aRes = array(
  128. ROOT_MODULE => array(
  129. 'version_db' => '',
  130. 'name_db' => '',
  131. 'version_code' => ITOP_VERSION.'.'.ITOP_REVISION,
  132. 'name_code' => ITOP_APPLICATION,
  133. )
  134. );
  135. $aDirs = is_array($modulesPath) ? $modulesPath : array($modulesPath);
  136. $aModules = ModuleDiscovery::GetAvailableModules($aDirs, $bAbortOnMissingDependency, $aModulesToLoad);
  137. foreach($aModules as $sModuleId => $aModuleInfo)
  138. {
  139. list($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId);
  140. if ($sModuleName == '')
  141. {
  142. throw new Exception("Missing name for the module: '$sModuleId'");
  143. }
  144. if ($sModuleVersion == '')
  145. {
  146. // The version must not be empty (it will be used as a criteria to determine wether a module has been installed or not)
  147. //throw new Exception("Missing version for the module: '$sModuleId'");
  148. $sModuleVersion = '1.0.0';
  149. }
  150. $sModuleAppVersion = $aModuleInfo['itop_version'];
  151. $aModuleInfo['version_db'] = '';
  152. $aModuleInfo['version_code'] = $sModuleVersion;
  153. if (!in_array($sModuleAppVersion, array('1.0.0', '1.0.1', '1.0.2')))
  154. {
  155. // This module is NOT compatible with the current version
  156. $aModuleInfo['install'] = array(
  157. 'flag' => MODULE_ACTION_IMPOSSIBLE,
  158. 'message' => 'the module is not compatible with the current version of the application'
  159. );
  160. }
  161. elseif ($aModuleInfo['mandatory'])
  162. {
  163. $aModuleInfo['install'] = array(
  164. 'flag' => MODULE_ACTION_MANDATORY,
  165. 'message' => 'the module is part of the application'
  166. );
  167. }
  168. else
  169. {
  170. $aModuleInfo['install'] = array(
  171. 'flag' => MODULE_ACTION_OPTIONAL,
  172. 'message' => ''
  173. );
  174. }
  175. $aRes[$sModuleName] = $aModuleInfo;
  176. }
  177. try
  178. {
  179. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  180. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  181. CMDBSource::SetCharacterSet($oConfig->GetDBCharacterSet(), $oConfig->GetDBCollation());
  182. $aSelectInstall = CMDBSource::QueryToArray("SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install");
  183. }
  184. catch (MySQLException $e)
  185. {
  186. // No database or erroneous information
  187. $aSelectInstall = array();
  188. }
  189. // Build the list of installed module (get the latest installation)
  190. //
  191. $aInstallByModule = array(); // array of <module> => array ('installed' => timestamp, 'version' => <version>)
  192. $iRootId = 0;
  193. foreach ($aSelectInstall as $aInstall)
  194. {
  195. if (($aInstall['parent_id'] == 0) && ($aInstall['name'] != 'datamodel'))
  196. {
  197. // Root module, what is its ID ?
  198. $iId = (int) $aInstall['id'];
  199. if ($iId > $iRootId)
  200. {
  201. $iRootId = $iId;
  202. }
  203. }
  204. }
  205. foreach ($aSelectInstall as $aInstall)
  206. {
  207. //$aInstall['comment']; // unsused
  208. $iInstalled = strtotime($aInstall['installed']);
  209. $sModuleName = $aInstall['name'];
  210. $sModuleVersion = $aInstall['version'];
  211. if ($sModuleVersion == '')
  212. {
  213. // Though the version cannot be empty in iTop 2.0, it used to be possible
  214. // therefore we have to put something here or the module will not be considered
  215. // as being installed
  216. $sModuleVersion = '0.0.0';
  217. }
  218. if ($aInstall['parent_id'] == 0)
  219. {
  220. $sModuleName = ROOT_MODULE;
  221. }
  222. else if($aInstall['parent_id'] != $iRootId)
  223. {
  224. // Skip all modules belonging to previous installations
  225. continue;
  226. }
  227. if (array_key_exists($sModuleName, $aInstallByModule))
  228. {
  229. if ($iInstalled < $aInstallByModule[$sModuleName]['installed'])
  230. {
  231. continue;
  232. }
  233. }
  234. if ($aInstall['parent_id'] == 0)
  235. {
  236. $aRes[$sModuleName]['version_db'] = $sModuleVersion;
  237. $aRes[$sModuleName]['name_db'] = $aInstall['name'];
  238. }
  239. $aInstallByModule[$sModuleName]['installed'] = $iInstalled;
  240. $aInstallByModule[$sModuleName]['version'] = $sModuleVersion;
  241. }
  242. // Adjust the list of proposed modules
  243. //
  244. foreach ($aInstallByModule as $sModuleName => $aModuleDB)
  245. {
  246. if ($sModuleName == ROOT_MODULE) continue; // Skip the main module
  247. if (!array_key_exists($sModuleName, $aRes))
  248. {
  249. // A module was installed, it is not proposed in the new build... skip
  250. continue;
  251. }
  252. $aRes[$sModuleName]['version_db'] = $aModuleDB['version'];
  253. if ($aRes[$sModuleName]['install']['flag'] == MODULE_ACTION_MANDATORY)
  254. {
  255. $aRes[$sModuleName]['uninstall'] = array(
  256. 'flag' => MODULE_ACTION_IMPOSSIBLE,
  257. 'message' => 'the module is part of the application'
  258. );
  259. }
  260. else
  261. {
  262. $aRes[$sModuleName]['uninstall'] = array(
  263. 'flag' => MODULE_ACTION_OPTIONAL,
  264. 'message' => ''
  265. );
  266. }
  267. }
  268. return $aRes;
  269. }
  270. public function WriteConfigFileSafe($oConfig)
  271. {
  272. self::MakeDirSafe(APPCONF);
  273. self::MakeDirSafe(APPCONF.$this->sTargetEnv);
  274. $sTargetConfigFile = APPCONF.$this->sTargetEnv.'/'.ITOP_CONFIG_FILE;
  275. // Write the config file
  276. @chmod($sTargetConfigFile, 0770); // In case it exists: RWX for owner and group, nothing for others
  277. $oConfig->WriteToFile($sTargetConfigFile);
  278. @chmod($sTargetConfigFile, 0440); // Read-only for owner and group, nothing for others
  279. }
  280. /**
  281. * Get the installed modules (only the installed ones)
  282. */
  283. protected function GetMFModulesToCompile($sSourceEnv, $sSourceDir)
  284. {
  285. $sSourceDirFull = APPROOT.$sSourceDir;
  286. if (!is_dir($sSourceDirFull))
  287. {
  288. throw new Exception("The source directory '$sSourceDirFull' does not exist (or could not be read)");
  289. }
  290. $aDirsToCompile = array($sSourceDirFull);
  291. if (is_dir(APPROOT.'extensions'))
  292. {
  293. $aDirsToCompile[] = APPROOT.'extensions';
  294. }
  295. $sExtraDir = APPROOT.'data/'.$this->sTargetEnv.'-modules/';
  296. if (is_dir($sExtraDir))
  297. {
  298. $aDirsToCompile[] = $sExtraDir;
  299. }
  300. $aRet = array();
  301. // Determine the installed modules
  302. //
  303. $oSourceConfig = new Config(APPCONF.$sSourceEnv.'/'.ITOP_CONFIG_FILE);
  304. $oSourceEnv = new RunTimeEnvironment($sSourceEnv);
  305. $aAvailableModules = $oSourceEnv->AnalyzeInstallation($oSourceConfig, $aDirsToCompile);
  306. // Do load the required modules
  307. //
  308. $oDictModule = new MFDictModule('dictionaries', 'iTop Dictionaries', APPROOT.'dictionaries');
  309. $aRet[$oDictModule->GetName()] = $oDictModule;
  310. $oFactory = new ModelFactory($aDirsToCompile);
  311. $sDeltaFile = APPROOT.'core/datamodel.core.xml';
  312. if (file_exists($sDeltaFile))
  313. {
  314. $oCoreModule = new MFCoreModule('core', 'Core Module', $sDeltaFile);
  315. $aRet[$oCoreModule->GetName()] = $oCoreModule;
  316. }
  317. $sDeltaFile = APPROOT.'application/datamodel.application.xml';
  318. if (file_exists($sDeltaFile))
  319. {
  320. $oApplicationModule = new MFCoreModule('application', 'Application Module', $sDeltaFile);
  321. $aRet[$oApplicationModule->GetName()] = $oApplicationModule;
  322. }
  323. $aModules = $oFactory->FindModules();
  324. foreach($aModules as $foo => $oModule)
  325. {
  326. $sModule = $oModule->GetName();
  327. $sModuleRootDir = $oModule->GetRootDir();
  328. $bIsExtra = (strpos($sModuleRootDir, $sExtraDir) !== false);
  329. if (array_key_exists($sModule, $aAvailableModules))
  330. {
  331. if (($aAvailableModules[$sModule]['version_db'] != '') || $bIsExtra && !$oModule->IsAutoSelect()) //Extra modules are always unless they are 'AutoSelect'
  332. {
  333. $aRet[$oModule->GetName()] = $oModule;
  334. }
  335. }
  336. }
  337. // Now process the 'AutoSelect' modules
  338. do
  339. {
  340. // Loop while new modules are added...
  341. $bModuleAdded = false;
  342. foreach($aModules as $foo => $oModule)
  343. {
  344. if (!array_key_exists($oModule->GetName(), $aRet) && $oModule->IsAutoSelect())
  345. {
  346. try
  347. {
  348. $bSelected = false;
  349. SetupInfo::SetSelectedModules($aRet);
  350. eval('$bSelected = ('.$oModule->GetAutoSelect().');');
  351. }
  352. catch(Exception $e)
  353. {
  354. $bSelected = false;
  355. }
  356. if ($bSelected)
  357. {
  358. $aRet[$oModule->GetName()] = $oModule; // store the Id of the selected module
  359. $bModuleAdded = true;
  360. }
  361. }
  362. }
  363. }
  364. while($bModuleAdded);
  365. $sDeltaFile = APPROOT.'data/'.$this->sTargetEnv.'.delta.xml';
  366. if (file_exists($sDeltaFile))
  367. {
  368. $oDelta = new MFDeltaModule($sDeltaFile);
  369. $aRet[$oDelta->GetName()] = $oDelta;
  370. }
  371. return $aRet;
  372. }
  373. /**
  374. * Compile the data model by imitating the given environment
  375. * The list of modules to be installed in the target environment is:
  376. * - the list of modules present in the "source_dir" (defined by the source environment) which are marked as "installed" in the source environment's database
  377. * - plus the list of modules present in the "extra" directory of the target environment: data/<target_environment>-modules/
  378. * @param string $sSourceEnv The name of the source environment to 'imitate'
  379. * @param bool $bUseSymLinks Whether to create symbolic links instead of copies
  380. */
  381. public function CompileFrom($sSourceEnv, $bUseSymLinks = false)
  382. {
  383. $oSourceConfig = new Config(utils::GetConfigFilePath($sSourceEnv));
  384. $sSourceDir = $oSourceConfig->Get('source_dir');
  385. $sSourceDirFull = APPROOT.$sSourceDir;
  386. // Do load the required modules
  387. //
  388. $oFactory = new ModelFactory($sSourceDirFull);
  389. foreach($this->GetMFModulesToCompile($sSourceEnv, $sSourceDir) as $oModule)
  390. {
  391. $sModule = $oModule->GetName();
  392. $oFactory->LoadModule($oModule);
  393. if ($oFactory->HasLoadErrors())
  394. {
  395. break;
  396. }
  397. }
  398. if ($oFactory->HasLoadErrors())
  399. {
  400. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  401. {
  402. echo "<h3>Module: ".$sModuleId."</h3>\n";
  403. foreach($aErrors as $oXmlError)
  404. {
  405. echo "<p>File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message."</p>\n";
  406. }
  407. }
  408. }
  409. else
  410. {
  411. $sTargetDir = APPROOT.'env-'.$this->sTargetEnv;
  412. self::MakeDirSafe($sTargetDir);
  413. $oMFCompiler = new MFCompiler($oFactory);
  414. $oMFCompiler->Compile($sTargetDir, null, $bUseSymLinks);
  415. $sCacheDir = APPROOT.'data/cache-'.$this->sTargetEnv;
  416. Setuputils::builddir($sCacheDir);
  417. Setuputils::tidydir($sCacheDir);
  418. require_once(APPROOT.'/core/dict.class.inc.php');
  419. MetaModel::ResetCache(md5(APPROOT).'-'.$this->sTargetEnv);
  420. }
  421. }
  422. /**
  423. * Helper function to create the database structure
  424. * @return boolean true on success, false otherwise
  425. */
  426. public function CreateDatabaseStructure(Config $oConfig, $sMode)
  427. {
  428. if (strlen($oConfig->GetDBSubname()) > 0)
  429. {
  430. $this->log_info("Creating the structure in '".$oConfig->GetDBName()."' (table names prefixed by '".$oConfig->GetDBSubname()."').");
  431. }
  432. else
  433. {
  434. $this->log_info("Creating the structure in '".$oConfig->GetDBSubname()."'.");
  435. }
  436. //MetaModel::CheckDefinitions();
  437. if ($sMode == 'install')
  438. {
  439. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  440. {
  441. MetaModel::DBCreate(array($this, 'LogQueryCallback'));
  442. $this->log_ok("Database structure successfully created.");
  443. }
  444. else
  445. {
  446. if (strlen($oConfig->GetDBSubname()) > 0)
  447. {
  448. 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.");
  449. }
  450. else
  451. {
  452. 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.");
  453. }
  454. }
  455. }
  456. else
  457. {
  458. if (MetaModel::DBExists(/* bMustBeComplete */ false))
  459. {
  460. MetaModel::DBCreate(array($this, 'LogQueryCallback'));
  461. $this->log_ok("Database structure successfully updated.");
  462. // Check (and update only if it seems needed) the hierarchical keys
  463. ob_start();
  464. MetaModel::CheckHKeys(false /* bDiagnosticsOnly */, true /* bVerbose*/, true /* bForceUpdate */); // Since in 1.2-beta the detection was buggy, let's force the rebuilding of HKeys
  465. $sFeedback = ob_get_clean();
  466. $this->log_ok("Hierchical keys rebuilt: $sFeedback");
  467. // Check (and fix) data sync configuration
  468. ob_start();
  469. MetaModel::CheckDataSources(false /*$bDiagnostics*/, true/*$bVerbose*/);
  470. $sFeedback = ob_get_clean();
  471. $this->log_ok("Data sources checked: $sFeedback");
  472. // Fix meta enums
  473. ob_start();
  474. MetaModel::RebuildMetaEnums(true /*bVerbose*/);
  475. $sFeedback = ob_get_clean();
  476. $this->log_ok("Meta enums rebuilt: $sFeedback");
  477. }
  478. else
  479. {
  480. if (strlen($oConfig->GetDBSubname()) > 0)
  481. {
  482. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."' (prefix: '".$oConfig->GetDBSubname()."'). Please, try selecting another database instance.");
  483. }
  484. else
  485. {
  486. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."'. Please, try selecting another database instance.");
  487. }
  488. }
  489. }
  490. return true;
  491. }
  492. public function UpdatePredefinedObjects()
  493. {
  494. // Constant classes (e.g. User profiles)
  495. //
  496. foreach (MetaModel::GetClasses() as $sClass)
  497. {
  498. $aPredefinedObjects = call_user_func(array(
  499. $sClass,
  500. 'GetPredefinedObjects'
  501. ));
  502. if ($aPredefinedObjects != null)
  503. {
  504. $this->log_info("$sClass::GetPredefinedObjects() returned " . count($aPredefinedObjects) . " elements.");
  505. // Create/Delete/Update objects of this class,
  506. // according to the given constant values
  507. //
  508. $aDBIds = array();
  509. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  510. while ($oObj = $oAll->Fetch())
  511. {
  512. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  513. {
  514. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  515. foreach ($aObjValues as $sAttCode => $value)
  516. {
  517. $oObj->Set($sAttCode, $value);
  518. }
  519. $oObj->DBUpdate();
  520. $aDBIds[$oObj->GetKey()] = true;
  521. }
  522. else
  523. {
  524. $oObj->DBDelete();
  525. }
  526. }
  527. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  528. {
  529. if (! array_key_exists($iRefId, $aDBIds))
  530. {
  531. $oNewObj = MetaModel::NewObject($sClass);
  532. $oNewObj->SetKey($iRefId);
  533. foreach ($aObjValues as $sAttCode => $value)
  534. {
  535. $oNewObj->Set($sAttCode, $value);
  536. }
  537. $oNewObj->DBInsert();
  538. }
  539. }
  540. }
  541. }
  542. }
  543. public function RecordInstallation(Config $oConfig, $sDataModelVersion, $aSelectedModules, $sModulesRelativePath, $sShortComment = null)
  544. {
  545. // Have it work fine even if the DB has been set in read-only mode for the users
  546. $iPrevAccessMode = $oConfig->Get('access_mode');
  547. $oConfig->Set('access_mode', ACCESS_FULL);
  548. if ($sShortComment === null)
  549. {
  550. $sShortComment = 'Done by the setup program';
  551. }
  552. $sMainComment = $sShortComment."\nBuilt on ".ITOP_BUILD_DATE;
  553. // Record datamodel version
  554. $aData = array(
  555. 'source_dir' => $oConfig->Get('source_dir'),
  556. );
  557. $iInstallationTime = time(); // Make sure that all modules record the same installation time
  558. $oInstallRec = new ModuleInstallation();
  559. $oInstallRec->Set('name', DATAMODEL_MODULE);
  560. $oInstallRec->Set('version', $sDataModelVersion);
  561. $oInstallRec->Set('comment', json_encode($aData));
  562. $oInstallRec->Set('parent_id', 0); // root module
  563. $oInstallRec->Set('installed', $iInstallationTime);
  564. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  565. // Record main installation
  566. $oInstallRec = new ModuleInstallation();
  567. $oInstallRec->Set('name', ITOP_APPLICATION);
  568. $oInstallRec->Set('version', ITOP_VERSION.'.'.ITOP_REVISION);
  569. $oInstallRec->Set('comment', $sMainComment);
  570. $oInstallRec->Set('parent_id', 0); // root module
  571. $oInstallRec->Set('installed', $iInstallationTime);
  572. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  573. // Record installed modules
  574. //
  575. $aAvailableModules = $this->AnalyzeInstallation($oConfig, APPROOT.$sModulesRelativePath);
  576. foreach($aSelectedModules as $sModuleId)
  577. {
  578. $aModuleData = $aAvailableModules[$sModuleId];
  579. $sName = $sModuleId;
  580. $sVersion = $aModuleData['version_code'];
  581. $aComments = array();
  582. $aComments[] = $sShortComment;
  583. if ($aModuleData['mandatory'])
  584. {
  585. $aComments[] = 'Mandatory';
  586. }
  587. else
  588. {
  589. $aComments[] = 'Optional';
  590. }
  591. if ($aModuleData['visible'])
  592. {
  593. $aComments[] = 'Visible (during the setup)';
  594. }
  595. else
  596. {
  597. $aComments[] = 'Hidden (selected automatically)';
  598. }
  599. foreach ($aModuleData['dependencies'] as $sDependOn)
  600. {
  601. $aComments[] = "Depends on module: $sDependOn";
  602. }
  603. $sComment = implode("\n", $aComments);
  604. $oInstallRec = new ModuleInstallation();
  605. $oInstallRec->Set('name', $sName);
  606. $oInstallRec->Set('version', $sVersion);
  607. $oInstallRec->Set('comment', $sComment);
  608. $oInstallRec->Set('parent_id', $iMainItopRecord);
  609. $oInstallRec->Set('installed', $iInstallationTime);
  610. $oInstallRec->DBInsertNoReload();
  611. }
  612. // Restore the previous access mode
  613. $oConfig->Set('access_mode', $iPrevAccessMode);
  614. // Database is created, installation has been tracked into it
  615. return true;
  616. }
  617. public function GetApplicationVersion(Config $oConfig)
  618. {
  619. $aResult = false;
  620. try
  621. {
  622. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  623. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  624. CMDBSource::SetCharacterSet($oConfig->GetDBCharacterSet(), $oConfig->GetDBCollation());
  625. $sSQLQuery = "SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install";
  626. $aSelectInstall = CMDBSource::QueryToArray($sSQLQuery);
  627. }
  628. catch (MySQLException $e)
  629. {
  630. // No database or erroneous information
  631. $this->log_error('Can not connect to the database: host: '.$oConfig->GetDBHost().', user:'.$oConfig->GetDBUser().', pwd:'.$oConfig->GetDBPwd().', db name:'.$oConfig->GetDBName());
  632. $this->log_error('Exception '.$e->getMessage());
  633. return false;
  634. }
  635. // Scan the list of installed modules to get the version of the 'ROOT' module which holds the main application version
  636. foreach ($aSelectInstall as $aInstall)
  637. {
  638. $sModuleVersion = $aInstall['version'];
  639. if ($sModuleVersion == '')
  640. {
  641. // Though the version cannot be empty in iTop 2.0, it used to be possible
  642. // therefore we have to put something here or the module will not be considered
  643. // as being installed
  644. $sModuleVersion = '0.0.0';
  645. }
  646. if ($aInstall['parent_id'] == 0)
  647. {
  648. if ($aInstall['name'] == DATAMODEL_MODULE)
  649. {
  650. $aResult['datamodel_version'] = $sModuleVersion;
  651. $aComments = json_decode($aInstall['comment'], true);
  652. if (is_array($aComments))
  653. {
  654. $aResult = array_merge($aResult, $aComments);
  655. }
  656. }
  657. else
  658. {
  659. $aResult['product_name'] = $aInstall['name'];
  660. $aResult['product_version'] = $sModuleVersion;
  661. }
  662. }
  663. }
  664. if (!array_key_exists('datamodel_version', $aResult))
  665. {
  666. // Versions prior to 2.0 did not record the version of the datamodel
  667. // so assume that the datamodel version is equal to the application version
  668. $aResult['datamodel_version'] = $aResult['product_version'];
  669. }
  670. $this->log_info("GetApplicationVersion returns: product_name: ".$aResult['product_name'].', product_version: '.$aResult['product_version']);
  671. return $aResult;
  672. }
  673. public static function MakeDirSafe($sDir)
  674. {
  675. if (!is_dir($sDir))
  676. {
  677. if (!@mkdir($sDir))
  678. {
  679. throw new Exception("Failed to create directory '$sDir', please check that the web server process has enough rights to create the directory.");
  680. }
  681. @chmod($sDir, 0770); // RWX for owner and group, nothing for others
  682. }
  683. }
  684. /**
  685. * Wrappers for logging into the setup log files
  686. */
  687. protected function log_error($sText)
  688. {
  689. SetupPage::log_error($sText);
  690. }
  691. protected function log_warning($sText)
  692. {
  693. SetupPage::log_warning($sText);
  694. }
  695. protected function log_info($sText)
  696. {
  697. SetupPage::log_info($sText);
  698. }
  699. protected function log_ok($sText)
  700. {
  701. SetupPage::log_ok($sText);
  702. }
  703. public function GetCurrentDataModelVersion()
  704. {
  705. $oSearch = DBObjectSearch::FromOQL("SELECT ModuleInstallation WHERE name='".DATAMODEL_MODULE."'");
  706. $oSet = new DBObjectSet($oSearch, array(), array('installed' => false));
  707. $oLatestDM = $oSet->Fetch();
  708. if ($oLatestDM == null)
  709. {
  710. return '0.0.0';
  711. }
  712. return $oLatestDM->Get('version');
  713. }
  714. } // End of class