wizardcontroller.class.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. <?php
  2. // Copyright (C) 2012 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Engine for displaying the various pages of a "wizard"
  18. * Each "step" of the wizard must be implemented as
  19. * separate class derived from WizardStep. each 'step' can also have its own
  20. * internal 'state' for developing complex wizards.
  21. * The WizardController provides the "<< Back" feature by storing a stack
  22. * of the previous screens. The WizardController also maintains from page
  23. * to page a list of "parameters" to be dispayed/edited by each of the steps.
  24. * @author Erwan Taloc <erwan.taloc@combodo.com>
  25. * @author Romain Quetiez <romain.quetiez@combodo.com>
  26. * @author Denis Flaven <denis.flaven@combodo.com>
  27. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  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. $oPage->add_linked_script('../setup/setup.js');
  157. $oPage->add_script("function CanMoveForward()\n{\n".$oStep->JSCanMoveForward()."\n}\n");
  158. $oPage->add_script("function CanMoveBackward()\n{\n".$oStep->JSCanMoveBackward()."\n}\n");
  159. $oPage->add('<form id="wiz_form" method="post">');
  160. $oStep->Display($oPage);
  161. // Add the back / next buttons and the hidden form
  162. // to store the parameters
  163. $oPage->add('<input type="hidden" id="_class" name="_class" value="'.get_class($oStep).'"/>');
  164. $oPage->add('<input type="hidden" id="_state" name="_state" value="'.$oStep->GetState().'"/>');
  165. foreach($this->aParameters as $sCode => $value)
  166. {
  167. $oPage->add('<input type="hidden" name="_params['.$sCode.']" value="'.htmlentities($value, ENT_QUOTES, 'UTF-8').'"/>');
  168. }
  169. $oPage->add('<input type="hidden" name="_steps" value="'.htmlentities(json_encode($this->aSteps), ENT_QUOTES, 'UTF-8').'"/>');
  170. $oPage->add('<table style="width:100%;"><tr>');
  171. if ((count($this->aSteps) > 0) && ($oStep->CanMoveBackward()))
  172. {
  173. $oPage->add('<td style="text-align: left"><button id="btn_back" type="submit" name="operation" value="back"> &lt;&lt; Back </button></td>');
  174. }
  175. if ($oStep->CanMoveForward())
  176. {
  177. $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>');
  178. }
  179. $oPage->add('</tr></table>');
  180. $oPage->add("</form>");
  181. $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
  182. // Hack to have the "Next >>" button, be the default button, since the first submit button in the form is the default one
  183. $oPage->add_ready_script(
  184. <<<EOF
  185. $('form').each(function () {
  186. var thisform = $(this);
  187. thisform.prepend(thisform.find('button.default').clone().removeAttr('id').removeAttr('disabled').css({
  188. position: 'absolute',
  189. left: '-999px',
  190. top: '-999px',
  191. height: 0,
  192. width: 0
  193. }));
  194. });
  195. $('#btn_back').click(function() { $('#wiz_form').data('back', true); });
  196. $('#wiz_form').submit(function() {
  197. if ($(this).data('back'))
  198. {
  199. return CanMoveBackward();
  200. }
  201. else
  202. {
  203. return CanMoveForward();
  204. }
  205. });
  206. $('#wiz_form').data('back', false);
  207. WizardUpdateButtons();
  208. EOF
  209. );
  210. $oPage->output();
  211. }
  212. /**
  213. * Make the wizard run: Start, Next or Back depending WizardUpdateButtons();
  214. on the page's parameters
  215. */
  216. public function Run()
  217. {
  218. $sOperation = utils::ReadParam('operation');
  219. $this->aParameters = utils::ReadParam('_params', array(), false, 'raw_data');
  220. $this->aSteps = json_decode(utils::ReadParam('_steps', '[]', false, 'raw_data'), true /* bAssoc */);
  221. switch($sOperation)
  222. {
  223. case 'next':
  224. $this->Next();
  225. break;
  226. case 'back':
  227. $this->Back();
  228. break;
  229. default:
  230. $this->Start();
  231. }
  232. }
  233. /**
  234. * Provides information about the structure/workflow of the wizard by listing
  235. * the possible list of 'steps' and their dependencies
  236. * @param string $sStep Name of the class to start from (used for recursion)
  237. * @param hash $aAllSteps List of steps (used for recursion)
  238. */
  239. public function DumpStructure($sStep = '', $aAllSteps = null)
  240. {
  241. if ($aAllSteps == null) $aAllSteps = array();
  242. if ($sStep == '') $sStep = $this->sInitialStepClass;
  243. $oStep = new $sStep($this, '');
  244. $aAllSteps[$sStep] = $oStep->GetPossibleSteps();
  245. foreach($aAllSteps[$sStep] as $sNextStep)
  246. {
  247. if (!array_key_exists($sNextStep, $aAllSteps))
  248. {
  249. $aAllSteps = $this->DumpStructure($sNextStep , $aAllSteps);
  250. }
  251. }
  252. return $aAllSteps;
  253. }
  254. /**
  255. * Dump the wizard's structure as a string suitable to produce a chart
  256. * using graphviz's "dot" program
  257. * @return string The 'dot' formatted output
  258. */
  259. public function DumpStructureAsDot()
  260. {
  261. $aAllSteps = $this->DumpStructure();
  262. $sOutput = "digraph finite_state_machine {\n";
  263. //$sOutput .= "\trankdir=LR;";
  264. $sOutput .= "\tsize=\"10,12\"\n";
  265. $aDeadEnds = array($this->sInitialStepClass);
  266. foreach($aAllSteps as $sStep => $aNextSteps)
  267. {
  268. if (count($aNextSteps) == 0)
  269. {
  270. $aDeadEnds[] = $sStep;
  271. }
  272. }
  273. $sOutput .= "\tnode [shape = doublecircle]; ".implode(' ', $aDeadEnds).";\n";
  274. $sOutput .= "\tnode [shape = box];\n";
  275. foreach($aAllSteps as $sStep => $aNextSteps)
  276. {
  277. $oStep = new $sStep($this, '');
  278. $sOutput .= "\t$sStep [ label = \"".$oStep->GetTitle()."\"];\n";
  279. if (count($aNextSteps) > 0)
  280. {
  281. foreach($aNextSteps as $sNextStep)
  282. {
  283. $sOutput .= "\t$sStep -> $sNextStep;\n";
  284. }
  285. }
  286. }
  287. $sOutput .= "}\n";
  288. return $sOutput;
  289. }
  290. }
  291. /**
  292. * Abstract class to build "steps" for the wizard controller
  293. * If a step needs to maintain an internal "state" (for complex steps)
  294. * then it's up to the derived class to implement the behavior based on
  295. * the internal 'sCurrentState' variable.
  296. * @author Erwan Taloc <erwan.taloc@combodo.com>
  297. * @author Romain Quetiez <romain.quetiez@combodo.com>
  298. * @author Denis Flaven <denis.flaven@combodo.com>
  299. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  300. */
  301. abstract class WizardStep
  302. {
  303. /**
  304. * A reference to the WizardController
  305. * @var WizardController
  306. */
  307. protected $oWizard;
  308. /**
  309. * Current 'state' of the wizard step. Simple 'steps' can ignore it
  310. * @var string
  311. */
  312. protected $sCurrentState;
  313. public function __construct(WizardController $oWizard, $sCurrentState)
  314. {
  315. $this->oWizard = $oWizard;
  316. $this->sCurrentState = $sCurrentState;
  317. }
  318. public function GetState()
  319. {
  320. return $this->sCurrentState;
  321. }
  322. /**
  323. * Displays the wizard page for the current class/state
  324. * The page can contain any number of "<input/>" fields, but no "<form>...</form>" tag
  325. * The name of the input fields (and their id if one is supplied) MUST NOT start with "_"
  326. * (this is reserved for the wizard's own parameters)
  327. * @return void
  328. */
  329. abstract public function Display(WebPage $oPage);
  330. /**
  331. * Processes the page's parameters and (if moving forward) returns the next step/state to be displayed
  332. * @param bool $bMoveForward True if the wizard is moving forward 'Next >>' button pressed, false otherwise
  333. * @return hash array('class' => $sNextClass, 'state' => $sNextState)
  334. */
  335. abstract public function ProcessParams($bMoveForward = true);
  336. /**
  337. * Returns the list of possible steps from this step forward
  338. * @return array Array of strings (step classes)
  339. */
  340. abstract public function GetPossibleSteps();
  341. /**
  342. * Returns title of the current step
  343. * @return string The title of the wizard page for the current step
  344. */
  345. abstract public function GetTitle();
  346. /**
  347. * Tells whether the parameters are Ok to move forward
  348. * @return boolean True to move forward, false to stey on the same step
  349. */
  350. public function ValidateParams()
  351. {
  352. return true;
  353. }
  354. /**
  355. * Tells whether this step/state is the last one of the wizard (dead-end)
  356. * @return boolean True if the 'Next >>' button should be displayed
  357. */
  358. public function CanMoveForward()
  359. {
  360. return true;
  361. }
  362. /**
  363. * Tells whether the "Next" button should be enabled interactively
  364. * @return string A piece of javascript code returning either true or false
  365. */
  366. public function JSCanMoveForward()
  367. {
  368. return 'return true;';
  369. }
  370. /**
  371. * Returns the label for the " Next >> " button
  372. * @return string The label for the button
  373. */
  374. public function GetNextButtonLabel()
  375. {
  376. return ' Next >> ';
  377. }
  378. /**
  379. * Tells whether this step/state allows to go back or not
  380. * @return boolean True if the '<< Back' button should be displayed
  381. */
  382. public function CanMoveBackward()
  383. {
  384. return true;
  385. }
  386. /**
  387. * Tells whether the "Back" button should be enabled interactively
  388. * @return string A piece of javascript code returning either true or false
  389. */
  390. public function JSCanMoveBackward()
  391. {
  392. return 'return true;';
  393. }
  394. /**
  395. * Overload this function to implement asynchronous action(s) (AJAX)
  396. * @param string $sCode The code of the action (if several actions need to be distinguished)
  397. * @param hash $aParameters The action's parameters name => value
  398. */
  399. public function AsyncAction(WebPage $oPage, $sCode, $aParameters)
  400. {
  401. }
  402. }
  403. /*
  404. * Example of a simple Setup Wizard with some parameters to store
  405. * the installation mode (install | upgrade) and a simple asynchronous
  406. * (AJAX) action.
  407. *
  408. * The setup wizard is executed by the following code:
  409. *
  410. * $oWizard = new WizardController('Step1');
  411. * $oWizard->Run();
  412. *
  413. class Step1 extends WizardStep
  414. {
  415. public function GetTitle()
  416. {
  417. return 'Welcome';
  418. }
  419. public function GetPossibleSteps()
  420. {
  421. return array('Step2', 'Step2bis');
  422. }
  423. public function ProcessParams($bMoveForward = true)
  424. {
  425. $sNextStep = '';
  426. $sInstallMode = utils::ReadParam('install_mode');
  427. if ($sInstallMode == 'install')
  428. {
  429. $this->oWizard->SetParameter('install_mode', 'install');
  430. $sNextStep = 'Step2';
  431. }
  432. else
  433. {
  434. $this->oWizard->SetParameter('install_mode', 'upgrade');
  435. $sNextStep = 'Step2bis';
  436. }
  437. return array('class' => $sNextStep, 'state' => '');
  438. }
  439. public function Display(WebPage $oPage)
  440. {
  441. $oPage->p('This is Step 1!');
  442. $sInstallMode = $this->oWizard->GetParameter('install_mode', 'install');
  443. $sChecked = ($sInstallMode == 'install') ? ' checked ' : '';
  444. $oPage->p('<input type="radio" name="install_mode" value="install"'.$sChecked.'/> Install');
  445. $sChecked = ($sInstallMode == 'upgrade') ? ' checked ' : '';
  446. $oPage->p('<input type="radio" name="install_mode" value="upgrade"'.$sChecked.'/> Upgrade');
  447. }
  448. }
  449. class Step2 extends WizardStep
  450. {
  451. public function GetTitle()
  452. {
  453. return 'Installation Parameters';
  454. }
  455. public function GetPossibleSteps()
  456. {
  457. return array('Step3');
  458. }
  459. public function ProcessParams($bMoveForward = true)
  460. {
  461. return array('class' => 'Step3', 'state' => '');
  462. }
  463. public function Display(WebPage $oPage)
  464. {
  465. $oPage->p('This is Step 2! (Installation)');
  466. }
  467. }
  468. class Step2bis extends WizardStep
  469. {
  470. public function GetTitle()
  471. {
  472. return 'Upgrade Parameters';
  473. }
  474. public function GetPossibleSteps()
  475. {
  476. return array('Step2ter');
  477. }
  478. public function ProcessParams($bMoveForward = true)
  479. {
  480. $sUpgradeInfo = utils::ReadParam('upgrade_info');
  481. $this->oWizard->SetParameter('upgrade_info', $sUpgradeInfo);
  482. $sAdditionalUpgradeInfo = utils::ReadParam('additional_upgrade_info');
  483. $this->oWizard->SetParameter('additional_upgrade_info', $sAdditionalUpgradeInfo);
  484. return array('class' => 'Step2ter', 'state' => '');
  485. }
  486. public function Display(WebPage $oPage)
  487. {
  488. $oPage->p('This is Step 2bis! (Upgrade)');
  489. $sUpgradeInfo = $this->oWizard->GetParameter('upgrade_info', '');
  490. $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>');
  491. $sAdditionalUpgradeInfo = $this->oWizard->GetParameter('additional_upgrade_info', '');
  492. $oPage->p('The installer replies: <input type="text" name="additional_upgrade_info" value="'.$sAdditionalUpgradeInfo.'" size="20"/>');
  493. $oPage->add_ready_script("$('#upgrade_info').change(function() {
  494. $('#v_upgrade_info').html('<img src=\"../images/indicator.gif\"/>');
  495. WizardAsyncAction('', { upgrade_info: $('#upgrade_info').val() }); });");
  496. }
  497. public function AsyncAction(WebPage $oPage, $sCode, $aParameters)
  498. {
  499. usleep(300000); // 300 ms
  500. $sName = $aParameters['upgrade_info'];
  501. $sReply = addslashes("Hello ".$sName);
  502. $oPage->add_ready_script(
  503. <<<EOF
  504. $("#v_upgrade_info").html('');
  505. $("input[name=additional_upgrade_info]").val("$sReply");
  506. EOF
  507. );
  508. }
  509. }
  510. class Step2ter extends WizardStep
  511. {
  512. public function GetTitle()
  513. {
  514. return 'Additional Upgrade Info';
  515. }
  516. public function GetPossibleSteps()
  517. {
  518. return array('Step3');
  519. }
  520. public function ProcessParams($bMoveForward = true)
  521. {
  522. return array('class' => 'Step3', 'state' => '');
  523. }
  524. public function Display(WebPage $oPage)
  525. {
  526. $oPage->p('This is Step 2ter! (Upgrade)');
  527. }
  528. }
  529. class Step3 extends WizardStep
  530. {
  531. public function GetTitle()
  532. {
  533. return 'Installation Complete';
  534. }
  535. public function GetPossibleSteps()
  536. {
  537. return array();
  538. }
  539. public function ProcessParams($bMoveForward = true)
  540. {
  541. return array('class' => '', 'state' => '');
  542. }
  543. public function Display(WebPage $oPage)
  544. {
  545. $oPage->p('This is the FINAL Step');
  546. }
  547. public function CanMoveForward()
  548. {
  549. return false;
  550. }
  551. }
  552. End of the example */