summaryrefslogtreecommitdiff
path: root/pearlib/HTML/QuickForm/Controller.php
blob: 4d4c79d7050764a3b86c134ea93024778de76a71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4.0                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | [email protected] so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Alexey Borzov <[email protected]>                                 |
// |          Bertrand Mansion <[email protected]>                     |
// +----------------------------------------------------------------------+
//
// $Id: Controller.php,v 1.9 2004/03/18 12:44:36 mansion Exp $

require_once 'HTML/QuickForm/Page.php';

/**
 * The class representing a Controller of MVC design pattern.
 * 
 * This class keeps track of pages and (default) action handlers for the form,
 * it manages keeping the form values in session, setting defaults and 
 * constants for the form as a whole and getting its submit values.
 * 
 * Generally you don't need to subclass this.
 *
 * @author  Alexey Borzov <[email protected]>
 * @package HTML_QuickForm_Controller
 * @version $Revision: 1.9 $
 */
class HTML_QuickForm_Controller
{
   /**
    * Contains the pages (HTML_QuickForm_Page objects) of the miultipage form
    * @var array
    */
    var $_pages = array();

   /**
    * Contains the mapping of actions to corresponding HTML_QuickForm_Action objects
    * @var array
    */
    var $_actions = array();

   /**
    * Name of the form, used to store the values in session 
    * @var string
    */
    var $_name;

   /**
    * Whether the form is modal  
    * @var bool
    */
    var $_modal = true;

   /**
    * The action extracted from HTTP request: array('page', 'action')
    * @var array
    */
    var $_actionName = null;

   /**
    * Class constructor.
    * 
    * Sets the form name and modal/non-modal behaviuor. Different multipage
    * forms should have different names, as they are used to store form 
    * values in session. Modal forms allow passing to the next page only when
    * all of the previous pages are valid.
    *
    * @access public
    * @param  string  form name
    * @param  bool    whether the form is modal
    */
    function HTML_QuickForm_Controller($name, $modal = true)
    {
        $this->_name  = $name;
        $this->_modal = $modal;
    }


   /**
    * Returns a reference to a session variable containing the form-page 
    * values and pages' validation status.
    * 
    * This is a "low-level" method, use exportValues() if you want just to
    * get the form's values.
    * 
    * @access public
    * @param  bool      If true, then reset the container: clear all default, constant and submitted values
    * @return array
    */
    function &container($reset = false)
    {
        $name = '_' . $this->_name . '_container';
        if (!isset($_SESSION[$name]) || $reset) {
            $_SESSION[$name] = array(
                'defaults'  => array(),
                'constants' => array(),
                'values'    => array(),
                'valid'     => array()
            );
        }
        foreach (array_keys($this->_pages) as $pageName) {
            if (!isset($_SESSION[$name]['values'][$pageName])) {
                $_SESSION[$name]['values'][$pageName] = array();
                $_SESSION[$name]['valid'][$pageName]  = null;
            }
        }
        return $_SESSION[$name];
    }


   /**
    * Processes the request.
    *
    * This finds the current page, the current action and passes the action
    * to the page's handle() method.
    *
    * @access public
    */
    function run()
    {
        // the names of the action and page should be saved
        list($page, $action) = $this->_actionName = $this->getActionName();
        return $this->_pages[$page]->handle($action);
    }


   /**
    * Registers a handler for a specific action.
    *
    * @access public
    * @param  string    name of the action
    * @param  object HTML_QuickForm_Action   the handler for the action
    */
    function addAction($actionName, &$action)
    {
        $this->_actions[$actionName] =& $action;
    }


   /**
    * Adds a new page to the form
    *
    * @access public
    * @param  object HTML_QuickForm_Page
    */
    function addPage(&$page)
    {
        $page->controller =& $this;
        $this->_pages[$page->getAttribute('id')] =& $page;
    }


   /**
    * Returns a page
    *
    * @access public
    * @param  string    Name of a page
    * @return object    HTML_QuickForm_Page     A reference to the page
    */
    function &getPage($pageName)
    {
        if (!isset($this->_pages[$pageName])) {
            return PEAR::raiseError('HTML_QuickForm_Controller: Unknown page "' . $pageName . '"');
        }
        return $this->_pages[$pageName];
    }


   /**
    * Handles an action.
    *
    * This will be called if the page itself does not have a handler
    * to a specific action. The method also loads and uses default handlers
    * for common actions, if specific ones were not added.
    * 
    * @access public
    * @param  object HTML_QuickForm_Page    The page that failed to handle the action
    * @param  string    Name of the action
    */
    function handle(&$page, $actionName)
    {
        if (isset($this->_actions[$actionName])) {
            return $this->_actions[$actionName]->perform($page, $actionName);
        }
        switch ($actionName) {
            case 'next':
            case 'back':
            case 'submit':
            case 'display':
            case 'jump':
                include_once 'HTML/QuickForm/Action/' . ucfirst($actionName) . '.php';
                $className = 'HTML_QuickForm_Action_' . $actionName;
                $this->_actions[$actionName] =& new $className();
                return $this->_actions[$actionName]->perform($page, $actionName);
                break;
            default:
                return PEAR::raiseError('HTML_QuickForm_Controller: Unhandled action "' . $actionName . '" in page "' . $page->getAttribute('id') . '"');
        } // switch
    }


