xmldataloader.class.inc.php 11 KB

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