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