runtimeenv.class.inc.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. <?php
  2. // Copyright (C) 2010-2017 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-2017 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.'setup/extensionsmap.class.inc.php');
  28. require_once(APPROOT.'core/metamodel.class.php');
  29. define ('MODULE_ACTION_OPTIONAL', 1);
  30. define ('MODULE_ACTION_MANDATORY', 2);
  31. define ('MODULE_ACTION_IMPOSSIBLE', 3);
  32. define ('ROOT_MODULE', '_Root_'); // Convention to store IN MEMORY the name/version of the root module i.e. application
  33. define ('DATAMODEL_MODULE', 'datamodel'); // Convention to store the version of the datamodel
  34. class RunTimeEnvironment
  35. {
  36. /**
  37. * The name of the environment that the caller wants to build
  38. * @var string sFinalEnv
  39. */
  40. protected $sFinalEnv;
  41. /**
  42. * Environment into which the build will be performed
  43. * @var string sTargetEnv
  44. */
  45. protected $sTargetEnv;
  46. /**
  47. * Extensions map of the source environment
  48. * @var iTopExtensionsMap
  49. */
  50. protected $oExtensionsMap;
  51. /**
  52. * Toolset for building a run-time environment
  53. *
  54. * @param string $sEnvironment (e.g. 'test')
  55. * @param bool $bAutoCommit (make the target environment directly, or build a temporary one)
  56. */
  57. public function __construct($sEnvironment = 'production', $bAutoCommit = true)
  58. {
  59. $this->sFinalEnv = $sEnvironment;
  60. if ($bAutoCommit)
  61. {
  62. // Build directly onto the requested environment
  63. $this->sTargetEnv = $sEnvironment;
  64. }
  65. else
  66. {
  67. // Build into a temporary target
  68. $this->sTargetEnv = $sEnvironment.'-build';
  69. }
  70. $this->oExtensionsMap = null;
  71. }
  72. /**
  73. * Return the full path to the compiled code (do not use after commit)
  74. * @return string
  75. */
  76. public function GetBuildDir()
  77. {
  78. return APPROOT.'env-'.$this->sTargetEnv;
  79. }
  80. /**
  81. * Callback function for logging the queries run by the setup.
  82. * According to the documentation the function must be defined before passing it to call_user_func...
  83. * @param string $sQuery
  84. * @param float $fDuration
  85. * @return void
  86. */
  87. public function LogQueryCallback($sQuery, $fDuration)
  88. {
  89. $this->log_info(sprintf('%.3fs - query: %s ', $fDuration, $sQuery));
  90. }
  91. /**
  92. * Helper function to initialize the ORM and load the data model
  93. * from the given file
  94. * @param $oConfig object The configuration (volatile, not necessarily already on disk)
  95. * @param $bModelOnly boolean Whether or not to allow loading a data model with no corresponding DB
  96. * @return none
  97. */
  98. public function InitDataModel($oConfig, $bModelOnly = true, $bUseCache = false)
  99. {
  100. require_once(APPROOT.'/core/log.class.inc.php');
  101. require_once(APPROOT.'/core/kpi.class.inc.php');
  102. require_once(APPROOT.'/core/coreexception.class.inc.php');
  103. require_once(APPROOT.'/core/dict.class.inc.php');
  104. require_once(APPROOT.'/core/attributedef.class.inc.php');
  105. require_once(APPROOT.'/core/filterdef.class.inc.php');
  106. require_once(APPROOT.'/core/stimulus.class.inc.php');
  107. require_once(APPROOT.'/core/MyHelpers.class.inc.php');
  108. require_once(APPROOT.'/core/oql/expression.class.inc.php');
  109. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  110. require_once(APPROOT.'/core/sqlquery.class.inc.php');
  111. require_once(APPROOT.'/core/sqlobjectquery.class.inc.php');
  112. require_once(APPROOT.'/core/sqlunionquery.class.inc.php');
  113. require_once(APPROOT.'/core/dbobject.class.php');
  114. require_once(APPROOT.'/core/dbsearch.class.php');
  115. require_once(APPROOT.'/core/dbobjectset.class.php');
  116. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  117. require_once(APPROOT.'/core/userrights.class.inc.php');
  118. require_once(APPROOT.'/setup/moduleinstallation.class.inc.php');
  119. $sConfigFile = $oConfig->GetLoadedFile();
  120. if (strlen($sConfigFile) > 0)
  121. {
  122. $this->log_info("MetaModel::Startup from $sConfigFile (ModelOnly = $bModelOnly)");
  123. }
  124. else
  125. {
  126. $this->log_info("MetaModel::Startup (ModelOnly = $bModelOnly)");
  127. }
  128. if (!$bUseCache)
  129. {
  130. // Reset the cache for the first use !
  131. MetaModel::ResetCache(md5(APPROOT).'-'.$this->sTargetEnv);
  132. }
  133. MetaModel::Startup($oConfig, $bModelOnly, $bUseCache, false /* $bTraceSourceFiles */, $this->sTargetEnv);
  134. if ($this->oExtensionsMap === null)
  135. {
  136. $this->oExtensionsMap = new iTopExtensionsMap($this->sTargetEnv);
  137. }
  138. }
  139. /**
  140. * Analyzes the current installation and the possibilities
  141. *
  142. * @param Config $oConfig Defines the target environment (DB)
  143. * @param mixed $modulesPath Either a single string or an array of absolute paths
  144. * @param bool $bAbortOnMissingDependency ...
  145. * @param hash $aModulesToLoad List of modules to search for, defaults to all if ommitted
  146. * @return hash Array with the following format:
  147. * array =>
  148. * 'iTop' => array(
  149. * 'version_db' => ... (could be empty in case of a fresh install)
  150. * 'version_code => ...
  151. * )
  152. * <module_name> => array(
  153. * 'version_db' => ...
  154. * 'version_code' => ...
  155. * 'install' => array(
  156. * 'flag' => SETUP_NEVER | SETUP_OPTIONAL | SETUP_MANDATORY
  157. * 'message' => ...
  158. * )
  159. * 'uninstall' => array(
  160. * 'flag' => SETUP_NEVER | SETUP_OPTIONAL | SETUP_MANDATORY
  161. * 'message' => ...
  162. * )
  163. * 'label' => ...
  164. * 'dependencies' => array(<module1>, <module2>, ...)
  165. * 'visible' => true | false
  166. * )
  167. * )
  168. */
  169. public function AnalyzeInstallation($oConfig, $modulesPath, $bAbortOnMissingDependency = false, $aModulesToLoad = null)
  170. {
  171. $aRes = array(
  172. ROOT_MODULE => array(
  173. 'version_db' => '',
  174. 'name_db' => '',
  175. 'version_code' => ITOP_VERSION.'.'.ITOP_REVISION,
  176. 'name_code' => ITOP_APPLICATION,
  177. )
  178. );
  179. $aDirs = is_array($modulesPath) ? $modulesPath : array($modulesPath);
  180. $aModules = ModuleDiscovery::GetAvailableModules($aDirs, $bAbortOnMissingDependency, $aModulesToLoad);
  181. foreach($aModules as $sModuleId => $aModuleInfo)
  182. {
  183. list($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId);
  184. if ($sModuleName == '')
  185. {
  186. throw new Exception("Missing name for the module: '$sModuleId'");
  187. }
  188. if ($sModuleVersion == '')
  189. {
  190. // The version must not be empty (it will be used as a criteria to determine wether a module has been installed or not)
  191. //throw new Exception("Missing version for the module: '$sModuleId'");
  192. $sModuleVersion = '1.0.0';
  193. }
  194. $sModuleAppVersion = $aModuleInfo['itop_version'];
  195. $aModuleInfo['version_db'] = '';
  196. $aModuleInfo['version_code'] = $sModuleVersion;
  197. if (!in_array($sModuleAppVersion, array('1.0.0', '1.0.1', '1.0.2')))
  198. {
  199. // This module is NOT compatible with the current version
  200. $aModuleInfo['install'] = array(
  201. 'flag' => MODULE_ACTION_IMPOSSIBLE,
  202. 'message' => 'the module is not compatible with the current version of the application'
  203. );
  204. }
  205. elseif ($aModuleInfo['mandatory'])
  206. {
  207. $aModuleInfo['install'] = array(
  208. 'flag' => MODULE_ACTION_MANDATORY,
  209. 'message' => 'the module is part of the application'
  210. );
  211. }
  212. else
  213. {
  214. $aModuleInfo['install'] = array(
  215. 'flag' => MODULE_ACTION_OPTIONAL,
  216. 'message' => ''
  217. );
  218. }
  219. $aRes[$sModuleName] = $aModuleInfo;
  220. }
  221. try
  222. {
  223. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  224. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  225. CMDBSource::SetCharacterSet($oConfig->GetDBCharacterSet(), $oConfig->GetDBCollation());
  226. $aSelectInstall = CMDBSource::QueryToArray("SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install");
  227. }
  228. catch (MySQLException $e)
  229. {
  230. // No database or erroneous information
  231. $aSelectInstall = array();
  232. }
  233. // Build the list of installed module (get the latest installation)
  234. //
  235. $aInstallByModule = array(); // array of <module> => array ('installed' => timestamp, 'version' => <version>)
  236. $iRootId = 0;
  237. foreach ($aSelectInstall as $aInstall)
  238. {
  239. if (($aInstall['parent_id'] == 0) && ($aInstall['name'] != 'datamodel'))
  240. {
  241. // Root module, what is its ID ?
  242. $iId = (int) $aInstall['id'];
  243. if ($iId > $iRootId)
  244. {
  245. $iRootId = $iId;
  246. }
  247. }
  248. }
  249. foreach ($aSelectInstall as $aInstall)
  250. {
  251. //$aInstall['comment']; // unsused
  252. $iInstalled = strtotime($aInstall['installed']);
  253. $sModuleName = $aInstall['name'];
  254. $sModuleVersion = $aInstall['version'];
  255. if ($sModuleVersion == '')
  256. {
  257. // Though the version cannot be empty in iTop 2.0, it used to be possible
  258. // therefore we have to put something here or the module will not be considered
  259. // as being installed
  260. $sModuleVersion = '0.0.0';
  261. }
  262. if ($aInstall['parent_id'] == 0)
  263. {
  264. $sModuleName = ROOT_MODULE;
  265. }
  266. else if($aInstall['parent_id'] != $iRootId)
  267. {
  268. // Skip all modules belonging to previous installations
  269. continue;
  270. }
  271. if (array_key_exists($sModuleName, $aInstallByModule))
  272. {
  273. if ($iInstalled < $aInstallByModule[$sModuleName]['installed'])
  274. {
  275. continue;
  276. }
  277. }
  278. if ($aInstall['parent_id'] == 0)
  279. {
  280. $aRes[$sModuleName]['version_db'] = $sModuleVersion;
  281. $aRes[$sModuleName]['name_db'] = $aInstall['name'];
  282. }
  283. $aInstallByModule[$sModuleName]['installed'] = $iInstalled;
  284. $aInstallByModule[$sModuleName]['version'] = $sModuleVersion;
  285. }
  286. // Adjust the list of proposed modules
  287. //
  288. foreach ($aInstallByModule as $sModuleName => $aModuleDB)
  289. {
  290. if ($sModuleName == ROOT_MODULE) continue; // Skip the main module
  291. if (!array_key_exists($sModuleName, $aRes))
  292. {
  293. // A module was installed, it is not proposed in the new build... skip
  294. continue;
  295. }
  296. $aRes[$sModuleName]['version_db'] = $aModuleDB['version'];
  297. if ($aRes[$sModuleName]['install']['flag'] == MODULE_ACTION_MANDATORY)
  298. {
  299. $aRes[$sModuleName]['uninstall'] = array(
  300. 'flag' => MODULE_ACTION_IMPOSSIBLE,
  301. 'message' => 'the module is part of the application'
  302. );
  303. }
  304. else
  305. {
  306. $aRes[$sModuleName]['uninstall'] = array(
  307. 'flag' => MODULE_ACTION_OPTIONAL,
  308. 'message' => ''
  309. );
  310. }
  311. }
  312. return $aRes;
  313. }
  314. public function WriteConfigFileSafe($oConfig)
  315. {
  316. self::MakeDirSafe(APPCONF);
  317. self::MakeDirSafe(APPCONF.$this->sTargetEnv);
  318. $sTargetConfigFile = APPCONF.$this->sTargetEnv.'/'.ITOP_CONFIG_FILE;
  319. // Write the config file
  320. @chmod($sTargetConfigFile, 0770); // In case it exists: RWX for owner and group, nothing for others
  321. $oConfig->WriteToFile($sTargetConfigFile);
  322. @chmod($sTargetConfigFile, 0440); // Read-only for owner and group, nothing for others
  323. }
  324. /**
  325. * Get the installed modules (only the installed ones)
  326. */
  327. protected function GetMFModulesToCompile($sSourceEnv, $sSourceDir)
  328. {
  329. $sSourceDirFull = APPROOT.$sSourceDir;
  330. if (!is_dir($sSourceDirFull))
  331. {
  332. throw new Exception("The source directory '$sSourceDirFull' does not exist (or could not be read)");
  333. }
  334. $aDirsToCompile = array($sSourceDirFull);
  335. if (is_dir(APPROOT.'extensions'))
  336. {
  337. $aDirsToCompile[] = APPROOT.'extensions';
  338. }
  339. $sExtraDir = APPROOT.'data/'.$this->sTargetEnv.'-modules/';
  340. if (is_dir($sExtraDir))
  341. {
  342. $aDirsToCompile[] = $sExtraDir;
  343. }
  344. $aRet = array();
  345. // Determine the installed modules and extensions
  346. //
  347. $oSourceConfig = new Config(APPCONF.$sSourceEnv.'/'.ITOP_CONFIG_FILE);
  348. $oSourceEnv = new RunTimeEnvironment($sSourceEnv);
  349. $aAvailableModules = $oSourceEnv->AnalyzeInstallation($oSourceConfig, $aDirsToCompile);
  350. // Actually read the modules available for the target environment,
  351. // but get the selection from the source environment and finally
  352. // mark as (automatically) chosen alll the "remote" modules present in the
  353. // target environment (data/<target-env>-modules)
  354. // The actual choices will be recorded by RecordInstallation below
  355. $this->oExtensionsMap = new iTopExtensionsMap($this->sTargetEnv);
  356. $this->oExtensionsMap->LoadChoicesFromDatabase($oSourceConfig);
  357. foreach($this->oExtensionsMap->GetAllExtensions() as $oExtension)
  358. {
  359. if($oExtension->sSource == iTopExtension::SOURCE_REMOTE)
  360. {
  361. $this->oExtensionsMap->MarkAsChosen($oExtension->sCode);
  362. }
  363. }
  364. // Do load the required modules
  365. //
  366. $oDictModule = new MFDictModule('dictionaries', 'iTop Dictionaries', APPROOT.'dictionaries');
  367. $aRet[$oDictModule->GetName()] = $oDictModule;
  368. $oFactory = new ModelFactory($aDirsToCompile);
  369. $sDeltaFile = APPROOT.'core/datamodel.core.xml';
  370. if (file_exists($sDeltaFile))
  371. {
  372. $oCoreModule = new MFCoreModule('core', 'Core Module', $sDeltaFile);
  373. $aRet[$oCoreModule->GetName()] = $oCoreModule;
  374. }
  375. $sDeltaFile = APPROOT.'application/datamodel.application.xml';
  376. if (file_exists($sDeltaFile))
  377. {
  378. $oApplicationModule = new MFCoreModule('application', 'Application Module', $sDeltaFile);
  379. $aRet[$oApplicationModule->GetName()] = $oApplicationModule;
  380. }
  381. $aModules = $oFactory->FindModules();
  382. foreach($aModules as $oModule)
  383. {
  384. $sModule = $oModule->GetName();
  385. $sModuleRootDir = $oModule->GetRootDir();
  386. $bIsExtra = (strpos($sModuleRootDir, $sExtraDir) !== false);
  387. if (array_key_exists($sModule, $aAvailableModules))
  388. {
  389. if (($aAvailableModules[$sModule]['version_db'] != '') || $bIsExtra && !$oModule->IsAutoSelect()) //Extra modules are always unless they are 'AutoSelect'
  390. {
  391. $aRet[$oModule->GetName()] = $oModule;
  392. }
  393. }
  394. }
  395. // Now process the 'AutoSelect' modules
  396. do
  397. {
  398. // Loop while new modules are added...
  399. $bModuleAdded = false;
  400. foreach($aModules as $oModule)
  401. {
  402. if (!array_key_exists($oModule->GetName(), $aRet) && $oModule->IsAutoSelect())
  403. {
  404. try
  405. {
  406. $bSelected = false;
  407. SetupInfo::SetSelectedModules($aRet);
  408. eval('$bSelected = ('.$oModule->GetAutoSelect().');');
  409. }
  410. catch(Exception $e)
  411. {
  412. $bSelected = false;
  413. }
  414. if ($bSelected)
  415. {
  416. $aRet[$oModule->GetName()] = $oModule; // store the Id of the selected module
  417. $bModuleAdded = true;
  418. }
  419. }
  420. }
  421. }
  422. while($bModuleAdded);
  423. $sDeltaFile = APPROOT.'data/'.$this->sTargetEnv.'.delta.xml';
  424. if (file_exists($sDeltaFile))
  425. {
  426. $oDelta = new MFDeltaModule($sDeltaFile);
  427. $aRet[$oDelta->GetName()] = $oDelta;
  428. }
  429. return $aRet;
  430. }
  431. /**
  432. * Compile the data model by imitating the given environment
  433. * The list of modules to be installed in the target environment is:
  434. * - 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
  435. * - plus the list of modules present in the "extra" directory of the target environment: data/<target_environment>-modules/
  436. * @param string $sSourceEnv The name of the source environment to 'imitate'
  437. * @param bool $bUseSymLinks Whether to create symbolic links instead of copies
  438. */
  439. public function CompileFrom($sSourceEnv, $bUseSymLinks = false)
  440. {
  441. $oSourceConfig = new Config(utils::GetConfigFilePath($sSourceEnv));
  442. $sSourceDir = $oSourceConfig->Get('source_dir');
  443. $sSourceDirFull = APPROOT.$sSourceDir;
  444. // Do load the required modules
  445. //
  446. $oFactory = new ModelFactory($sSourceDirFull);
  447. foreach($this->GetMFModulesToCompile($sSourceEnv, $sSourceDir) as $oModule)
  448. {
  449. if ($oModule instanceof MFDeltaModule)
  450. {
  451. // Just before loading the delta, let's save an image of the datamodel
  452. // in case there is no delta the operation will be done after the end of the loop
  453. $oFactory->SaveToFile(APPROOT.'data/datamodel-'.$this->sTargetEnv.'.xml');
  454. }
  455. $oFactory->LoadModule($oModule);
  456. if ($oFactory->HasLoadErrors())
  457. {
  458. break;
  459. }
  460. }
  461. if ($oFactory->HasLoadErrors())
  462. {
  463. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  464. {
  465. echo "<h3>Module: ".$sModuleId."</h3>\n";
  466. foreach($aErrors as $oXmlError)
  467. {
  468. echo "<p>File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message."</p>\n";
  469. }
  470. }
  471. }
  472. else
  473. {
  474. if ($oModule instanceof MFDeltaModule)
  475. {
  476. // A delta was loaded, let's save a second copy of the datamodel
  477. $oFactory->SaveToFile(APPROOT.'data/datamodel-'.$this->sTargetEnv.'-with-delta.xml');
  478. }
  479. else
  480. {
  481. // No delta was loaded, let's save the datamodel now
  482. $oFactory->SaveToFile(APPROOT.'data/datamodel-'.$this->sTargetEnv.'.xml');
  483. }
  484. $sTargetDir = APPROOT.'env-'.$this->sTargetEnv;
  485. self::MakeDirSafe($sTargetDir);
  486. $bSkipTempDir = ($this->sFinalEnv != $this->sTargetEnv); // No need for a temporary directory if sTargetEnv is already a temporary directory
  487. $oMFCompiler = new MFCompiler($oFactory);
  488. $oMFCompiler->Compile($sTargetDir, null, $bUseSymLinks, $bSkipTempDir);
  489. $sCacheDir = APPROOT.'data/cache-'.$this->sTargetEnv;
  490. SetupUtils::builddir($sCacheDir);
  491. SetupUtils::tidydir($sCacheDir);
  492. MetaModel::ResetCache(md5(APPROOT).'-'.$this->sTargetEnv);
  493. }
  494. }
  495. /**
  496. * Helper function to create the database structure
  497. * @return boolean true on success, false otherwise
  498. */
  499. public function CreateDatabaseStructure(Config $oConfig, $sMode)
  500. {
  501. if (strlen($oConfig->GetDBSubname()) > 0)
  502. {
  503. $this->log_info("Creating the structure in '".$oConfig->GetDBName()."' (table names prefixed by '".$oConfig->GetDBSubname()."').");
  504. }
  505. else
  506. {
  507. $this->log_info("Creating the structure in '".$oConfig->GetDBSubname()."'.");
  508. }
  509. //MetaModel::CheckDefinitions();
  510. if ($sMode == 'install')
  511. {
  512. if (!MetaModel::DBExists(/* bMustBeComplete */ false))
  513. {
  514. MetaModel::DBCreate(array($this, 'LogQueryCallback'));
  515. $this->log_ok("Database structure successfully created.");
  516. }
  517. else
  518. {
  519. if (strlen($oConfig->GetDBSubname()) > 0)
  520. {
  521. 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.");
  522. }
  523. else
  524. {
  525. 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.");
  526. }
  527. }
  528. }
  529. else
  530. {
  531. if (MetaModel::DBExists(/* bMustBeComplete */ false))
  532. {
  533. // Have it work fine even if the DB has been set in read-only mode for the users
  534. // (fix copied from RunTimeEnvironment::RecordInstallation)
  535. $iPrevAccessMode = $oConfig->Get('access_mode');
  536. $oConfig->Set('access_mode', ACCESS_FULL);
  537. MetaModel::DBCreate(array($this, 'LogQueryCallback'));
  538. $this->log_ok("Database structure successfully updated.");
  539. // Check (and update only if it seems needed) the hierarchical keys
  540. ob_start();
  541. MetaModel::CheckHKeys(false /* bDiagnosticsOnly */, true /* bVerbose*/, true /* bForceUpdate */); // Since in 1.2-beta the detection was buggy, let's force the rebuilding of HKeys
  542. $sFeedback = ob_get_clean();
  543. $this->log_ok("Hierchical keys rebuilt: $sFeedback");
  544. // Check (and fix) data sync configuration
  545. ob_start();
  546. MetaModel::CheckDataSources(false /*$bDiagnostics*/, true/*$bVerbose*/);
  547. $sFeedback = ob_get_clean();
  548. $this->log_ok("Data sources checked: $sFeedback");
  549. // Fix meta enums
  550. ob_start();
  551. MetaModel::RebuildMetaEnums(true /*bVerbose*/);
  552. $sFeedback = ob_get_clean();
  553. $this->log_ok("Meta enums rebuilt: $sFeedback");
  554. // Restore the previous access mode
  555. $oConfig->Set('access_mode', $iPrevAccessMode);
  556. }
  557. else
  558. {
  559. if (strlen($oConfig->GetDBSubname()) > 0)
  560. {
  561. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."' (prefix: '".$oConfig->GetDBSubname()."'). Please, try selecting another database instance.");
  562. }
  563. else
  564. {
  565. throw new Exception("Error: No previous instance of iTop found into the database '".$oConfig->GetDBName()."'. Please, try selecting another database instance.");
  566. }
  567. }
  568. }
  569. return true;
  570. }
  571. public function UpdatePredefinedObjects()
  572. {
  573. // Have it work fine even if the DB has been set in read-only mode for the users
  574. $oConfig = MetaModel::GetConfig();
  575. $iPrevAccessMode = $oConfig->Get('access_mode');
  576. $oConfig->Set('access_mode', ACCESS_FULL);
  577. // Constant classes (e.g. User profiles)
  578. //
  579. foreach (MetaModel::GetClasses() as $sClass)
  580. {
  581. $aPredefinedObjects = call_user_func(array(
  582. $sClass,
  583. 'GetPredefinedObjects'
  584. ));
  585. if ($aPredefinedObjects != null)
  586. {
  587. $this->log_info("$sClass::GetPredefinedObjects() returned " . count($aPredefinedObjects) . " elements.");
  588. // Create/Delete/Update objects of this class,
  589. // according to the given constant values
  590. //
  591. $aDBIds = array();
  592. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  593. while ($oObj = $oAll->Fetch())
  594. {
  595. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  596. {
  597. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  598. foreach ($aObjValues as $sAttCode => $value)
  599. {
  600. $oObj->Set($sAttCode, $value);
  601. }
  602. $oObj->DBUpdate();
  603. $aDBIds[$oObj->GetKey()] = true;
  604. }
  605. else
  606. {
  607. $oObj->DBDelete();
  608. }
  609. }
  610. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  611. {
  612. if (! array_key_exists($iRefId, $aDBIds))
  613. {
  614. $oNewObj = MetaModel::NewObject($sClass);
  615. $oNewObj->SetKey($iRefId);
  616. foreach ($aObjValues as $sAttCode => $value)
  617. {
  618. $oNewObj->Set($sAttCode, $value);
  619. }
  620. $oNewObj->DBInsert();
  621. }
  622. }
  623. }
  624. }
  625. // Restore the previous access mode
  626. $oConfig->Set('access_mode', $iPrevAccessMode);
  627. }
  628. public function RecordInstallation(Config $oConfig, $sDataModelVersion, $aSelectedModuleCodes, $aSelectedExtensionCodes, $sShortComment = null)
  629. {
  630. // Have it work fine even if the DB has been set in read-only mode for the users
  631. $iPrevAccessMode = $oConfig->Get('access_mode');
  632. $oConfig->Set('access_mode', ACCESS_FULL);
  633. if (CMDBSource::DBName() == '')
  634. {
  635. // In case this has not yet been done
  636. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  637. CMDBSource::SetCharacterSet($oConfig->GetDBCharacterSet(), $oConfig->GetDBCollation());
  638. }
  639. if ($sShortComment === null)
  640. {
  641. $sShortComment = 'Done by the setup program';
  642. }
  643. $sMainComment = $sShortComment."\nBuilt on ".ITOP_BUILD_DATE;
  644. // Record datamodel version
  645. $aData = array(
  646. 'source_dir' => $oConfig->Get('source_dir'),
  647. );
  648. $iInstallationTime = time(); // Make sure that all modules record the same installation time
  649. $oInstallRec = new ModuleInstallation();
  650. $oInstallRec->Set('name', DATAMODEL_MODULE);
  651. $oInstallRec->Set('version', $sDataModelVersion);
  652. $oInstallRec->Set('comment', json_encode($aData));
  653. $oInstallRec->Set('parent_id', 0); // root module
  654. $oInstallRec->Set('installed', $iInstallationTime);
  655. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  656. // Record main installation
  657. $oInstallRec = new ModuleInstallation();
  658. $oInstallRec->Set('name', ITOP_APPLICATION);
  659. $oInstallRec->Set('version', ITOP_VERSION.'.'.ITOP_REVISION);
  660. $oInstallRec->Set('comment', $sMainComment);
  661. $oInstallRec->Set('parent_id', 0); // root module
  662. $oInstallRec->Set('installed', $iInstallationTime);
  663. $iMainItopRecord = $oInstallRec->DBInsertNoReload();
  664. // Record installed modules and extensions
  665. //
  666. $aAvailableExtensions = array();
  667. $aAvailableModules = $this->AnalyzeInstallation($oConfig, $this->GetBuildDir());
  668. foreach($aSelectedModuleCodes as $sModuleId)
  669. {
  670. $aModuleData = $aAvailableModules[$sModuleId];
  671. $sName = $sModuleId;
  672. $sVersion = $aModuleData['version_code'];
  673. $aComments = array();
  674. $aComments[] = $sShortComment;
  675. if ($aModuleData['mandatory'])
  676. {
  677. $aComments[] = 'Mandatory';
  678. }
  679. else
  680. {
  681. $aComments[] = 'Optional';
  682. }
  683. if ($aModuleData['visible'])
  684. {
  685. $aComments[] = 'Visible (during the setup)';
  686. }
  687. else
  688. {
  689. $aComments[] = 'Hidden (selected automatically)';
  690. }
  691. foreach ($aModuleData['dependencies'] as $sDependOn)
  692. {
  693. $aComments[] = "Depends on module: $sDependOn";
  694. }
  695. $sComment = implode("\n", $aComments);
  696. $oInstallRec = new ModuleInstallation();
  697. $oInstallRec->Set('name', $sName);
  698. $oInstallRec->Set('version', $sVersion);
  699. $oInstallRec->Set('comment', $sComment);
  700. $oInstallRec->Set('parent_id', $iMainItopRecord);
  701. $oInstallRec->Set('installed', $iInstallationTime);
  702. $oInstallRec->DBInsertNoReload();
  703. }
  704. if ($this->oExtensionsMap)
  705. {
  706. // Mark as chosen the selected extensions code passed to us
  707. // Note: some other extensions may already be marked as chosen
  708. foreach($this->oExtensionsMap->GetAllExtensions() as $oExtension)
  709. {
  710. if (in_array($oExtension->sCode, $aSelectedExtensionCodes))
  711. {
  712. $this->oExtensionsMap->MarkAsChosen($oExtension->sCode);
  713. }
  714. }
  715. foreach($this->oExtensionsMap->GetChoices() as $oExtension)
  716. {
  717. $oInstallRec = new ExtensionInstallation();
  718. $oInstallRec->Set('code', $oExtension->sCode);
  719. $oInstallRec->Set('label', $oExtension->sLabel);
  720. $oInstallRec->Set('version', $oExtension->sVersion);
  721. $oInstallRec->Set('source', $oExtension->sSource);
  722. $oInstallRec->Set('installed', $iInstallationTime);
  723. $oInstallRec->DBInsertNoReload();
  724. }
  725. }
  726. // Restore the previous access mode
  727. $oConfig->Set('access_mode', $iPrevAccessMode);
  728. // Database is created, installation has been tracked into it
  729. return true;
  730. }
  731. public function GetApplicationVersion(Config $oConfig)
  732. {
  733. $aResult = false;
  734. try
  735. {
  736. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  737. CMDBSource::Init($oConfig->GetDBHost(), $oConfig->GetDBUser(), $oConfig->GetDBPwd(), $oConfig->GetDBName());
  738. CMDBSource::SetCharacterSet($oConfig->GetDBCharacterSet(), $oConfig->GetDBCollation());
  739. $sSQLQuery = "SELECT * FROM ".$oConfig->GetDBSubname()."priv_module_install";
  740. $aSelectInstall = CMDBSource::QueryToArray($sSQLQuery);
  741. }
  742. catch (MySQLException $e)
  743. {
  744. // No database or erroneous information
  745. $this->log_error('Can not connect to the database: host: '.$oConfig->GetDBHost().', user:'.$oConfig->GetDBUser().', pwd:'.$oConfig->GetDBPwd().', db name:'.$oConfig->GetDBName());
  746. $this->log_error('Exception '.$e->getMessage());
  747. return false;
  748. }
  749. // Scan the list of installed modules to get the version of the 'ROOT' module which holds the main application version
  750. foreach ($aSelectInstall as $aInstall)
  751. {
  752. $sModuleVersion = $aInstall['version'];
  753. if ($sModuleVersion == '')
  754. {
  755. // Though the version cannot be empty in iTop 2.0, it used to be possible
  756. // therefore we have to put something here or the module will not be considered
  757. // as being installed
  758. $sModuleVersion = '0.0.0';
  759. }
  760. if ($aInstall['parent_id'] == 0)
  761. {
  762. if ($aInstall['name'] == DATAMODEL_MODULE)
  763. {
  764. $aResult['datamodel_version'] = $sModuleVersion;
  765. $aComments = json_decode($aInstall['comment'], true);
  766. if (is_array($aComments))
  767. {
  768. $aResult = array_merge($aResult, $aComments);
  769. }
  770. }
  771. else
  772. {
  773. $aResult['product_name'] = $aInstall['name'];
  774. $aResult['product_version'] = $sModuleVersion;
  775. }
  776. }
  777. }
  778. if (!array_key_exists('datamodel_version', $aResult))
  779. {
  780. // Versions prior to 2.0 did not record the version of the datamodel
  781. // so assume that the datamodel version is equal to the application version
  782. $aResult['datamodel_version'] = $aResult['product_version'];
  783. }
  784. $this->log_info("GetApplicationVersion returns: product_name: ".$aResult['product_name'].', product_version: '.$aResult['product_version']);
  785. return $aResult;
  786. }
  787. public static function MakeDirSafe($sDir)
  788. {
  789. if (!is_dir($sDir))
  790. {
  791. if (!@mkdir($sDir))
  792. {
  793. throw new Exception("Failed to create directory '$sDir', please check that the web server process has enough rights to create the directory.");
  794. }
  795. @chmod($sDir, 0770); // RWX for owner and group, nothing for others
  796. }
  797. }
  798. /**
  799. * Wrappers for logging into the setup log files
  800. */
  801. protected function log_error($sText)
  802. {
  803. SetupPage::log_error($sText);
  804. }
  805. protected function log_warning($sText)
  806. {
  807. SetupPage::log_warning($sText);
  808. }
  809. protected function log_info($sText)
  810. {
  811. SetupPage::log_info($sText);
  812. }
  813. protected function log_ok($sText)
  814. {
  815. SetupPage::log_ok($sText);
  816. }
  817. public function GetCurrentDataModelVersion()
  818. {
  819. $oSearch = DBObjectSearch::FromOQL("SELECT ModuleInstallation WHERE name='".DATAMODEL_MODULE."'");
  820. $oSet = new DBObjectSet($oSearch, array(), array('installed' => false));
  821. $oLatestDM = $oSet->Fetch();
  822. if ($oLatestDM == null)
  823. {
  824. return '0.0.0';
  825. }
  826. return $oLatestDM->Get('version');
  827. }
  828. public function Commit()
  829. {
  830. if ($this->sFinalEnv != $this->sTargetEnv)
  831. {
  832. if (file_exists(APPROOT.'data/'.$this->sTargetEnv.'.delta.xml'))
  833. {
  834. if (file_exists(APPROOT.'data/'.$this->sFinalEnv.'.delta.xml'))
  835. {
  836. // Make a "previous" file
  837. copy(
  838. APPROOT.'data/'.$this->sTargetEnv.'.delta.xml',
  839. APPROOT.'data/'.$this->sFinalEnv.'.delta.prev.xml'
  840. );
  841. }
  842. $this->CommitFile(
  843. APPROOT.'data/'.$this->sTargetEnv.'.delta.xml',
  844. APPROOT.'data/'.$this->sFinalEnv.'.delta.xml'
  845. );
  846. }
  847. $this->CommitFile(
  848. APPROOT.'data/datamodel-'.$this->sTargetEnv.'.xml',
  849. APPROOT.'data/datamodel-'.$this->sFinalEnv.'.xml'
  850. );
  851. $this->CommitFile(
  852. APPROOT.'data/datamodel-'.$this->sTargetEnv.'-with-delta.xml',
  853. APPROOT.'data/datamodel-'.$this->sFinalEnv.'-with-delta.xml',
  854. false
  855. );
  856. $this->CommitDir(
  857. APPROOT.'data/'.$this->sTargetEnv.'-modules/',
  858. APPROOT.'data/'.$this->sFinalEnv.'-modules/',
  859. false
  860. );
  861. $this->CommitDir(
  862. APPROOT.'data/cache-'.$this->sTargetEnv,
  863. APPROOT.'data/cache-'.$this->sFinalEnv,
  864. false
  865. );
  866. $this->CommitDir(
  867. APPROOT.'env-'.$this->sTargetEnv,
  868. APPROOT.'env-'.$this->sFinalEnv,
  869. true,
  870. false
  871. );
  872. // Move the config file
  873. //
  874. $sTargetConfig = APPCONF.$this->sTargetEnv.'/config-itop.php';
  875. $sFinalConfig = APPCONF.$this->sFinalEnv.'/config-itop.php';
  876. @chmod($sFinalConfig, 0770); // In case it exists: RWX for owner and group, nothing for others
  877. $this->CommitFile($sTargetConfig, $sFinalConfig);
  878. @chmod($sFinalConfig, 0440); // Read-only for owner and group, nothing for others
  879. @rmdir(dirname($sTargetConfig)); // Cleanup the temporary build dir if empty
  880. MetaModel::ResetCache(md5(APPROOT).'-'.$this->sFinalEnv);
  881. }
  882. }
  883. /**
  884. * Overwrite or create the destination file
  885. *
  886. * @param $sSource
  887. * @param $sDest
  888. * @param bool $bSourceMustExist
  889. * @throws Exception
  890. */
  891. protected function CommitFile($sSource, $sDest, $bSourceMustExist = true)
  892. {
  893. if (file_exists($sSource))
  894. {
  895. SetupUtils::builddir(dirname($sDest));
  896. if (file_exists($sDest))
  897. {
  898. $bRes = @unlink($sDest);
  899. if (!$bRes)
  900. {
  901. throw new Exception('Commit - Failed to cleanup destination file: '.$sDest);
  902. }
  903. }
  904. rename($sSource, $sDest);
  905. }
  906. else
  907. {
  908. // The file does not exist
  909. if ($bSourceMustExist)
  910. {
  911. throw new Exception('Commit - Missing file: '.$sSource);
  912. }
  913. else
  914. {
  915. // Align the destination with the source... make sure there is NO file
  916. if (file_exists($sDest))
  917. {
  918. $bRes = @unlink($sDest);
  919. if (!$bRes)
  920. {
  921. throw new Exception('Commit - Failed to cleanup destination file: '.$sDest);
  922. }
  923. }
  924. }
  925. }
  926. }
  927. /**
  928. * Overwrite or create the destination directory
  929. *
  930. * @param $sSource
  931. * @param $sDest
  932. * @param boolean $bSourceMustExist
  933. * @param boolean $bRemoveSource If true $sSource will be removed, otherwise $sSource will just be emptied
  934. * @throws Exception
  935. */
  936. protected function CommitDir($sSource, $sDest, $bSourceMustExist = true, $bRemoveSource = true)
  937. {
  938. if (file_exists($sSource))
  939. {
  940. SetupUtils::movedir($sSource, $sDest, $bRemoveSource);
  941. }
  942. else
  943. {
  944. // The file does not exist
  945. if ($bSourceMustExist)
  946. {
  947. throw new Exception('Commit - Missing directory: '.$sSource);
  948. }
  949. else
  950. {
  951. // Align the destination with the source... make sure there is NO file
  952. if (file_exists($sDest))
  953. {
  954. SetupUtils::rrmdir($sDest);
  955. }
  956. }
  957. }
  958. }
  959. } // End of class