xmldataloader.class.inc.php 11 KB

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