itopdesignformat.class.inc.php 12 KB

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