xref: /plugin/addnewpage/syntax.php (revision 9418ebb801290cfb39b21fcf66b7ff91b61c4bba)
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    /**
16     * Syntax Type
17     */
18    public function getType() {
19        return 'substition';
20    }
21
22    /**
23     * Paragraph Type
24     */
25    public function getPType() {
26        return 'block';
27    }
28
29    /**
30     * @return int
31     */
32    public function getSort() {
33        return 199;
34    }
35
36    /**
37     * @param string $mode
38     */
39    public function connectTo($mode) {
40        $this->Lexer->addSpecialPattern('\{\{NEWPAGE[^\}]*\}\}', $mode, 'plugin_addnewpage');
41    }
42
43    /**
44     * Handler to prepare matched data for the rendering process
45     *
46     * Handled syntax options:
47     *   {{NEWPAGE}}
48     *   {{NEWPAGE>your:namespace}}
49     *   {{NEWPAGE#newtpl1,newtpl2}}
50     *   {{NEWPAGE#newtpl1|Title1,newtpl2|Title1}}
51     *   {{NEWPAGE>your:namespace#newtpl1|Title1,newtpl2|Title1}}
52     *   {{NEWPAGE>your:namespace#newtpl1|Title1,newtpl2|Title1#@HI@,Howdy}}
53     *
54     * @param   string       $match   The text matched by the patterns
55     * @param   int          $state   The lexer state for the match
56     * @param   int          $pos     The character position of the matched text
57     * @param   Doku_Handler $handler The Doku_Handler object
58     * @return  array Return an array with all data you want to use in render
59     * @codingStandardsIgnoreStart
60     */
61    public function handle($match, $state, $pos, Doku_Handler $handler) {
62        /* @codingStandardsIgnoreEnd */
63        $options = substr($match, 9, -2); // strip markup
64        $options = explode('#', $options, 3);
65
66        $namespace = trim(ltrim($options[0], '>'));
67        $templates = explode(',', $options[1] ?? '');
68        $templates = array_map('trim', $templates);
69        $newpagevars = trim($options[2] ?? '');
70        return array(
71            'namespace' => $namespace,
72            'newpagetemplates' => $templates,
73            'newpagevars' => $newpagevars
74        );
75    }
76
77    /**
78     * Create the new-page form.
79     *
80     * @param   $mode     string        output format being rendered
81     * @param   $renderer Doku_Renderer the current renderer object
82     * @param   $data     array         data created by handler()
83     * @return  boolean                 rendered correctly?
84     */
85    public function render($mode, Doku_Renderer $renderer, $data) {
86        global $lang;
87
88        if($mode == 'xhtml') {
89            $disablecache = null;
90            $namespaceinput = $this->_htmlNamespaceInput($data['namespace'], $disablecache);
91            if($namespaceinput === false) {
92                if($this->getConf('addpage_hideACL')) {
93                    $renderer->doc .= '';
94                } else {
95                    $renderer->doc .= $this->getLang('nooption');
96                }
97                return true;
98            }
99            if($disablecache) $renderer->info['cache'] = false;
100
101            $newpagetemplateinput = $this->_htmlTemplateInput($data['newpagetemplates']);
102
103            $form = '<div class="addnewpage">' . DOKU_LF
104                . DOKU_TAB . '<form name="addnewpage" method="get" action="' . DOKU_BASE . DOKU_SCRIPT . '" accept-charset="' . $lang['encoding'] . '">' . DOKU_LF
105                . DOKU_TAB . DOKU_TAB . $namespaceinput . DOKU_LF
106                . DOKU_TAB . DOKU_TAB . '<input class="edit" type="text" name="title" size="20" maxlength="255" tabindex="2" />' . DOKU_LF
107                . $newpagetemplateinput
108                . DOKU_TAB . DOKU_TAB . '<input type="hidden" name="newpagevars" value="' . $data['newpagevars'] . '"/>' . DOKU_LF
109                . DOKU_TAB . DOKU_TAB . '<input type="hidden" name="do" value="edit" />' . DOKU_LF
110                . DOKU_TAB . DOKU_TAB . '<input type="hidden" name="id" />' . DOKU_LF
111                . DOKU_TAB . DOKU_TAB . '<input class="button" type="submit" value="' . $this->getLang('okbutton') . '" tabindex="4" />' . DOKU_LF
112                . DOKU_TAB . '</form>' . DOKU_LF
113                . '</div>';
114            $renderer->doc .= $form;
115
116            return true;
117        }
118        return false;
119    }
120
121    /**
122     * Parse namespace request
123     *
124     * @author Samuele Tognini <samuele@cli.di.unipi.it>
125     * @author Michael Braun <michael-dev@fami-braun.de>
126     */
127    protected function _parseNS($ns) {
128        global $ID;
129        if(strpos($ns, '@PAGE@') !== false) {
130            return cleanID(str_replace('@PAGE@', $ID, $ns));
131        }
132        if($ns == "@NS@") return getNS($ID);
133        $ns = preg_replace("/^\.(:|$)/", dirname(str_replace(':', '/', $ID)) . "$1", $ns);
134        $ns = str_replace("/", ":", $ns);
135        $ns = cleanID($ns);
136        return $ns;
137    }
138
139    /**
140     * Create the HTML Select element for namespace selection.
141     *
142     * @param string|false $dest_ns The destination namespace, or false if none provided.
143     * @param bool $disablecache reference indicates if caching need to be disabled
144     * @global string $ID The page ID
145     * @return string Select element with appropriate NS selected.
146     */
147    protected function _htmlNamespaceInput($dest_ns, &$disablecache) {
148        global $ID;
149        $disablecache = false;
150
151        // If a NS has been provided:
152        // Whether to hide the NS selection (otherwise, show only subnamespaces).
153        $hide = $this->getConf('addpage_hide');
154
155        $parsed_dest_ns = $this->_parseNS($dest_ns);
156        // Whether the user can create pages in the provided NS (or root, if no
157        // destination NS has been set.
158        $can_create = (auth_quickaclcheck($parsed_dest_ns . ":") >= AUTH_CREATE);
159
160        //namespace given, but hidden
161        if($hide && !empty($dest_ns)) {
162            if($can_create) {
163                return '<input type="hidden" name="np_cat" id="np_cat" value="' . $parsed_dest_ns . '"/>';
164            } else {
165                return false;
166            }
167        }
168
169        //show select of given namespace
170        $currentns = getNS($ID);
171
172        $ret = '<select class="edit" id="np_cat" name="np_cat" tabindex="1">';
173
174        // Whether the NS select element has any options
175        $someopt = false;
176
177        // Show root namespace if requested and allowed
178        if($this->getConf('addpage_showroot') && $can_create) {
179            if(empty($dest_ns)) {
180                // If no namespace has been provided, add an option for the root NS.
181                $ret .= '<option ' . (($currentns == '') ? 'selected ' : '') . 'value="">' . $this->getLang('namespaceRoot') . '</option>';
182                $someopt = true;
183            } else {
184                // If a namespace has been provided, add an option for it.
185                $ret .= '<option ' . (($currentns == $dest_ns) ? 'selected ' : '') . 'value="' . formText($dest_ns) . '">' . formText($dest_ns) . '</option>';
186                $someopt = true;
187            }
188        }
189
190        $subnamespaces = $this->_getNamespaceList($dest_ns);
191
192        // The top of this stack will always be the last printed ancestor namespace
193        $ancestor_stack = array();
194        if (!empty($dest_ns)) {
195            array_push($ancestor_stack, $dest_ns);
196        }
197
198        foreach($subnamespaces as $ns) {
199
200            if(auth_quickaclcheck($ns . ":") < AUTH_CREATE) continue;
201
202            // Pop any elements off the stack that are not ancestors of the current namespace
203            while(!empty($ancestor_stack) && strpos($ns, $ancestor_stack[count($ancestor_stack) - 1] . ':') !== 0) {
204                array_pop($ancestor_stack);
205            }
206
207            $nsparts = explode(':', $ns);
208            $first_unprinted_depth = empty($ancestor_stack)? 1 : (2 + substr_count($ancestor_stack[count($ancestor_stack) - 1], ':'));
209            for ($i = $first_unprinted_depth, $end = count($nsparts); $i <= $end; $i++) {
210                $namespace = implode(':', array_slice($nsparts, 0, $i));
211                array_push($ancestor_stack, $namespace);
212                $selectOptionText = str_repeat('&nbsp;&nbsp;', substr_count($namespace, ':')) . $nsparts[$i - 1];
213                $ret .= '<option ' .
214                    (($currentns == $namespace) ? 'selected ' : '') .
215                    ($i == $end? ('value="' . $namespace . '">') : 'disabled>') .
216                    $selectOptionText .
217                    '</option>';
218            }
219            $someopt = true;
220            $disablecache = true;
221        }
222
223        $ret .= '</select>';
224
225        if($someopt) {
226            return $ret;
227        } else {
228            return false;
229        }
230    }
231
232    /**
233     * Get a list of namespaces below the given namespace.
234     * Recursively fetches subnamespaces.
235     *
236     * @param string $topns The top namespace
237     * @return array Multi-dimensional array of all namespaces below $tns
238     */
239    protected function _getNamespaceList($topns = '') {
240        global $conf;
241
242        $topns = utf8_encodeFN(str_replace(':', '/', $topns));
243
244        $excludes = $this->getConf('addpage_exclude');
245        if($excludes == "") {
246            $excludes = array();
247        } else {
248            $excludes = @explode(';', strtolower($excludes));
249        }
250        $searchdata = array();
251        search($searchdata, $conf['datadir'], 'search_namespaces', array(), $topns);
252
253        $namespaces = array();
254        foreach($searchdata as $ns) {
255            foreach($excludes as $exclude) {
256                if( ! empty($exclude) && strpos($ns['id'], $exclude) === 0) {
257                    continue 2;
258                }
259            }
260            $namespaces[] = $ns['id'];
261        }
262
263        return $namespaces;
264    }
265
266    /**
267     * Create html for selection of namespace templates
268     *
269     * @param array $newpagetemplates array of namespace templates
270     * @return string html of select or hidden input
271     */
272    public function _htmlTemplateInput($newpagetemplates) {
273        $cnt = count($newpagetemplates);
274        if($cnt < 1 || $cnt == 1 && $newpagetemplates[0] == '') {
275            $input = '';
276
277        } else {
278            if($cnt == 1) {
279                list($template, ) = $this->_parseNSTemplatePage($newpagetemplates[0]);
280                $input = '<input type="hidden" name="newpagetemplate" value="' . formText($template) . '" />';
281            } else {
282                $first = true;
283                $input = '<select name="newpagetemplate" tabindex="3">';
284                foreach($newpagetemplates as $template) {
285                    $p = ($first ? ' selected="selected"' : '');
286                    $first = false;
287
288                    list($template, $name) = $this->_parseNSTemplatePage($template);
289                    $p .= ' value="'.formText($template).'"';
290                    $input .= "<option $p>".formText($name)."</option>";
291                }
292                $input .= '</select>';
293            }
294            $input = DOKU_TAB . DOKU_TAB . $input . DOKU_LF;
295        }
296        return $input;
297    }
298
299    /**
300     * Parses and resolves the namespace template page
301     *
302     * @param $nstemplate
303     * @return array
304     */
305    protected function _parseNSTemplatePage($nstemplate) {
306        global $ID;
307
308        @list($template, $name) = explode('|', $nstemplate, 2);
309
310        $exist = null;
311        resolve_pageid(getNS($ID), $template, $exist); //get absolute id
312
313        if (is_null($name)) $name = $template;
314
315        return array($template, $name);
316    }
317
318}
319