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