ajax.dataloader.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Does load data from XML files (currently used in the setup only)
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. /**
  25. * This page is called to perform "asynchronously" the setup actions
  26. * parameters
  27. * 'operation': one of 'compile_data_model', 'update_db_schema', 'after_db_creation', 'file'
  28. *
  29. * if 'operation' == 'update_db_schema':
  30. * 'mode': install | upgrade
  31. *
  32. * if 'operation' == 'after_db_creation':
  33. * 'mode': install | upgrade
  34. *
  35. * if 'operation' == 'file':
  36. * 'file': string Name of the file to load
  37. * 'session_status': string 'start', 'continue' or 'end'
  38. * 'percent': integer 0..100 the percentage of completion once the file has been loaded
  39. */
  40. define('SAFE_MINIMUM_MEMORY', 32*1024*1024);
  41. require_once('../approot.inc.php');
  42. require_once(APPROOT.'/application/utils.inc.php');
  43. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  44. require_once(APPROOT.'/setup/moduleinstaller.class.inc.php');
  45. $sMemoryLimit = trim(ini_get('memory_limit'));
  46. if (empty($sMemoryLimit))
  47. {
  48. // On some PHP installations, memory_limit does not exist as a PHP setting!
  49. // (encountered on a 5.2.0 under Windows)
  50. // In that case, ini_set will not work, let's keep track of this and proceed with the data load
  51. SetupPage::log_info("No memory limit has been defined in this instance of PHP");
  52. }
  53. else
  54. {
  55. // Check that the limit will allow us to load the data
  56. //
  57. $iMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
  58. if ($iMemoryLimit < SAFE_MINIMUM_MEMORY)
  59. {
  60. if (ini_set('memory_limit', SAFE_MINIMUM_MEMORY) === FALSE)
  61. {
  62. SetupPage::log_error("memory_limit is too small: $iMemoryLimit and can not be increased by the script itself.");
  63. }
  64. else
  65. {
  66. SetupPage::log_info("memory_limit increased from $iMemoryLimit to ".SAFE_MINIMUM_MEMORY.".");
  67. }
  68. }
  69. }
  70. function FatalErrorCatcher($sOutput)
  71. {
  72. if ( preg_match('|<phpfatalerror>.*</phpfatalerror>|s', $sOutput, $aMatches) )
  73. {
  74. header("HTTP/1.0 500 Internal server error.");
  75. foreach ($aMatches as $sMatch)
  76. {
  77. $errors .= strip_tags($sMatch)."\n";
  78. }
  79. $sOutput = "$errors\n";
  80. // Logging to a file does not work if the whole memory is exhausted...
  81. //SetupPage::log_error("Fatal error - in $__FILE__ , $errors");
  82. }
  83. return $sOutput;
  84. }
  85. /**
  86. * Helper function to create and administrator account for iTop
  87. * @return boolean true on success, false otherwise
  88. */
  89. function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  90. {
  91. SetupPage::log_info('CreateAdminAccount');
  92. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  93. {
  94. return true;
  95. }
  96. else
  97. {
  98. return false;
  99. }
  100. }
  101. //Define some bogus, invalid HTML tags that no sane
  102. //person would ever put in an actual document and tell
  103. //PHP to delimit fatal error warnings with them.
  104. ini_set('error_prepend_string', '<phpfatalerror>');
  105. ini_set('error_append_string', '</phpfatalerror>');
  106. // Starts the capture of the ouput, and sets a filter to capture the fatal errors.
  107. ob_start('FatalErrorCatcher'); // Start capturing the output, and pass it through the fatal error catcher
  108. require_once(APPROOT.'/core/config.class.inc.php');
  109. require_once(APPROOT.'/core/log.class.inc.php');
  110. require_once(APPROOT.'/core/kpi.class.inc.php');
  111. require_once(APPROOT.'/core/cmdbsource.class.inc.php');
  112. require_once('./xmldataloader.class.inc.php');
  113. require_once(APPROOT.'/application/ajaxwebpage.class.inc.php');
  114. // Never cache this page
  115. header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  116. header("Expires: Fri, 17 Jul 1970 05:00:00 GMT"); // Date in the past
  117. /**
  118. * Main program
  119. */
  120. $sOperation = Utils::ReadParam('operation', '');
  121. try
  122. {
  123. switch($sOperation)
  124. {
  125. case 'async_action':
  126. ini_set('max_execution_time', max(240, ini_get('max_execution_time')));
  127. // While running the setup it is desirable to see any error that may happen
  128. ini_set('display_errors', true);
  129. ini_set('display_startup_errors', true);
  130. require_once(APPROOT.'/setup/wizardcontroller.class.inc.php');
  131. require_once(APPROOT.'/setup/wizardsteps.class.inc.php');
  132. $sClass = utils::ReadParam('step_class', '');
  133. $sState = utils::ReadParam('step_state', '');
  134. $sActionCode = utils::ReadParam('code', '');
  135. $aParams = utils::ReadParam('params', array(), false, 'raw_data');
  136. $oPage = new ajax_page('');
  137. $oDummyController = new WizardController('');
  138. if (is_subclass_of($sClass, 'WizardStep'))
  139. {
  140. $oStep = new $sClass($oDummyController, $sState);
  141. $sConfigFile = utils::GetConfigFilePath();
  142. if (file_exists($sConfigFile) && !is_writable($sConfigFile) && $oStep->RequiresWritableConfig())
  143. {
  144. $oPage->error("<b>Error:</b> the configuration file '".$sConfigFile."' already exists and cannot be overwritten.");
  145. $oPage->p("The wizard cannot modify the configuration file for you. If you want to upgrade ".ITOP_APPLICATION.", make sure that the file '<b>".realpath($sConfigFile)."</b>' can be modified by the web server.");
  146. $oPage->output();
  147. }
  148. else
  149. {
  150. $oStep->AsyncAction($oPage, $sActionCode, $aParams);
  151. }
  152. }
  153. $oPage->output();
  154. break;
  155. //////////////////////////////
  156. //
  157. case 'compile_data_model':
  158. //
  159. SetupPage::log_info("Compiling data model.");
  160. require_once(APPROOT.'setup/modulediscovery.class.inc.php');
  161. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  162. require_once(APPROOT.'setup/compiler.class.inc.php');
  163. $sSelectedModules = Utils::ReadParam('selected_modules', '', false, 'raw_data');
  164. $aSelectedModules = explode(',', $sSelectedModules);
  165. $sWorkspace = Utils::ReadParam('workspace_dir', '', false, 'raw_data');
  166. $sSourceDir = Utils::ReadParam('source_dir', '', false, 'raw_data');
  167. $sTargetDir = Utils::ReadParam('target_dir', '', false, 'raw_data');
  168. if (empty($sSourceDir) || empty($sTargetDir))
  169. {
  170. throw new Exception("missing parameter source_dir and/or target_dir");
  171. }
  172. $sSourcePath = APPROOT.$sSourceDir;
  173. $sTargetPath = APPROOT.$sTargetDir;
  174. if (!is_dir($sSourcePath))
  175. {
  176. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  177. }
  178. if (!is_dir($sTargetPath) && !mkdir($sTargetPath))
  179. {
  180. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  181. }
  182. // owner:rwx user/group:rx
  183. chmod($sTargetPath, 0755);
  184. $oFactory = new ModelFactory($sSourcePath);
  185. $aModules = $oFactory->FindModules();
  186. foreach($aModules as $foo => $oModule)
  187. {
  188. $sModule = $oModule->GetName();
  189. if (in_array($sModule, $aSelectedModules))
  190. {
  191. $oFactory->LoadModule($oModule);
  192. }
  193. }
  194. if (strlen($sWorkspace) > 0)
  195. {
  196. $oWorkspace = new MFWorkspace(APPROOT.$sWorkspace);
  197. if (file_exists($oWorkspace->GetWorkspacePath()))
  198. {
  199. $oFactory->LoadModule($oWorkspace);
  200. }
  201. }
  202. //$oFactory->Dump();
  203. if ($oFactory->HasLoadErrors())
  204. {
  205. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  206. {
  207. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  208. foreach($aErrors as $oXmlError)
  209. {
  210. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  211. }
  212. }
  213. throw new Exception("The data model could not be compiled. Please check the setup error log");
  214. }
  215. else
  216. {
  217. $oMFCompiler = new MFCompiler($oFactory, $sSourcePath);
  218. $oMFCompiler->Compile($sTargetPath);
  219. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  220. }
  221. break;
  222. //////////////////////////////
  223. //
  224. case 'update_db_schema':
  225. //
  226. SetupPage::log_info("Update Database Schema.");
  227. $oConfig = new Config();
  228. $aParamValues = array(
  229. 'db_server' => utils::ReadParam('db_server', '', false, 'raw_data'),
  230. 'db_user' => utils::ReadParam('db_user', '', false, 'raw_data'),
  231. 'db_pwd' => utils::ReadParam('db_pwd', '', false, 'raw_data'),
  232. 'db_name' => utils::ReadParam('db_name', '', false, 'raw_data'),
  233. 'new_db_name' => utils::ReadParam('new_db_name', '', false, 'raw_data'),
  234. 'db_prefix' => utils::ReadParam('db_prefix', '', false, 'raw_data')
  235. );
  236. $sModuleDir = Utils::ReadParam('modules_dir', '');
  237. $oConfig->UpdateFromParams($aParamValues, $sModuleDir);
  238. $oProductionEnv = new RunTimeEnvironment();
  239. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  240. $sMode = Utils::ReadParam('mode', 'install');
  241. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  242. {
  243. throw(new Exception("Failed to create/upgrade the database structure"));
  244. }
  245. SetupPage::log_info("Database Schema Successfully Updated.");
  246. break;
  247. //////////////////////////////
  248. //
  249. case 'after_db_create':
  250. //
  251. SetupPage::log_info('After Database Creation');
  252. $oConfig = new Config();
  253. $aParamValues = array(
  254. 'db_server' => utils::ReadParam('db_server', '', false, 'raw_data'),
  255. 'db_user' => utils::ReadParam('db_user', '', false, 'raw_data'),
  256. 'db_pwd' => utils::ReadParam('db_pwd', '', false, 'raw_data'),
  257. 'db_name' => utils::ReadParam('db_name', '', false, 'raw_data'),
  258. 'new_db_name' => utils::ReadParam('new_db_name', '', false, 'raw_data'),
  259. 'db_prefix' => utils::ReadParam('db_prefix', '', false, 'raw_data')
  260. );
  261. $sModuleDir = Utils::ReadParam('modules_dir', '');
  262. $oConfig->UpdateFromParams($aParamValues, $sModuleDir);
  263. $oProductionEnv = new RunTimeEnvironment();
  264. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  265. $sMode = Utils::ReadParam('mode', 'install');
  266. $sSelectedModules = Utils::ReadParam('selected_modules', '', false, 'raw_data');
  267. $aSelectedModules = explode(',', $sSelectedModules);
  268. // Perform here additional DB setup... profiles, etc...
  269. //
  270. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), $sModuleDir);
  271. foreach($aAvailableModules as $sModuleId => $aModule)
  272. {
  273. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  274. isset($aAvailableModules[$sModuleId]['installer']) )
  275. {
  276. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  277. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  278. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  279. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  280. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  281. }
  282. }
  283. // Constant classes (e.g. User profiles)
  284. //
  285. foreach (MetaModel::GetClasses() as $sClass)
  286. {
  287. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  288. if ($aPredefinedObjects != null)
  289. {
  290. // Create/Delete/Update objects of this class,
  291. // according to the given constant values
  292. //
  293. $aDBIds = array();
  294. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  295. while ($oObj = $oAll->Fetch())
  296. {
  297. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  298. {
  299. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  300. foreach ($aObjValues as $sAttCode => $value)
  301. {
  302. $oObj->Set($sAttCode, $value);
  303. }
  304. $oObj->DBUpdate();
  305. $aDBIds[$oObj->GetKey()] = true;
  306. }
  307. else
  308. {
  309. $oObj->DBDelete();
  310. }
  311. }
  312. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  313. {
  314. if (!array_key_exists($iRefId, $aDBIds))
  315. {
  316. $oNewObj = MetaModel::NewObject($sClass);
  317. $oNewObj->SetKey($iRefId);
  318. foreach ($aObjValues as $sAttCode => $value)
  319. {
  320. $oNewObj->Set($sAttCode, $value);
  321. }
  322. $oNewObj->DBInsert();
  323. }
  324. }
  325. }
  326. }
  327. if (!$oProductionEnv->RecordInstallation($oConfig, $aSelectedModules, $sModuleDir))
  328. {
  329. throw(new Exception("Failed to record the installation information"));
  330. }
  331. if($sMode == 'install')
  332. {
  333. // Create the admin user only in case of installation
  334. $sAdminUser = Utils::ReadParam('auth_user', '', false, 'raw_data');
  335. $sAdminPwd = Utils::ReadParam('auth_pwd', '', false, 'raw_data');
  336. $sLanguage = Utils::ReadParam('language', '');
  337. if (!CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sLanguage))
  338. {
  339. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  340. }
  341. else
  342. {
  343. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  344. }
  345. }
  346. break;
  347. //////////////////////////////
  348. //
  349. case 'load_data': // Load data files
  350. //
  351. $sFileName = Utils::ReadParam('file', '', false, 'raw_data');
  352. $sSessionStatus = Utils::ReadParam('session_status', '');
  353. $iPercent = (integer)Utils::ReadParam('percent', 0);
  354. SetupPage::log_info("Loading file: $sFileName");
  355. if (empty($sFileName) || !file_exists($sFileName))
  356. {
  357. throw(new Exception("File $sFileName does not exist"));
  358. }
  359. $oConfig = new Config();
  360. $aParamValues = array(
  361. 'db_server' => utils::ReadParam('db_server', '', false, 'raw_data'),
  362. 'db_user' => utils::ReadParam('db_user', '', false, 'raw_data'),
  363. 'db_pwd' => utils::ReadParam('db_pwd', '', false, 'raw_data'),
  364. 'db_name' => utils::ReadParam('db_name', '', false, 'raw_data'),
  365. 'new_db_name' => utils::ReadParam('new_db_name', '', false, 'raw_data'),
  366. 'db_prefix' => utils::ReadParam('db_prefix', '', false, 'raw_data')
  367. );
  368. $sModuleDir = Utils::ReadParam('modules_dir', '');
  369. $oConfig->UpdateFromParams($aParamValues, $sModuleDir);
  370. $oProductionEnv = new RunTimeEnvironment();
  371. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  372. $oDataLoader = new XMLDataLoader();
  373. if ($sSessionStatus == 'start')
  374. {
  375. $oChange = MetaModel::NewObject("CMDBChange");
  376. $oChange->Set("date", time());
  377. $oChange->Set("userinfo", "Initialization");
  378. $iChangeId = $oChange->DBInsert();
  379. SetupPage::log_info("starting data load session");
  380. $oDataLoader->StartSession($oChange);
  381. }
  382. $oDataLoader->LoadFile($sFileName);
  383. $sResult = sprintf("loading of %s done. (Overall %d %% completed).", basename($sFileName), $iPercent);
  384. SetupPage::log_info($sResult);
  385. if ($sSessionStatus == 'end')
  386. {
  387. $oDataLoader->EndSession();
  388. SetupPage::log_info("ending data load session");
  389. }
  390. break;
  391. default:
  392. throw(new Exception("Error unsupported operation '$sOperation'"));
  393. }
  394. }
  395. catch(Exception $e)
  396. {
  397. header("HTTP/1.0 500 Internal server error.");
  398. echo "<p>An error happened while processing the installation:</p>\n";
  399. echo '<p>'.$e."</p>\n";
  400. SetupPage::log_error("An error happened while processing the installation: ".$e);
  401. }
  402. if (function_exists('memory_get_peak_usage'))
  403. {
  404. if ($sOperation == 'file')
  405. {
  406. SetupPage::log_info("loading file '$sFileName', peak memory usage. ".memory_get_peak_usage());
  407. }
  408. else
  409. {
  410. SetupPage::log_info("operation '$sOperation', peak memory usage. ".memory_get_peak_usage());
  411. }
  412. }
  413. ?>