   /**
    * Checks whether the form is modal.
    * 
    * @access public
    * @return bool
    */
    function isModal()
    {
        return $this->_modal;
    }


   /**
    * Checks whether the pages of the controller are valid
    * 
    * @access public
    * @param  string    If set, check only the pages before (not including) that page
    * @return bool
    */
    function isValid($pageName = null)
    {
        $data =& $this->container();
        foreach (array_keys($this->_pages) as $key) {
            if (isset($pageName) && $pageName == $key) {
                return true;
            } elseif (!$data['valid'][$key]) {
                // We should handle the possible situation when the user has never
                // seen a page of a non-modal multipage form
                if (!$this->isModal() && null === $data['valid'][$key]) {
                    $page =& $this->_pages[$key];
                    // Use controller's defaults and constants, if present
                    $this->applyDefaults($key);
                    $page->isFormBuilt() or $page->BuildForm();
                    // We use defaults and constants as if they were submitted
                    $data['values'][$key] = $page->exportValues();
                    $page->loadValues($data['values'][$key]);
                    // Is the page now valid?
                    if (true === ($data['valid'][$key] = $page->validate())) {
                        continue;
                    }
                }
                return false;
            }
        }
        return true;
    }


   /**
    * Returns the name of the page before the given.
    * 
    * @access public
    * @param  string 
    * @return string
    */
    function getPrevName($pageName)
    {
        $prev = null;
        foreach (array_keys($this->_pages) as $key) {
            if ($key == $pageName) {
                return $prev;
            }
            $prev = $key;
        }
    }


   /**
    * Returns the name of the page after the given.
    * 
    * @access public
    * @param  string 
    * @return string
    */
    function getNextName($pageName)
    {
        $prev = null;
        foreach (array_keys($this->_pages) as $key) {
            if ($prev == $pageName) {
                return $key;
            }
            $prev = $key;
        }
        return null;
    }


   /**
    * Finds the (first) invalid page
    * 
    * @access public
    * @return string  Name of an invalid page
    */
    function findInvalid()
    {
        $data =& $this->container();
        foreach (array_keys($this->_pages) as $key) {
            if (!$data['valid'][$key]) {
                return $key;
            }
        }
        return null;
    }


   /**
    * Extracts the names of the current page and the current action from
    * HTTP request data. 
    *
    * @access public
    * @return array     first element is page name, second is action name
    */
    function getActionName()
    {
        if (is_array($this->_actionName)) {
            return $this->_actionName;
        }
        $names = array_map('preg_quote', array_keys($this->_pages));
        $regex = '/^_qf_(' . implode('|', $names) . ')_(.+?)(_x)?$/';
        foreach (array_keys($_REQUEST) as $key) {
            if (preg_match($regex, $key, $matches)) {
                return array($matches[1], $matches[2]);
            }
        }
        if (isset($_REQUEST['_qf_default'])) {
            $matches = explode(':', $_REQUEST['_qf_default'], 2);
            if (isset($this->_pages[$matches[0]])) {
                return $matches;
            }
        }
        reset($this->_pages);
        return array(key($this->_pages), 'display');
    }


   /**
    * Initializes default form values.
    *
    * @access public
    * @param  array  default values
    */
    function setDefaults($defaultValues = null)
    {
        if (is_array($defaultValues)) {
            $data =& $this->container();
            $data['defaults'] = HTML_QuickForm::arrayMerge($data['defaults'], $defaultValues);
        }
    }


   /**
    * Initializes constant form values.
    * These values won't get overridden by POST or GET vars
    *
    * @access public
    * @param  array  constant values
    */
    function setConstants($constantValues = null)
    {
        if (is_array($constantValues)) {
            $data =& $this->container();
            $data['constants'] = HTML_QuickForm::arrayMerge($data['constants'], $constantValues);
        }
    }


   /**
    * Sets the default values for the given page
    *
    * @access public
    * @param  string  Name of a page
    */
    function applyDefaults($pageName)
    {
        $data =& $this->container();
        if (!empty($data['defaults'])) {
            $this->_pages[$pageName]->setDefaults($data['defaults']);
        }
        if (!empty($data['constants'])) {
            $this->_pages[$pageName]->setConstants($data['constants']);
        }
    }


   /**
    * Returns the form's values
    * 
    * @access public
    * @param  string    name of the page, if not set then returns values for all pages
    * @return array
    */
    function exportValues($pageName = null)
    {
        $data   =& $this->container();
        $values =  array();
        if (isset($pageName)) {
            $pages = array($pageName);
        } else {
            $pages = array_keys($data['values']);
        }
        foreach ($pages as $page) {
            // skip elements representing actions
            foreach ($data['values'][$page] as $key => $value) {
                if (0 !== strpos($key, '_qf_')) {
                    if (isset($values[$key]) && is_array($value)) {
                        $values[$key] = HTML_QuickForm::arrayMerge($values[$key], $value);
                    } else {
                        $values[$key] = $value;
                    }
                }
            }
        }
        return $values;
    }


   /**
    * Returns the element's value
    * 
    * @access public
    * @param  string    name of the page
    * @param  string    name of the element in the page
    * @return mixed     value for the element
    */
    function exportValue($pageName, $elementName)
    {
        $data =& $this->container();
        return isset($data['values'][$pageName][$elementName])? $data['values'][$pageName][$elementName]: null;
    }
}
?>