xmldataloader.class.inc.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. define ('KEYS_CACHE_FILE', '../keyscache.tmp');
  3. /**
  4. * Class to load sets of objects from XML files into the database
  5. * XML files can be produced by the 'export' web service or by any other means
  6. * Here is a simple example:
  7. * $oLoader = new XMLDataLoader('../itop-config.php');
  8. * $oLoader->StartSession();
  9. * $oLoader->LoadFile('./organizations.xml');
  10. * $oLoader->LoadFile('./locations.xml');
  11. * $oLoader->EndSession();
  12. */
  13. class XMLDataLoader
  14. {
  15. protected $m_aKeys;
  16. protected $m_aObjectsCache;
  17. protected $m_bSessionActive;
  18. protected $m_oChange;
  19. protected $m_sCacheFileName;
  20. public function __construct($sConfigFileName)
  21. {
  22. $this->m_aKeys = array();
  23. $this->m_aObjectsCache = array();
  24. $this->m_oChange = null;
  25. $this->m_sCacheFileName = dirname(__FILE__).'/'.KEYS_CACHE_FILE;
  26. $this->InitDataModel($sConfigFileName);
  27. $this->LoadKeysCache();
  28. $this->m_bSessionActive = true;
  29. }
  30. public function StartSession($oChange)
  31. {
  32. // Do cleanup any existing cache file (shall not be necessary unless a setup was interrupted abruptely)
  33. $this->ClearKeysCache();
  34. $this->m_oChange = $oChange;
  35. $this->m_bSessionActive = true;
  36. }
  37. public function EndSession()
  38. {
  39. $this->ResolveExternalKeys();
  40. $this->m_bSessionActive = false;
  41. }
  42. public function __destruct()
  43. {
  44. // Stopping in the middle of a session, let's save the context information
  45. if ($this->m_bSessionActive)
  46. {
  47. $this->SaveKeysCache();
  48. }
  49. else
  50. {
  51. $this->ClearKeysCache();
  52. }
  53. }
  54. /**
  55. * Initializes the ORM (MetaModel)
  56. */
  57. protected function InitDataModel($sConfigFileName, $bAllowMissingDatabase = true)
  58. {
  59. require_once('../core/log.class.inc.php');
  60. require_once('../core/coreexception.class.inc.php');
  61. require_once('../core/attributedef.class.inc.php');
  62. require_once('../core/filterdef.class.inc.php');
  63. require_once('../core/stimulus.class.inc.php');
  64. require_once('../core/MyHelpers.class.inc.php');
  65. require_once('../core/expression.class.inc.php');
  66. require_once('../core/cmdbsource.class.inc.php');
  67. require_once('../core/sqlquery.class.inc.php');
  68. require_once('../core/dbobject.class.php');
  69. require_once('../core/dbobjectsearch.class.php');
  70. require_once('../core/dbobjectset.class.php');
  71. require_once('../core/userrights.class.inc.php');
  72. MetaModel::Startup($sConfigFileName, $bAllowMissingDatabase);
  73. }
  74. /**
  75. * Stores the keys & object cache in a file
  76. */
  77. protected function SaveKeysCache()
  78. {
  79. $hFile = @fopen($this->m_sCacheFileName, 'w');
  80. if ($hFile !== false)
  81. {
  82. $sData = serialize( array('keys' => $this->m_aKeys,
  83. 'objects' => $this->m_aObjectsCache,
  84. 'change' => $this->m_oChange));
  85. fwrite($hFile, $sData);
  86. fclose($hFile);
  87. }
  88. else
  89. {
  90. throw new Exception("Cannot write to file: '{$this->m_sCacheFileName}'");
  91. }
  92. }
  93. /**
  94. * Loads the keys & object cache from the tmp file
  95. */
  96. protected function LoadKeysCache()
  97. {
  98. $sFileContent = @file_get_contents($this->m_sCacheFileName);
  99. if (!empty($sFileContent))
  100. {
  101. $aCache = unserialize($sFileContent);
  102. $this->m_aKeys = $aCache['keys'];
  103. $this->m_aObjectsCache = $aCache['objects'];
  104. $this->m_oChange = $aCache['change'];
  105. }
  106. }
  107. /**
  108. * Remove the tmp file used to store the keys cache
  109. */
  110. protected function ClearKeysCache()
  111. {
  112. if(is_file($this->m_sCacheFileName))
  113. {
  114. unlink($this->m_sCacheFileName);
  115. }
  116. else
  117. {
  118. //echo "<p>Hm, it looks like the file does not exist!!!</p>";
  119. }
  120. $this->m_aKeys = array();
  121. $this->m_aObjectsCache = array();
  122. }
  123. /**
  124. * Helper function to load the objects from a standard XML file into the database
  125. */
  126. function LoadFile($sFilePath)
  127. {
  128. global $aKeys;
  129. $oXml = simplexml_load_file($sFilePath);
  130. $aReplicas = array();
  131. foreach($oXml as $sClass => $oXmlObj)
  132. {
  133. $iSrcId = (integer)$oXmlObj['id']; // Mandatory to cast
  134. // Import algorithm
  135. // Here enumerate all the attributes of the object
  136. // for all attribute that is neither an external field
  137. // not an external key, assign it
  138. // Store all external keys for further reference
  139. // Create the object an store the correspondence between its newly created Id
  140. // and its original Id
  141. // Once all the objects have been created re-assign all the external keys to
  142. // their actual Ids
  143. $oTargetObj = MetaModel::NewObject($sClass);
  144. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  145. {
  146. if (($oAttDef->IsWritable()) && ($oAttDef->IsScalar()))
  147. {
  148. if ($oAttDef->IsExternalKey())
  149. {
  150. $iDstObj = (integer)($oXmlObj->$sAttCode);
  151. // Attempt to find the object in the list of loaded objects
  152. $iExtKey = $this->GetObjectKey($oAttDef->GetTargetClass(), $iDstObj);
  153. if ($iExtKey == 0)
  154. {
  155. $iExtKey = -$iDstObj; // Convention: Unresolved keys are stored as negative !
  156. $oTargetObj->RegisterAsDirty();
  157. }
  158. // here we allow external keys to be invalid because we will resolve them later on...
  159. //$oTargetObj->CheckValue($sAttCode, $iExtKey);
  160. $oTargetObj->Set($sAttCode, $iExtKey);
  161. }
  162. else
  163. {
  164. // tested by Romain, little impact on perf (not significant on the intial setup)
  165. if (!$oTargetObj->CheckValue($sAttCode, (string)$oXmlObj->$sAttCode))
  166. {
  167. SetupWebPage::log_error("Value not allowed - $sClass/$iSrcId - $sAttCode: '".$oXmlObj->$sAttCode."'");
  168. echo "Wrong value for attribute $sAttCode: '".$oXmlObj->$sAttCode."'";
  169. }
  170. $oTargetObj->Set($sAttCode, (string)$oXmlObj->$sAttCode);
  171. }
  172. }
  173. }
  174. $this->StoreObject($sClass, $oTargetObj, $iSrcId);
  175. }
  176. return true;
  177. }
  178. /**
  179. * Get the new ID of an object in the database given its original ID
  180. * This may fail (return 0) if the object has not yet been created in the database
  181. * This is why the order of the import may be important
  182. */
  183. protected function GetObjectKey($sClass, $iSrcId)
  184. {
  185. if (isset($this->m_aKeys[$sClass]) && isset($this->m_aKeys[$sClass][$iSrcId]))
  186. {
  187. return $this->m_aKeys[$sClass][$iSrcId];
  188. }
  189. return 0;
  190. }
  191. /**
  192. * Store an object in the database and remember the mapping
  193. * between its original ID and the newly created ID in the database
  194. */
  195. protected function StoreObject($sClass, $oTargetObj, $iSrcId)
  196. {
  197. try
  198. {
  199. if (is_subclass_of($oTargetObj, 'CMDBObject'))
  200. {
  201. $iObjId = $oTargetObj->DBInsertTrackedNoReload($this->m_oChange);
  202. }
  203. else
  204. {
  205. $iObjId = $oTargetObj->DBInsertNoReload();
  206. }
  207. }
  208. catch(Exception $e)
  209. {
  210. SetupWebPage::log_error("An object could not be loaded - $sClass/$iSrcId - ".$e->getMessage());
  211. echo $e->GetHtmlDesc();
  212. }
  213. $aParentClasses = MetaModel::EnumParentClasses($sClass);
  214. $aParentClasses[] = $sClass;
  215. foreach($aParentClasses as $sObjClass)
  216. {
  217. $this->m_aKeys[$sObjClass][$iSrcId] = $iObjId;
  218. }
  219. $this->m_aObjectsCache[$sClass][$iObjId] = $oTargetObj;
  220. }
  221. /**
  222. * Maps an external key to its (newly created) value
  223. */
  224. protected function ResolveExternalKeys()
  225. {
  226. foreach($this->m_aObjectsCache as $sClass => $oObjList)
  227. {
  228. foreach($oObjList as $oTargetObj)
  229. {
  230. $bChanged = false;
  231. $sClass = get_class($oTargetObj);
  232. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  233. {
  234. if ( ($oAttDef->IsExternalKey()) && ($oTargetObj->Get($sAttCode) < 0) ) // Convention unresolved key = negative
  235. {
  236. $sTargetClass = $oAttDef->GetTargetClass();
  237. $iTempKey = $oTargetObj->Get($sAttCode);
  238. $iExtKey = $this->GetObjectKey($sTargetClass, -$iTempKey);
  239. if ($iExtKey == 0)
  240. {
  241. $sMsg = "unresolved extkey in $sClass::".$oTargetObj->GetKey()."(".$oTargetObj->GetName().")::$sAttCode=$sTargetClass::$iTempKey";
  242. SetupWebPage::log_warning($sMsg);
  243. echo "Warning: $sMsg<br/>\n";
  244. echo "<pre>aKeys[".$sTargetClass."]:\n";
  245. print_r($this->m_aKeys[$sTargetClass]);
  246. echo "</pre>\n";
  247. }
  248. else
  249. {
  250. $bChanged = true;
  251. $oTargetObj->Set($sAttCode, $iExtKey);
  252. }
  253. }
  254. }
  255. if ($bChanged)
  256. {
  257. try
  258. {
  259. if (is_subclass_of($oTargetObj, 'CMDBObject'))
  260. {
  261. $oTargetObj->DBUpdateTracked($this->m_oChange);
  262. }
  263. else
  264. {
  265. $oTargetObj->DBUpdate();
  266. }
  267. }
  268. catch(Exception $e)
  269. {
  270. echo $e->GetHtmlDesc();
  271. }
  272. }
  273. }
  274. }
  275. return true;
  276. }
  277. }
  278. ?>