runtimeenv.class.inc.php 24 KB

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