xmldataloader.class.inc.php 13 KB

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