itopdesignformat.class.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. <?php
  2. // Copyright (C) 2014-2016 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. * Utility to upgrade the format of a given XML datamodel to the latest version
  20. * The datamodel is supplied as a loaded DOMDocument and modified in-place.
  21. *
  22. * Usage:
  23. *
  24. * $oDocument = new DOMDocument();
  25. * $oDocument->load($sXMLFile);
  26. * $oFormat = new iTopDesignFormat($oDocument);
  27. * if ($oFormat->Convert())
  28. * {
  29. * $oDocument->save($sXMLFile);
  30. * }
  31. * else
  32. * {
  33. * echo "Error, failed to upgrade the format, reason(s):\n".implode("\n", $oFormat->GetErrors());
  34. * }
  35. */
  36. define('ITOP_DESIGN_LATEST_VERSION', '1.3'); // iTop > 2.2.0
  37. class iTopDesignFormat
  38. {
  39. protected static $aVersions = array(
  40. '1.0' => array(
  41. 'previous' => null,
  42. 'go_to_previous' => null,
  43. 'next' => '1.1',
  44. 'go_to_next' => 'From10To11',
  45. ),
  46. '1.1' => array(
  47. 'previous' => '1.0',
  48. 'go_to_previous' => 'From11To10',
  49. 'next' => '1.2',
  50. 'go_to_next' => 'From11To12',
  51. ),
  52. '1.2' => array(
  53. 'previous' => '1.1',
  54. 'go_to_previous' => 'From12To11',
  55. 'next' => '1.3',
  56. 'go_to_next' => 'From12To13',
  57. ),
  58. '1.3' => array(
  59. 'previous' => '1.2',
  60. 'go_to_previous' => 'From13To12',
  61. 'next' => null,
  62. 'go_to_next' => null,
  63. ),
  64. );
  65. /**
  66. * The Document to work on
  67. * @var DOMDocument
  68. */
  69. protected $oDocument;
  70. /**
  71. * The log for the ongoing operation
  72. * @var DOMDocument
  73. */
  74. protected $aLog;
  75. protected $bStatus;
  76. /**
  77. * Creation from a loaded DOMDocument
  78. * @param DOMDocument $oDocument The document to transform
  79. */
  80. public function __construct(DOMDocument $oDocument)
  81. {
  82. $this->oDocument = $oDocument;
  83. }
  84. /**
  85. * Helper to fill the log structure
  86. * @param string $sMessage The error description
  87. */
  88. protected function LogError($sMessage)
  89. {
  90. $this->aLog[] = array(
  91. 'severity' => 'Error',
  92. 'msg' => $sMessage
  93. );
  94. $this->bStatus = false;
  95. }
  96. /**
  97. * Helper to fill the log structure
  98. * @param string $sMessage The error description
  99. */
  100. protected function LogWarning($sMessage)
  101. {
  102. $this->aLog[] = array(
  103. 'severity' => 'Warning',
  104. 'msg' => $sMessage
  105. );
  106. }
  107. /**
  108. * Helper to fill the log structure
  109. * @param string $sMessage The message
  110. */
  111. protected function LogInfo($sMessage)
  112. {
  113. $this->aLog[] = array(
  114. 'severity' => 'Info',
  115. 'msg' => $sMessage
  116. );
  117. }
  118. /**
  119. * Get all the errors in one single array
  120. */
  121. public function GetErrors()
  122. {
  123. $aErrors = array();
  124. foreach ($this->aLog as $aLogEntry)
  125. {
  126. if ($aLogEntry['severity'] == 'Error')
  127. {
  128. $aErrors[] = $aLogEntry['msg'];
  129. }
  130. }
  131. return $aErrors;
  132. }
  133. /**
  134. * Get all the warnings in one single array
  135. */
  136. public function GetWarnings()
  137. {
  138. $aErrors = array();
  139. foreach ($this->aLog as $aLogEntry)
  140. {
  141. if ($aLogEntry['severity'] == 'Warning')
  142. {
  143. $aErrors[] = $aLogEntry['msg'];
  144. }
  145. }
  146. return $aErrors;
  147. }
  148. /**
  149. * Get the whole log
  150. */
  151. public function GetLog()
  152. {
  153. return $this->aLog;
  154. }
  155. /**
  156. * An alternative to getNodePath, that gives the id of nodes instead of the position within the children
  157. */
  158. public static function GetItopNodePath($oNode)
  159. {
  160. if ($oNode instanceof DOMDocument) return '';
  161. $sId = $oNode->getAttribute('id');
  162. $sNodeDesc = ($sId != '') ? $oNode->nodeName.'['.$sId.']' : $oNode->nodeName;
  163. return self::GetItopNodePath($oNode->parentNode).'/'.$sNodeDesc;
  164. }
  165. /**
  166. * Test the conversion without altering the DOM
  167. *
  168. * @param string $sTargetVersion The desired version (or the latest possible version if not specified)
  169. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  170. * @return bool True on success
  171. */
  172. public function CheckConvert($sTargetVersion = ITOP_DESIGN_LATEST_VERSION, $oFactory = null)
  173. {
  174. // Clone the document
  175. $this->oDocument = $this->oDocument->cloneNode(true);
  176. return $this->Convert($sTargetVersion, $oFactory);
  177. }
  178. /**
  179. * Make adjustements to the DOM to migrate it to the specified version (default is latest)
  180. * For now only the conversion from version 1.0 to 1.1 is supported.
  181. *
  182. * @param string $sTargetVersion The desired version (or the latest possible version if not specified)
  183. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  184. * @return bool True on success, False if errors have been encountered (still the DOM may be altered!)
  185. */
  186. public function Convert($sTargetVersion = ITOP_DESIGN_LATEST_VERSION, $oFactory = null)
  187. {
  188. $this->aLog = array();
  189. $this->bStatus = true;
  190. $oXPath = new DOMXPath($this->oDocument);
  191. // Retrieve the version number
  192. $oNodeList = $oXPath->query('/itop_design');
  193. if ($oNodeList->length == 0)
  194. {
  195. // Hmm, not an iTop Data Model file...
  196. $this->LogError('File format, no root <itop_design> tag found');
  197. }
  198. else
  199. {
  200. $sVersion = $oNodeList->item(0)->getAttribute('version');
  201. if ($sVersion == '')
  202. {
  203. // Originaly, the information was missing: default to 1.0
  204. $sVersion = '1.0';
  205. }
  206. $this->LogInfo("Converting from $sVersion to $sTargetVersion");
  207. $this->DoConvert($sVersion, $sTargetVersion, $oFactory);
  208. if ($this->bStatus)
  209. {
  210. // Update the version number
  211. $oNodeList->item(0)->setAttribute('version', $sTargetVersion);
  212. }
  213. }
  214. return $this->bStatus;
  215. }
  216. /**
  217. * Does the conversion, eventually in a recursive manner
  218. *
  219. * @param string $sFrom The source format version
  220. * @param string $sTo The desired format version
  221. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  222. * @return bool True on success
  223. */
  224. protected function DoConvert($sFrom, $sTo, $oFactory = null)
  225. {
  226. if ($sFrom == $sTo)
  227. {
  228. return;
  229. }
  230. if (!array_key_exists($sFrom, self::$aVersions))
  231. {
  232. $this->LogError("Unknown source format version: $sFrom");
  233. return;
  234. }
  235. if (!array_key_exists($sTo, self::$aVersions))
  236. {
  237. $this->LogError("Unknown target format version: $sTo");
  238. return; // unknown versions are not supported
  239. }
  240. $aVersionIds = array_keys(self::$aVersions);
  241. $iFrom = array_search($sFrom, $aVersionIds);
  242. $iTo = array_search($sTo, $aVersionIds);
  243. if ($iFrom < $iTo)
  244. {
  245. // This is an upgrade
  246. $sIntermediate = self::$aVersions[$sFrom]['next'];
  247. $sTransform = self::$aVersions[$sFrom]['go_to_next'];
  248. $this->LogInfo("Upgrading from $sFrom to $sIntermediate ($sTransform)");
  249. }
  250. else
  251. {
  252. // This is a downgrade
  253. $sIntermediate = self::$aVersions[$sFrom]['previous'];
  254. $sTransform = self::$aVersions[$sFrom]['go_to_previous'];
  255. $this->LogInfo("Downgrading from $sFrom to $sIntermediate ($sTransform)");
  256. }
  257. // Transform to the intermediate format
  258. $aCallSpec = array($this, $sTransform);
  259. try
  260. {
  261. call_user_func($aCallSpec, $oFactory);
  262. // Recurse
  263. $this->DoConvert($sIntermediate, $sTo, $oFactory);
  264. }
  265. catch (Exception $e)
  266. {
  267. $this->LogError($e->getMessage());
  268. }
  269. return;
  270. }
  271. /**
  272. * Upgrade the format from version 1.0 to 1.1
  273. * @return void (Errors are logged)
  274. */
  275. protected function From10To11($oFactory)
  276. {
  277. // Adjust the XML to transparently add an id (=stimulus) on all life-cycle transitions
  278. // which don't already have one
  279. $oXPath = new DOMXPath($this->oDocument);
  280. $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition/stimulus');
  281. foreach ($oNodeList as $oNode)
  282. {
  283. $oNode->parentNode->SetAttribute('id', $oNode->textContent);
  284. $this->DeleteNode($oNode);
  285. }
  286. // Adjust the XML to transparently add an id (=percent) on all thresholds of stopwatches
  287. // which don't already have one
  288. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold/percent");
  289. foreach ($oNodeList as $oNode)
  290. {
  291. $oNode->parentNode->SetAttribute('id', $oNode->textContent);
  292. $this->DeleteNode($oNode);
  293. }
  294. // Adjust the XML to transparently add an id (=action:<type>) on all allowed actions (profiles)
  295. // which don't already have one
  296. $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action');
  297. foreach ($oNodeList as $oNode)
  298. {
  299. if ($oNode->getAttribute('id') == '')
  300. {
  301. $oNode->SetAttribute('id', 'action:' . $oNode->getAttribute('xsi:type'));
  302. $oNode->removeAttribute('xsi:type');
  303. }
  304. elseif ($oNode->getAttribute('xsi:type') == 'stimulus')
  305. {
  306. $oNode->SetAttribute('id', 'stimulus:' . $oNode->getAttribute('id'));
  307. $oNode->removeAttribute('xsi:type');
  308. }
  309. }
  310. // Adjust the XML to transparently add an id (=value) on all values of an enum which don't already have one.
  311. // This enables altering an enum for just adding/removing one value, intead of redefining the whole list of values.
  312. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value");
  313. foreach ($oNodeList as $oNode)
  314. {
  315. if ($oNode->getAttribute('id') == '')
  316. {
  317. $oNode->SetAttribute('id', $oNode->textContent);
  318. }
  319. }
  320. }
  321. /**
  322. * Downgrade the format from version 1.1 to 1.0
  323. * @return void (Errors are logged)
  324. */
  325. protected function From11To10($oFactory)
  326. {
  327. // Move the id down to a stimulus node on all life-cycle transitions
  328. $oXPath = new DOMXPath($this->oDocument);
  329. $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition[@id]');
  330. foreach ($oNodeList as $oNode)
  331. {
  332. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  333. {
  334. $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode));
  335. }
  336. $oStimulus = $oNode->ownerDocument->createElement('stimulus', $oNode->getAttribute('id'));
  337. $oNode->appendChild($oStimulus);
  338. $oNode->removeAttribute('id');
  339. }
  340. // Move the id down to a percent node on all thresholds
  341. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold[@id]");
  342. foreach ($oNodeList as $oNode)
  343. {
  344. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  345. {
  346. $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode));
  347. }
  348. $oStimulus = $oNode->ownerDocument->createElement('percent', $oNode->getAttribute('id'));
  349. $oNode->appendChild($oStimulus);
  350. $oNode->removeAttribute('id');
  351. }
  352. // Restore the type and id on profile/actions
  353. $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action');
  354. foreach ($oNodeList as $oNode)
  355. {
  356. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  357. {
  358. $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode));
  359. }
  360. if (substr($oNode->getAttribute('id'), 0, strlen('action')) == 'action')
  361. {
  362. // The id has the form 'action:<action_code>'
  363. $sActionCode = substr($oNode->getAttribute('id'), strlen('action:'));
  364. $oNode->removeAttribute('id');
  365. $oNode->setAttribute('xsi:type', $sActionCode);
  366. }
  367. else
  368. {
  369. // The id has the form 'stimulus:<stimulus_code>'
  370. $sStimulusCode = substr($oNode->getAttribute('id'), strlen('stimulus:'));
  371. $oNode->setAttribute('id', $sStimulusCode);
  372. $oNode->setAttribute('xsi:type', 'stimulus');
  373. }
  374. }
  375. // Remove the id on all enum values
  376. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value[@id]");
  377. foreach ($oNodeList as $oNode)
  378. {
  379. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  380. {
  381. $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode));
  382. }
  383. $oNode->removeAttribute('id');
  384. }
  385. }
  386. /**
  387. * Upgrade the format from version 1.1 to 1.2
  388. * @return void (Errors are logged)
  389. */
  390. protected function From11To12($oFactory)
  391. {
  392. }
  393. /**
  394. * Downgrade the format from version 1.2 to 1.1
  395. * @return void (Errors are logged)
  396. */
  397. protected function From12To11($oFactory)
  398. {
  399. $oXPath = new DOMXPath($this->oDocument);
  400. // Transform ObjectKey attributes into Integer
  401. //
  402. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeObjectKey']");
  403. foreach ($oNodeList as $oNode)
  404. {
  405. $oNode->setAttribute('xsi:type', 'AttributeInteger');
  406. // The property class_attcode is left there (doing no harm)
  407. $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' has been degraded into an integer attribute. Any OQL query using this attribute will fail.');
  408. }
  409. // Remove Redundancy settings attributes (no redundancy could be defined in the previous format)
  410. //
  411. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeRedundancySettings']");
  412. foreach ($oNodeList as $oNode)
  413. {
  414. $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is of no use and must be removed.');
  415. $this->DeleteNode($oNode);
  416. }
  417. // Later: transform the relations into code (iif defined as an SQL query)
  418. $oNodeList = $oXPath->query('/itop_design/classes//class/relations');
  419. foreach ($oNodeList as $oNode)
  420. {
  421. $this->LogWarning('The relations defined in '.self::GetItopNodePath($oNode).' will be lost.');
  422. $this->DeleteNode($oNode);
  423. }
  424. $oNodeList = $oXPath->query('/itop_design/portal');
  425. foreach ($oNodeList as $oNode)
  426. {
  427. $this->LogWarning('Portal definition will be lost.');
  428. $this->DeleteNode($oNode);
  429. }
  430. $oNodeList = $oXPath->query('/itop_design/module_parameters');
  431. foreach ($oNodeList as $oNode)
  432. {
  433. $this->LogWarning('Module parameters will be lost.');
  434. $this->DeleteNode($oNode);
  435. }
  436. $oNodeList = $oXPath->query('/itop_design/snippets');
  437. foreach ($oNodeList as $oNode)
  438. {
  439. $this->LogWarning('Code snippets will be lost.');
  440. $this->DeleteNode($oNode);
  441. }
  442. }
  443. /**
  444. * Upgrade the format from version 1.2 to 1.3
  445. * @return void (Errors are logged)
  446. */
  447. protected function From12To13($oFactory)
  448. {
  449. }
  450. /**
  451. * Downgrade the format from version 1.3 to 1.2
  452. * @return void (Errors are logged)
  453. */
  454. protected function From13To12($oFactory)
  455. {
  456. $oXPath = new DOMXPath($this->oDocument);
  457. $oNodeList = $oXPath->query('/itop_design/module_designs/module_design');
  458. foreach ($oNodeList as $oNode)
  459. {
  460. $this->LogWarning('The module design defined in '.self::GetItopNodePath($oNode).' will be lost.');
  461. $this->DeleteNode($oNode);
  462. }
  463. // Remove MetaEnum attributes
  464. //
  465. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeMetaEnum']");
  466. foreach ($oNodeList as $oNode)
  467. {
  468. $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is irrelevant and must be removed.');
  469. $this->DeleteNode($oNode);
  470. }
  471. // Remove CustomFields attributes
  472. //
  473. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeCustomFields']");
  474. foreach ($oNodeList as $oNode)
  475. {
  476. $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is irrelevant and must be removed.');
  477. $this->DeleteNode($oNode);
  478. }
  479. }
  480. /**
  481. * Delete a node from the DOM and make sure to also remove the immediately following line break (DOMText), if any.
  482. * This prevents generating empty lines in the middle of the XML
  483. * @param DOMNode $oNode
  484. */
  485. protected function DeleteNode($oNode)
  486. {
  487. if ( $oNode->nextSibling && ($oNode->nextSibling instanceof DOMText) && ($oNode->nextSibling->isWhitespaceInElementContent()) )
  488. {
  489. $oNode->parentNode->removeChild($oNode->nextSibling);
  490. }
  491. $oNode->parentNode->removeChild($oNode);
  492. }
  493. }