xref: /plugin/addnewpage/syntax.php (revision 31967e049694389408c9c98a49524275a2789360)
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        if(preg_match('/#(.*?)(#.*?)?(\?|$)/', $match, $m)) {
91            $data['newpagetemplates'] = array_map('trim', explode(',', $m[1]));
92            $data['newpagevars'] = trim($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="'.$input.'" 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        return str_replace($keep, '@INPUT@', $ns);
224    }
225
226    /**
227     * Create the HTML Select element for namespace selection.
228     *
229     * @param string|false $dest_ns The destination namespace, or false if none provided.
230     * @param bool $disablecache reference indicates if caching need to be disabled
231     * @global string $ID The page ID
232     * @return string Select element with appropriate NS selected.
233     */
234    protected function _htmlNamespaceInput($dest_ns, &$disablecache) {
235        global $ID;
236        $disablecache = false;
237
238        // If a NS has been provided:
239        // Whether to hide the NS selection (otherwise, show only subnamespaces).
240        $hide = $this->options['hide'];
241
242        $parsed_dest_ns = $this->_parseNS($dest_ns);
243        // Whether the user can create pages in the provided NS (or root, if no
244        // destination NS has been set.
245        $can_create = (auth_quickaclcheck($parsed_dest_ns . ":") >= AUTH_CREATE);
246
247        //namespace given, but hidden
248        if($hide && !empty($dest_ns)) {
249            if($can_create) {
250                return '<input type="hidden" name="np_cat" id="np_cat" value="' . $parsed_dest_ns . '"/>';
251            } else {
252                return false;
253            }
254        }
255
256        //show select of given namespace
257        $currentns = getNS($ID);
258
259        $ret = '<select class="edit" id="np_cat" name="np_cat" tabindex="1">';
260
261        // Whether the NS select element has any options
262        $someopt = false;
263
264        // Show root namespace if requested and allowed
265        if($this->options['showroot'] && $can_create) {
266            if(empty($dest_ns)) {
267                // If no namespace has been provided, add an option for the root NS.
268                $ret .= '<option ' . (($currentns == '') ? 'selected ' : '') . ' value="">' . $this->getLang('namespaceRoot') . '</option>';
269            } else {
270                // If a namespace has been provided, add an option for it.
271                $ret .= '<option ' . (($currentns == $dest_ns) ? 'selected ' : '') . ' value="' . formText($dest_ns) . '">' . formText($dest_ns) . '</option>';
272            }
273            $someopt = true;
274        }
275
276        $subnamespaces = $this->_getNamespaceList($dest_ns);
277
278        // The top of this stack will always be the last printed ancestor namespace
279        $ancestor_stack = array();
280        if (!empty($dest_ns)) {
281            $ancestor_stack[] = $dest_ns;
282        }
283
284        foreach($subnamespaces as $ns) {
285
286            if(auth_quickaclcheck($ns . ":") < AUTH_CREATE) continue;
287
288            // Pop any elements off the stack that are not ancestors of the current namespace
289            while(!empty($ancestor_stack) && strpos($ns, $ancestor_stack[count($ancestor_stack) - 1] . ':') !== 0) {
290                array_pop($ancestor_stack);
291            }
292
293            $nsparts = explode(':', $ns);
294            $first_unprinted_depth = empty($ancestor_stack) ? 1 : (2 + substr_count($ancestor_stack[count($ancestor_stack) - 1], ':'));
295            for($i = $first_unprinted_depth, $end = count($nsparts); $i <= $end; $i++) {
296                $namespace = implode(':', array_slice($nsparts, 0, $i));
297                $ancestor_stack[] = $namespace;
298                $selectOptionText = str_repeat('&nbsp;&nbsp;', substr_count($namespace, ':')) . $nsparts[$i - 1];
299                $ret .= '<option ' .
300                    (($currentns == $namespace) ? 'selected ' : '') .
301                    ($i == $end ? ('value="' . $namespace . '">') : 'disabled>') .
302                    $selectOptionText .
303                    '</option>';
304            }
305            $someopt = true;
306            $disablecache = true;
307        }
308
309        $ret .= '</select>';
310
311        if($someopt) {
312            return $ret;
313        } else {
314            return false;
315        }
316    }
317
318    /**
319     * Get a list of namespaces below the given namespace.
320     * Recursively fetches subnamespaces.
321     *
322     * @param string $topns The top namespace
323     * @return array Multi-dimensional array of all namespaces below $tns
324     */
325    protected function _getNamespaceList($topns = '') {
326        global $conf;
327
328        $topns = utf8_encodeFN(str_replace(':', '/', $topns));
329
330        $excludes = $this->options['exclude'];
331        if($excludes == "") {
332            $excludes = array();
333        } else {
334            $excludes = @explode(';', strtolower($excludes));
335        }
336        $searchdata = array();
337        search($searchdata, $conf['datadir'], 'search_namespaces', array(), $topns);
338
339        $namespaces = array();
340        foreach($searchdata as $ns) {
341            foreach($excludes as $exclude) {
342                if(!empty($exclude) && strpos($ns['id'], $exclude) === 0) {
343                    continue 2;
344                }
345            }
346            $namespaces[] = $ns['id'];
347        }
348
349        return $namespaces;
350    }
351
352    /**
353     * Create html for selection of namespace templates
354     *
355     * @param array $newpagetemplates array of namespace templates
356     * @return string html of select or hidden input
357     */
358    public function _htmlTemplateInput($newpagetemplates) {
359        $cnt = count($newpagetemplates);
360        if($cnt < 1 || $cnt == 1 && $newpagetemplates[0] == '') {
361            $input = '';
362
363        } else {
364            if($cnt == 1) {
365                list($template,) = $this->_parseNSTemplatePage($newpagetemplates[0]);
366                $input = '<input type="hidden" name="newpagetemplate" value="' . formText($template) . '" />';
367            } else {
368                $first = true;
369                $input = '<select name="newpagetemplate" tabindex="3">';
370                foreach($newpagetemplates as $template) {
371                    $p = ($first ? ' selected="selected"' : '');
372                    $first = false;
373
374                    list($template, $name) = $this->_parseNSTemplatePage($template);
375                    $p .= ' value="' . formText($template) . '"';
376                    $input .= "<option $p>" . formText($name) . "</option>";
377                }
378                $input .= '</select>';
379            }
380            $input = DOKU_TAB . DOKU_TAB . $input . DOKU_LF;
381        }
382        return $input;
383    }
384
385    /**
386     * Parses and resolves the namespace template page
387     *
388     * @param $nstemplate
389     * @return array
390     */
391    protected function _parseNSTemplatePage($nstemplate) {
392        global $ID;
393
394        @list($template, $name) = explode('|', $nstemplate, 2);
395        $template = (new PageResolver($ID))->resolveId($template);
396        if (is_null($name)) $name = $template;
397
398        return array($template, $name);
399    }
400
401}
402