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