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