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