-
Notifications
You must be signed in to change notification settings - Fork 3
/
syntax.php
318 lines (272 loc) · 11.3 KB
/
syntax.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php
/**
* Templater Plugin: Based from the include plugin, like MediaWiki's template
* Usage:
* {{template>page}} for "page" in same namespace
* {{template>:page}} for "page" in top namespace
* {{template>namespace:page}} for "page" in namespace "namespace"
* {{template>.namespace:page}} for "page" in subnamespace "namespace"
* {{template>page#section}} for a section of "page"
*
* Replacers are handled in a simple key/value pair method:
* {{template>page|key=val|key2=val|key3=val}}
*
* Templates are wiki pages, with replacers being delimited like:
* @key1@ @key2@ @key3@
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Jonathan Arkell <jonnay@jonnay.net>
* based on code by Esther Brunner <esther@kaffeehaus.ch>
* @maintainer Daniel Dias Rodrigues (aka Nerun) <danieldiasr@gmail.com>
* @contributors Vincent de Lau <vincent@delau.nl>
* Ximin Luo <xl269@cam.ac.uk>
* jack126guy <halfgray7e@gmail.com>
* Turq Whiteside <turq@mage.city>
*/
use dokuwiki\File\PageResolver;
define('BEGIN_REPLACE_DELIMITER', '@');
define('END_REPLACE_DELIMITER', '@');
require_once('debug.php');
/**
* All DokuWiki plugins to extend the parser/rendering mechanism
* need to inherit from this class
*/
class syntax_plugin_templater extends DokuWiki_Syntax_Plugin {
/**
* What kind of syntax are we?
*/
function getType() {
return 'container';
}
function getAllowedTypes() {
return array('container', 'substition', 'protected', 'disabled', 'formatting');
}
/**
* Where to sort in?
*/
function getSort() {
return 302;
}
/**
* Paragraph Type
*/
function getPType() {
return 'block';
}
/**
* Connect pattern to lexer
*/
function connectTo($mode) {
$this->Lexer->addSpecialPattern("{{template>.+?}}", $mode, 'plugin_templater');
}
/**
* Handle the match
*/
function handle($match, $state, $pos, Doku_Handler $handler) {
global $ID;
$match = substr($match, 11, -2); // strip markup
$replacers = preg_split('/(?<!\\\\)\|/', $match); // Get the replacers
$wikipage = array_shift($replacers);
$replacers = $this->_massageReplacers($replacers);
$wikipage = preg_split('/\#/u', $wikipage, 2); // split hash from filename
$parentpage = empty(self::$pagestack)? $ID : end(self::$pagestack); // get correct namespace
// resolve shortcuts:
$resolver = new PageResolver(getNS($parentpage));
$wikipage[0] = $resolver->resolveId($wikipage[0]);
$exists = page_exists($wikipage[0]);
// check for perrmission
if (auth_quickaclcheck($wikipage[0]) < 1)
return false;
// $wikipage[1] is the header of a template enclosed within a section {{template>page#section}}
// Not all template calls will be {{template>page#section}}, some will be {{template>page}}
// It fix "Undefined array key 1" warning
if (array_key_exists(1, $wikipage)) {
$section = cleanID($wikipage[1]);
} else {
$section = null;
}
return array($wikipage[0], $replacers, $section);
}
private static $pagestack = array(); // keep track of recursing template renderings
/**
* Create output
* This is a refactoring candidate. Needs to be a little clearer.
*/
function render($mode, Doku_Renderer $renderer, $data) {
if ($mode != 'xhtml')
return false;
if ($data[0] === false) {
// False means no permissions
$renderer->doc .= '<div class="templater"> ';
$renderer->doc .= $this->getLang('no_permissions_view');
$renderer->doc .= ' </div>';
$renderer->info['cache'] = FALSE;
return true;
}
$file = wikiFN($data[0]);
if (!@file_exists($file)) {
$renderer->doc .= '<div class="templater">— ';
$renderer->doc .= $this->getLang('template');
$renderer->doc .= ' ';
$renderer->internalLink($data[0]);
$renderer->doc .= ' ';
$renderer->doc .= $this->getLang('not_found');
$renderer->doc .= '<br/><br/></div>';
$renderer->info['cache'] = FALSE;
return true;
} else if (array_search($data[0], self::$pagestack) !== false) {
$renderer->doc .= '<div class="templater">— ';
$renderer->doc .= $this->getLang('processing_template');
$renderer->doc .= ' ';
$renderer->internalLink($data[0]);
$renderer->doc .= ' ';
$renderer->doc .= $this->getLang('stopped_recursion');
$renderer->doc .= '<br/><br/></div>';
return true;
}
self::$pagestack[] = $data[0]; // push this onto the stack
// Get the raw file, and parse it into its instructions. This could be cached... maybe.
$rawFile = io_readfile($file);
// fill in all known values
if(!empty($data[1]['keys']) && !empty($data[1]['vals'])) {
$rawFile = str_replace($data[1]['keys'], $data[1]['vals'], $rawFile);
}
// replace unmatched substitutions with "" or use DEFAULT_STR from data arguments if exists.
$left_overs = '/'.BEGIN_REPLACE_DELIMITER.'.*'.END_REPLACE_DELIMITER.'/';
if(!empty($data[1]['keys']) && !empty($data[1]['vals'])) {
$def_key = array_search(BEGIN_REPLACE_DELIMITER."DEFAULT_STR".END_REPLACE_DELIMITER, $data[1]['keys']);
$DEFAULT_STR = $def_key ? $data[1]['vals'][$def_key] : "";
$rawFile = preg_replace($left_overs, $DEFAULT_STR, $rawFile);
}
$instr = p_get_instructions($rawFile);
// filter section if given
if ($data[2]) {
$getSection = $this->_getSection($data[2], $instr);
$instr = $getSection[0];
if(!is_null($getSection[1])) {
$renderer->doc .= sprintf($getSection[1], $data[2]);
$renderer->internalLink($data[0]);
$renderer->doc .= '.<br/><br/></div>';
}
}
// correct relative internal links and media
$instr = $this->_correctRelNS($instr, $data[0]);
// doesn't show the heading for each template if {{template>page#section}}
if (sizeof($instr) > 0 && !isset($getSection[1])) {
if (array_key_exists(0, $instr[0][1]) && $instr[0][1][0] == $data[2]) {
$instr[0][1][0] = null;
}
}
// render the instructructions on the fly
$text = p_render('xhtml', $instr, $info);
// remove toc, section edit buttons and category tags
$patterns = array('!<div class="toc">.*?(</div>\n</div>)!s',
'#<!-- SECTION \[(\d*-\d*)\] -->#',
'!<div class="category">.*?</div>!s');
$replace = array('', '', '');
$text = preg_replace($patterns, $replace, $text);
// prevent caching to ensure the included page is always fresh
$renderer->info['cache'] = FALSE;
// embed the included page
$renderer->doc .= '<div class="templater">';
$renderer->doc .= $text;
$renderer->doc .= '</div>';
array_pop(self::$pagestack); // pop off the stack when done
return true;
}
/**
* Get a section including its subsections
*/
function _getSection($title, $instructions) {
$i = (array) null;
$level = null;
$no_section = null;
foreach ($instructions as $instruction) {
if ($instruction[0] == 'header') {
// found the right header
if (cleanID($instruction[1][0]) == $title) {
$level = $instruction[1][1];
$i[] = $instruction;
} else {
if (isset($level) && isset($i)) {
if ($instruction[1][1] > $level) {
$i[] = $instruction;
// next header of the same level or higher -> exit
} else {
return array($i,null);
}
}
}
} else { // content between headers
if (isset($level) && isset($i)) {
$i[] = $instruction;
}
}
}
// Fix for when page#section doesn't exist
if(sizeof($i) == 0) {
$no_section_begin = '<div class="templater">— ';
$no_section_end = $this->getLang('no_such_section');
$no_section = $no_section_begin . $no_section_end . ' ';
}
return array($i,$no_section);
}
/**
* Corrects relative internal links and media
*/
function _correctRelNS($instr, $incl) {
global $ID;
// check if included page is in same namespace
$iNS = getNS($incl);
if (getNS($ID) == $iNS)
return $instr;
// convert internal links and media from relative to absolute
$n = count($instr);
for($i = 0; $i < $n; $i++) {
if (substr($instr[$i][0], 0, 8) != 'internal')
continue;
// relative subnamespace
if ($instr[$i][1][0][0] == '.') {
$instr[$i][1][0] = $iNS.':'.substr($instr[$i][1][0], 1);
// relative link
} else if (strpos($instr[$i][1][0], ':') === false) {
$instr[$i][1][0] = $iNS.':'.$instr[$i][1][0];
}
}
return $instr;
}
/**
* Handles the replacement array
*/
function _massageReplacers($replacers) {
$r = array();
if (is_null($replacers)) {
$r['keys'] = null;
$r['vals'] = null;
} else if (is_string($replacers)) {
if ( str_contains($replacers, '=') && (substr(trim($replacers), -1) != '=') ){
list($k, $v) = explode('=', $replacers, 2);
$r['keys'] = BEGIN_REPLACE_DELIMITER.trim($k).END_REPLACE_DELIMITER;
$r['vals'] = trim(str_replace('\|', '|', $v));
}
} else if ( is_array($replacers) ) {
foreach($replacers as $rep) {
if ( str_contains($rep, '=') && (substr(trim($rep), -1) != '=') ){
list($k, $v) = explode('=', $rep, 2);
$r['keys'][] = BEGIN_REPLACE_DELIMITER.trim($k).END_REPLACE_DELIMITER;
if (trim($v)[0] == '"' and trim($v)[-1] == '"') {
$r['vals'][] = substr(trim(str_replace('\|','|',$v)), 1, -1);
} else {
$r['vals'][] = trim(str_replace('\|','|',$v));
}
}
}
} else {
// This is an assertion failure. We should NEVER get here.
//die("FATAL ERROR! Unknown type passed to syntax_plugin_templater::massageReplaceMentArray() can't message syntax_plugin_templater::\$replacers! Type is:".gettype($r)." Value is:".$r);
$r['keys'] = null;
$r['vals'] = null;
}
return $r;
}
}