itopdesignformat.class.inc.php 18 KB

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