xref: /plugin/struct/helper/field.php (revision b360e3b5f0dd65e1a784310a1ef841ecb24beeab)
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        $value = $this->getParam('value');
112
113        if (is_array($value)) {
114            return array($this, 'replacementMultiValueCallback');
115        }
116
117        if (!empty($value) && $this->column->getType() instanceof User) {
118            return userlink($value, true);
119        }
120
121        return parent::getReplacementValue();
122    }
123
124    /**
125     * Adds handling of type user to the parent method
126     *
127     * @param $matches
128     * @return string
129     */
130    public function replacementMultiValueCallback($matches) {
131        $value = $this->opt['value'];
132
133        //default value
134        if (is_null($value) || $value === false) {
135            if (isset($matches['default']) && $matches['default'] != '') {
136                return $matches['default'];
137            }
138            return $matches[0];
139        }
140
141        if (!empty($value) && $this->column->getType() instanceof User) {
142            $value = array_map(function ($user) {
143                return userlink($user, true);
144            }, $value);
145        }
146
147        //check if matched string containts a pair of brackets
148        $delimiter = preg_match('/\(.*\)/s', $matches[0]) ? $matches['delimiter'] : ', ';
149
150        return implode($delimiter, $value);
151    }
152
153    /**
154     * Returns a Value object for the current column.
155     * Special handling for Page and Lookup literal form values.
156     *
157     * @return Value
158     */
159    protected function createValue()
160    {
161        $preparedValue = $this->opt['value'] ?? '';
162
163        // page fields might need to be JSON encoded depending on usetitles config
164        if (
165            $this->column->getType() instanceof Page
166            && $this->column->getType()->getConfig()['usetitles']
167        ) {
168            $preparedValue = json_encode([$preparedValue, null]);
169        }
170
171        $value = new Value($this->column, $preparedValue);
172
173        // no way to pass $israw parameter to constructor, so re-set the Lookup value
174        if ($this->column->getType() instanceof Lookup) {
175            $value->setValue($preparedValue, true);
176        }
177
178        return $value;
179    }
180
181    /**
182     * Create the input field
183     *
184     * @param Value $field
185     * @param String $name field's name
186     * @return string
187     */
188    protected function makeField(Value $field, $name)
189    {
190        $trans = hsc($field->getColumn()->getTranslatedLabel());
191        $hint = hsc($field->getColumn()->getTranslatedHint());
192        $class = $hint ? 'hashint' : '';
193        $lclass = $this->error ? 'bureaucracy_error' : '';
194        $colname = $field->getColumn()->getFullQualifiedLabel();
195        $required = !empty($this->opt['optional']) ? '' : ' <sup>*</sup>';
196
197        $id = uniqid('struct__', true);
198        $input = $field->getValueEditor($name, $id);
199
200        $html = '<div class="field">';
201        $html .= "<label class=\"$lclass\" data-column=\"$colname\" for=\"$id\">";
202        $html .= "<span class=\"label $class\" title=\"$hint\">$trans$required</span>";
203        $html .= '</label>';
204        $html .= "<span class=\"input\">$input</span>";
205        $html .= '</div>';
206
207        return $html;
208    }
209
210    /**
211     * Tries to find the correct column and schema
212     *
213     * @param string $colname
214     * @return \dokuwiki\plugin\struct\meta\Column
215     * @throws StructException
216     */
217    protected function findColumn($colname)
218    {
219        list($table, $label) = explode('.', $colname, 2);
220        if (!$table || !$label) {
221            throw new StructException('Field \'%s\' not given in schema.field form', $colname);
222        }
223        $schema = new Schema($table);
224        return $schema->findColumn($label);
225    }
226
227    /**
228     * This ensures all language strings are still working
229     *
230     * @return string always 'bureaucracy'
231     */
232    public function getPluginName()
233    {
234        return 'bureaucracy';
235    }
236}
237