xmldataloader.class.inc.php 12 KB

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