xmldataloader.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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', APPROOT.'/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. $hFile = @fopen($this->m_sCacheFileName, 'w');
  111. if ($hFile !== false)
  112. {
  113. $sData = serialize( array('keys' => $this->m_aKeys,
  114. 'objects' => $this->m_aObjectsCache,
  115. 'change' => $this->m_oChange,
  116. 'errors' => $this->m_aErrors,
  117. 'warnings' => $this->m_aWarnings,
  118. ));
  119. fwrite($hFile, $sData);
  120. fclose($hFile);
  121. }
  122. else
  123. {
  124. throw new Exception("Cannot write to file: '{$this->m_sCacheFileName}'");
  125. }
  126. }
  127. /**
  128. * Loads the keys & object cache from the tmp file
  129. */
  130. protected function LoadKeysCache()
  131. {
  132. $sFileContent = @file_get_contents($this->m_sCacheFileName);
  133. if (!empty($sFileContent))
  134. {
  135. $aCache = unserialize($sFileContent);
  136. $this->m_aKeys = $aCache['keys'];
  137. $this->m_aObjectsCache = $aCache['objects'];
  138. $this->m_oChange = $aCache['change'];
  139. $this->m_aErrors = $aCache['errors'];
  140. $this->m_aWarnings = $aCache['warnings'];
  141. }
  142. }
  143. /**
  144. * Remove the tmp file used to store the keys cache
  145. */
  146. protected function ClearKeysCache()
  147. {
  148. if(is_file($this->m_sCacheFileName))
  149. {
  150. unlink($this->m_sCacheFileName);
  151. }
  152. else
  153. {
  154. //echo "<p>Hm, it looks like the file does not exist!!!</p>";
  155. }
  156. $this->m_aKeys = array();
  157. $this->m_aObjectsCache = array();
  158. }
  159. /**
  160. * Helper function to load the objects from a standard XML file into the database
  161. */
  162. function LoadFile($sFilePath)
  163. {
  164. global $aKeys;
  165. $oXml = simplexml_load_file($sFilePath);
  166. $aReplicas = array();
  167. foreach($oXml as $sClass => $oXmlObj)
  168. {
  169. if (!MetaModel::IsValidClass($sClass))
  170. {
  171. SetupWebPage::log_error("Unknown class - $sClass");
  172. throw(new Exception("Unknown class - $sClass"));
  173. }
  174. $iSrcId = (integer)$oXmlObj['id']; // Mandatory to cast
  175. // Import algorithm
  176. // Here enumerate all the attributes of the object
  177. // for all attribute that is neither an external field
  178. // not an external key, assign it
  179. // Store all external keys for further reference
  180. // Create the object an store the correspondance between its newly created Id
  181. // and its original Id
  182. // Once all the objects have been created re-assign all the external keys to
  183. // their actual Ids
  184. $oTargetObj = MetaModel::NewObject($sClass);
  185. foreach($oXmlObj as $sAttCode => $oSubNode)
  186. {
  187. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  188. {
  189. $sMsg = "Unknown attribute code - $sClass/$sAttCode";
  190. SetupWebPage::log_error($sMsg);
  191. throw(new Exception($sMsg));
  192. }
  193. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  194. if (($oAttDef->IsWritable()) && ($oAttDef->IsScalar()))
  195. {
  196. if ($oAttDef->IsExternalKey())
  197. {
  198. if (substr(trim($oSubNode), 0, 6) == 'SELECT')
  199. {
  200. $sQuery = trim($oSubNode);
  201. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sQuery));
  202. $iMatches = $oSet->Count();
  203. if ($iMatches == 1)
  204. {
  205. $oFoundObject = $oSet->Fetch();
  206. $iExtKey = $oFoundObject->GetKey();
  207. }
  208. else
  209. {
  210. $sMsg = "Ext key not reconcilied - $sClass/$iSrcId - $sAttCode: '".$sQuery."' - found $iMatches matche(s)";
  211. SetupWebPage::log_error($sMsg);
  212. $this->m_aErrors[] = $sMsg;
  213. $iExtKey = 0;
  214. }
  215. }
  216. else
  217. {
  218. $iDstObj = (integer)($oSubNode);
  219. // Attempt to find the object in the list of loaded objects
  220. $iExtKey = $this->GetObjectKey($oAttDef->GetTargetClass(), $iDstObj);
  221. if ($iExtKey == 0)
  222. {
  223. $iExtKey = -$iDstObj; // Convention: Unresolved keys are stored as negative !
  224. $oTargetObj->RegisterAsDirty();
  225. }
  226. // here we allow external keys to be invalid because we will resolve them later on...
  227. }
  228. //$oTargetObj->CheckValue($sAttCode, $iExtKey);
  229. $oTargetObj->Set($sAttCode, $iExtKey);
  230. }
  231. elseif ($oAttDef instanceof AttributeBlob)
  232. {
  233. $sMimeType = (string) $oSubNode->mimetype;
  234. $sFileName = (string) $oSubNode->filename;
  235. $data = base64_decode((string) $oSubNode->data);
  236. $oDoc = new ormDocument($data, $sMimeType, $sFileName);
  237. $oTargetObj->Set($sAttCode, $oDoc);
  238. }
  239. else
  240. {
  241. $value = (string)$oSubNode;
  242. if ($value == '')
  243. {
  244. $value = $oAttDef->GetNullValue();
  245. }
  246. $res = $oTargetObj->CheckValue($sAttCode, $value);
  247. if ($res !== true)
  248. {
  249. // $res contains the error description
  250. $sMsg = "Value not allowed - $sClass/$iSrcId - $sAttCode: '".$oSubNode."' ; $res";
  251. SetupWebPage::log_error($sMsg);
  252. $this->m_aErrors[] = $sMsg;
  253. }
  254. $oTargetObj->Set($sAttCode, $value);
  255. }
  256. }
  257. }
  258. $this->StoreObject($sClass, $oTargetObj, $iSrcId);
  259. }
  260. return true;
  261. }
  262. /**
  263. * Get the new ID of an object in the database given its original ID
  264. * This may fail (return 0) if the object has not yet been created in the database
  265. * This is why the order of the import may be important
  266. */
  267. protected function GetObjectKey($sClass, $iSrcId)
  268. {
  269. if (isset($this->m_aKeys[$sClass]) && isset($this->m_aKeys[$sClass][$iSrcId]))
  270. {
  271. return $this->m_aKeys[$sClass][$iSrcId];
  272. }
  273. return 0;
  274. }
  275. /**
  276. * Store an object in the database and remember the mapping
  277. * between its original ID and the newly created ID in the database
  278. */
  279. protected function StoreObject($sClass, $oTargetObj, $iSrcId, $bSearch = false)
  280. {
  281. $iObjId = 0;
  282. try
  283. {
  284. if ($bSearch)
  285. {
  286. // Check if the object does not already exist, based on its usual reconciliation keys...
  287. $aReconciliationKeys = MetaModel::GetReconcKeys($sClass);
  288. if (count($aReconciliationKeys) > 0)
  289. {
  290. // Some reconciliation keys have been defined, use them to search for the object
  291. $oSearch = new DBObjectSearch($sClass);
  292. $iConditionsCount = 0;
  293. foreach($aReconciliationKeys as $sAttCode)
  294. {
  295. if ($oTargetObj->Get($sAttCode) != '')
  296. {
  297. $oSearch->AddCondition($sAttCode, $oTargetObj->Get($sAttCode), '=');
  298. $iConditionsCount++;
  299. }
  300. }
  301. if ($iConditionsCount > 0) // Search only if there are some valid conditions...
  302. {
  303. $oSet = new DBObjectSet($oSearch);
  304. if ($oSet->count() == 1)
  305. {
  306. // The object already exists, reuse it
  307. $oExistingObject = $oSet->Fetch();
  308. $iObjId = $oExistingObject->GetKey();
  309. }
  310. }
  311. }
  312. }
  313. if ($iObjId == 0)
  314. {
  315. // No similar object found for sure, let's create it
  316. if (is_subclass_of($oTargetObj, 'CMDBObject'))
  317. {
  318. $iObjId = $oTargetObj->DBInsertTrackedNoReload($this->m_oChange);
  319. }
  320. else
  321. {
  322. $iObjId = $oTargetObj->DBInsertNoReload();
  323. }
  324. $this->m_iCountCreated++;
  325. }
  326. }
  327. catch(Exception $e)
  328. {
  329. SetupWebPage::log_error("An object could not be recorded - $sClass/$iSrcId - ".$e->getMessage());
  330. $this->m_aErrors[] = "An object could not be recorded - $sClass/$iSrcId - ".$e->getMessage();
  331. }
  332. $aParentClasses = MetaModel::EnumParentClasses($sClass);
  333. $aParentClasses[] = $sClass;
  334. foreach($aParentClasses as $sObjClass)
  335. {
  336. $this->m_aKeys[$sObjClass][$iSrcId] = $iObjId;
  337. }
  338. $this->m_aObjectsCache[$sClass][$iObjId] = $oTargetObj;
  339. }
  340. /**
  341. * Maps an external key to its (newly created) value
  342. */
  343. protected function ResolveExternalKeys()
  344. {
  345. foreach($this->m_aObjectsCache as $sClass => $oObjList)
  346. {
  347. foreach($oObjList as $oTargetObj)
  348. {
  349. $bChanged = false;
  350. $sClass = get_class($oTargetObj);
  351. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  352. {
  353. if ( ($oAttDef->IsExternalKey()) && ($oTargetObj->Get($sAttCode) < 0) ) // Convention unresolved key = negative
  354. {
  355. $sTargetClass = $oAttDef->GetTargetClass();
  356. $iTempKey = $oTargetObj->Get($sAttCode);
  357. $iExtKey = $this->GetObjectKey($sTargetClass, -$iTempKey);
  358. if ($iExtKey == 0)
  359. {
  360. $sMsg = "unresolved extkey in $sClass::".$oTargetObj->GetKey()."(".$oTargetObj->GetName().")::$sAttCode=$sTargetClass::$iTempKey";
  361. SetupWebPage::log_warning($sMsg);
  362. $this->m_aWarnings[] = $sMsg;
  363. //echo "<pre>aKeys[".$sTargetClass."]:\n";
  364. //print_r($this->m_aKeys[$sTargetClass]);
  365. //echo "</pre>\n";
  366. }
  367. else
  368. {
  369. $bChanged = true;
  370. $oTargetObj->Set($sAttCode, $iExtKey);
  371. }
  372. }
  373. }
  374. if ($bChanged)
  375. {
  376. try
  377. {
  378. if (is_subclass_of($oTargetObj, 'CMDBObject'))
  379. {
  380. $oTargetObj->DBUpdateTracked($this->m_oChange);
  381. }
  382. else
  383. {
  384. $oTargetObj->DBUpdate();
  385. }
  386. }
  387. catch(Exception $e)
  388. {
  389. $this->m_aErrors[] = "The object changes could not be tracked - $sClass/$iSrcId - ".$e->getMessage();
  390. }
  391. }
  392. }
  393. }
  394. return true;
  395. }
  396. }
  397. ?>