xref: /plugin/struct/helper/field.php (revision 64480a7b452b659e799eac49e0d5307f940e6095)
1<?php
2
3use dokuwiki\plugin\struct\meta\Column;
4use dokuwiki\plugin\struct\meta\Schema;
5use dokuwiki\plugin\struct\meta\StructException;
6use dokuwiki\plugin\struct\meta\Value;
7use dokuwiki\plugin\struct\meta\ValueValidator;
8use dokuwiki\plugin\struct\types\Lookup;
9use dokuwiki\plugin\struct\types\Page;
10use dokuwiki\plugin\struct\types\User;
11
12/**
13 * Allows adding a single struct field as a bureaucracy field
14 *
15 * This class is used when a field of the type struct_field is encountered in the
16 * bureaucracy syntax.
17 */
18class helper_plugin_struct_field extends helper_plugin_bureaucracy_field
19{
20    /** @var  Column */
21    public $column;
22
23    /**
24     * Initialize the appropriate column
25     *
26     * @param array $args
27     */
28    public function initialize($args)
29    {
30        $this->init($args);
31
32        // find the column
33        try {
34            $this->column = $this->findColumn($this->opt['label']);
35        } catch (StructException $e) {
36            msg(hsc($e->getMessage()), -1);
37        }
38
39        $this->standardArgs($args);
40    }
41
42    /**
43     * Sets the value and validates it
44     *
45     * @param mixed $value
46     * @return bool value was set successfully validated
47     */
48    protected function setVal($value)
49    {
50        if (!$this->column) {
51            $value = '';
52            //don't validate placeholders here
53        } elseif ($this->replace($value) == $value) {
54            $validator = new ValueValidator();
55            $this->error = !$validator->validateValue($this->column, $value);
56            if ($this->error) {
57                foreach ($validator->getErrors() as $error) {
58                    msg(hsc($error), -1);
59                }
60            }
61        }
62
63        if ($value === array() || $value === '') {
64            if (!isset($this->opt['optional'])) {
65                $this->error = true;
66                if ($this->column) {
67                    $label = $this->column->getTranslatedLabel();
68                } else {
69                    $label = $this->opt['label'];
70                }
71                msg(sprintf($this->getLang('e_required'), hsc($label)), -1);
72            }
73        }
74
75        $this->opt['value'] = $value;
76        return !$this->error;
77    }
78
79    /**
80     * Creates the HTML for the field
81     *
82     * @param array $params
83     * @param Doku_Form $form
84     * @param int $formid
85     */
86    public function renderfield($params, Doku_Form $form, $formid)
87    {
88        if (!$this->column) return;
89
90        // this is what parent does
91        $this->_handlePreload();
92        if (!$form->_infieldset) {
93            $form->startFieldset('');
94        }
95        if ($this->error) {
96            $params['class'] = 'bureaucracy_error';
97        }
98
99        // output the field
100        $value = $this->createValue();
101        $field = $this->makeField($value, $params['name']);
102        $form->addElement($field);
103    }
104
105    /**
106     * Adds replacement for type user to the parent method
107     *
108     * @return array|mixed|string
109     */
110    public function getReplacementValue()
111    {
112        $value = $this->getParam('value');
113
114        if (is_array($value)) {
115            return array($this, 'replacementMultiValueCallback');
116        }
117
118        if (!empty($value) && $this->column->getType() instanceof User) {
119            return userlink($value, true);
120        }
121
122        return parent::getReplacementValue();
123    }
124
125    /**
126     * Adds handling of type user to the parent method
127     *
128     * @param $matches
129     * @return string
130     */
131    public function replacementMultiValueCallback($matches)
132    {
133        $value = $this->opt['value'];
134
135        //default value
136        if (is_null($value) || $value === false) {
137            if (isset($matches['default']) && $matches['default'] != '') {
138                return $matches['default'];
139            }
140            return $matches[0];
141        }
142
143        if (!empty($value) && $this->column->getType() instanceof User) {
144            $value = array_map(function ($user) {
145                return userlink($user, true);
146            }, $value);
147        }
148
149        //check if matched string containts a pair of brackets
150        $delimiter = preg_match('/\(.*\)/s', $matches[0]) ? $matches['delimiter'] : ', ';
151
152        return implode($delimiter, $value);
153    }
154
155    /**
156     * Returns a Value object for the current column.
157     * Special handling for Page and Lookup literal form values.
158     *
159     * @return Value
160     */
161    protected function createValue()
162    {
163        $preparedValue = $this->opt['value'] ?? '';
164
165        // page fields might need to be JSON encoded depending on usetitles config
166        if (
167            $this->column->getType() instanceof Page
168            && $this->column->getType()->getConfig()['usetitles']
169        ) {
170            $preparedValue = json_encode([$preparedValue, null]);
171        }
172
173        $value = new Value($this->column, $preparedValue);
174
175        // no way to pass $israw parameter to constructor, so re-set the Lookup value
176        if ($this->column->getType() instanceof Lookup) {
177            $value->setValue($preparedValue, true);
178        }
179
180        return $value;
181    }
182
183    /**
184     * Create the input field
185     *
186     * @param Value $field
187     * @param String $name field's name
188     * @return string
189     */
190    protected function makeField(Value $field, $name)
191    {
192        $trans = hsc($field->getColumn()->getTranslatedLabel());
193        $hint = hsc($field->getColumn()->getTranslatedHint());
194        $class = $hint ? 'hashint' : '';
195        $lclass = $this->error ? 'bureaucracy_error' : '';
196        $colname = $field->getColumn()->getFullQualifiedLabel();
197        $required = !empty($this->opt['optional']) ? '' : ' <sup>*</sup>';
198
199        $id = uniqid('struct__', true);
200        $input = $field->getValueEditor($name, $id);
201
202        $html = '<div class="field">';
203        $html .= "<label class=\"$lclass\" data-column=\"$colname\" for=\"$id\">";
204        $html .= "<span class=\"label $class\" title=\"$hint\">$trans$required</span>";
205        $html .= '</label>';
206        $html .= "<span class=\"input\">$input</span>";
207        $html .= '</div>';
208
209        return $html;
210    }
211
212    /**
213     * Tries to find the correct column and schema
214     *
215     * @param string $colname
216     * @return \dokuwiki\plugin\struct\meta\Column
217     * @throws StructException
218     */
219    protected function findColumn($colname)
220    {
221        list($table, $label) = explode('.', $colname, 2);
222        if (!$table || !$label) {
223            throw new StructException('Field \'%s\' not given in schema.field form', $colname);
224        }
225        $schema = new Schema($table);
226        return $schema->findColumn($label);
227    }
228
229    /**
230     * This ensures all language strings are still working
231     *
232     * @return string always 'bureaucracy'
233     */
234    public function getPluginName()
235    {
236        return 'bureaucracy';
237    }
238}
239