runtimeenv.class.inc.php 22 KB

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