xref: /plugin/addnewpage/syntax.php (revision 2c2790779b251360ab37a4f2de7eb805c175d179)
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 = strtolower(trim($opt));
185            $val = true;
186            // booleans can be negated with a no prefix
187            if(substr($opt, 0, 2) == 'no') {
188                $opt = substr($opt, 2);
189                $val = false;
190            }
191
192            // not a known option? might be a key=value pair
193            if(!isset($options[$opt])) {
194                list($opt, $val) = array_map('trim', sexplode('=', $opt, 2));
195            }
196
197            // still unknown? skip it
198            if(!isset($options[$opt])) continue;
199
200            // overwrite the current value
201            $options[$opt] = $val;
202        }
203    }
204
205    /**
206     * Parse namespace request
207     *
208     * This creates the final ID to be created (still having an @INPUT@ variable
209     * which is filled in via JavaScript)
210     *
211     * @author Samuele Tognini <samuele@cli.di.unipi.it>
212     * @author Michael Braun <michael-dev@fami-braun.de>
213     * @author Andreas Gohr <gohr@cosmocode.de>
214     * @param string $ns The namespace as given in the syntax
215     * @return string
216     */
217    protected function _parseNS($ns) {
218        global $INFO;
219
220        $selfid = $INFO['id'];
221        $selfns = getNS($selfid);
222        // replace the input variable with something unique that survives cleanID
223        $keep = sha1(time());
224
225        // by default append the input to the namespace (except on autopage)
226        if(strpos($ns, '@INPUT@') === false && !$this->options['autopage']) $ns .= ":@INPUT@";
227
228        // date replacements
229        $ns = dformat(null, $ns);
230
231        // placeholders
232        $replacements = array(
233            '/\//' => ':', // forward slashes to colons
234            '/@PAGE@/' => $selfid,
235            '/@NS@/' => $selfns,
236            '/^\.(:|\/|$)/' => "$selfns:",
237            '/@INPUT@/' => $keep,
238        );
239        $ns = preg_replace(array_keys($replacements), array_values($replacements), $ns);
240
241        // clean up, then reinsert the input variable
242        $ns = cleanID($ns);
243        return str_replace($keep, '@INPUT@', $ns);
244    }
245
246    /**
247     * Create the HTML Select element for namespace selection.
248     *
249     * @param string|false $dest_ns The destination namespace, or false if none provided.
250     * @param bool $disablecache reference indicates if caching need to be disabled
251     * @global string $ID The page ID
252     * @return string Select element with appropriate NS selected.
253     */
254    protected function _htmlNamespaceInput($dest_ns, &$disablecache) {
255        global $ID;
256        $disablecache = false;
257
258        // If a NS has been provided:
259        // Whether to hide the NS selection (otherwise, show only subnamespaces).
260        $hide = $this->options['hide'];
261
262        $parsed_dest_ns = $this->_parseNS($dest_ns);
263        // Whether the user can create pages in the provided NS (or root, if no
264        // destination NS has been set.
265        $can_create = (auth_quickaclcheck($parsed_dest_ns . ":") >= AUTH_CREATE);
266
267        //namespace given, but hidden
268        if($hide && !empty($dest_ns)) {
269            if($can_create) {
270                return '<input type="hidden" name="np_cat" id="np_cat" value="' . $parsed_dest_ns . '"/>';
271            } else {
272                return false;
273            }
274        }
275
276        //show select of given namespace
277        $currentns = getNS($ID);
278
279        $ret = '<select class="edit" id="np_cat" name="np_cat" tabindex="1">';
280
281        // Whether the NS select element has any options
282        $someopt = false;
283
284        // Show root namespace if requested and allowed
285        if($this->options['showroot'] && $can_create) {
286            if(empty($dest_ns)) {
287                // If no namespace has been provided, add an option for the root NS.
288                $ret .= '<option ' . (($currentns == '') ? 'selected ' : '') . ' value="">' . $this->getLang('namespaceRoot') . '</option>';
289            } else {
290                // If a namespace has been provided, add an option for it.
291                $ret .= '<option ' . (($currentns == $dest_ns) ? 'selected ' : '') . ' value="' . formText($dest_ns) . '">' . formText($dest_ns) . '</option>';
292            }
293            $someopt = true;
294        }
295
296        $subnamespaces = $this->_getNamespaceList($dest_ns);
297
298        // The top of this stack will always be the last printed ancestor namespace
299        $ancestor_stack = array();
300        if (!empty($dest_ns)) {
301            $ancestor_stack[] = $dest_ns;
302        }
303
304        foreach($subnamespaces as $ns) {
305
306            if(auth_quickaclcheck($ns . ":") < AUTH_CREATE) continue;
307
308            // Pop any elements off the stack that are not ancestors of the current namespace
309            while(!empty($ancestor_stack) && strpos($ns, $ancestor_stack[count($ancestor_stack) - 1] . ':') !== 0) {
310                array_pop($ancestor_stack);
311            }
312
313            $nsparts = explode(':', $ns);
314            $first_unprinted_depth = empty($ancestor_stack) ? 1 : (2 + substr_count($ancestor_stack[count($ancestor_stack) - 1], ':'));
315            for($i = $first_unprinted_depth, $end = count($nsparts); $i <= $end; $i++) {
316                $namespace = implode(':', array_slice($nsparts, 0, $i));
317                $ancestor_stack[] = $namespace;
318                $selectOptionText = str_repeat('&nbsp;&nbsp;', substr_count($namespace, ':')) . $nsparts[$i - 1];
319                $ret .= '<option ' .
320                    (($currentns == $namespace) ? 'selected ' : '') .
321                    ($i == $end ? ('value="' . $namespace . '">') : 'disabled>') .
322                    $selectOptionText .
323                    '</option>';
324            }
325            $someopt = true;
326            $disablecache = true;
327        }
328
329        $ret .= '</select>';
330
331        if($someopt) {
332            return $ret;
333        } else {
334            return false;
335        }
336    }
337
338    /**
339     * Get a list of namespaces below the given namespace.
340     * Recursively fetches subnamespaces.
341     *
342     * @param string $topns The top namespace
343     * @return array Multi-dimensional array of all namespaces below $tns
344     */
345    protected function _getNamespaceList($topns = '') {
346        global $conf;
347
348        $topns = utf8_encodeFN(str_replace(':', '/', $topns));
349
350        $excludes = $this->options['exclude'];
351        if($excludes == "") {
352            $excludes = array();
353        } else {
354            $excludes = @explode(';', strtolower($excludes));
355        }
356        $searchdata = array();
357        search($searchdata, $conf['datadir'], 'search_namespaces', array(), $topns);
358
359        $namespaces = array();
360        foreach($searchdata as $ns) {
361            foreach($excludes as $exclude) {
362                if(!empty($exclude) && strpos($ns['id'], $exclude) === 0) {
363                    continue 2;
364                }
365            }
366            $namespaces[] = $ns['id'];
367        }
368
369        return $namespaces;
370    }
371
372    /**
373     * Create html for selection of namespace templates
374     *
375     * @param array $newpagetemplates array of namespace templates
376     * @return string html of select or hidden input
377     */
378    public function _htmlTemplateInput($newpagetemplates) {
379        $cnt = count($newpagetemplates);
380        if($cnt < 1 || $cnt == 1 && $newpagetemplates[0] == '') {
381            $input = '';
382
383        } else {
384            if($cnt == 1) {
385                list($template,) = $this->_parseNSTemplatePage($newpagetemplates[0]);
386                $input = '<input type="hidden" name="newpagetemplate" value="' . formText($template) . '" />';
387            } else {
388                $first = true;
389                $input = '<select name="newpagetemplate" tabindex="3">';
390                foreach($newpagetemplates as $template) {
391                    $p = ($first ? ' selected="selected"' : '');
392                    $first = false;
393
394                    list($template, $name) = $this->_parseNSTemplatePage($template);
395                    $p .= ' value="' . formText($template) . '"';
396                    $input .= "<option $p>" . formText($name) . "</option>";
397                }
398                $input .= '</select>';
399            }
400            $input = DOKU_TAB . DOKU_TAB . $input . DOKU_LF;
401        }
402        return $input;
403    }
404
405    /**
406     * Parses and resolves the namespace template page
407     *
408     * @param $nstemplate
409     * @return array
410     */
411    protected function _parseNSTemplatePage($nstemplate) {
412        global $ID;
413
414        @list($template, $name) = explode('|', $nstemplate, 2);
415        $template = (new PageResolver($ID))->resolveId($template);
416        if (is_null($name)) $name = $template;
417
418        return array($template, $name);
419    }
420
421}
422