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