xmldataloader.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. * @param $sFilePath string The full path to the XML file to load
  166. * @param $bUpdateKeyCacheOnly bool Set to true to *just* update the keys cache but not reload the objects
  167. */
  168. function LoadFile($sFilePath, $bUpdateKeyCacheOnly = false)
  169. {
  170. global $aKeys;
  171. $oXml = simplexml_load_file($sFilePath);
  172. $aReplicas = array();
  173. foreach($oXml as $sClass => $oXmlObj)
  174. {
  175. if (!MetaModel::IsValidClass($sClass))
  176. {
  177. SetupPage::log_error("Unknown class - $sClass");
  178. throw(new Exception("Unknown class - $sClass"));
  179. }
  180. $iSrcId = (integer)$oXmlObj['id']; // Mandatory to cast
  181. // Import algorithm
  182. // Here enumerate all the attributes of the object
  183. // for all attribute that is neither an external field
  184. // not an external key, assign it
  185. // Store all external keys for further reference
  186. // Create the object an store the correspondance between its newly created Id
  187. // and its original Id
  188. // Once all the objects have been created re-assign all the external keys to
  189. // their actual Ids
  190. $iExistingId = $this->GetObjectKey($sClass, $iSrcId);
  191. if ($iExistingId != 0)
  192. {
  193. $oTargetObj = MetaModel::GetObject($sClass, $iExistingId);
  194. }
  195. else
  196. {
  197. $oTargetObj = MetaModel::NewObject($sClass);
  198. }
  199. foreach($oXmlObj as $sAttCode => $oSubNode)
  200. {
  201. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  202. {
  203. $sMsg = "Unknown attribute code - $sClass/$sAttCode";
  204. continue; // ignore silently...
  205. //SetupPage::log_error($sMsg);
  206. //throw(new Exception($sMsg));
  207. }
  208. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  209. if (($oAttDef->IsWritable()) && ($oAttDef->IsScalar()))
  210. {
  211. if ($oAttDef->IsExternalKey())
  212. {
  213. if (substr(trim($oSubNode), 0, 6) == 'SELECT')
  214. {
  215. $sQuery = trim($oSubNode);
  216. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sQuery));
  217. $iMatches = $oSet->Count();
  218. if ($iMatches == 1)
  219. {
  220. $oFoundObject = $oSet->Fetch();
  221. $iExtKey = $oFoundObject->GetKey();
  222. }
  223. else
  224. {
  225. $sMsg = "Ext key not reconcilied - $sClass/$iSrcId - $sAttCode: '".$sQuery."' - found $iMatches matche(s)";
  226. SetupPage::log_error($sMsg);
  227. $this->m_aErrors[] = $sMsg;
  228. $iExtKey = 0;
  229. }
  230. }
  231. else
  232. {
  233. $iDstObj = (integer)($oSubNode);
  234. // Attempt to find the object in the list of loaded objects
  235. $iExtKey = $this->GetObjectKey($oAttDef->GetTargetClass(), $iDstObj);
  236. if ($iExtKey == 0)
  237. {
  238. $iExtKey = -$iDstObj; // Convention: Unresolved keys are stored as negative !
  239. $oTargetObj->RegisterAsDirty();
  240. }
  241. // here we allow external keys to be invalid because we will resolve them later on...
  242. }
  243. //$oTargetObj->CheckValue($sAttCode, $iExtKey);
  244. $oTargetObj->Set($sAttCode, $iExtKey);
  245. }
  246. elseif ($oAttDef instanceof AttributeBlob)
  247. {
  248. $sMimeType = (string) $oSubNode->mimetype;
  249. $sFileName = (string) $oSubNode->filename;
  250. $data = base64_decode((string) $oSubNode->data);
  251. $oDoc = new ormDocument($data, $sMimeType, $sFileName);
  252. $oTargetObj->Set($sAttCode, $oDoc);
  253. }
  254. else
  255. {
  256. $value = (string)$oSubNode;
  257. if ($value == '')
  258. {
  259. $value = $oAttDef->GetNullValue();
  260. }
  261. $res = $oTargetObj->CheckValue($sAttCode, $value);
  262. if ($res !== true)
  263. {
  264. // $res contains the error description
  265. $sMsg = "Value not allowed - $sClass/$iSrcId - $sAttCode: '".$oSubNode."' ; $res";
  266. SetupPage::log_error($sMsg);
  267. $this->m_aErrors[] = $sMsg;
  268. }
  269. $oTargetObj->Set($sAttCode, $value);
  270. }
  271. }
  272. }
  273. $this->StoreObject($sClass, $oTargetObj, $iSrcId, $bUpdateKeyCacheOnly, $bUpdateKeyCacheOnly);
  274. }
  275. return true;
  276. }
  277. /**
  278. * Get the new ID of an object in the database given its original ID
  279. * This may fail (return 0) if the object has not yet been created in the database
  280. * This is why the order of the import may be important
  281. */
  282. protected function GetObjectKey($sClass, $iSrcId)
  283. {
  284. if (isset($this->m_aKeys[$sClass]) && isset($this->m_aKeys[$sClass][$iSrcId]))
  285. {
  286. return $this->m_aKeys[$sClass][$iSrcId];
  287. }
  288. return 0;
  289. }
  290. /**
  291. * Store an object in the database and remember the mapping
  292. * between its original ID and the newly created ID in the database
  293. */
  294. protected function StoreObject($sClass, $oTargetObj, $iSrcId, $bSearch = false, $bUpdateKeyCacheOnly = false)
  295. {
  296. $iObjId = 0;
  297. try
  298. {
  299. if ($bSearch)
  300. {
  301. // Check if the object does not already exist, based on its usual reconciliation keys...
  302. $aReconciliationKeys = MetaModel::GetReconcKeys($sClass);
  303. if (count($aReconciliationKeys) > 0)
  304. {
  305. // Some reconciliation keys have been defined, use them to search for the object
  306. $oSearch = new DBObjectSearch($sClass);
  307. $iConditionsCount = 0;
  308. foreach($aReconciliationKeys as $sAttCode)
  309. {
  310. if ($oTargetObj->Get($sAttCode) != '')
  311. {
  312. $oSearch->AddCondition($sAttCode, $oTargetObj->Get($sAttCode), '=');
  313. $iConditionsCount++;
  314. }
  315. }
  316. if ($iConditionsCount > 0) // Search only if there are some valid conditions...
  317. {
  318. $oSet = new DBObjectSet($oSearch);
  319. if ($oSet->count() == 1)
  320. {
  321. // The object already exists, reuse it
  322. $oExistingObject = $oSet->Fetch();
  323. $iObjId = $oExistingObject->GetKey();
  324. }
  325. }
  326. }
  327. }
  328. if ($iObjId == 0)
  329. {
  330. if($oTargetObj->IsNew())
  331. {
  332. if (!$bUpdateKeyCacheOnly)
  333. {
  334. $iObjId = $oTargetObj->DBInsertNoReload();
  335. $this->m_iCountCreated++;
  336. }
  337. }
  338. else
  339. {
  340. $iObjId = $oTargetObj->GetKey();
  341. if (!$bUpdateKeyCacheOnly)
  342. {
  343. $oTargetObj->DBUpdate();
  344. }
  345. }
  346. }
  347. }
  348. catch(Exception $e)
  349. {
  350. SetupPage::log_error("An object could not be recorded - $sClass/$iSrcId - ".$e->getMessage());
  351. $this->m_aErrors[] = "An object could not be recorded - $sClass/$iSrcId - ".$e->getMessage();
  352. }
  353. $aParentClasses = MetaModel::EnumParentClasses($sClass);
  354. $aParentClasses[] = $sClass;
  355. foreach($aParentClasses as $sObjClass)
  356. {
  357. $this->m_aKeys[$sObjClass][$iSrcId] = $iObjId;
  358. }
  359. $this->m_aObjectsCache[$sClass][$iObjId] = $oTargetObj;
  360. }
  361. /**
  362. * Maps an external key to its (newly created) value
  363. */
  364. protected function ResolveExternalKeys()
  365. {
  366. foreach($this->m_aObjectsCache as $sClass => $oObjList)
  367. {
  368. foreach($oObjList as $oTargetObj)
  369. {
  370. $bChanged = false;
  371. $sClass = get_class($oTargetObj);
  372. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  373. {
  374. if ( ($oAttDef->IsExternalKey()) && ($oTargetObj->Get($sAttCode) < 0) ) // Convention unresolved key = negative
  375. {
  376. $sTargetClass = $oAttDef->GetTargetClass();
  377. $iTempKey = $oTargetObj->Get($sAttCode);
  378. $iExtKey = $this->GetObjectKey($sTargetClass, -$iTempKey);
  379. if ($iExtKey == 0)
  380. {
  381. $sMsg = "unresolved extkey in $sClass::".$oTargetObj->GetKey()."(".$oTargetObj->GetName().")::$sAttCode=$sTargetClass::$iTempKey";
  382. SetupPage::log_warning($sMsg);
  383. $this->m_aWarnings[] = $sMsg;
  384. //echo "<pre>aKeys[".$sTargetClass."]:\n";
  385. //print_r($this->m_aKeys[$sTargetClass]);
  386. //echo "</pre>\n";
  387. }
  388. else
  389. {
  390. $bChanged = true;
  391. $oTargetObj->Set($sAttCode, $iExtKey);
  392. }
  393. }
  394. }
  395. if ($bChanged)
  396. {
  397. try
  398. {
  399. if (is_subclass_of($oTargetObj, 'CMDBObject'))
  400. {
  401. $oTargetObj->DBUpdateTracked($this->m_oChange);
  402. }
  403. else
  404. {
  405. $oTargetObj->DBUpdate();
  406. }
  407. }
  408. catch(Exception $e)
  409. {
  410. $this->m_aErrors[] = "The object changes could not be tracked - $sClass/$iExtKey - ".$e->getMessage();
  411. }
  412. }
  413. }
  414. }
  415. return true;
  416. }
  417. }
  418. ?>