xmldataloader.class.inc.php 13 KB

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