itopdesignformat.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. $this->LogInfo("Converting from $sVersion to $sTargetVersion");
  154. $this->DoConvert($sVersion, $sTargetVersion, $oFactory);
  155. if ($this->bStatus)
  156. {
  157. // Update the version number
  158. $oNodeList->item(0)->setAttribute('version', $sTargetVersion);
  159. }
  160. }
  161. return $this->bStatus;
  162. }
  163. /**
  164. * Does the conversion, eventually in a recursive manner
  165. *
  166. * @param string $sFrom The source format version
  167. * @param string $sTo The desired format version
  168. * @param object $oFactory Full data model (not yet used, aimed at allowing conversion that could not be performed without knowing the whole data model)
  169. * @return bool True on success
  170. */
  171. protected function DoConvert($sFrom, $sTo, $oFactory = null)
  172. {
  173. if ($sFrom == $sTo)
  174. {
  175. return;
  176. }
  177. if (!array_key_exists($sFrom, self::$aVersions))
  178. {
  179. $this->LogError("Unknown source format version: $sFrom");
  180. return;
  181. }
  182. if (!array_key_exists($sTo, self::$aVersions))
  183. {
  184. $this->LogError("Unknown target format version: $sTo");
  185. return; // unknown versions are not supported
  186. }
  187. $aVersionIds = array_keys(self::$aVersions);
  188. $iFrom = array_search($sFrom, $aVersionIds);
  189. $iTo = array_search($sTo, $aVersionIds);
  190. if ($iFrom < $iTo)
  191. {
  192. // This is an upgrade
  193. $sIntermediate = self::$aVersions[$sFrom]['next'];
  194. $sTransform = self::$aVersions[$sFrom]['go_to_next'];
  195. $this->LogInfo("Upgrading from $sFrom to $sIntermediate ($sTransform)");
  196. }
  197. else
  198. {
  199. // This is a downgrade
  200. $sIntermediate = self::$aVersions[$sFrom]['previous'];
  201. $sTransform = self::$aVersions[$sFrom]['go_to_previous'];
  202. $this->LogInfo("Downgrading from $sFrom to $sIntermediate ($sTransform)");
  203. }
  204. // Transform to the intermediate format
  205. $aCallSpec = array($this, $sTransform);
  206. try
  207. {
  208. call_user_func($aCallSpec, $oFactory);
  209. // Recurse
  210. $this->DoConvert($sIntermediate, $sTo, $oFactory);
  211. }
  212. catch (Exception $e)
  213. {
  214. $this->LogError($e->getMessage());
  215. }
  216. return;
  217. }
  218. /**
  219. * Upgrade the format from version 1.0 to 1.1
  220. * @return void (Errors are logged)
  221. */
  222. protected function From10To11($oFactory)
  223. {
  224. // Adjust the XML to transparently add an id (=stimulus) on all life-cycle transitions
  225. // which don't already have one
  226. $oXPath = new DOMXPath($this->oDocument);
  227. $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition/stimulus');
  228. foreach ($oNodeList as $oNode)
  229. {
  230. $oNode->parentNode->SetAttribute('id', $oNode->textContent);
  231. $this->DeleteNode($oNode);
  232. }
  233. // Adjust the XML to transparently add an id (=percent) on all thresholds of stopwatches
  234. // which don't already have one
  235. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold/percent");
  236. foreach ($oNodeList as $oNode)
  237. {
  238. $oNode->parentNode->SetAttribute('id', $oNode->textContent);
  239. $this->DeleteNode($oNode);
  240. }
  241. // Adjust the XML to transparently add an id (=action:<type>) on all allowed actions (profiles)
  242. // which don't already have one
  243. $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action');
  244. foreach ($oNodeList as $oNode)
  245. {
  246. if ($oNode->getAttribute('id') == '')
  247. {
  248. $oNode->SetAttribute('id', 'action:' . $oNode->getAttribute('xsi:type'));
  249. $oNode->removeAttribute('xsi:type');
  250. }
  251. elseif ($oNode->getAttribute('xsi:type') == 'stimulus')
  252. {
  253. $oNode->SetAttribute('id', 'stimulus:' . $oNode->getAttribute('id'));
  254. $oNode->removeAttribute('xsi:type');
  255. }
  256. }
  257. // Adjust the XML to transparently add an id (=value) on all values of an enum which don't already have one.
  258. // This enables altering an enum for just adding/removing one value, intead of redefining the whole list of values.
  259. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value");
  260. foreach ($oNodeList as $oNode)
  261. {
  262. if ($oNode->getAttribute('id') == '')
  263. {
  264. $oNode->SetAttribute('id', $oNode->textContent);
  265. }
  266. }
  267. }
  268. /**
  269. * Downgrade the format from version 1.1 to 1.0
  270. * @return void (Errors are logged)
  271. */
  272. protected function From11To10($oFactory)
  273. {
  274. // Move the id down to a stimulus node on all life-cycle transitions
  275. $oXPath = new DOMXPath($this->oDocument);
  276. $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition[@id]');
  277. foreach ($oNodeList as $oNode)
  278. {
  279. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  280. {
  281. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  282. }
  283. $oStimulus = $oNode->ownerDocument->createElement('stimulus', $oNode->getAttribute('id'));
  284. $oNode->appendChild($oStimulus);
  285. $oNode->removeAttribute('id');
  286. }
  287. // Move the id down to a percent node on all thresholds
  288. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold[@id]");
  289. foreach ($oNodeList as $oNode)
  290. {
  291. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  292. {
  293. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  294. }
  295. $oStimulus = $oNode->ownerDocument->createElement('percent', $oNode->getAttribute('id'));
  296. $oNode->appendChild($oStimulus);
  297. $oNode->removeAttribute('id');
  298. }
  299. // Restore the type and id on profile/actions
  300. $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action');
  301. foreach ($oNodeList as $oNode)
  302. {
  303. if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0)
  304. {
  305. $this->LogError('Alterations have been defined under the node: '.MFDocument::GetItopNodePath($oNode));
  306. }
  307. if (substr($oNode->getAttribute('id'), 0, strlen('action')) == 'action')
  308. {
  309. // The id has the form 'action:<action_code>'
  310. $sActionCode = substr($oNode->getAttribute('id'), strlen('action:'));
  311. $oNode->removeAttribute('id');
  312. $oNode->setAttribute('xsi:type', $sActionCode);
  313. }
  314. else
  315. {
  316. // The id has the form 'stimulus:<stimulus_code>'
  317. $sStimulusCode = substr($oNode->getAttribute('id'), strlen('stimulus:'));
  318. $oNode->setAttribute('id', $sStimulusCode);
  319. $oNode->setAttribute('xsi:type', 'stimulus');
  320. }
  321. }
  322. // Remove the id on all enum values
  323. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value[@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: '.MFDocument::GetItopNodePath($oNode));
  329. }
  330. $oNode->removeAttribute('id');
  331. }
  332. }
  333. /**
  334. * Delete a node from the DOM and make sure to also remove the immediately following line break (DOMText), if any.
  335. * This prevents generating empty lines in the middle of the XML
  336. * @param DOMNode $oNode
  337. */
  338. protected function DeleteNode($oNode)
  339. {
  340. if ( $oNode->nextSibling && ($oNode->nextSibling instanceof DOMText) && ($oNode->nextSibling->isWhitespaceInElementContent()) )
  341. {
  342. $oNode->parentNode->removeChild($oNode->nextSibling);
  343. }
  344. $oNode->parentNode->removeChild($oNode);
  345. }
  346. }