xref: /plugin/addnewpage/syntax.php (revision 641f0487ea9954b1ef223b55832d3664c320d4e3)
1<?php
2/**
3 * Add-New-Page Plugin: a simple form for adding new pages.
4 *
5 * @license  GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author   iDO <ido@idotech.info>
7 * @author   Sam Wilson <sam@samwilson.id.au>
8 *
9 * @noinspection PhpUnused
10 * @noinspection PhpMissingParamTypeInspection, PhpMissingReturnTypeInspection
11 */
12
13use dokuwiki\File\PageResolver;
14
15// must be run within Dokuwiki
16if(!defined('DOKU_INC')) die();
17
18class syntax_plugin_addnewpage extends DokuWiki_Syntax_Plugin {
19
20    /** @var array the parsed options */
21    protected $options;
22
23    /**
24     * Syntax Type
25     */
26    public function getType() {
27        return 'substition';
28    }
29
30    /**
31     * Paragraph Type
32     */
33    public function getPType() {
34        return 'block';
35    }
36
37    /**
38     * @return int
39     */
40    public function getSort() {
41        return 199;
42    }
43
44    /**
45     * @param string $mode
46     */
47    public function connectTo($mode) {
48        $this->Lexer->addSpecialPattern('\{\{NEWPAGE[^\}]*\}\}', $mode, 'plugin_addnewpage');
49    }
50
51    /**
52     * Handler to prepare matched data for the rendering process
53     *
54     * Handled syntax options:
55     *   {{NEWPAGE}}
56     *   {{NEWPAGE>your:namespace}}
57     *   {{NEWPAGE#newtpl1,newtpl2}}
58     *   {{NEWPAGE#newtpl1|Title1,newtpl2|Title1}}
59     *   {{NEWPAGE>your:namespace#newtpl1|Title1,newtpl2|Title1}}
60     *   {{NEWPAGE>your:namespace#newtpl1|Title1,newtpl2|Title1#@HI@,Howdy}}
61     *
62     * @param   string $match The text matched by the patterns
63     * @param   int $state The lexer state for the match
64     * @param   int $pos The character position of the matched text
65     * @param   Doku_Handler $handler The Doku_Handler object
66     * @return  array Return an array with all data you want to use in render
67     * @codingStandardsIgnoreStart
68     */
69    public function handle($match, $state, $pos, Doku_Handler $handler) {
70        /* @codingStandardsIgnoreEnd */
71        $match = substr($match, 9, -2); // strip markup
72
73        $data = array(
74            'namespace' => '',
75            'newpagetemplates' => array(),
76            'newpagevars' => '',
77            'options' => array(
78                'exclude' => $this->getConf('addpage_exclude'),
79                'showroot' => $this->getConf('addpage_showroot'),
80                'hide' => $this->getConf('addpage_hide'),
81                'hideacl' => $this->getConf('addpage_hideACL'),
82                'autopage' => $this->getConf('addpage_autopage'),
83            )
84        );
85
86        if(preg_match('/>(.*?)(#|\?|$)/', $match, $m)) {
87            $data['namespace'] = trim($m[1]);
88        }
89
90        # Extract the newpagetemplate plugin parameters
91        # - after the initial #: the template name
92        # - after optional 2nd #: custom variable names
93        if(preg_match('/#(.*?)(?:#(.*?))?(?:\?|$)/', $match, $m)) {
94            $data['newpagetemplates'] = array_map('trim', explode(',', $m[1]));
95            $data['newpagevars'] = trim($m[2] ?? '');
96        }
97
98        if(preg_match('/\?(.*?)(#|$)/', $match, $m)) {
99            $this->_parseOptions($m[1], $data['options']);
100        }
101
102        return $data;
103    }
104
105    /**
106     * Create the new-page form.
107     *
108     * @param   $format     string        output format being rendered
109     * @param   $renderer Doku_Renderer the current renderer object
110     * @param   $data     array         data created by handler()
111     * @return  boolean                 rendered correctly?
112     */
113    public function render($format, Doku_Renderer $renderer, $data) {
114        global $lang;
115
116        // make options available in class
117        $this->options = $data['options'];
118
119        if($format == 'xhtml') {
120            $disablecache = false;
121            $namespaceinput = $this->_htmlNamespaceInput($data['namespace'], $disablecache);
122            if($namespaceinput === false) {
123                if($this->options['hideacl']) {
124                    $renderer->doc .= '';
125                } else {
126                    $renderer->doc .= $this->getLang('nooption');
127                }
128                return true;
129            }
130            if($disablecache) $renderer->info['cache'] = false;
131
132            $newpagetemplateinput = $this->_htmlTemplateInput($data['newpagetemplates']);
133
134            $input = 'text';
135            if($this->options['autopage']) $input = 'hidden';
136
137            $form = '<div class="addnewpage"><p>'
138                . '<form name="addnewpage" method="get" action="' . DOKU_BASE . DOKU_SCRIPT . '" accept-charset="' . $lang['encoding'] . '">'
139                . $namespaceinput
140                . '<input class="edit" type="'.$input.'" name="title" size="20" maxlength="255" tabindex="2" />'
141                . $newpagetemplateinput
142                . '<input type="hidden" name="newpagevars" value="' . $data['newpagevars'] . '"/>'
143                . '<input type="hidden" name="do" value="edit" />'
144                . '<input type="hidden" name="id" />'
145                . '<input class="button" type="submit" value="' . $this->getLang('okbutton') . '" tabindex="4" />'
146                . '</form>'
147                . '</p></div>';
148
149            $renderer->doc .= $form;
150
151            return true;
152        }
153        return false;
154    }
155
156    /**
157     * Overwrites the $options with the ones parsed from $optstr
158     *
159     * @param string $optstr
160     * @param array $options
161     * @author Andreas Gohr <gohr@cosmocode.de>
162     */
163    protected function _parseOptions($optstr, &$options) {
164        $opts = preg_split('/[,&]/', $optstr);
165
166        foreach($opts as $opt) {
167            $opt = strtolower(trim($opt));
168            $val = true;
169            // booleans can be negated with a no prefix
170            if(substr($opt, 0, 2) == 'no') {
171                $opt = substr($opt, 2);
172                $val = false;
173            }
174
175            // not a known option? might be a key=value pair
176            if(!isset($options[$opt])) {
177                list($opt, $val) = array_map('trim', explode('=', $opt, 2));
178            }
179
180            // still unknown? skip it
181            if(!isset($options[$opt])) continue;
182
183            // overwrite the current value
184            $options[$opt] = $val;
185        }
186    }
187
188    /**
189     * Parse namespace request
190     *
191     * This creates the final ID to be created (still having an @INPUT@ variable
192     * which is filled in via JavaScript)
193     *
194     * @author Samuele Tognini <samuele@cli.di.unipi.it>
195     * @author Michael Braun <michael-dev@fami-braun.de>
196     * @author Andreas Gohr <gohr@cosmocode.de>
197     * @param string $ns The namespace as given in the syntax
198     * @return string
199     */
200    protected function _parseNS($ns) {
201        global $INFO;
202
203        $selfid = $INFO['id'];
204        $selfns = getNS($selfid);
205        // replace the input variable with something unique that survives cleanID
206        $keep = sha1(time());
207
208        // by default append the input to the namespace (except on autopage)
209        if(strpos($ns, '@INPUT@') === false && !$this->options['autopage']) $ns .= ":@INPUT@";
210
211        // date replacements
212        $ns = dformat(null, $ns);
213
214        // placeholders
215        $replacements = array(
216            '/\//' => ':', // forward slashes to colons
217            '/@PAGE@/' => $selfid,
218            '/@NS@/' => $selfns,
219            '/^\.(:|\/|$)/' => "$selfns:",
220            '/@INPUT@/' => $keep,
221        );
222        $ns = preg_replace(array_keys($replacements), array_values($replacements), $ns);
223
224        // clean up, then reinsert the input variable
225        $ns = cleanID($ns);
226        return str_replace($keep, '@INPUT@', $ns);
227    }
228
229    /**
230     * Create the HTML Select element for namespace selection.
231     *
232     * @param string|false $dest_ns The destination namespace, or false if none provided.
233     * @param bool $disablecache reference indicates if caching need to be disabled
234     * @global string $ID The page ID
235     * @return string Select element with appropriate NS selected.
236     */
237    protected function _htmlNamespaceInput($dest_ns, &$disablecache) {
238        global $ID;
239        $disablecache = false;
240
241        // If a NS has been provided:
242        // Whether to hide the NS selection (otherwise, show only subnamespaces).
243        $hide = $this->options['hide'];
244
245        $parsed_dest_ns = $this->_parseNS($dest_ns);
246        // Whether the user can create pages in the provided NS (or root, if no
247        // destination NS has been set.
248        $can_create = (auth_quickaclcheck($parsed_dest_ns . ":") >= AUTH_CREATE);
249
250        //namespace given, but hidden
251        if($hide && !empty($dest_ns)) {
252            if($can_create) {
253                return '<input type="hidden" name="np_cat" id="np_cat" value="' . $parsed_dest_ns . '"/>';
254            } else {
255                return false;
256            }
257        }
258
259        //show select of given namespace
260        $currentns = getNS($ID);
261
262        $ret = '<select class="edit" id="np_cat" name="np_cat" tabindex="1">';
263
264        // Whether the NS select element has any options
265        $someopt = false;
266
267        // Show root namespace if requested and allowed
268        if($this->options['showroot'] && $can_create) {
269            if(empty($dest_ns)) {
270                // If no namespace has been provided, add an option for the root NS.
271                $ret .= '<option ' . (($currentns == '') ? 'selected ' : '') . ' value="">' . $this->getLang('namespaceRoot') . '</option>';
272            } else {
273                // If a namespace has been provided, add an option for it.
274                $ret .= '<option ' . (($currentns == $dest_ns) ? 'selected ' : '') . ' value="' . formText($dest_ns) . '">' . formText($dest_ns) . '</option>';
275            }
276            $someopt = true;
277        }
278
279        $subnamespaces = $this->_getNamespaceList($dest_ns);
280
281        // The top of this stack will always be the last printed ancestor namespace
282        $ancestor_stack = array();
283        if (!empty($dest_ns)) {
284            $ancestor_stack[] = $dest_ns;
285        }
286
287        foreach($subnamespaces as $ns) {
288
289            if(auth_quickaclcheck($ns . ":") < AUTH_CREATE) continue;
290
291            // Pop any elements off the stack that are not ancestors of the current namespace
292            while(!empty($ancestor_stack) && strpos($ns, $ancestor_stack[count($ancestor_stack) - 1] . ':') !== 0) {
293                array_pop($ancestor_stack);
294            }
295
296            $nsparts = explode(':', $ns);
297            $first_unprinted_depth = empty($ancestor_stack) ? 1 : (2 + substr_count($ancestor_stack[count($ancestor_stack) - 1], ':'));
298            for($i = $first_unprinted_depth, $end = count($nsparts); $i <= $end; $i++) {
299                $namespace = implode(':', array_slice($nsparts, 0, $i));
300                $ancestor_stack[] = $namespace;
301                $selectOptionText = str_repeat('&nbsp;&nbsp;', substr_count($namespace, ':')) . $nsparts[$i - 1];
302                $ret .= '<option ' .
303                    (($currentns == $namespace) ? 'selected ' : '') .
304                    ($i == $end ? ('value="' . $namespace . '">') : 'disabled>') .
305                    $selectOptionText .
306                    '</option>';
307            }
308            $someopt = true;
309            $disablecache = true;
310        }
311
312        $ret .= '</select>';
313
314        if($someopt) {
315            return $ret;
316        } else {
317            return false;
318        }
319    }
320
321    /**
322     * Get a list of namespaces below the given namespace.
323     * Recursively fetches subnamespaces.
324     *
325     * @param string $topns The top namespace
326     * @return array Multi-dimensional array of all namespaces below $tns
327     */
328    protected function _getNamespaceList($topns = '') {
329        global $conf;
330
331        $topns = utf8_encodeFN(str_replace(':', '/', $topns));
332
333        $excludes = $this->options['exclude'];
334        if($excludes == "") {
335            $excludes = array();
336        } else {
337            $excludes = @explode(';', strtolower($excludes));
338        }
339        $searchdata = array();
340        search($searchdata, $conf['datadir'], 'search_namespaces', array(), $topns);
341
342        $namespaces = array();
343        foreach($searchdata as $ns) {
344            foreach($excludes as $exclude) {
345                if(!empty($exclude) && strpos($ns['id'], $exclude) === 0) {
346                    continue 2;
347                }
348            }
349            $namespaces[] = $ns['id'];
350        }
351
352        return $namespaces;
353    }
354
355    /**
356     * Create html for selection of namespace templates
357     *
358     * @param array $newpagetemplates array of namespace templates
359     * @return string html of select or hidden input
360     */
361    public function _htmlTemplateInput($newpagetemplates) {
362        $cnt = count($newpagetemplates);
363        if($cnt < 1 || $cnt == 1 && $newpagetemplates[0] == '') {
364            $input = '';
365
366        } else {
367            if($cnt == 1) {
368                list($template,) = $this->_parseNSTemplatePage($newpagetemplates[0]);
369                $input = '<input type="hidden" name="newpagetemplate" value="' . formText($template) . '" />';
370            } else {
371                $first = true;
372                $input = '<select name="newpagetemplate" tabindex="3">';
373                foreach($newpagetemplates as $template) {
374                    $p = ($first ? ' selected="selected"' : '');
375                    $first = false;
376
377                    list($template, $name) = $this->_parseNSTemplatePage($template);
378                    $p .= ' value="' . formText($template) . '"';
379                    $input .= "<option $p>" . formText($name) . "</option>";
380                }
381                $input .= '</select>';
382            }
383            $input = DOKU_TAB . DOKU_TAB . $input . DOKU_LF;
384        }
385        return $input;
386    }
387
388    /**
389     * Parses and resolves the namespace template page
390     *
391     * @param $nstemplate
392     * @return array
393     */
394    protected function _parseNSTemplatePage($nstemplate) {
395        global $ID;
396
397        @list($template, $name) = explode('|', $nstemplate, 2);
398        $template = (new PageResolver($ID))->resolveId($template);
399        if (is_null($name)) $name = $template;
400
401        return array($template, $name);
402    }
403
404}
405