xref: /plugin/struct/action/entry.php (revision d2b31c9b2b42ab6635b261d1f4bcd72551c4ffbf)
1<?php
2/**
3 * DokuWiki Plugin struct (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr, Michael Große <dokuwiki@cosmocode.de>
7 */
8
9// must be run within Dokuwiki
10if(!defined('DOKU_INC')) die();
11
12use plugin\struct\meta\Assignments;
13use plugin\struct\meta\SchemaData;
14use plugin\struct\meta\ValidationException;
15use plugin\struct\types\AbstractBaseType;
16
17/**
18 * Class action_plugin_struct_entry
19 *
20 * Handles the whole struct data entry process
21 */
22class action_plugin_struct_entry extends DokuWiki_Action_Plugin {
23
24    /**
25     * @var string The form name we use to transfer schema data
26     */
27    protected static $VAR = 'struct_schema_data';
28
29    /** @var helper_plugin_sqlite */
30    protected $sqlite;
31
32    /** @var  bool has the data been validated correctly? */
33    protected $validated;
34
35    /** @var  array these schemas have changed data and need to be saved */
36    protected $tosave;
37
38    /**
39     * Registers a callback function for a given event
40     *
41     * @param Doku_Event_Handler $controller DokuWiki's event controller object
42     * @return void
43     */
44    public function register(Doku_Event_Handler $controller) {
45        // add the struct editor to the edit form;
46        $controller->register_hook('HTML_EDITFORM_OUTPUT', 'BEFORE', $this, 'handle_editform');
47        // validate data on preview and save;
48        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handle_validation');
49        // ensure a page revision is created when struct data changes:
50        $controller->register_hook('COMMON_WIKIPAGE_SAVE', 'BEFORE', $this, 'handle_pagesave_before');
51        // save struct data after page has been saved:
52        $controller->register_hook('COMMON_WIKIPAGE_SAVE', 'AFTER', $this, 'handle_pagesave_after');
53    }
54
55    /**
56     * Enhance the editing form with structural data editing
57     *
58     * @param Doku_Event $event event object by reference
59     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
60     *                           handler was registered]
61     * @return bool
62     */
63    public function handle_editform(Doku_Event $event, $param) {
64        global $ID;
65
66        $assignments = new Assignments();
67        $tables = $assignments->getPageAssignments($ID);
68
69        $html = '';
70        foreach($tables as $table) {
71            $html .= $this->createForm($table);
72        }
73
74        /** @var Doku_Form $form */
75        $form = $event->data;
76        $html = "<div class=\"struct\">$html</div>";
77        $pos = $form->findElementById('wiki__editbar'); // insert the form before the main buttons
78        $form->insertElement($pos, $html);
79
80        return true;
81    }
82
83    /**
84     * Clean up and validate the input data
85     *
86     * @param Doku_Event $event event object by reference
87     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
88     *                           handler was registered]
89     * @return bool
90     */
91    public function handle_validation(Doku_Event $event, $param) {
92        global $ID, $INPUT;
93        $act = act_clean($event->data);
94        if(!in_array($act, array('save', 'preview'))) return false;
95
96        $assignments = new Assignments();
97        $tables = $assignments->getPageAssignments($ID);
98        $structData = $INPUT->arr(self::$VAR);
99        $timestamp = time();
100
101        $this->tosave = array();
102        $this->validated = true;
103        foreach($tables as $table) {
104            $schemaData = new SchemaData($table, $ID, $timestamp);
105            if(!$schemaData->getId()) {
106                // this schema is not available for some reason. skip it
107                continue;
108            }
109
110            $newData = $structData[$table];
111            foreach($schemaData->getColumns() as $col) {
112                // fix multi value types
113                $type = $col->getType();
114                $label = $type->getLabel();
115                $trans = $type->getTranslatedLabel();
116                if($type->isMulti() && !is_array($newData[$label])) {
117                    $newData[$label] = $type->splitValues($newData[$label]);
118                }
119
120                // validate data
121                $this->validated = $this->validated && $this->validate($type, $trans, $newData[$label]);
122            }
123
124            // has the data changed? mark it for saving.
125            $olddata = $schemaData->getDataArray();
126            if($olddata != $newData) {
127                $this->tosave[] = $table;
128            }
129
130            // write back cleaned up data
131            $structData[$table] = $newData;
132        }
133        // write back cleaned up structData
134        $INPUT->post->set(self::$VAR, $structData);
135
136        // did validation go through? otherwise abort saving
137        if(!$this->validated && $act == 'save') {
138            $event->data = 'edit';
139        }
140
141        return false;
142    }
143
144    /**
145     * Check if the page has to be changed
146     *
147     * @param Doku_Event $event event object by reference
148     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
149     *                           handler was registered]
150     * @return bool
151     */
152    public function handle_pagesave_before(Doku_Event $event, $param) {
153        global $lang;
154
155        if($event->data['contentChanged']) return; // will be saved for page changes
156        if(count($this->tosave)) {
157            if(trim($event->data['newContent']) === '') {
158                // this happens when a new page is tried to be created with only struct data
159                msg($this->getLang('emptypage'), -1);
160            } else {
161                $event->data['contentChanged'] = true; // save for data changes
162            }
163        }
164    }
165
166    /**
167     * Save the data
168     *
169     * @param Doku_Event $event event object by reference
170     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
171     *                           handler was registered]
172     * @return bool
173     */
174    public function handle_pagesave_after(Doku_Event $event, $param) {
175        global $INPUT;
176
177        // this should never happen, because the validation is checked in handle_validation already
178        if(!$this->validated) return;
179
180        if($event->data['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
181            // FIXME we should probably clean out all data on delete!?
182            return;
183        }
184
185        $structData = $INPUT->arr(self::$VAR);
186
187        foreach($this->tosave as $table) {
188            $schemaData = new SchemaData($table, $event->data['id'], $event->data['newRevision']);
189            $schemaData->saveData($structData[$table]);
190        }
191    }
192
193    /**
194     * Validate the given data
195     *
196     * Catches the Validation exceptions and transforms them into proper messages.
197     *
198     * Blank values are not validated and always pass
199     *
200     * @param AbstractBaseType $type
201     * @param string $label
202     * @param array|string|int $data
203     * @return bool true if the data validates, otherwise false
204     */
205    protected function validate(AbstractBaseType $type, $label, $data) {
206        $prefix = sprintf($this->getLang('validation_prefix'), $label);
207
208        $ok = true;
209        if(is_array($data)) {
210            foreach($data as $value) {
211                if(!blank($value)) {
212                    try {
213                        $type->validate($value);
214                    } catch(ValidationException $e) {
215                        msg($prefix . $e->getMessage(), -1);
216                        $ok = false;
217                    }
218                }
219            }
220            return $ok;
221        }
222
223        if(!blank($data)) {
224            try {
225                $type->validate($data);
226            } catch(ValidationException $e) {
227                msg($prefix . $e->getMessage(), -1);
228                $ok = false;
229            }
230        }
231        return $ok;
232    }
233
234    /**
235     * Create the form to edit schemadata
236     *
237     * @param string $tablename
238     * @return string The HTML for this schema's form
239     */
240    protected function createForm($tablename) {
241        global $ID;
242        global $REV;
243        global $INPUT;
244        $schema = new SchemaData($tablename, $ID, $REV);
245        $schemadata = $schema->getData();
246
247        $structdata = $INPUT->arr(self::$VAR);
248        if(isset($structdata[$tablename])) {
249            $postdata = $structdata[$tablename];
250        } else {
251            $postdata = array();
252        }
253
254        $html = "<h3>$tablename</h3>";
255        foreach($schemadata as $field) {
256            $label = $field->getColumn()->getLabel();
257            if(isset($postdata[$label])) {
258                // posted data trumps stored data
259                $field->setValue($postdata[$label]);
260            }
261            $trans = hsc($field->getColumn()->getTranslatedLabel());
262            $name = self::$VAR . "[$tablename][$label]";
263            $input = $field->getValueEditor($name);
264            $element = "<label>$trans $input</label><br />";
265            $html .= $element;
266        }
267
268        return $html;
269    }
270
271}
272
273// vim:ts=4:sw=4:et:
274