ajax.dataloader.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 '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. SetupWebPage::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. SetupWebPage::log_error("memory_limit is too small: $iMemoryLimit and can not be increased by the script itself.");
  63. }
  64. else
  65. {
  66. SetupWebPage::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. //SetupWebPage::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. SetupWebPage::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. define('TMP_CONFIG_FILE', APPROOT.'/tmp-config-itop.php');
  114. //define('FINAL_CONFIG_FILE', APPROOT.'/config-itop.php');
  115. // Never cache this page
  116. header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  117. header("Expires: Fri, 17 Jul 1970 05:00:00 GMT"); // Date in the past
  118. /**
  119. * Main program
  120. */
  121. $sOperation = Utils::ReadParam('operation', '');
  122. try
  123. {
  124. switch($sOperation)
  125. {
  126. case 'update_db_schema':
  127. SetupWebPage::log_info("Update Database Schema.");
  128. InitDataModel(TMP_CONFIG_FILE, true); // load data model and connect to the database
  129. $sMode = Utils::ReadParam('mode', 'install');
  130. $sSelectedModules = Utils::ReadParam('selected_modules', '', false, 'raw_data');
  131. $aSelectedModules = explode(',', $sSelectedModules);
  132. if(!CreateDatabaseStructure(MetaModel::GetConfig(), $aSelectedModules, $sMode))
  133. {
  134. throw(new Exception("Failed to create/upgrade the database structure"));
  135. }
  136. SetupWebPage::log_info("Database Schema Successfully Updated.");
  137. break;
  138. case 'after_db_create':
  139. SetupWebPage::log_info('After Database Creation');
  140. $sMode = Utils::ReadParam('mode', 'install');
  141. $sSelectedModules = Utils::ReadParam('selected_modules', '', false, 'raw_data');
  142. $aSelectedModules = explode(',', $sSelectedModules);
  143. InitDataModel(TMP_CONFIG_FILE, true); // load data model and connect to the database
  144. // Perform here additional DB setup... profiles, etc...
  145. $aAvailableModules = AnalyzeInstallation(MetaModel::GetConfig());
  146. $aStructureDataFiles = array();
  147. $aSampleDataFiles = array();
  148. foreach($aAvailableModules as $sModuleId => $aModule)
  149. {
  150. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  151. isset($aAvailableModules[$sModuleId]['installer']) )
  152. {
  153. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  154. SetupWebPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  155. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  156. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  157. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  158. }
  159. }
  160. if (!RecordInstallation(MetaModel::GetConfig(), $aSelectedModules))
  161. {
  162. throw(new Exception("Failed to record the installation information"));
  163. }
  164. if($sMode == 'install')
  165. {
  166. // Create the admin user only in case of installation
  167. $sAdminUser = Utils::ReadParam('auth_user', '', false, 'raw_data');
  168. $sAdminPwd = Utils::ReadParam('auth_pwd', '', false, 'raw_data');
  169. $sLanguage = Utils::ReadParam('language', '');
  170. if (!CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sLanguage))
  171. {
  172. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  173. }
  174. else
  175. {
  176. SetupWebPage::log_info("Administrator account '$sAdminUser' created.");
  177. }
  178. }
  179. break;
  180. case 'load_data': // Load data files
  181. $sFileName = Utils::ReadParam('file', '', false, 'raw_data');
  182. $sSessionStatus = Utils::ReadParam('session_status', '');
  183. $iPercent = (integer)Utils::ReadParam('percent', 0);
  184. SetupWebPage::log_info("Loading file: $sFileName");
  185. if (empty($sFileName) || !file_exists($sFileName))
  186. {
  187. throw(new Exception("File $sFileName does not exist"));
  188. }
  189. InitDataModel(TMP_CONFIG_FILE, false); // When called by the wizard, the final config is not yet there
  190. $oDataLoader = new XMLDataLoader();
  191. if ($sSessionStatus == 'start')
  192. {
  193. $oChange = MetaModel::NewObject("CMDBChange");
  194. $oChange->Set("date", time());
  195. $oChange->Set("userinfo", "Initialization");
  196. $iChangeId = $oChange->DBInsert();
  197. SetupWebPage::log_info("starting data load session");
  198. $oDataLoader->StartSession($oChange);
  199. }
  200. $oDataLoader->LoadFile($sFileName);
  201. $sResult = sprintf("loading of %s done. (Overall %d %% completed).", basename($sFileName), $iPercent);
  202. SetupWebPage::log_info($sResult);
  203. if ($sSessionStatus == 'end')
  204. {
  205. $oDataLoader->EndSession();
  206. SetupWebPage::log_info("ending data load session");
  207. }
  208. break;
  209. default:
  210. throw(new Exception("Error unsupported operation '$sOperation'"));
  211. }
  212. }
  213. catch(Exception $e)
  214. {
  215. header("HTTP/1.0 500 Internal server error.");
  216. echo "<p>An error happened while processing the installation:</p>\n";
  217. echo '<p>'.$e."</p>\n";
  218. SetupWebPage::log_error("An error happened while processing the installation: ".$e);
  219. }
  220. if (function_exists('memory_get_peak_usage'))
  221. {
  222. if ($sOperation == 'file')
  223. {
  224. SetupWebPage::log_info("loading file '$sFileName', peak memory usage. ".memory_get_peak_usage());
  225. }
  226. else
  227. {
  228. SetupWebPage::log_info("operation '$sOperation', peak memory usage. ".memory_get_peak_usage());
  229. }
  230. }
  231. ?>