xref: /dokuwiki/inc/Form/Form.php (revision abbfdfefc9bf5549b7f6a6c6697fa4f4426e7922)
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     * Add fixed HTML to the form
238     *
239     * @param $html
240     * @param int $pos
241     * @return HTMLElement
242     */
243    public function addHTML($html, $pos = -1) {
244        return $this->addElement(new HTMLElement($html), $pos);
245    }
246
247    /**
248     * Add a closed HTML tag to the form
249     *
250     * @param $tag
251     * @param int $pos
252     * @return TagElement
253     */
254    public function addTag($tag, $pos = -1) {
255        return $this->addElement(new TagElement($tag), $pos);
256    }
257
258    /**
259     * Add an open HTML tag to the form
260     *
261     * Be sure to close it again!
262     *
263     * @param $tag
264     * @param int $pos
265     * @return TagOpenElement
266     */
267    public function addTagOpen($tag, $pos = -1) {
268        return $this->addElement(new TagOpenElement($tag), $pos);
269    }
270
271    /**
272     * Add a closing HTML tag to the form
273     *
274     * Be sure it had been opened before
275     *
276     * @param $tag
277     * @param int $pos
278     * @return TagCloseElement
279     */
280    public function addTagClose($tag, $pos = -1) {
281        return $this->addElement(new TagCloseElement($tag), $pos);
282    }
283
284    /**
285     * Open a Fieldset
286     *
287     * @param $legend
288     * @param int $pos
289     * @return FieldsetOpenElement
290     */
291    public function addFieldsetOpen($legend = '', $pos = -1) {
292        return $this->addElement(new FieldsetOpenElement($legend), $pos);
293    }
294
295    /**
296     * Close a fieldset
297     *
298     * @param int $pos
299     * @return TagCloseElement
300     */
301    public function addFieldsetClose($pos = -1) {
302        return $this->addElement(new FieldsetCloseElement(), $pos);
303    }
304
305    #endregion
306
307    /**
308     * Adjust the elements so that fieldset open and closes are matching
309     */
310    protected function balanceFieldsets() {
311        $lastclose = 0;
312        $isopen = false;
313        $len = count($this->elements);
314
315        for($pos = 0; $pos < $len; $pos++) {
316            $type = $this->elements[$pos]->getType();
317            if($type == 'fieldsetopen') {
318                if($isopen) {
319                    //close previous fieldset
320                    $this->addFieldsetClose($pos);
321                    $lastclose = $pos + 1;
322                    $pos++;
323                    $len++;
324                }
325                $isopen = true;
326            } else if($type == 'fieldsetclose') {
327                if(!$isopen) {
328                    // make sure there was a fieldsetopen
329                    // either right after the last close or at the begining
330                    $this->addFieldsetOpen('', $lastclose);
331                    $len++;
332                    $pos++;
333                }
334                $lastclose = $pos;
335                $isopen = false;
336            }
337        }
338
339        // close open fieldset at the end
340        if($isopen) {
341            $this->addFieldsetClose();
342        }
343    }
344
345    /**
346     * The HTML representation of the whole form
347     *
348     * @return string
349     */
350    public function toHTML() {
351        $this->balanceFieldsets();
352
353        $html = '<form ' . buildAttributes($this->attrs()) . '>' . DOKU_LF;
354
355        foreach($this->hidden as $name => $value) {
356            $html .= '<input type="hidden" name="' . $name . '" value="' . formText($value) . '" />' . DOKU_LF;
357        }
358
359        foreach($this->elements as $element) {
360            $html .= $element->toHTML() . DOKU_LF;
361        }
362
363        $html .= '</form>' . DOKU_LF;
364
365        return $html;
366    }
367}
368