xref: /dokuwiki/inc/Form/Form.php (revision 8f0df229ed3e82191f118594ea5145c9d5942d7b)
1<?php
2namespace dokuwiki\Form;
3
4/**
5 * Class Form
6 *
7 * Represents the whole Form. This is what you work on, and add Elements to
8 *
9 * @package dokuwiki\Form
10 */
11class Form extends Element {
12
13    /**
14     * @var array name value pairs for hidden values
15     */
16    protected $hidden = array();
17
18    /**
19     * @var Element[] the elements of the form
20     */
21    protected $elements = array();
22
23    /**
24     * Creates a new, empty form with some default attributes
25     *
26     * @param array $attributes
27     */
28    public function __construct($attributes = array()) {
29        global $ID;
30
31        parent::__construct('form', $attributes);
32
33        // use the current URL as default action
34        if(!$this->attr('action')) {
35            $get = $_GET;
36            if(isset($get['id'])) unset($get['id']);
37            $self = wl($ID, $get, false, '&'); //attributes are escaped later
38            $this->attr('action', $self);
39        }
40
41        // post is default
42        if(!$this->attr('method')) {
43            $this->attr('method', 'post');
44        }
45
46        // we like UTF-8
47        if(!$this->attr('accept-charset')) {
48            $this->attr('accept-charset', 'utf-8');
49        }
50
51        // add the security token by default
52        $this->setHiddenField('sectok', getSecurityToken());
53
54        // identify this as a new form based form in HTML
55        $this->addClass('doku_form');
56    }
57
58    /**
59     * Sets a hidden field
60     *
61     * @param $name
62     * @param $value
63     * @return $this
64     */
65    public function setHiddenField($name, $value) {
66        $this->hidden[$name] = $value;
67        return $this;
68    }
69
70    #region element query function
71
72    /**
73     * Returns the numbers of elements in the form
74     *
75     * @return int
76     */
77    public function elementCount() {
78        return count($this->elements);
79    }
80
81    /**
82     * Returns a reference to the element at a position.
83     * A position out-of-bounds will return either the
84     * first (underflow) or last (overflow) element.
85     *
86     * @param $pos
87     * @return Element
88     */
89    public function getElementAt($pos) {
90        if($pos < 0) $pos = count($this->elements) + $pos;
91        if($pos < 0) $pos = 0;
92        if($pos >= count($this->elements)) $pos = count($this->elements) - 1;
93        return $this->elements[$pos];
94    }
95
96    /**
97     * Gets the position of the first of a type of element
98     *
99     * @param string $type Element type to look for.
100     * @param int $offset search from this position onward
101     * @return false|int position of element if found, otherwise false
102     */
103    public function findPositionByType($type, $offset = 0) {
104        $len = $this->elementCount();
105        for($pos = $offset; $pos < $len; $pos++) {
106            if($this->elements[$pos]->getType() == $type) {
107                return $pos;
108            }
109        }
110        return false;
111    }
112
113    /**
114     * Gets the position of the first element matching the attribute
115     *
116     * @param string $name Name of the attribute
117     * @param string $value Value the attribute should have
118     * @param int $offset search from this position onward
119     * @return false|int position of element if found, otherwise false
120     */
121    public function findPositionByAttribute($name, $value, $offset = 0) {
122        $len = $this->elementCount();
123        for($pos = $offset; $pos < $len; $pos++) {
124            if($this->elements[$pos]->attr($name) == $value) {
125                return $pos;
126            }
127        }
128        return false;
129    }
130
131    #endregion
132
133    #region Element positioning functions
134
135    /**
136     * Adds or inserts an element to the form
137     *
138     * @param Element $element
139     * @param int $pos 0-based position in the form, -1 for at the end
140     * @return Element
141     */
142    public function addElement(Element $element, $pos = -1) {
143        if(is_a($element, '\dokuwiki\Form')) throw new \InvalidArgumentException('You can\'t add a form to a form');
144        if($pos < 0) {
145            $this->elements[] = $element;
146        } else {
147            array_splice($this->elements, $pos, 0, array($element));
148        }
149        return $element;
150    }
151
152    /**
153     * Replaces an existing element with a new one
154     *
155     * @param Element $element the new element
156     * @param $pos 0-based position of the element to replace
157     */
158    public function replaceElement(Element $element, $pos) {
159        if(is_a($element, '\dokuwiki\Form')) throw new \InvalidArgumentException('You can\'t add a form to a form');
160        array_splice($this->elements, $pos, 1, array($element));
161    }
162
163    /**
164     * Remove an element from the form completely
165     *
166     * @param $pos 0-based position of the element to remove
167     */
168    public function removeElement($pos) {
169        array_splice($this->elements, $pos, 1);
170    }
171
172    #endregion
173
174    #region Element adding functions
175
176    /**
177     * Adds a text input field
178     *
179     * @param $name
180     * @param $label
181     * @param int $pos
182     * @return InputElement
183     */
184    public function addTextInput($name, $label = '', $pos = -1) {
185        return $this->addElement(new InputElement('text', $name, $label), $pos);
186    }
187
188    /**
189     * Adds a password input field
190     *
191     * @param $name
192     * @param $label
193     * @param int $pos
194     * @return InputElement
195     */
196    public function addPasswordInput($name, $label = '', $pos = -1) {
197        return $this->addElement(new InputElement('password', $name, $label), $pos);
198    }
199
200    /**
201     * Adds a radio button field
202     *
203     * @param $name
204     * @param $label
205     * @param int $pos
206     * @return CheckableElement
207     */
208    public function addRadioButton($name, $label = '', $pos = -1) {
209        return $this->addElement(new CheckableElement('radio', $name, $label), $pos);
210    }
211
212    /**
213     * Adds a checkbox field
214     *
215     * @param $name
216     * @param $label
217     * @param int $pos
218     * @return CheckableElement
219     */
220    public function addCheckbox($name, $label = '', $pos = -1) {
221        return $this->addElement(new CheckableElement('checkbox', $name, $label), $pos);
222    }
223
224    /**
225     * Adds a textarea field
226     *
227     * @param $name
228     * @param $label
229     * @param int $pos
230     * @return TextareaElement
231     */
232    public function addTextarea($name, $label = '', $pos = -1) {
233        return $this->addElement(new TextareaElement($name, $label), $pos);
234    }
235
236    /**
237     * Adds a simple button, escapes the content for you
238     *
239     * @param string $name
240     * @param string $content
241     * @param int $pos
242     * @return Element
243     */
244    public function addButton($name, $content, $pos = -1) {
245        return $this->addElement(new ButtonElement($name, hsc($content)), $pos);
246    }
247
248    /**
249     * Adds a simple button, allows HTML for content
250     *
251     * @param string $name
252     * @param string $html
253     * @param int $pos
254     * @return Element
255     */
256    public function addButtonHTML($name, $html, $pos = -1) {
257        return $this->addElement(new ButtonElement($name, $html), $pos);
258    }
259
260    /**
261     * Add fixed HTML to the form
262     *
263     * @param $html
264     * @param int $pos
265     * @return HTMLElement
266     */
267    public function addHTML($html, $pos = -1) {
268        return $this->addElement(new HTMLElement($html), $pos);
269    }
270
271    /**
272     * Add a closed HTML tag to the form
273     *
274     * @param $tag
275     * @param int $pos
276     * @return TagElement
277     */
278    public function addTag($tag, $pos = -1) {
279        return $this->addElement(new TagElement($tag), $pos);
280    }
281
282    /**
283     * Add an open HTML tag to the form
284     *
285     * Be sure to close it again!
286     *
287     * @param $tag
288     * @param int $pos
289     * @return TagOpenElement
290     */
291    public function addTagOpen($tag, $pos = -1) {
292        return $this->addElement(new TagOpenElement($tag), $pos);
293    }
294
295    /**
296     * Add a closing HTML tag to the form
297     *
298     * Be sure it had been opened before
299     *
300     * @param $tag
301     * @param int $pos
302     * @return TagCloseElement
303     */
304    public function addTagClose($tag, $pos = -1) {
305        return $this->addElement(new TagCloseElement($tag), $pos);
306    }
307
308    /**
309     * Open a Fieldset
310     *
311     * @param $legend
312     * @param int $pos
313     * @return FieldsetOpenElement
314     */
315    public function addFieldsetOpen($legend = '', $pos = -1) {
316        return $this->addElement(new FieldsetOpenElement($legend), $pos);
317    }
318
319    /**
320     * Close a fieldset
321     *
322     * @param int $pos
323     * @return TagCloseElement
324     */
325    public function addFieldsetClose($pos = -1) {
326        return $this->addElement(new FieldsetCloseElement(), $pos);
327    }
328
329    #endregion
330
331    /**
332     * Adjust the elements so that fieldset open and closes are matching
333     */
334    protected function balanceFieldsets() {
335        $lastclose = 0;
336        $isopen = false;
337        $len = count($this->elements);
338
339        for($pos = 0; $pos < $len; $pos++) {
340            $type = $this->elements[$pos]->getType();
341            if($type == 'fieldsetopen') {
342                if($isopen) {
343                    //close previous fieldset
344                    $this->addFieldsetClose($pos);
345                    $lastclose = $pos + 1;
346                    $pos++;
347                    $len++;
348                }
349                $isopen = true;
350            } else if($type == 'fieldsetclose') {
351                if(!$isopen) {
352                    // make sure there was a fieldsetopen
353                    // either right after the last close or at the begining
354                    $this->addFieldsetOpen('', $lastclose);
355                    $len++;
356                    $pos++;
357                }
358                $lastclose = $pos;
359                $isopen = false;
360            }
361        }
362
363        // close open fieldset at the end
364        if($isopen) {
365            $this->addFieldsetClose();
366        }
367    }
368
369    /**
370     * The HTML representation of the whole form
371     *
372     * @return string
373     */
374    public function toHTML() {
375        $this->balanceFieldsets();
376
377        $html = '<form ' . buildAttributes($this->attrs()) . '>' . DOKU_LF;
378
379        foreach($this->hidden as $name => $value) {
380            $html .= '<input type="hidden" name="' . $name . '" value="' . formText($value) . '" />' . DOKU_LF;
381        }
382
383        foreach($this->elements as $element) {
384            $html .= $element->toHTML() . DOKU_LF;
385        }
386
387        $html .= '</form>' . DOKU_LF;
388
389        return $html;
390    }
391}
392