itopdesignformat.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. // Copyright (C) 2014 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.1');
  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' => null,
  50. 'go_to_next' => null,
  51. ),
  52. );
  53. /**
  54. * The Document to work on
  55. * @var DOMDocument
  56. */
  57. protected $oDocument;
  58. /**
  59. * The log for the ongoing operation
  60. * @var DOMDocument
  61. */
  62. protected $aLog;
  63. protected $bStatus;
  64. /**
  65. * Creation from a loaded DOMDocument
  66. * @param DOMDocument $oDocument The document to transform
  67. */
  68. public function __construct(DOMDocument $oDocument)
  69. {
  70. $this->oDocument = $oDocument;
  71. }
  72. /**
  73. * Helper to fill the log structure
  74. * @param string $sMessage The error description
  75. */
  76. protected function LogError($sMessage)
  77. {
  78. $this->aLog[] = array(
  79. 'severity' => 'Error',
  80. 'msg' => $sMessage
  81. );
  82. $this->bStatus = false;
  83. }
  84. /**
  85. * Helper to fill the log structure
  86. * @param string $sMessage The message
  87. */
  88. protected function LogInfo($sMessage)
  89. {
  90. $this->aLog[] = array(
  91. 'severity' => 'Info',
  92. 'msg' => $sMessage
  93. );
  94. }
  95. /**
  96. * Get all the errors in one single line
  97. */
  98. public function GetErrors()
  99. {
  100. $aErrors = array();
  101. foreach ($this->aLog as $aLogEntry)
  102. {
  103. if ($aLogEntry['severity'] == 'Error')
  104. {
  105. $aErrors[] = $aLogEntry['msg'];
  106. }
  107. }
  108. return $aErrors;
  109. }
  110. /**
  111. * Get the whole log
  112. */
  113. public function GetLog()
  114. {
  115. return $this->aLog;
  116. }
  117. /**
  118. * Test the conversion without altering the DOM
  119. *
  120. * @param string $sTargetVersion The desired version (or the latest possible version if not specified)
  121. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  122. * @return bool True on success
  123. */
  124. public function CheckConvert($sTargetVersion = ITOP_DESIGN_LATEST_VERSION, $oFactory = null)
  125. {
  126. // Clone the document
  127. $this->oDocument = $this->oDocument->cloneNode(true);
  128. return $this->Convert($sTargetVersion, $oFactory);
  129. }
  130. /**
  131. * Make adjustements to the DOM to migrate it to the specified version (default is latest)
  132. * For now only the conversion from version 1.0 to 1.1 is supported.
  133. *
  134. * @param string $sTargetVersion The desired version (or the latest possible version if not specified)
  135. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  136. * @return bool True on success, False if errors have been encountered (still the DOM may be altered!)
  137. */
  138. public function Convert($sTargetVersion = ITOP_DESIGN_LATEST_VERSION, $oFactory = null)
  139. {
  140. $this->aLog = array();
  141. $this->bStatus = true;
  142. $oXPath = new DOMXPath($this->oDocument);
  143. // Retrieve the version number
  144. $oNodeList = $oXPath->query('/itop_design');
  145. if ($oNodeList->length == 0)
  146. {
  147. // Hmm, not an iTop Data Model file...
  148. $this->LogError('File format, no root <itop_design> tag found');
  149. }
  150. else
  151. {
  152. $sVersion = $oNodeList->item(0)->getAttribute('version');
  153. if ($sVersion == '')
  154. {
  155. // Originaly, the information was missing: default to 1.0
  156. $sVersion = '1.0';
  157. }
  158. $this->LogInfo("Converting from $sVersion to $sTargetVersion");
  159. $this->DoConvert($sVersion, $sTargetVersion, $oFactory);
  160. if ($this->bStatus)
  161. {
  162. // Update the version number
  163. $oNodeList->item(0)->setAttribute('version', $sTargetVersion);
  164. }
  165. }
  166. return $this->bStatus;
  167. }
  168. /**
  169. * Does the conversion, eventually in a recursive manner
  170. *
  171. * @param string $sFrom The source format version
  172. * @param string $sTo The desired format version
  173. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  174. * @return bool True on success
  175. */
  176. protected function DoConvert($sFrom, $sTo, $oFactory = null)
  177. {
  178. if ($sFrom == $sTo)
  179. {
  180. return;
  181. }
  182. if (!array_key_exists($sFrom, self::$aVersions))
  183. {
  184. $this->LogError("Unknown source format version: $sFrom");
  185. return;
  186. }
  187. if (!array_key_exists($sTo, self::$aVersions))
  188. {
  189. $this->LogError("Unknown target format version: $sTo");
  190. return; // unknown versions are not supported
  191. }
  192. $aVersionIds = array_keys(self::$aVersions);
  193. $iFrom = array_search($sFrom, $aVersionIds);
  194. $iTo = array_search($sTo, $aVersionIds);
  195. if ($iFrom < $iTo)
  196. {
  197. // This is an upgrade
  198. $sIntermediate = self::$aVersions[$sFrom]['next'];
  199. $sTransform = self::$aVersions[$sFrom]['go_to_next'];
  200. $this->LogInfo("Upgrading from $sFrom to $sIntermediate ($sTransform)");
  201. }
  202. else
  203. {
  204. // This is a downgrade
  205. $sIntermediate = self::$aVersions[$sFrom]['previous'];
  206. $sTransform = self::$aVersions[$sFrom]['go_to_previous'];
  207. $this->LogInfo("Downgrading from $sFrom to $sIntermediate ($sTransform)");
  208. }
  209. // Transform to the intermediate format
  210. $aCallSpec = array($this, $sTransform);
  211. try
  212. {
  213. call_user_func($aCallSpec, $oFactory);
  214. // Recurse
  215. $this->DoConvert($sIntermediate, $sTo, $oFactory);
  216. }
  217. catch (Exception $e)
  218. {
  219. $this->LogError($e->getMessage());
  220. }
  221. return;
  222. }
  223. /**
  224. * Upgrade the format from version 1.0 to 1.1
  225. * @return void (Errors are logged)
  226. */
  227. protected function From10To11($oFactory)
  228. {
  229. // Adjust the XML to transparently add an id (=stimulus) on all life-cycle transitions
  230. // which don't already have one
  231. $oXPath = new DOMXPath($this->oDocument);
  232. $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition/stimulus');
  233. foreach ($oNodeList as $oNode)
  234. {
  235. $oNode->parentNode->SetAttribute('id', $oNode->textContent);
  236. $this->DeleteNode($oNode);
  237. }
  238. // Adjust the XML to transparently add an id (=percent) on all thresholds of stopwatches
  239. // which don't already have one
  240. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold/percent");
  241. foreach ($oNodeList as $oNode)
  242. {
  243. $oNode->parentNode->SetAttribute('id', $oNode->textContent);
  244. $this->DeleteNode($oNode);
  245. }
  246. // Adjust the XML to transparently add an id (=action:<type>) on all allowed actions (profiles)
  247. // which don't already have one
  248. $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action');
  249. foreach ($oNodeList as $oNode)
  250. {
  251. if ($oNode->getAttribute('id') == '')
  252. {
  253. $oNode->SetAttribute('id', 'action:' . $oNode->getAttribute('xsi:type'));
  254. $oNode->removeAttribute('xsi:type');
  255. }
  256. elseif ($oNode->getAttribute('xsi:type') == 'stimulus')
  257. {
  258. $oNode->SetAttribute('id', 'stimulus:' . $oNode->getAttribute('id'));
  259. $oNode->removeAttribute('xsi:type');
  260. }
  261. }
  262. // Adjust the XML to transparently add an id (=value) on all values of an enum which don't already have one.
  263. // This enables altering an enum for just adding/removing one value, intead of redefining the whole list of values.
  264. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value");
  265. foreach ($oNodeList as $oNode)
  266. {
  267. if ($oNode->getAttribute('id') == '')
  268. {
  269. $oNode->SetAttribute('id', $oNode->textContent);
  270. }
  271. }
  272. }
  273. /**
  274. * Downgrade the format from version 1.1 to 1.0
  275. * @return void (Errors are logged)
  276. */
  277. protected function From11To10($oFactory)
  278. {
  279. // Move the id down to a stimulus node on all life-cycle transitions
  280. $oXPath = new DOMXPath($this->oDocument);
  281. $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition[@id]');
  282. foreach ($oNodeList as $oNode)
  283. {
  284. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  285. {
  286. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  287. }
  288. $oStimulus = $oNode->ownerDocument->createElement('stimulus', $oNode->getAttribute('id'));
  289. $oNode->appendChild($oStimulus);
  290. $oNode->removeAttribute('id');
  291. }
  292. // Move the id down to a percent node on all thresholds
  293. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold[@id]");
  294. foreach ($oNodeList as $oNode)
  295. {
  296. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  297. {
  298. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  299. }
  300. $oStimulus = $oNode->ownerDocument->createElement('percent', $oNode->getAttribute('id'));
  301. $oNode->appendChild($oStimulus);
  302. $oNode->removeAttribute('id');
  303. }
  304. // Restore the type and id on profile/actions
  305. $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action');
  306. foreach ($oNodeList as $oNode)
  307. {
  308. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  309. {
  310. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  311. }
  312. if (substr($oNode->getAttribute('id'), 0, strlen('action')) == 'action')
  313. {
  314. // The id has the form 'action:<action_code>'
  315. $sActionCode = substr($oNode->getAttribute('id'), strlen('action:'));
  316. $oNode->removeAttribute('id');
  317. $oNode->setAttribute('xsi:type', $sActionCode);
  318. }
  319. else
  320. {
  321. // The id has the form 'stimulus:<stimulus_code>'
  322. $sStimulusCode = substr($oNode->getAttribute('id'), strlen('stimulus:'));
  323. $oNode->setAttribute('id', $sStimulusCode);
  324. $oNode->setAttribute('xsi:type', 'stimulus');
  325. }
  326. }
  327. // Remove the id on all enum values
  328. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value[@id]");
  329. foreach ($oNodeList as $oNode)
  330. {
  331. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  332. {
  333. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  334. }
  335. $oNode->removeAttribute('id');
  336. }
  337. }
  338. /**
  339. * Delete a node from the DOM and make sure to also remove the immediately following line break (DOMText), if any.
  340. * This prevents generating empty lines in the middle of the XML
  341. * @param DOMNode $oNode
  342. */
  343. protected function DeleteNode($oNode)
  344. {
  345. if ( $oNode->nextSibling && ($oNode->nextSibling instanceof DOMText) && ($oNode->nextSibling->isWhitespaceInElementContent()) )
  346. {
  347. $oNode->parentNode->removeChild($oNode->nextSibling);
  348. }
  349. $oNode->parentNode->removeChild($oNode);
  350. }
  351. }