xref: /plugin/struct/action/entry.php (revision bf4e3880a98336c9f3d6e62ad6bdc3ad402ac771)
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 dokuwiki\plugin\struct\meta\Assignments;
13use dokuwiki\plugin\struct\meta\SchemaData;
14use dokuwiki\plugin\struct\meta\Validator;
15use dokuwiki\plugin\struct\meta\Value;
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        // execute the validator
97        $validator = new Validator();
98        $this->validated = $validator->validate($INPUT->arr(self::$VAR), $ID);
99        $this->tosave = $validator->getChangedSchemas();
100        $INPUT->post->set(self::$VAR, $validator->getCleanedData());
101
102        if(!$this->validated) foreach($validator->getErrors() as $error) {
103            msg(hsc($error), -1);
104        }
105
106        // did validation go through? otherwise abort saving
107        if(!$this->validated && $act == 'save') {
108            $event->data = 'edit';
109        }
110
111        return false;
112    }
113
114    /**
115     * Check if the page has to be changed
116     *
117     * @param Doku_Event $event event object by reference
118     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
119     *                           handler was registered]
120     * @return bool
121     */
122    public function handle_pagesave_before(Doku_Event $event, $param) {
123        if($event->data['contentChanged']) return; // will be saved for page changes
124
125        if(count($this->tosave) || isset($GLOBALS['struct_plugin_force_page_save'])) {
126            if(trim($event->data['newContent']) === '') {
127                // this happens when a new page is tried to be created with only struct data
128                msg($this->getLang('emptypage'), -1);
129            } else {
130                $event->data['contentChanged'] = true; // save for data changes
131
132                // add a summary
133                if(empty($event->data['summary'])) {
134                    $event->data['summary'] = $this->getLang('summary');
135                }
136            }
137        }
138    }
139
140    /**
141     * Save the data
142     *
143     * When this is called, INPUT data has been validated already. On a restore action, the data is
144     * loaded from the database and not validated again.
145     *
146     * @param Doku_Event $event event object by reference
147     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
148     *                           handler was registered]
149     * @return bool
150     */
151    public function handle_pagesave_after(Doku_Event $event, $param) {
152        global $INPUT;
153        global $ACT;
154        global $REV;
155
156        $assignments = new Assignments();
157
158        if($ACT == 'revert' && $REV) {
159            // reversion is a special case, we load the data to restore from DB:
160            $structData = array();
161            $this->tosave = $assignments->getPageAssignments($event->data['id']);
162            foreach($this->tosave as $table) {
163                $oldData = new SchemaData($table, $event->data['id'], $REV);
164                $oldData->optionRawValue(true);
165                $structData[$table] = $oldData->getDataArray();
166            }
167        } else {
168            // data comes from the edit form
169            $structData = $INPUT->arr(self::$VAR);
170        }
171
172        if($event->data['changeType'] == DOKU_CHANGE_TYPE_DELETE && empty($GLOBALS['PLUGIN_MOVE_WORKING'])) {
173            // clear all data on delete unless it's a move operation
174            $tables = $assignments->getPageAssignments($event->data['id']);
175            foreach($tables as $table) {
176                $schemaData = new SchemaData($table, $event->data['id'], time());
177                $schemaData->clearData();
178            }
179        } else {
180            // save the provided data
181            if($this->tosave) foreach($this->tosave as $table) {
182                $schemaData = new SchemaData($table, $event->data['id'], $event->data['newRevision']);
183                $schemaData->saveData($structData[$table]);
184
185                // make sure this schema is assigned
186                $assignments->assignPageSchema($event->data['id'], $table);
187            }
188        }
189    }
190
191    /**
192     * Create the form to edit schemadata
193     *
194     * @param string $tablename
195     * @return string The HTML for this schema's form
196     */
197    protected function createForm($tablename) {
198        global $ID;
199        global $REV;
200        global $INPUT;
201        if (auth_quickaclcheck($ID) == AUTH_READ) return '';
202        if (checklock($ID)) return '';
203        $schema = new SchemaData($tablename, $ID, $REV);
204        $schemadata = $schema->getData();
205
206        $structdata = $INPUT->arr(self::$VAR);
207        if(isset($structdata[$tablename])) {
208            $postdata = $structdata[$tablename];
209        } else {
210            $postdata = array();
211        }
212
213        // we need a short, unique identifier to use in the cookie. this should be good enough
214        $schemaid = 'SRCT'.substr(str_replace(array('+', '/'), '', base64_encode(sha1($tablename, true))), 0, 5);
215        $html = '<fieldset data-schema="' . $schemaid . '">';
216        $html .= '<legend>' . hsc($tablename) . '</legend>';
217        foreach($schemadata as $field) {
218            $label = $field->getColumn()->getLabel();
219            if(isset($postdata[$label])) {
220                // posted data trumps stored data
221                $field->setValue($postdata[$label]);
222            }
223            $html .=  $this->makeField($field, self::$VAR . "[$tablename][$label]");
224        }
225        $html .= '</fieldset>';
226
227        return $html;
228    }
229
230    /**
231     * Create the input field
232     *
233     * @param Value $field
234     * @param String $name field's name
235     * @return string
236     */
237    protected function makeField(Value $field, $name) {
238        $trans = hsc($field->getColumn()->getTranslatedLabel());
239        $hint  = hsc($field->getColumn()->getTranslatedHint());
240        $class = $hint ? 'hashint' : '';
241        $colname = $field->getColumn()->getFullQualifiedLabel();
242
243        $input = $field->getValueEditor($name);
244
245        // we keep all the custom form stuff the field might produce, but hide it
246        if(!$field->getColumn()->isVisibleInEditor()) {
247            $hide = 'style="display:none"';
248        } else {
249            $hide = '';
250        }
251
252        $html = '';
253        $html .= "<label $hide data-column=\"$colname\">";
254        $html .= "<span class=\"label $class\" title=\"$hint\">$trans</span>";
255        $html .= "<span class=\"input\">$input</span>";
256        $html .= '</label>';
257
258        return $html;
259    }
260}
261
262// vim:ts=4:sw=4:et:
263