runtimeenv.class.inc.php 24 KB

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