runtimeenv.class.inc.php 24 KB

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