xref: /plugin/struct/action/entry.php (revision c8a548a86ff277414b4aa64fb1d00e574940a79d)
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\meta\Validator;
16use plugin\struct\types\AbstractBaseType;
17
18/**
19 * Class action_plugin_struct_entry
20 *
21 * Handles the whole struct data entry process
22 */
23class action_plugin_struct_entry extends DokuWiki_Action_Plugin {
24
25    /**
26     * @var string The form name we use to transfer schema data
27     */
28    protected static $VAR = 'struct_schema_data';
29
30    /** @var helper_plugin_sqlite */
31    protected $sqlite;
32
33    /** @var  bool has the data been validated correctly? */
34    protected $validated;
35
36    /** @var  array these schemas have changed data and need to be saved */
37    protected $tosave;
38
39    /**
40     * Registers a callback function for a given event
41     *
42     * @param Doku_Event_Handler $controller DokuWiki's event controller object
43     * @return void
44     */
45    public function register(Doku_Event_Handler $controller) {
46        // add the struct editor to the edit form;
47        $controller->register_hook('HTML_EDITFORM_OUTPUT', 'BEFORE', $this, 'handle_editform');
48        // validate data on preview and save;
49        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handle_validation');
50        // ensure a page revision is created when struct data changes:
51        $controller->register_hook('COMMON_WIKIPAGE_SAVE', 'BEFORE', $this, 'handle_pagesave_before');
52        // save struct data after page has been saved:
53        $controller->register_hook('COMMON_WIKIPAGE_SAVE', 'AFTER', $this, 'handle_pagesave_after');
54    }
55
56    /**
57     * Enhance the editing form with structural data editing
58     *
59     * @param Doku_Event $event event object by reference
60     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
61     *                           handler was registered]
62     * @return bool
63     */
64    public function handle_editform(Doku_Event $event, $param) {
65        global $ID;
66
67        $assignments = new Assignments();
68        $tables = $assignments->getPageAssignments($ID);
69
70        $html = '';
71        foreach($tables as $table) {
72            $html .= $this->createForm($table);
73        }
74
75        /** @var Doku_Form $form */
76        $form = $event->data;
77        $html = "<div class=\"struct\">$html</div>";
78        $pos = $form->findElementById('wiki__editbar'); // insert the form before the main buttons
79        $form->insertElement($pos, $html);
80
81        return true;
82    }
83
84    /**
85     * Clean up and validate the input data
86     *
87     * @param Doku_Event $event event object by reference
88     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
89     *                           handler was registered]
90     * @return bool
91     */
92    public function handle_validation(Doku_Event $event, $param) {
93        global $ID, $INPUT;
94        $act = act_clean($event->data);
95        if(!in_array($act, array('save', 'preview'))) return false;
96
97        // execute the validator
98        $validator = new Validator();
99        $this->validated = $validator->validate($INPUT->arr(self::$VAR), $ID);
100        $this->tosave = $validator->getChangedSchemas();
101        $INPUT->post->set(self::$VAR, $validator->getCleanedData());
102
103        if(!$this->validated) foreach($validator->getErrors() as $error) {
104            msg(hsc($error), -1);
105        }
106
107        // did validation go through? otherwise abort saving
108        if(!$this->validated && $act == 'save') {
109            $event->data = 'edit';
110        }
111
112        return false;
113    }
114
115    /**
116     * Check if the page has to be changed
117     *
118     * @param Doku_Event $event event object by reference
119     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
120     *                           handler was registered]
121     * @return bool
122     */
123    public function handle_pagesave_before(Doku_Event $event, $param) {
124        if($event->data['contentChanged']) return; // will be saved for page changes
125        if(count($this->tosave)) {
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        }
133    }
134
135    /**
136     * Save the data
137     *
138     * When this is called, INPUT data has been validated already. On a restore action, the data is
139     * loaded from the database and not validated again.
140     *
141     * @param Doku_Event $event event object by reference
142     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
143     *                           handler was registered]
144     * @return bool
145     */
146    public function handle_pagesave_after(Doku_Event $event, $param) {
147        global $INPUT;
148        global $ACT;
149        global $REV;
150
151        $assignments = new Assignments();
152
153        if($ACT == 'revert' && $REV) {
154            // reversion is a special case, we load the data to restore from DB:
155            $structData = array();
156            $this->tosave = $assignments->getPageAssignments($event->data['id']);
157            foreach($this->tosave as $table) {
158                $oldData = new SchemaData($table, $event->data['id'], $REV);
159                $structData[$table] = $oldData->getDataArray();
160            }
161        } else {
162            // data comes from the edit form
163            $structData = $INPUT->arr(self::$VAR);
164        }
165
166        if($event->data['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
167            // clear all data
168            $tables = $assignments->getPageAssignments($event->data['id']);
169            foreach($tables as $table) {
170                $schemaData = new SchemaData($table, $event->data['id'], time());
171                $schemaData->clearData();
172            }
173        } else {
174            // save the provided data
175            foreach($this->tosave as $table) {
176                $schemaData = new SchemaData($table, $event->data['id'], $event->data['newRevision']);
177                $schemaData->saveData($structData[$table]);
178
179                // make sure this schema is assigned
180                $assignments->assignPageSchema($event->data['id'], $table);
181            }
182        }
183    }
184
185    /**
186     * Create the form to edit schemadata
187     *
188     * @param string $tablename
189     * @return string The HTML for this schema's form
190     */
191    protected function createForm($tablename) {
192        global $ID;
193        global $REV;
194        global $INPUT;
195        if (auth_quickaclcheck($ID) == AUTH_READ) return '';
196        if (checklock($ID)) return '';
197        $schema = new SchemaData($tablename, $ID, $REV);
198        $schemadata = $schema->getData();
199
200        $structdata = $INPUT->arr(self::$VAR);
201        if(isset($structdata[$tablename])) {
202            $postdata = $structdata[$tablename];
203        } else {
204            $postdata = array();
205        }
206
207        // we need a short, unique identifier to use in the cookie. this should be good enough
208        $schemaid = 'SRCT'.substr(str_replace(array('+', '/'), '', base64_encode(sha1($tablename, true))), 0, 5);
209        $html = '<fieldset data-schema="' . $schemaid . '">';
210        $html .= '<legend>' . hsc($tablename) . '</legend>';
211        foreach($schemadata as $field) {
212            $label = $field->getColumn()->getLabel();
213            if(isset($postdata[$label])) {
214                // posted data trumps stored data
215                $field->setValue($postdata[$label]);
216            }
217            $trans = hsc($field->getColumn()->getTranslatedLabel());
218            $hint  = hsc($field->getColumn()->getTranslatedHint());
219            $class = $hint ? 'hashint' : '';
220
221            $name = self::$VAR . "[$tablename][$label]";
222            $input = $field->getValueEditor($name);
223            $html .= '<label>';
224            $html .= "<span class=\"label $class\" title=\"$hint\">$trans</span>";
225            $html .= "<span class=\"input\">$input</span>";
226            $html .= '</label>';
227        }
228        $html .= '</fieldset>';
229
230        return $html;
231    }
232
233
234}
235
236// vim:ts=4:sw=4:et:
237