xmldataloader.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Load XML data from a set of files
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. define ('KEYS_CACHE_FILE', APPROOT.'data/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. protected $m_aErrors;
  43. protected $m_aWarnings;
  44. protected $m_iCountCreated;
  45. public function __construct()
  46. {
  47. $this->m_aKeys = array();
  48. $this->m_aObjectsCache = array();
  49. $this->m_oChange = null;
  50. $this->m_sCacheFileName = KEYS_CACHE_FILE;
  51. $this->LoadKeysCache();
  52. $this->m_bSessionActive = true;
  53. $this->m_aErrors = array();
  54. $this->m_aWarnings = array();
  55. $this->m_iCountCreated = 0;
  56. }
  57. public function StartSession($oChange)
  58. {
  59. // Do cleanup any existing cache file (shall not be necessary unless a setup was interrupted abruptely)
  60. $this->ClearKeysCache();
  61. $this->m_oChange = $oChange;
  62. $this->m_bSessionActive = true;
  63. }
  64. public function EndSession($bStrict = false)
  65. {
  66. $this->ResolveExternalKeys();
  67. $this->m_bSessionActive = false;
  68. if (count($this->m_aErrors) > 0)
  69. {
  70. return false;
  71. }
  72. elseif ($bStrict && count($this->m_aWarnings) > 0)
  73. {
  74. return false;
  75. }
  76. else
  77. {
  78. return true;
  79. }
  80. }
  81. public function GetErrors()
  82. {
  83. return $this->m_aErrors;
  84. }
  85. public function GetWarnings()
  86. {
  87. return $this->m_aWarnings;
  88. }
  89. public function GetCountCreated()
  90. {
  91. return $this->m_iCountCreated;
  92. }
  93. public function __destruct()
  94. {
  95. // Stopping in the middle of a session, let's save the context information
  96. if ($this->m_bSessionActive)
  97. {
  98. $this->SaveKeysCache();
  99. }
  100. else
  101. {
  102. $this->ClearKeysCache();
  103. }
  104. }
  105. /**
  106. * Stores the keys & object cache in a file
  107. */
  108. protected function SaveKeysCache()
  109. {
  110. if (!is_dir(APPROOT.'data'))
  111. {
  112. mkdir(APPROOT.'data');
  113. }
  114. $hFile = @fopen($this->m_sCacheFileName, 'w');
  115. if ($hFile !== false)
  116. {
  117. $sData = serialize( array('keys' => $this->m_aKeys,
  118. 'objects' => $this->m_aObjectsCache,
  119. 'change' => $this->m_oChange,
  120. 'errors' => $this->m_aErrors,
  121. 'warnings' => $this->m_aWarnings,
  122. ));
  123. fwrite($hFile, $sData);
  124. fclose($hFile);
  125. }
  126. else
  127. {
  128. throw new Exception("Cannot write to file: '{$this->m_sCacheFileName}'");
  129. }
  130. }
  131. /**
  132. * Loads the keys & object cache from the tmp file
  133. */
  134. protected function LoadKeysCache()
  135. {
  136. $sFileContent = @file_get_contents($this->m_sCacheFileName);
  137. if (!empty($sFileContent))
  138. {
  139. $aCache = unserialize($sFileContent);
  140. $this->m_aKeys = $aCache['keys'];
  141. $this->m_aObjectsCache = $aCache['objects'];
  142. $this->m_oChange = $aCache['change'];
  143. $this->m_aErrors = $aCache['errors'];
  144. $this->m_aWarnings = $aCache['warnings'];
  145. }
  146. }
  147. /**
  148. * Remove the tmp file used to store the keys cache
  149. */
  150. protected function ClearKeysCache()
  151. {
  152. if(is_file($this->m_sCacheFileName))
  153. {
  154. unlink($this->m_sCacheFileName);
  155. }
  156. else
  157. {
  158. //echo "<p>Hm, it looks like the file does not exist!!!</p>";
  159. }
  160. $this->m_aKeys = array();
  161. $this->m_aObjectsCache = array();
  162. }
  163. /**
  164. * Helper function to load the objects from a standard XML file into the database
  165. */
  166. function LoadFile($sFilePath)
  167. {
  168. global $aKeys;
  169. $oXml = simplexml_load_file($sFilePath);
  170. $aReplicas = array();
  171. foreach($oXml as $sClass => $oXmlObj)
  172. {
  173. if (!MetaModel::IsValidClass($sClass))
  174. {
  175. SetupPage::log_error("Unknown class - $sClass");
  176. throw(new Exception("Unknown class - $sClass"));
  177. }
  178. $iSrcId = (integer)$oXmlObj['id']; // Mandatory to cast
  179. // Import algorithm
  180. // Here enumerate all the attributes of the object
  181. // for all attribute that is neither an external field
  182. // not an external key, assign it
  183. // Store all external keys for further reference
  184. // Create the object an store the correspondance between its newly created Id
  185. // and its original Id
  186. // Once all the objects have been created re-assign all the external keys to
  187. // their actual Ids
  188. $iExistingId = $this->GetObjectKey($sClass, $iSrcId);
  189. if ($iExistingId != 0)
  190. {
  191. $oTargetObj = MetaModel::GetObject($sClass, $iExistingId);
  192. }
  193. else
  194. {
  195. $oTargetObj = MetaModel::NewObject($sClass);
  196. }
  197. foreach($oXmlObj as $sAttCode => $oSubNode)
  198. {
  199. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  200. {
  201. $sMsg = "Unknown attribute code - $sClass/$sAttCode";
  202. continue; // ignore silently...
  203. //SetupPage::log_error($sMsg);
  204. //throw(new Exception($sMsg));
  205. }
  206. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  207. if (($oAttDef->IsWritable()) && ($oAttDef->IsScalar()))
  208. {
  209. if ($oAttDef->IsExternalKey())
  210. {
  211. if (substr(trim($oSubNode), 0, 6) == 'SELECT')
  212. {
  213. $sQuery = trim($oSubNode);
  214. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sQuery));
  215. $iMatches = $oSet->Count();
  216. if ($iMatches == 1)
  217. {
  218. $oFoundObject = $oSet->Fetch();
  219. $iExtKey = $oFoundObject->GetKey();
  220. }
  221. else
  222. {
  223. $sMsg = "Ext key not reconcilied - $sClass/$iSrcId - $sAttCode: '".$sQuery."' - found $iMatches matche(s)";
  224. SetupPage::log_error($sMsg);
  225. $this->m_aErrors[] = $sMsg;
  226. $iExtKey = 0;
  227. }
  228. }
  229. else
  230. {
  231. $iDstObj = (integer)($oSubNode);
  232. // Attempt to find the object in the list of loaded objects
  233. $iExtKey = $this->GetObjectKey($oAttDef->GetTargetClass(), $iDstObj);
  234. if ($iExtKey == 0)
  235. {
  236. $iExtKey = -$iDstObj; // Convention: Unresolved keys are stored as negative !
  237. $oTargetObj->RegisterAsDirty();
  238. }
  239. // here we allow external keys to be invalid because we will resolve them later on...
  240. }
  241. //$oTargetObj->CheckValue($sAttCode, $iExtKey);
  242. $oTargetObj->Set($sAttCode, $iExtKey);
  243. }
  244. elseif ($oAttDef instanceof AttributeBlob)
  245. {
  246. $sMimeType = (string) $oSubNode->mimetype;
  247. $sFileName = (string) $oSubNode->filename;
  248. $data = base64_decode((string) $oSubNode->data);
  249. $oDoc = new ormDocument($data, $sMimeType, $sFileName);
  250. $oTargetObj->Set($sAttCode, $oDoc);
  251. }
  252. else
  253. {
  254. $value = (string)$oSubNode;
  255. if ($value == '')
  256. {
  257. $value = $oAttDef->GetNullValue();
  258. }
  259. $res = $oTargetObj->CheckValue($sAttCode, $value);
  260. if ($res !== true)
  261. {
  262. // $res contains the error description
  263. $sMsg = "Value not allowed - $sClass/$iSrcId - $sAttCode: '".$oSubNode."' ; $res";
  264. SetupPage::log_error($sMsg);
  265. $this->m_aErrors[] = $sMsg;
  266. }
  267. $oTargetObj->Set($sAttCode, $value);
  268. }
  269. }
  270. }
  271. $this->StoreObject($sClass, $oTargetObj, $iSrcId);
  272. }
  273. return true;
  274. }
  275. /**
  276. * Get the new ID of an object in the database given its original ID
  277. * This may fail (return 0) if the object has not yet been created in the database
  278. * This is why the order of the import may be important
  279. */
  280. protected function GetObjectKey($sClass, $iSrcId)
  281. {
  282. if (isset($this->m_aKeys[$sClass]) && isset($this->m_aKeys[$sClass][$iSrcId]))
  283. {
  284. return $this->m_aKeys[$sClass][$iSrcId];
  285. }
  286. return 0;
  287. }
  288. /**
  289. * Store an object in the database and remember the mapping
  290. * between its original ID and the newly created ID in the database
  291. */
  292. protected function StoreObject($sClass, $oTargetObj, $iSrcId, $bSearch = false)
  293. {
  294. $iObjId = 0;
  295. try
  296. {
  297. if ($bSearch)
  298. {
  299. // Check if the object does not already exist, based on its usual reconciliation keys...
  300. $aReconciliationKeys = MetaModel::GetReconcKeys($sClass);
  301. if (count($aReconciliationKeys) > 0)
  302. {
  303. // Some reconciliation keys have been defined, use them to search for the object
  304. $oSearch = new DBObjectSearch($sClass);
  305. $iConditionsCount = 0;
  306. foreach($aReconciliationKeys as $sAttCode)
  307. {
  308. if ($oTargetObj->Get($sAttCode) != '')
  309. {
  310. $oSearch->AddCondition($sAttCode, $oTargetObj->Get($sAttCode), '=');
  311. $iConditionsCount++;
  312. }
  313. }
  314. if ($iConditionsCount > 0) // Search only if there are some valid conditions...
  315. {
  316. $oSet = new DBObjectSet($oSearch);
  317. if ($oSet->count() == 1)
  318. {
  319. // The object already exists, reuse it
  320. $oExistingObject = $oSet->Fetch();
  321. $iObjId = $oExistingObject->GetKey();
  322. }
  323. }
  324. }
  325. }
  326. if ($iObjId == 0)
  327. {
  328. if($oTargetObj->IsNew())
  329. {
  330. $iObjId = $oTargetObj->DBInsertNoReload();
  331. $this->m_iCountCreated++;
  332. }
  333. else
  334. {
  335. $iObjId = $oTargetObj->GetKey();
  336. $oTargetObj->DBUpdate();
  337. }
  338. }
  339. }
  340. catch(Exception $e)
  341. {
  342. SetupPage::log_error("An object could not be recorded - $sClass/$iSrcId - ".$e->getMessage());
  343. $this->m_aErrors[] = "An object could not be recorded - $sClass/$iSrcId - ".$e->getMessage();
  344. }
  345. $aParentClasses = MetaModel::EnumParentClasses($sClass);
  346. $aParentClasses[] = $sClass;
  347. foreach($aParentClasses as $sObjClass)
  348. {
  349. $this->m_aKeys[$sObjClass][$iSrcId] = $iObjId;
  350. }
  351. $this->m_aObjectsCache[$sClass][$iObjId] = $oTargetObj;
  352. }
  353. /**
  354. * Maps an external key to its (newly created) value
  355. */
  356. protected function ResolveExternalKeys()
  357. {
  358. foreach($this->m_aObjectsCache as $sClass => $oObjList)
  359. {
  360. foreach($oObjList as $oTargetObj)
  361. {
  362. $bChanged = false;
  363. $sClass = get_class($oTargetObj);
  364. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  365. {
  366. if ( ($oAttDef->IsExternalKey()) && ($oTargetObj->Get($sAttCode) < 0) ) // Convention unresolved key = negative
  367. {
  368. $sTargetClass = $oAttDef->GetTargetClass();
  369. $iTempKey = $oTargetObj->Get($sAttCode);
  370. $iExtKey = $this->GetObjectKey($sTargetClass, -$iTempKey);
  371. if ($iExtKey == 0)
  372. {
  373. $sMsg = "unresolved extkey in $sClass::".$oTargetObj->GetKey()."(".$oTargetObj->GetName().")::$sAttCode=$sTargetClass::$iTempKey";
  374. SetupPage::log_warning($sMsg);
  375. $this->m_aWarnings[] = $sMsg;
  376. //echo "<pre>aKeys[".$sTargetClass."]:\n";
  377. //print_r($this->m_aKeys[$sTargetClass]);
  378. //echo "</pre>\n";
  379. }
  380. else
  381. {
  382. $bChanged = true;
  383. $oTargetObj->Set($sAttCode, $iExtKey);
  384. }
  385. }
  386. }
  387. if ($bChanged)
  388. {
  389. try
  390. {
  391. if (is_subclass_of($oTargetObj, 'CMDBObject'))
  392. {
  393. $oTargetObj->DBUpdateTracked($this->m_oChange);
  394. }
  395. else
  396. {
  397. $oTargetObj->DBUpdate();
  398. }
  399. }
  400. catch(Exception $e)
  401. {
  402. $this->m_aErrors[] = "The object changes could not be tracked - $sClass/$iExtKey - ".$e->getMessage();
  403. }
  404. }
  405. }
  406. }
  407. return true;
  408. }
  409. }
  410. ?>