xref: /plugin/struct/action/inline.php (revision 8925ba298f12cecb837c2c249b3a592d289eabe2)
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
10use dokuwiki\plugin\struct\meta\AccessTable;
11use dokuwiki\plugin\struct\meta\AccessTableData;
12use dokuwiki\plugin\struct\meta\Assignments;
13use dokuwiki\plugin\struct\meta\Column;
14use dokuwiki\plugin\struct\meta\StructException;
15use dokuwiki\plugin\struct\meta\ValueValidator;
16
17if(!defined('DOKU_INC')) die();
18
19/**
20 * Class action_plugin_struct_inline
21 *
22 * Handle inline editing
23 */
24class action_plugin_struct_inline extends DokuWiki_Action_Plugin {
25
26    /** @var  AccessTableData */
27    protected $schemadata = null;
28
29    /** @var  Column */
30    protected $column = null;
31
32    /** @var String */
33    protected $pid = '';
34
35    /**
36     * Registers a callback function for a given event
37     *
38     * @param Doku_Event_Handler $controller DokuWiki's event controller object
39     * @return void
40     */
41    public function register(Doku_Event_Handler $controller) {
42        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax');
43    }
44
45    /**
46     * @param Doku_Event $event
47     * @param $param
48     */
49    public function handle_ajax(Doku_Event $event, $param) {
50        $len = strlen('plugin_struct_inline_');
51        if(substr($event->data, 0, $len) != 'plugin_struct_inline_') return;
52        $event->preventDefault();
53        $event->stopPropagation();
54
55        if(substr($event->data, $len) == 'editor') {
56            $this->inline_editor();
57        }
58
59        if(substr($event->data, $len) == 'save') {
60            try {
61                $this->inline_save();
62            } catch(StructException $e) {
63                http_status(500);
64                header('Content-Type: text/plain; charset=utf-8');
65                echo $e->getMessage();
66            }
67        }
68
69        if(substr($event->data, $len) == 'cancel') {
70            $this->inline_cancel();
71        }
72    }
73
74    /**
75     * Creates the inline editor
76     */
77    protected function inline_editor() {
78        // silently fail when editing not possible
79        if(!$this->initFromInput()) return;
80        if(auth_quickaclcheck($this->pid) < AUTH_EDIT) return;
81        if(!$this->schemadata->getSchema()->isEditable()) return;
82        if(checklock($this->pid)) return;
83
84        // lock page
85        lock($this->pid);
86
87        // output the editor
88        $value = $this->schemadata->getDataColumn($this->column);
89        echo '<label data-column="' . hsc($this->column->getFullQualifiedLabel()) . '">';
90        echo $value->getValueEditor('entry');
91        echo '</label>';
92        $hint = $this->column->getType()->getTranslatedHint();
93        if($hint) {
94            echo '<div class="hint">';
95            echo hsc($hint);
96            echo '</div>';
97        }
98
99        // csrf protection
100        formSecurityToken();
101    }
102
103    /**
104     * Save the data posted by the inline editor
105     */
106    protected function inline_save() {
107        global $INPUT;
108
109        // check preconditions
110        if(!$this->initFromInput()) {
111            throw new StructException('inline save error: init');
112        }
113        self::checkCSRF();
114        if(!$this->schemadata->getSchema()->isLookup()) {
115            $this->checkPage();
116            $assignments = Assignments::getInstance();
117            $tables = $assignments->getPageAssignments($this->pid, true);
118            if (!in_array($this->schemadata->getSchema()->getTable(), $tables)) {
119                throw new StructException('inline save error: schema not assigned to page');
120            }
121        }
122        if(!$this->schemadata->getSchema()->isEditable()) {
123            throw new StructException('inline save error: no permission for schema');
124        }
125
126        // validate
127        $value = $INPUT->param('entry');
128        $validator = new ValueValidator();
129        if(!$validator->validateValue($this->column, $value)) {
130            throw new StructException(join("\n", $validator->getErrors()));
131        }
132
133        // current data
134        $tosave = $this->schemadata->getDataArray();
135        $tosave[$this->column->getLabel()] = $value;
136
137        // save
138        if($this->schemadata->getSchema()->isLookup()) {
139            $revision = 0;
140        } else {
141            $revision = helper_plugin_struct::createPageRevision($this->pid, 'inline edit');
142            p_get_metadata($this->pid); // reparse the metadata of the page top update the titles/rev/lasteditor table
143        }
144        $this->schemadata->setTimestamp($revision);
145        try {
146            if(!$this->schemadata->saveData($tosave)) {
147                throw new StructException('saving failed');
148            }
149            if(!$this->schemadata->getSchema()->isLookup()) {
150                // make sure this schema is assigned
151                /** @noinspection PhpUndefinedVariableInspection */
152                $assignments->assignPageSchema(
153                    $this->pid,
154                    $this->schemadata->getSchema()->getTable()
155                );
156            }
157        } catch (\Exception $e) {
158            // PHP <7 needs a catch block
159            throw $e;
160        } finally {
161            // unlock (unlocking a non-existing file is okay,
162            // so we don't check if it's a lookup here
163            unlock($this->pid);
164        }
165
166        // reinit then render
167        $this->initFromInput();
168        $value = $this->schemadata->getDataColumn($this->column);
169        $R = new Doku_Renderer_xhtml();
170        $value->render($R, 'xhtml'); // FIXME use configured default renderer
171        echo $R->doc;
172    }
173
174    /**
175     * Unlock a page (on cancel action)
176     */
177    protected function inline_cancel() {
178        global $INPUT;
179        $pid = $INPUT->str('pid');
180        unlock($pid);
181    }
182
183    /**
184     * Initialize internal state based on input variables
185     *
186     * @return bool if initialization was successfull
187     */
188    protected function initFromInput() {
189        global $INPUT;
190
191        $this->schemadata = null;
192        $this->column = null;
193
194        $pid = $INPUT->str('pid');
195        list($table, $field) = explode('.', $INPUT->str('field'));
196        if(blank($pid)) return false;
197        if(blank($table)) return false;
198        if(blank($field)) return false;
199
200        $this->pid = $pid;
201        try {
202            $this->schemadata = AccessTable::byTableName($table, $pid);
203        } catch(StructException $ignore) {
204            return false;
205        }
206
207        $this->column = $this->schemadata->getSchema()->findColumn($field);
208        if(!$this->column || !$this->column->isVisibleInEditor()) {
209            $this->schemadata = null;
210            $this->column = null;
211            return false;
212        }
213
214        return true;
215    }
216
217    /**
218     * Checks if a page can be edited
219     *
220     * @throws StructException when check fails
221     */
222    protected function checkPage() {
223        if(!page_exists($this->pid)) {
224            throw new StructException('inline save error: no such page');
225        }
226        if(auth_quickaclcheck($this->pid) < AUTH_EDIT) {
227            throw new StructException('inline save error: acl');
228        }
229        if(checklock($this->pid)) {
230            throw new StructException('inline save error: lock');
231        }
232    }
233
234    /**
235     * Our own implementation of checkSecurityToken because we don't want the msg() call
236     *
237     * @throws StructException when check fails
238     */
239    public static function checkCSRF() {
240        global $INPUT;
241        if(
242            $INPUT->server->str('REMOTE_USER') &&
243            getSecurityToken() != $INPUT->str('sectok')
244        ) {
245            throw new StructException('CSRF check failed');
246        }
247    }
248
249}
250