xref: /dokuwiki/inc/Form/Form.php (revision f28fdf54fe5b1a3ba7fb4034266963201853a4f6)
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\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\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     * Adds a label referencing another input element, escapes the label for you
262     *
263     * @param $label
264     * @param string $for
265     * @param int $pos
266     * @return Element
267     */
268    public function addLabel($label, $for='', $pos = -1) {
269        return $this->addLabelHTML(hsc($label), $for, $pos);
270    }
271
272    /**
273     * Adds a label referencing another input element, allows HTML for content
274     *
275     * @param string $content
276     * @param string|Element $for
277     * @param int $pos
278     * @return Element
279     */
280    public function addLabelHTML($content, $for='', $pos = -1) {
281        $element = new LabelElement(hsc($content));
282
283        if(is_a($for, '\dokuwiki\Form\Element')) {
284            /** @var Element $for */
285            $for = $for->id();
286        }
287        $for = (string) $for;
288        if($for !== '') {
289            $element->attr('for', $for);
290        }
291
292        return $this->addElement($element, $pos);
293    }
294
295    /**
296     * Add fixed HTML to the form
297     *
298     * @param $html
299     * @param int $pos
300     * @return HTMLElement
301     */
302    public function addHTML($html, $pos = -1) {
303        return $this->addElement(new HTMLElement($html), $pos);
304    }
305
306    /**
307     * Add a closed HTML tag to the form
308     *
309     * @param $tag
310     * @param int $pos
311     * @return TagElement
312     */
313    public function addTag($tag, $pos = -1) {
314        return $this->addElement(new TagElement($tag), $pos);
315    }
316
317    /**
318     * Add an open HTML tag to the form
319     *
320     * Be sure to close it again!
321     *
322     * @param $tag
323     * @param int $pos
324     * @return TagOpenElement
325     */
326    public function addTagOpen($tag, $pos = -1) {
327        return $this->addElement(new TagOpenElement($tag), $pos);
328    }
329
330    /**
331     * Add a closing HTML tag to the form
332     *
333     * Be sure it had been opened before
334     *
335     * @param $tag
336     * @param int $pos
337     * @return TagCloseElement
338     */
339    public function addTagClose($tag, $pos = -1) {
340        return $this->addElement(new TagCloseElement($tag), $pos);
341    }
342
343    /**
344     * Open a Fieldset
345     *
346     * @param $legend
347     * @param int $pos
348     * @return FieldsetOpenElement
349     */
350    public function addFieldsetOpen($legend = '', $pos = -1) {
351        return $this->addElement(new FieldsetOpenElement($legend), $pos);
352    }
353
354    /**
355     * Close a fieldset
356     *
357     * @param int $pos
358     * @return TagCloseElement
359     */
360    public function addFieldsetClose($pos = -1) {
361        return $this->addElement(new FieldsetCloseElement(), $pos);
362    }
363
364    #endregion
365
366    /**
367     * Adjust the elements so that fieldset open and closes are matching
368     */
369    protected function balanceFieldsets() {
370        $lastclose = 0;
371        $isopen = false;
372        $len = count($this->elements);
373
374        for($pos = 0; $pos < $len; $pos++) {
375            $type = $this->elements[$pos]->getType();
376            if($type == 'fieldsetopen') {
377                if($isopen) {
378                    //close previous fieldset
379                    $this->addFieldsetClose($pos);
380                    $lastclose = $pos + 1;
381                    $pos++;
382                    $len++;
383                }
384                $isopen = true;
385            } else if($type == 'fieldsetclose') {
386                if(!$isopen) {
387                    // make sure there was a fieldsetopen
388                    // either right after the last close or at the begining
389                    $this->addFieldsetOpen('', $lastclose);
390                    $len++;
391                    $pos++;
392                }
393                $lastclose = $pos;
394                $isopen = false;
395            }
396        }
397
398        // close open fieldset at the end
399        if($isopen) {
400            $this->addFieldsetClose();
401        }
402    }
403
404    /**
405     * The HTML representation of the whole form
406     *
407     * @return string
408     */
409    public function toHTML() {
410        $this->balanceFieldsets();
411
412        $html = '<form ' . buildAttributes($this->attrs()) . '>' . DOKU_LF;
413
414        foreach($this->hidden as $name => $value) {
415            $html .= '<input type="hidden" name="' . $name . '" value="' . formText($value) . '" />' . DOKU_LF;
416        }
417
418        foreach($this->elements as $element) {
419            $html .= $element->toHTML() . DOKU_LF;
420        }
421
422        $html .= '</form>' . DOKU_LF;
423
424        return $html;
425    }
426}
427