runtimeenv.class.inc.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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;
  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;
  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;
  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) //Extra modules are always selected
  332. {
  333. $aRet[] = $oModule;
  334. }
  335. }
  336. }
  337. $sDeltaFile = APPROOT.'data/'.$this->sTargetEnv.'.delta.xml';
  338. if (file_exists($sDeltaFile))
  339. {
  340. $oDelta = new MFDeltaModule($sDeltaFile);
  341. $aRet[] = $oDelta;
  342. }
  343. return $aRet;
  344. }
  345. /**
  346. * Compile the data model by imitating the given environment
  347. * The list of modules to be installed in the target environment is:
  348. * - 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
  349. * - plus the list of modules present in the "extra" directory of the target environment: data/<target_environment>-modules/
  350. * @param string $sSourceEnv The name of the source environment to 'imitate'
  351. * @param bool $bUseSymLinks Whether to create symbolic links instead of copies
  352. */
  353. public function CompileFrom($sSourceEnv, $bUseSymLinks = false)
  354. {
  355. $oSourceConfig = new Config(utils::GetConfigFilePath($sSourceEnv));
  356. $sSourceDir = $oSourceConfig->Get('source_dir');
  357. $sSourceDirFull = APPROOT.$sSourceDir;
  358. // Do load the required modules
  359. //
  360. $oFactory = new ModelFactory($sSourceDirFull);
  361. foreach($this->GetMFModulesToCompile($sSourceEnv, $sSourceDir) as $oModule)
  362. {
  363. $sModule = $oModule->GetName();
  364. $oFactory->LoadModule($oModule);
  365. if ($oFactory->HasLoadErrors())
  366. {
  367. break;
  368. }
  369. }
  370. if ($oFactory->HasLoadErrors())
  371. {
  372. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  373. {
  374. echo "<h3>Module: ".$sModuleId."</h3>\n";
  375. foreach($aErrors as $oXmlError)
  376. {
  377. echo "<p>File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message."</p>\n";
  378. }
  379. }
  380. }
  381. else
  382. {
  383. $sTargetDir = APPROOT.'env-'.$this->sTargetEnv;
  384. self::MakeDirSafe($sTargetDir);
  385. $oMFCompiler = new MFCompiler($oFactory);
  386. $oMFCompiler->Compile($sTargetDir, null, $bUseSymLinks);
  387. $sCacheDir = APPROOT.'data/cache-'.$this->sTargetEnv;
  388. Setuputils::builddir($sCacheDir);
  389. Setuputils::tidydir($sCacheDir);
  390. require_once(APPROOT.'/core/dict.class.inc.php');
  391. MetaModel::ResetCache(md5(APPROOT).'-'.$this->sTargetEnv);
  392. }
  393. }
  394. /**
  395. * Helper function to create the database structure
  396. * @return boolean true on success, false otherwise
  397. */
  398. public function CreateDatabaseStructure(Config $oConfig, $sMode)
  399. {
  400. if (strlen($oConfig->GetDBSubname()) > 0)
  401. {
  402. $this->log_info("Creating the structure in '".$oConfig->GetDBName()."' (table names prefixed by '".$oConfig->GetDBSubname()."').");
  403. }
  404. else
  405. {
  406. $this->log_info("Creating the structure in '".$oConfig->GetDBSubname()."'.");
  407. }
  408. //MetaModel::CheckDefinitions();
  409. if ($sMode == 'install')
  410. {
  411. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  412. {
  413. MetaModel::DBCreate(array($this, 'LogQueryCallback'));
  414. $this->log_ok("Database structure successfully created.");
  415. }
  416. else
  417. {
  418. if (strlen($oConfig->GetDBSubname()) > 0)
  419. {
  420. 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.");
  421. }
  422. else
  423. {
  424. 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.");
  425. }
  426. }
  427. }
  428. else
  429. {
  430. if (MetaModel::DBExists(/* bMustBeComplete */ false))
  431. {
  432. MetaModel::DBCreate(array($this, 'LogQueryCallback'));
  433. $this->log_ok("Database structure successfully updated.");
  434. // Check (and update only if it seems needed) the hierarchical keys
  435. ob_start();
  436. MetaModel::CheckHKeys(false /* bDiagnosticsOnly */, true /* bVerbose*/, true /* bForceUpdate */); // Since in 1.2-beta the detection was buggy, let's force the rebuilding of HKeys
  437. $sFeedback = ob_get_clean();
  438. $this->log_ok("Hierchical keys rebuilt: $sFeedback");
  439. // Check (and fix) data sync configuration
  440. ob_start();
  441. MetaModel::CheckDataSources(false /*$bDiagnostics*/, true/*$bVerbose*/);
  442. $sFeedback = ob_get_clean();
  443. $this->log_ok("Data sources checked: $sFeedback");
  444. // Fix meta enums
  445. ob_start();
  446. MetaModel::RebuildMetaEnums(true /*bVerbose*/);
  447. $sFeedback = ob_get_clean();
  448. $this->log_ok("Meta enums rebuilt: $sFeedback");
  449. }
  450. else
  451. {
  452. if (strlen($oConfig->GetDBSubname()) > 0)
  453. {
  454. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."' (prefix: '".$oConfig->GetDBSubname()."'). Please, try selecting another database instance.");
  455. }
  456. else
  457. {
  458. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."'. Please, try selecting another database instance.");
  459. }
  460. }
  461. }
  462. return true;
  463. }
  464. public function UpdatePredefinedObjects()
  465. {
  466. // Constant classes (e.g. User profiles)
  467. //
  468. foreach (MetaModel::GetClasses() as $sClass)
  469. {
  470. $aPredefinedObjects = call_user_func(array(
  471. $sClass,
  472. 'GetPredefinedObjects'
  473. ));
  474. if ($aPredefinedObjects != null)
  475. {
  476. $this->log_info("$sClass::GetPredefinedObjects() returned " . count($aPredefinedObjects) . " elements.");
  477. // Create/Delete/Update objects of this class,
  478. // according to the given constant values
  479. //
  480. $aDBIds = array();
  481. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  482. while ($oObj = $oAll->Fetch())
  483. {
  484. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  485. {
  486. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  487. foreach ($aObjValues as $sAttCode => $value)
  488. {
  489. $oObj->Set($sAttCode, $value);
  490. }
  491. $oObj->DBUpdate();
  492. $aDBIds[$oObj->GetKey()] = true;
  493. }
  494. else
  495. {
  496. $oObj->DBDelete();
  497. }
  498. }
  499. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  500. {
  501. if (! array_key_exists($iRefId, $aDBIds))
  502. {
  503. $oNewObj = MetaModel::NewObject($sClass);
  504. $oNewObj->SetKey($iRefId);
  505. foreach ($aObjValues as $sAttCode => $value)
  506. {
  507. $oNewObj->Set($sAttCode, $value);
  508. }
  509. $oNewObj->DBInsert();
  510. }
  511. }
  512. }
  513. }
  514. }
  515. public function RecordInstallation(Config $oConfig, $sDataModelVersion, $aSelectedModules, $sModulesRelativePath, $sShortComment = null)
  516. {
  517. if ($sShortComment === null)
  518. {
  519. $sShortComment = 'Done by the setup program';
  520. }
  521. $sMainComment = $sShortComment."\nBuilt on ".ITOP_BUILD_DATE;
  522. // Record datamodel version
  523. $aData = array(
  524. 'source_dir' => $oConfig->Get('source_dir'),
  525. );
  526. $iInstallationTime = time(); // Make sure that all modules record the same installation time
  527. $oInstallRec = new ModuleInstallation();
  528. $oInstallRec->Set('name', DATAMODEL_MODULE);
  529. $oInstallRec->Set('version', $sDataModelVersion);
  530. $oInstallRec->Set('comment', json_encode($aData));
  531. $oInstallRec->Set('parent_id', 0); // root module
  532. $oInstallRec->Set('installed', $iInstallationTime);
  533. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  534. // Record main installation
  535. $oInstallRec = new ModuleInstallation();
  536. $oInstallRec->Set('name', ITOP_APPLICATION);
  537. $oInstallRec->Set('version', ITOP_VERSION.'.'.ITOP_REVISION);
  538. $oInstallRec->Set('comment', $sMainComment);
  539. $oInstallRec->Set('parent_id', 0); // root module
  540. $oInstallRec->Set('installed', $iInstallationTime);
  541. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  542. // Record installed modules
  543. //
  544. $aAvailableModules = $this->AnalyzeInstallation($oConfig, APPROOT.$sModulesRelativePath);
  545. foreach($aSelectedModules as $sModuleId)
  546. {
  547. $aModuleData = $aAvailableModules[$sModuleId];
  548. $sName = $sModuleId;
  549. $sVersion = $aModuleData['version_code'];
  550. $aComments = array();
  551. $aComments[] = $sShortComment;
  552. if ($aModuleData['mandatory'])
  553. {
  554. $aComments[] = 'Mandatory';
  555. }
  556. else
  557. {
  558. $aComments[] = 'Optional';
  559. }
  560. if ($aModuleData['visible'])
  561. {
  562. $aComments[] = 'Visible (during the setup)';
  563. }
  564. else
  565. {
  566. $aComments[] = 'Hidden (selected automatically)';
  567. }
  568. foreach ($aModuleData['dependencies'] as $sDependOn)
  569. {
  570. $aComments[] = "Depends on module: $sDependOn";
  571. }
  572. $sComment = implode("\n", $aComments);
  573. $oInstallRec = new ModuleInstallation();
  574. $oInstallRec->Set('name', $sName);
  575. $oInstallRec->Set('version', $sVersion);
  576. $oInstallRec->Set('comment', $sComment);
  577. $oInstallRec->Set('parent_id', $iMainItopRecord);
  578. $oInstallRec->Set('installed', $iInstallationTime);
  579. $oInstallRec->DBInsertNoReload();
  580. }
  581. // Database is created, installation has been tracked into it
  582. return true;
  583. }
  584. public function GetApplicationVersion(Config $oConfig)
  585. {
  586. $aResult = false;
  587. try
  588. {
  589. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  590. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  591. CMDBSource::SetCharacterSet($oConfig->GetDBCharacterSet(), $oConfig->GetDBCollation());
  592. $sSQLQuery = "SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install";
  593. $aSelectInstall = CMDBSource::QueryToArray($sSQLQuery);
  594. }
  595. catch (MySQLException $e)
  596. {
  597. // No database or erroneous information
  598. $this->log_error('Can not connect to the database: host: '.$oConfig->GetDBHost().', user:'.$oConfig->GetDBUser().', pwd:'.$oConfig->GetDBPwd().', db name:'.$oConfig->GetDBName());
  599. $this->log_error('Exception '.$e->getMessage());
  600. return false;
  601. }
  602. // Scan the list of installed modules to get the version of the 'ROOT' module which holds the main application version
  603. foreach ($aSelectInstall as $aInstall)
  604. {
  605. $sModuleVersion = $aInstall['version'];
  606. if ($sModuleVersion == '')
  607. {
  608. // Though the version cannot be empty in iTop 2.0, it used to be possible
  609. // therefore we have to put something here or the module will not be considered
  610. // as being installed
  611. $sModuleVersion = '0.0.0';
  612. }
  613. if ($aInstall['parent_id'] == 0)
  614. {
  615. if ($aInstall['name'] == DATAMODEL_MODULE)
  616. {
  617. $aResult['datamodel_version'] = $sModuleVersion;
  618. $aComments = json_decode($aInstall['comment'], true);
  619. if (is_array($aComments))
  620. {
  621. $aResult = array_merge($aResult, $aComments);
  622. }
  623. }
  624. else
  625. {
  626. $aResult['product_name'] = $aInstall['name'];
  627. $aResult['product_version'] = $sModuleVersion;
  628. }
  629. }
  630. }
  631. if (!array_key_exists('datamodel_version', $aResult))
  632. {
  633. // Versions prior to 2.0 did not record the version of the datamodel
  634. // so assume that the datamodel version is equal to the application version
  635. $aResult['datamodel_version'] = $aResult['product_version'];
  636. }
  637. $this->log_info("GetApplicationVersion returns: product_name: ".$aResult['product_name'].', product_version: '.$aResult['product_version']);
  638. return $aResult;
  639. }
  640. public static function MakeDirSafe($sDir)
  641. {
  642. if (!is_dir($sDir))
  643. {
  644. if (!@mkdir($sDir))
  645. {
  646. throw new Exception("Failed to create directory '$sDir', please check that the web server process has enough rights to create the directory.");
  647. }
  648. @chmod($sDir, 0770); // RWX for owner and group, nothing for others
  649. }
  650. }
  651. /**
  652. * Wrappers for logging into the setup log files
  653. */
  654. protected function log_error($sText)
  655. {
  656. SetupPage::log_error($sText);
  657. }
  658. protected function log_warning($sText)
  659. {
  660. SetupPage::log_warning($sText);
  661. }
  662. protected function log_info($sText)
  663. {
  664. SetupPage::log_info($sText);
  665. }
  666. protected function log_ok($sText)
  667. {
  668. SetupPage::log_ok($sText);
  669. }
  670. public function GetCurrentDataModelVersion()
  671. {
  672. $oSearch = DBObjectSearch::FromOQL("SELECT ModuleInstallation WHERE name='".DATAMODEL_MODULE."'");
  673. $oSet = new DBObjectSet($oSearch, array(), array('installed' => false));
  674. $oLatestDM = $oSet->Fetch();
  675. if ($oLatestDM == null)
  676. {
  677. return '0.0.0';
  678. }
  679. return $oLatestDM->Get('version');
  680. }
  681. } // End of class