itopdesignformat.class.inc.php 15 KB

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