xmldataloader.class.inc.php 12 KB

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