wizardcontroller.class.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Engine for displaying the various pages of a "wizard"
  20. * Each "step" of the wizard must be implemented as
  21. * separate class derived from WizardStep. each 'step' can also have its own
  22. * internal 'state' for developing complex wizards.
  23. * The WizardController provides the "<< Back" feature by storing a stack
  24. * of the previous screens. The WizardController also maintains from page
  25. * to page a list of "parameters" to be dispayed/edited by each of the steps.
  26. * @copyright Copyright (C) 2010-2012 Combodo SARL
  27. * @license http://opensource.org/licenses/AGPL-3.0
  28. */
  29. class WizardController
  30. {
  31. protected $aSteps;
  32. protected $sInitialStepClass;
  33. protected $sInitialState;
  34. protected $aParameters;
  35. /**
  36. * Initiailization of the wizard controller
  37. * @param string $sInitialStepClass Class of the initial step/page of the wizard
  38. * @param string $sInitialState Initial state of the initial page (if this class manages states)
  39. */
  40. public function __construct($sInitialStepClass, $sInitialState = '')
  41. {
  42. $this->sInitialStepClass = $sInitialStepClass;
  43. $this->sInitialState = $sInitialState;
  44. $this->aParameters = array();
  45. $this->aSteps = array();
  46. }
  47. /**
  48. * Pushes information about the current step onto the stack
  49. * @param hash $aStepInfo Array('class' => , 'state' => )
  50. */
  51. protected function PushStep($aStepInfo)
  52. {
  53. array_push($this->aSteps, $aStepInfo);
  54. }
  55. /**
  56. * Removes information about the previous step from the stack
  57. * @return hash Array('class' => , 'state' => )
  58. */
  59. protected function PopStep()
  60. {
  61. return array_pop($this->aSteps);
  62. }
  63. /**
  64. * Reads a "persistent" parameter from the wizard's context
  65. * @param string $sParamCode The code identifying this parameter
  66. * @param mixed $defaultValue The default value of the parameter in case it was not set
  67. */
  68. public function GetParameter($sParamCode, $defaultValue = '')
  69. {
  70. if (array_key_exists($sParamCode, $this->aParameters))
  71. {
  72. return $this->aParameters[$sParamCode];
  73. }
  74. return $defaultValue;
  75. }
  76. /**
  77. * Stores a "persistent" parameter in the wizard's context
  78. * @param string $sParamCode The code identifying this parameter
  79. * @param mixed $value The value to store
  80. */
  81. public function SetParameter($sParamCode, $value)
  82. {
  83. $this->aParameters[$sParamCode] = $value;
  84. }
  85. /**
  86. * Stores the value of the page's parameter in a "persistent" parameter in the wizard's context
  87. * @param string $sParamCode The code identifying this parameter
  88. * @param mixed $defaultValue The default value for the parameter
  89. * @param string $sSanitizationFilter A 'sanitization' fitler. Default is 'raw_data', which means no filtering
  90. */
  91. public function SaveParameter($sParamCode, $defaultValue, $sSanitizationFilter = 'raw_data')
  92. {
  93. $value = utils::ReadParam($sParamCode, $defaultValue, false, $sSanitizationFilter);
  94. $this->aParameters[$sParamCode] = $value;
  95. }
  96. /**
  97. * Starts the wizard by displaying it in its initial state
  98. */
  99. protected function Start()
  100. {
  101. $sCurrentStepClass = $this->sInitialStepClass;
  102. $oStep = new $sCurrentStepClass($this, $this->sInitialState);
  103. $this->DisplayStep($oStep);
  104. }
  105. /**
  106. * Progress towards the next step of the wizard
  107. * @throws Exception
  108. */
  109. protected function Next()
  110. {
  111. $sCurrentStepClass = utils::ReadParam('_class', $this->sInitialStepClass);
  112. $sCurrentState = utils::ReadParam('_state', $this->sInitialState);
  113. $oStep = new $sCurrentStepClass($this, $sCurrentState);
  114. if ($oStep->ValidateParams($sCurrentState))
  115. {
  116. $this->PushStep(array('class' => $sCurrentStepClass, 'state' => $sCurrentState));
  117. $aPossibleSteps = $oStep->GetPossibleSteps();
  118. $aNextStepInfo = $oStep->ProcessParams(true); // true => moving forward
  119. if (in_array($aNextStepInfo['class'], $aPossibleSteps))
  120. {
  121. $oNextStep = new $aNextStepInfo['class']($this, $aNextStepInfo['state']);
  122. $this->DisplayStep($oNextStep);
  123. }
  124. else
  125. {
  126. throw new Exception("Internal error: Unexpected next step '{$aNextStepInfo['class']}'. The possible next steps are: ".implode(', ', $aPossibleSteps));
  127. }
  128. }
  129. else
  130. {
  131. $this->DisplayStep($oStep);
  132. }
  133. }
  134. /**
  135. * Move one step back
  136. */
  137. protected function Back()
  138. {
  139. // let the current step save its parameters
  140. $sCurrentStepClass = utils::ReadParam('_class', $this->sInitialStepClass);
  141. $sCurrentState = utils::ReadParam('_state', $this->sInitialState);
  142. $oStep = new $sCurrentStepClass($this, $sCurrentState);
  143. $aNextStepInfo = $oStep->ProcessParams();
  144. // Display the previous step
  145. $aCurrentStepInfo = $this->PopStep();
  146. $oStep = new $aCurrentStepInfo['class']($this, $aCurrentStepInfo['state']);
  147. $this->DisplayStep($oStep);
  148. }
  149. /**
  150. * Displays the specified 'step' of the wizard
  151. * @param WizardStep $oStep The 'step' to display
  152. */
  153. protected function DisplayStep(WizardStep $oStep)
  154. {
  155. $oPage = new SetupPage($oStep->GetTitle());
  156. if ($oStep->RequiresWritableConfig())
  157. {
  158. $sConfigFile = utils::GetConfigFilePath();
  159. if (file_exists($sConfigFile))
  160. {
  161. // The configuration file already exists
  162. if (!is_writable($sConfigFile))
  163. {
  164. $oP = new SetupPage('Installation Cannot Continue');
  165. $oP->add("<h2>Fatal error</h2>\n");
  166. $oP->error("<b>Error:</b> the configuration file '".$sConfigFile."' already exists and cannot be overwritten.");
  167. $oP->p("The wizard cannot modify the configuration file for you. If you want to upgrade ".ITOP_APPLICATION.", make sure that the file '<b>".realpath($sConfigFile)."</b>' can be modified by the web server.");
  168. $oP->output();
  169. return;
  170. }
  171. }
  172. }
  173. $oPage->add_linked_script('../setup/setup.js');
  174. $oPage->add_script("function CanMoveForward()\n{\n".$oStep->JSCanMoveForward()."\n}\n");
  175. $oPage->add_script("function CanMoveBackward()\n{\n".$oStep->JSCanMoveBackward()."\n}\n");
  176. $oPage->add('<form id="wiz_form" method="post">');
  177. $oStep->Display($oPage);
  178. // Add the back / next buttons and the hidden form
  179. // to store the parameters
  180. $oPage->add('<input type="hidden" id="_class" name="_class" value="'.get_class($oStep).'"/>');
  181. $oPage->add('<input type="hidden" id="_state" name="_state" value="'.$oStep->GetState().'"/>');
  182. foreach($this->aParameters as $sCode => $value)
  183. {
  184. $oPage->add('<input type="hidden" name="_params['.$sCode.']" value="'.htmlentities($value, ENT_QUOTES, 'UTF-8').'"/>');
  185. }
  186. $oPage->add('<input type="hidden" name="_steps" value="'.htmlentities(json_encode($this->aSteps), ENT_QUOTES, 'UTF-8').'"/>');
  187. $oPage->add('<table style="width:100%;"><tr>');
  188. if ((count($this->aSteps) > 0) && ($oStep->CanMoveBackward()))
  189. {
  190. $oPage->add('<td style="text-align: left"><button id="btn_back" type="submit" name="operation" value="back"> &lt;&lt; Back </button></td>');
  191. }
  192. if ($oStep->CanMoveForward())
  193. {
  194. $oPage->add('<td style="text-align:right;"><button id="btn_next" class="default" type="submit" name="operation" value="next">'.htmlentities($oStep->GetNextButtonLabel(), ENT_QUOTES, 'UTF-8').'</button></td>');
  195. }
  196. $oPage->add('</tr></table>');
  197. $oPage->add("</form>");
  198. $oPage->add('<div id="async_action" style="display:none;overflow:auto;max-height:100px;color:#F00;font-size:small;"></div>'); // The div may become visible in case of error
  199. // Hack to have the "Next >>" button, be the default button, since the first submit button in the form is the default one
  200. $oPage->add_ready_script(
  201. <<<EOF
  202. $('form').each(function () {
  203. var thisform = $(this);
  204. thisform.prepend(thisform.find('button.default').clone().removeAttr('id').removeAttr('disabled').css({
  205. position: 'absolute',
  206. left: '-999px',
  207. top: '-999px',
  208. height: 0,
  209. width: 0
  210. }));
  211. });
  212. $('#btn_back').click(function() { $('#wiz_form').data('back', true); });
  213. $('#wiz_form').submit(function() {
  214. if ($(this).data('back'))
  215. {
  216. return CanMoveBackward();
  217. }
  218. else
  219. {
  220. return CanMoveForward();
  221. }
  222. });
  223. $('#wiz_form').data('back', false);
  224. WizardUpdateButtons();
  225. EOF
  226. );
  227. $oPage->output();
  228. }
  229. /**
  230. * Make the wizard run: Start, Next or Back depending WizardUpdateButtons();
  231. on the page's parameters
  232. */
  233. public function Run()
  234. {
  235. $sOperation = utils::ReadParam('operation');
  236. $this->aParameters = utils::ReadParam('_params', array(), false, 'raw_data');
  237. $this->aSteps = json_decode(utils::ReadParam('_steps', '[]', false, 'raw_data'), true /* bAssoc */);
  238. switch($sOperation)
  239. {
  240. case 'next':
  241. $this->Next();
  242. break;
  243. case 'back':
  244. $this->Back();
  245. break;
  246. default:
  247. $this->Start();
  248. }
  249. }
  250. /**
  251. * Provides information about the structure/workflow of the wizard by listing
  252. * the possible list of 'steps' and their dependencies
  253. * @param string $sStep Name of the class to start from (used for recursion)
  254. * @param hash $aAllSteps List of steps (used for recursion)
  255. */
  256. public function DumpStructure($sStep = '', $aAllSteps = null)
  257. {
  258. if ($aAllSteps == null) $aAllSteps = array();
  259. if ($sStep == '') $sStep = $this->sInitialStepClass;
  260. $oStep = new $sStep($this, '');
  261. $aAllSteps[$sStep] = $oStep->GetPossibleSteps();
  262. foreach($aAllSteps[$sStep] as $sNextStep)
  263. {
  264. if (!array_key_exists($sNextStep, $aAllSteps))
  265. {
  266. $aAllSteps = $this->DumpStructure($sNextStep , $aAllSteps);
  267. }
  268. }
  269. return $aAllSteps;
  270. }
  271. /**
  272. * Dump the wizard's structure as a string suitable to produce a chart
  273. * using graphviz's "dot" program
  274. * @return string The 'dot' formatted output
  275. */
  276. public function DumpStructureAsDot()
  277. {
  278. $aAllSteps = $this->DumpStructure();
  279. $sOutput = "digraph finite_state_machine {\n";
  280. //$sOutput .= "\trankdir=LR;";
  281. $sOutput .= "\tsize=\"10,12\"\n";
  282. $aDeadEnds = array($this->sInitialStepClass);
  283. foreach($aAllSteps as $sStep => $aNextSteps)
  284. {
  285. if (count($aNextSteps) == 0)
  286. {
  287. $aDeadEnds[] = $sStep;
  288. }
  289. }
  290. $sOutput .= "\tnode [shape = doublecircle]; ".implode(' ', $aDeadEnds).";\n";
  291. $sOutput .= "\tnode [shape = box];\n";
  292. foreach($aAllSteps as $sStep => $aNextSteps)
  293. {
  294. $oStep = new $sStep($this, '');
  295. $sOutput .= "\t$sStep [ label = \"".$oStep->GetTitle()."\"];\n";
  296. if (count($aNextSteps) > 0)
  297. {
  298. foreach($aNextSteps as $sNextStep)
  299. {
  300. $sOutput .= "\t$sStep -> $sNextStep;\n";
  301. }
  302. }
  303. }
  304. $sOutput .= "}\n";
  305. return $sOutput;
  306. }
  307. }
  308. /**
  309. * Abstract class to build "steps" for the wizard controller
  310. * If a step needs to maintain an internal "state" (for complex steps)
  311. * then it's up to the derived class to implement the behavior based on
  312. * the internal 'sCurrentState' variable.
  313. * @copyright Copyright (C) 2010-2012 Combodo SARL
  314. * @license http://opensource.org/licenses/AGPL-3.0
  315. */
  316. abstract class WizardStep
  317. {
  318. /**
  319. * A reference to the WizardController
  320. * @var WizardController
  321. */
  322. protected $oWizard;
  323. /**
  324. * Current 'state' of the wizard step. Simple 'steps' can ignore it
  325. * @var string
  326. */
  327. protected $sCurrentState;
  328. public function __construct(WizardController $oWizard, $sCurrentState)
  329. {
  330. $this->oWizard = $oWizard;
  331. $this->sCurrentState = $sCurrentState;
  332. }
  333. public function GetState()
  334. {
  335. return $this->sCurrentState;
  336. }
  337. /**
  338. * Displays the wizard page for the current class/state
  339. * The page can contain any number of "<input/>" fields, but no "<form>...</form>" tag
  340. * The name of the input fields (and their id if one is supplied) MUST NOT start with "_"
  341. * (this is reserved for the wizard's own parameters)
  342. * @return void
  343. */
  344. abstract public function Display(WebPage $oPage);
  345. /**
  346. * Processes the page's parameters and (if moving forward) returns the next step/state to be displayed
  347. * @param bool $bMoveForward True if the wizard is moving forward 'Next >>' button pressed, false otherwise
  348. * @return hash array('class' => $sNextClass, 'state' => $sNextState)
  349. */
  350. abstract public function ProcessParams($bMoveForward = true);
  351. /**
  352. * Returns the list of possible steps from this step forward
  353. * @return array Array of strings (step classes)
  354. */
  355. abstract public function GetPossibleSteps();
  356. /**
  357. * Returns title of the current step
  358. * @return string The title of the wizard page for the current step
  359. */
  360. abstract public function GetTitle();
  361. /**
  362. * Tells whether the parameters are Ok to move forward
  363. * @return boolean True to move forward, false to stey on the same step
  364. */
  365. public function ValidateParams()
  366. {
  367. return true;
  368. }
  369. /**
  370. * Tells whether this step/state is the last one of the wizard (dead-end)
  371. * @return boolean True if the 'Next >>' button should be displayed
  372. */
  373. public function CanMoveForward()
  374. {
  375. return true;
  376. }
  377. /**
  378. * Tells whether the "Next" button should be enabled interactively
  379. * @return string A piece of javascript code returning either true or false
  380. */
  381. public function JSCanMoveForward()
  382. {
  383. return 'return true;';
  384. }
  385. /**
  386. * Returns the label for the " Next >> " button
  387. * @return string The label for the button
  388. */
  389. public function GetNextButtonLabel()
  390. {
  391. return ' Next >> ';
  392. }
  393. /**
  394. * Tells whether this step/state allows to go back or not
  395. * @return boolean True if the '<< Back' button should be displayed
  396. */
  397. public function CanMoveBackward()
  398. {
  399. return true;
  400. }
  401. /**
  402. * Tells whether the "Back" button should be enabled interactively
  403. * @return string A piece of javascript code returning either true or false
  404. */
  405. public function JSCanMoveBackward()
  406. {
  407. return 'return true;';
  408. }
  409. /**
  410. * Tells whether this step of the wizard requires that the configuration file be writable
  411. * @return bool True if the wizard will possibly need to modify the configuration at some point
  412. */
  413. public function RequiresWritableConfig()
  414. {
  415. return true;
  416. }
  417. /**
  418. * Overload this function to implement asynchronous action(s) (AJAX)
  419. * @param string $sCode The code of the action (if several actions need to be distinguished)
  420. * @param hash $aParameters The action's parameters name => value
  421. */
  422. public function AsyncAction(WebPage $oPage, $sCode, $aParameters)
  423. {
  424. }
  425. }
  426. /*
  427. * Example of a simple Setup Wizard with some parameters to store
  428. * the installation mode (install | upgrade) and a simple asynchronous
  429. * (AJAX) action.
  430. *
  431. * The setup wizard is executed by the following code:
  432. *
  433. * $oWizard = new WizardController('Step1');
  434. * $oWizard->Run();
  435. *
  436. class Step1 extends WizardStep
  437. {
  438. public function GetTitle()
  439. {
  440. return 'Welcome';
  441. }
  442. public function GetPossibleSteps()
  443. {
  444. return array('Step2', 'Step2bis');
  445. }
  446. public function ProcessParams($bMoveForward = true)
  447. {
  448. $sNextStep = '';
  449. $sInstallMode = utils::ReadParam('install_mode');
  450. if ($sInstallMode == 'install')
  451. {
  452. $this->oWizard->SetParameter('install_mode', 'install');
  453. $sNextStep = 'Step2';
  454. }
  455. else
  456. {
  457. $this->oWizard->SetParameter('install_mode', 'upgrade');
  458. $sNextStep = 'Step2bis';
  459. }
  460. return array('class' => $sNextStep, 'state' => '');
  461. }
  462. public function Display(WebPage $oPage)
  463. {
  464. $oPage->p('This is Step 1!');
  465. $sInstallMode = $this->oWizard->GetParameter('install_mode', 'install');
  466. $sChecked = ($sInstallMode == 'install') ? ' checked ' : '';
  467. $oPage->p('<input type="radio" name="install_mode" value="install"'.$sChecked.'/> Install');
  468. $sChecked = ($sInstallMode == 'upgrade') ? ' checked ' : '';
  469. $oPage->p('<input type="radio" name="install_mode" value="upgrade"'.$sChecked.'/> Upgrade');
  470. }
  471. }
  472. class Step2 extends WizardStep
  473. {
  474. public function GetTitle()
  475. {
  476. return 'Installation Parameters';
  477. }
  478. public function GetPossibleSteps()
  479. {
  480. return array('Step3');
  481. }
  482. public function ProcessParams($bMoveForward = true)
  483. {
  484. return array('class' => 'Step3', 'state' => '');
  485. }
  486. public function Display(WebPage $oPage)
  487. {
  488. $oPage->p('This is Step 2! (Installation)');
  489. }
  490. }
  491. class Step2bis extends WizardStep
  492. {
  493. public function GetTitle()
  494. {
  495. return 'Upgrade Parameters';
  496. }
  497. public function GetPossibleSteps()
  498. {
  499. return array('Step2ter');
  500. }
  501. public function ProcessParams($bMoveForward = true)
  502. {
  503. $sUpgradeInfo = utils::ReadParam('upgrade_info');
  504. $this->oWizard->SetParameter('upgrade_info', $sUpgradeInfo);
  505. $sAdditionalUpgradeInfo = utils::ReadParam('additional_upgrade_info');
  506. $this->oWizard->SetParameter('additional_upgrade_info', $sAdditionalUpgradeInfo);
  507. return array('class' => 'Step2ter', 'state' => '');
  508. }
  509. public function Display(WebPage $oPage)
  510. {
  511. $oPage->p('This is Step 2bis! (Upgrade)');
  512. $sUpgradeInfo = $this->oWizard->GetParameter('upgrade_info', '');
  513. $oPage->p('Type your name here: <input type="text" id="upgrade_info" name="upgrade_info" value="'.$sUpgradeInfo.'" size="20"/><span id="v_upgrade_info"></span>');
  514. $sAdditionalUpgradeInfo = $this->oWizard->GetParameter('additional_upgrade_info', '');
  515. $oPage->p('The installer replies: <input type="text" name="additional_upgrade_info" value="'.$sAdditionalUpgradeInfo.'" size="20"/>');
  516. $oPage->add_ready_script("$('#upgrade_info').change(function() {
  517. $('#v_upgrade_info').html('<img src=\"../images/indicator.gif\"/>');
  518. WizardAsyncAction('', { upgrade_info: $('#upgrade_info').val() }); });");
  519. }
  520. public function AsyncAction(WebPage $oPage, $sCode, $aParameters)
  521. {
  522. usleep(300000); // 300 ms
  523. $sName = $aParameters['upgrade_info'];
  524. $sReply = addslashes("Hello ".$sName);
  525. $oPage->add_ready_script(
  526. <<<EOF
  527. $("#v_upgrade_info").html('');
  528. $("input[name=additional_upgrade_info]").val("$sReply");
  529. EOF
  530. );
  531. }
  532. }
  533. class Step2ter extends WizardStep
  534. {
  535. public function GetTitle()
  536. {
  537. return 'Additional Upgrade Info';
  538. }
  539. public function GetPossibleSteps()
  540. {
  541. return array('Step3');
  542. }
  543. public function ProcessParams($bMoveForward = true)
  544. {
  545. return array('class' => 'Step3', 'state' => '');
  546. }
  547. public function Display(WebPage $oPage)
  548. {
  549. $oPage->p('This is Step 2ter! (Upgrade)');
  550. }
  551. }
  552. class Step3 extends WizardStep
  553. {
  554. public function GetTitle()
  555. {
  556. return 'Installation Complete';
  557. }
  558. public function GetPossibleSteps()
  559. {
  560. return array();
  561. }
  562. public function ProcessParams($bMoveForward = true)
  563. {
  564. return array('class' => '', 'state' => '');
  565. }
  566. public function Display(WebPage $oPage)
  567. {
  568. $oPage->p('This is the FINAL Step');
  569. }
  570. public function CanMoveForward()
  571. {
  572. return false;
  573. }
  574. }
  575. End of the example */