summaryrefslogtreecommitdiff
path: root/includes/ParserXML.php
blob: e7b64f6e9240b8d2fe25fb752e77be72fbbdfc88 (plain)
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
<?php
/**
 *
 * @package MediaWiki
 * @subpackage Experimental
 */

/** */
require_once ('Parser.php');

/**
 * This should one day become the XML->(X)HTML parser
 * Based on work by Jan Hidders and Magnus Manske
 * To use, set
 *    $wgUseXMLparser = true ;
 *    $wgEnableParserCache = false ;
 *    $wgWiki2xml to the path and executable of the command line version (cli)
 * in LocalSettings.php
 * @package MediaWiki
 * @subpackage Experimental
 */

/**
 * the base class for an element
 * @package MediaWiki
 * @subpackage Experimental
 */
class element {
	var $name = '';
	var $attrs = array ();
	var $children = array ();

	/**
	* This finds the ATTRS element and returns the ATTR sub-children as a single string
	* @todo FIXME $parser always empty when calling makeXHTML()
	*/
	function getSourceAttrs() {
		$ret = '';
		foreach ($this->children as $child) {
			if (!is_string($child) AND $child->name == 'ATTRS') {
				$ret = $child->makeXHTML($parser);
			}
		}
		return $ret;
	}

	/**
	 * This collects the ATTR thingies for getSourceAttrs()
	 */
	function getTheseAttrs() {
		$ret = array ();
		foreach ($this->children as $child) {
			if (!is_string($child) AND $child->name == 'ATTR') {
				$ret[] = $child->attrs["NAME"]."='".$child->children[0]."'";
			}
		}
		return implode(' ', $ret);
	}

	function fixLinkTails(& $parser, $key) {
		$k2 = $key +1;
		if (!isset ($this->children[$k2]))
			return;
		if (!is_string($this->children[$k2]))
			return;
		if (is_string($this->children[$key]))
			return;
		if ($this->children[$key]->name != "LINK")
			return;

		$n = $this->children[$k2];
		$s = '';
		while ($n != '' AND (($n[0] >= 'a' AND $n[0] <= 'z') OR $n[0] == 'ä' OR $n[0] == 'ö' OR $n[0] == 'ü' OR $n[0] == 'ß')) {
			$s .= $n[0];
			$n = substr($n, 1);
		}
		$this->children[$k2] = $n;

		if (count($this->children[$key]->children) > 1) {
			$kl = array_keys($this->children[$key]->children);
			$kl = array_pop($kl);
			$this->children[$key]->children[$kl]->children[] = $s;
		} else {
			$e = new element;
			$e->name = "LINKOPTION";
			$t = $this->children[$key]->sub_makeXHTML($parser);
			$e->children[] = trim($t).$s;
			$this->children[$key]->children[] = $e;
		}
	}

	/**
	* This function generates the XHTML for the entire subtree
	*/
	function sub_makeXHTML(& $parser, $tag = '', $attr = '') {
		$ret = '';

		$attr2 = $this->getSourceAttrs();
		if ($attr != '' AND $attr2 != '')
			$attr .= ' ';
		$attr .= $attr2;

		if ($tag != '') {
			$ret .= '<'.$tag;
			if ($attr != '')
				$ret .= ' '.$attr;
			$ret .= '>';
		}

		# THIS SHOULD BE DONE IN THE WIKI2XML-PARSER INSTEAD
		#	foreach ( array_keys ( $this->children ) AS $x )
		#	   $this->fixLinkTails ( $parser , $x ) ;

		foreach ($this->children as $child) {
			if (is_string($child)) {
				$ret .= $child;
			} elseif ($child->name != 'ATTRS') {
				$ret .= $child->makeXHTML($parser);
			}
		}
		if ($tag != '')
			$ret .= '</'.$tag.">\n";
		return $ret;
	}

	/**
	* Link functions
	*/
	function createInternalLink(& $parser, $target, $display_title, $options) {
		global $wgUser;
		$skin = $wgUser->getSkin();
		$tp = explode(':', $target); # tp = target parts
		$title = ''; # The plain title
		$language = ''; # The language/meta/etc. part
		$namespace = ''; # The namespace, if any
		$subtarget = ''; # The '#' thingy

		$nt = Title :: newFromText($target);
		$fl = strtoupper($this->attrs['FORCEDLINK']) == 'YES';

		if ($fl || count($tp) == 1) {
			# Plain and simple case
			$title = $target;
		} else {
			# There's stuff missing here...
			if ($nt->getNamespace() == NS_IMAGE) {
				$options[] = $display_title;
				return $parser->makeImage($nt, implode('|', $options));
			} else {
				# Default
				$title = $target;
			}
		}

		if ($language != '') {
			# External link within the WikiMedia project
			return "{language link}";
		} else {
			if ($namespace != '') {
				# Link to another namespace, check for image/media stuff
				return "{namespace link}";
			} else {
				return $skin->makeLink($target, $display_title);
			}
		}
	}

	/** @todo document */
	function makeInternalLink(& $parser) {
		$target = '';
		$option = array ();
		foreach ($this->children as $child) {
			if (is_string($child)) {
				# This shouldn't be the case!
			} else {
				if ($child->name == 'LINKTARGET') {
					$target = trim($child->makeXHTML($parser));
				} else {
					$option[] = trim($child->makeXHTML($parser));
				}
			}
		}

		if (count($option) == 0)
			$option[] = $target; # Create dummy display title
		$display_title = array_pop($option);
		return $this->createInternalLink($parser, $target, $display_title, $option);
	}

	/** @todo document */
	function getTemplateXHTML($title, $parts, & $parser) {
		global $wgLang, $wgUser;
		$skin = $wgUser->getSkin();
		$ot = $title; # Original title
		if (count(explode(':', $title)) == 1)
			$title = $wgLang->getNsText(NS_TEMPLATE).":".$title;
		$nt = Title :: newFromText($title);
		$id = $nt->getArticleID();
		if ($id == 0) {
			# No/non-existing page
			return $skin->makeBrokenLink($title, $ot);
		}

		$a = 0;
		$tv = array (); # Template variables
		foreach ($parts AS $part) {
			$a ++;
			$x = explode('=', $part, 2);
			if (count($x) == 1)
				$key = "{$a}";
			else
				$key = $x[0];
			$value = array_pop($x);
			$tv[$key] = $value;
		}
		$art = new Article($nt);
		$text = $art->getContent(false);
		$parser->plain_parse($text, true, $tv);

		return $text;
	}

	/**
	 * This function actually converts wikiXML into XHTML tags
	 * @todo use switch() !
	 */
	function makeXHTML(& $parser) {
		$ret = '';
		$n = $this->name; # Shortcut

		if ($n == 'EXTENSION') {
			# Fix allowed HTML
			$old_n = $n;
			$ext = strtoupper($this->attrs['NAME']);

			switch($ext) {
				case 'B':
				case 'STRONG':
					$n = 'BOLD';
					break;
				case 'I':
				case 'EM':
					$n = 'ITALICS';
					break;
				case 'U':
					$n = 'UNDERLINED'; # Hey, virtual wiki tag! ;-)
					break;
				case 'S':
					$n = 'STRIKE';
					break;
				case 'P':
					$n = 'PARAGRAPH';
					break;
				case 'TABLE':
					$n = 'TABLE';
					break;
				case 'TR':
					$n = 'TABLEROW';
					break;
				case 'TD':
					$n = 'TABLECELL';
					break;
				case 'TH':
					$n = 'TABLEHEAD';
					break;
				case 'CAPTION':
					$n = 'CAPTION';
					break;
				case 'NOWIKI':
					$n = 'NOWIKI';
					break;
				}
			if ($n != $old_n) {
				unset ($this->attrs['NAME']); # Cleanup
			} elseif ($parser->nowiki > 0) {
				# No 'real' wiki tags allowed in nowiki section
				$n = '';
			}
		} // $n = 'EXTENSION'

		switch($n) {
			case 'ARTICLE':
				$ret .= $this->sub_makeXHTML($parser);
				break;
			case 'HEADING':
				$ret .= $this->sub_makeXHTML($parser, 'h'.$this->attrs['LEVEL']);
				break;
			case 'PARAGRAPH':
				$ret .= $this->sub_makeXHTML($parser, 'p');
				break;
			case 'BOLD':
				$ret .= $this->sub_makeXHTML($parser, 'strong');
				break;
			case 'ITALICS':
				$ret .= $this->sub_makeXHTML($parser, 'em');
				break;

			# These don't exist as wiki markup
			case 'UNDERLINED':
				$ret .= $this->sub_makeXHTML($parser, 'u');
				break;
			case 'STRIKE':
				$ret .= $this->sub_makeXHTML($parser, 'strike');
				break;

			# HTML comment
			case 'COMMENT':
				# Comments are parsed out
				$ret .= '';
				break;


			# Links
			case 'LINK':
				$ret .= $this->makeInternalLink($parser);
				break;
			case 'LINKTARGET':
			case 'LINKOPTION':
				$ret .= $this->sub_makeXHTML($parser);
				break;

			case 'TEMPLATE':
				$parts = $this->sub_makeXHTML($parser);
				$parts = explode('|', $parts);
				$title = array_shift($parts);
				$ret .= $this->getTemplateXHTML($title, $parts, & $parser);
				break;

			case 'TEMPLATEVAR':
				$x = $this->sub_makeXHTML($parser);
				if (isset ($parser->mCurrentTemplateOptions["{$x}"]))
					$ret .= $parser->mCurrentTemplateOptions["{$x}"];
				break;

			# Internal use, not generated by wiki2xml parser
			case 'IGNORE':
				$ret .= $this->sub_makeXHTML($parser);

			case 'NOWIKI':
				$parser->nowiki++;
				$ret .= $this->sub_makeXHTML($parser, '');
				$parser->nowiki--;


			# Unknown HTML extension
			case 'EXTENSION': # This is currently a dummy!!!
				$ext = $this->attrs['NAME'];

				$ret .= '&lt;'.$ext.'&gt;';
				$ret .= $this->sub_makeXHTML($parser);
				$ret .= '&lt;/'.$ext.'&gt; ';
				break;


			# Table stuff

			case 'TABLE':
				$ret .= $this->sub_makeXHTML($parser, 'table');
				break;
			case 'TABLEROW':
				$ret .= $this->sub_makeXHTML($parser, 'tr');
				break;
			case 'TABLECELL':
				$ret .= $this->sub_makeXHTML($parser, 'td');
				break;
			case 'TABLEHEAD':
				$ret .= $this->sub_makeXHTML($parser, 'th');
				break;
			case 'CAPTION':
				$ret .= $this->sub_makeXHTML($parser, 'caption');
				break;
			case 'ATTRS': # SPECIAL CASE : returning attributes
				return $this->getTheseAttrs();


			# Lists stuff
			case 'LISTITEM':
				if ($parser->mListType == 'dl')
					$ret .= $this->sub_makeXHTML($parser, 'dd');
				else
					$ret .= $this->sub_makeXHTML($parser, 'li');
				break;
			case 'LIST':
					$type = 'ol'; # Default
					if ($this->attrs['TYPE'] == 'bullet')
						$type = 'ul';
					else
						if ($this->attrs['TYPE'] == 'indent')
							$type = 'dl';
					$oldtype = $parser->mListType;
					$parser->mListType = $type;
					$ret .= $this->sub_makeXHTML($parser, $type);
					$parser->mListType = $oldtype;
				break;

			# Something else entirely
			default:
				$ret .= '&lt;'.$n.'&gt;';
				$ret .= $this->sub_makeXHTML($parser);
				$ret .= '&lt;/'.$n.'&gt; ';
			} // switch($n)

		$ret = "\n{$ret}\n";
		$ret = str_replace("\n\n", "\n", $ret);
		return $ret;
	}

	/**
	 * A function for additional debugging output
	 */
	function myPrint() {
		$ret = "<ul>\n";
		$ret .= "<li> <b> Name: </b> $this->name </li>\n";
		// print attributes
		$ret .= '<li> <b> Attributes: </b>';
		foreach ($this->attrs as $name => $value) {
			$ret .= "$name => $value; ";
		}
		$ret .= " </li>\n";
		// print children
		foreach ($this->children as $child) {
			if (is_string($child)) {
				$ret .= "<li> $child </li>\n";
			} else {
				$ret .= $child->myPrint();
			}
		}
		$ret .= "</ul>\n";
		return $ret;
	}
}

$ancStack = array (); // the stack with ancestral elements

// START Three global functions needed for parsing, sorry guys
/** @todo document */
function wgXMLstartElement($parser, $name, $attrs) {
	global $ancStack;

	$newElem = new element;
	$newElem->name = $name;
	$newElem->attrs = $attrs;

	array_push($ancStack, $newElem);
}

/** @todo document */
function wgXMLendElement($parser, $name) {
	global $ancStack, $rootElem;
	// pop element off stack
	$elem = array_pop($ancStack);
	if (count($ancStack) == 0)
		$rootElem = $elem;
	else
		// add it to its parent
		array_push($ancStack[count($ancStack) - 1]->children, $elem);
}

/** @todo document */
function wgXMLcharacterData($parser, $data) {
	global $ancStack;
	$data = trim($data); // Don't add blank lines, they're no use...
	// add to parent if parent exists
	if ($ancStack && $data != "") {
		array_push($ancStack[count($ancStack) - 1]->children, $data);
	}
}
// END Three global functions needed for parsing, sorry guys

/**
 * Here's the class that generates a nice tree
 * @package MediaWiki
 * @subpackage Experimental
 */
class xml2php {

	/** @todo document */
	function & scanFile($filename) {
		global $ancStack, $rootElem;
		$ancStack = array ();

		$xml_parser = xml_parser_create();
		xml_set_element_handler($xml_parser, 'wgXMLstartElement', 'wgXMLendElement');
		xml_set_character_data_handler($xml_parser, 'wgXMLcharacterData');
		if (!($fp = fopen($filename, 'r'))) {
			die('could not open XML input');
		}
		while ($data = fread($fp, 4096)) {
			if (!xml_parse($xml_parser, $data, feof($fp))) {
				die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
			}
		}
		xml_parser_free($xml_parser);

		// return the remaining root element we copied in the beginning
		return $rootElem;
	}

	/** @todo document */
	function scanString($input) {
		global $ancStack, $rootElem;
		$ancStack = array ();

		$xml_parser = xml_parser_create();
		xml_set_element_handler($xml_parser, 'wgXMLstartElement', 'wgXMLendElement');
		xml_set_character_data_handler($xml_parser, 'wgXMLcharacterData');

		if (!xml_parse($xml_parser, $input, true)) {
			die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
		}
		xml_parser_free($xml_parser);

		// return the remaining root element we copied in the beginning
		return $rootElem;
	}

}

/**
 * @todo document
 * @package MediaWiki
 * @subpackage Experimental
 */
class ParserXML extends Parser {
	/**#@+
	 * @private
	 */
	# Persistent:
	var $mTagHooks, $mListType;

	# Cleared with clearState():
	var $mOutput, $mAutonumber, $mDTopen, $mStripState = array ();
	var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;

	# Temporary:
	var $mOptions, $mTitle, $mOutputType, $mTemplates, // cache of already loaded templates, avoids
	// multiple SQL queries for the same string
	$mTemplatePath; // stores an unsorted hash of all the templates already loaded
	// in this path. Used for loop detection.

	var $nowikicount, $mCurrentTemplateOptions;

	/**#@-*/

	/**
	 * Constructor
	 *
	 * @public
	 */
	function ParserXML() {
		$this->mTemplates = array ();
		$this->mTemplatePath = array ();
		$this->mTagHooks = array ();
		$this->clearState();
	}

	/**
	 * Clear Parser state
	 *
	 * @private
	 */
	function clearState() {
		$this->mOutput = new ParserOutput;
		$this->mAutonumber = 0;
		$this->mLastSection = "";
		$this->mDTopen = false;
		$this->mVariables = false;
		$this->mIncludeCount = array ();
		$this->mStripState = array ();
		$this->mArgStack = array ();
		$this->mInPre = false;
	}

	/**
	* Turns the wikitext into XML by calling the external parser
	*
	*/
	function html2xml(& $text) {
		global $wgWiki2xml;

		# generating html2xml command path
		$a = $wgWiki2xml;
		$a = explode('/', $a);
		array_pop($a);
		$a[] = 'html2xml';
		$html2xml = implode('/', $a);
		$a = array ();

		$tmpfname = tempnam( wfTempDir(), 'FOO' );
		$handle = fopen($tmpfname, 'w');
		fwrite($handle, utf8_encode($text));
		fclose($handle);
		exec($html2xml.' < '.$tmpfname, $a);
		$text = utf8_decode(implode("\n", $a));
		unlink($tmpfname);
	}

	/** @todo document */
	function runXMLparser(& $text) {
		global $wgWiki2xml;

		$this->html2xml($text);

		$tmpfname = tempnam( wfTempDir(), 'FOO');
		$handle = fopen($tmpfname, 'w');
		fwrite($handle, $text);
		fclose($handle);
		exec($wgWiki2xml.' < '.$tmpfname, $a);
		$text = utf8_decode(implode("\n", $a));
		unlink($tmpfname);
	}

	/** @todo document */
	function plain_parse(& $text, $inline = false, $templateOptions = array ()) {
		$this->runXMLparser($text);
		$nowikicount = 0;
		$w = new xml2php;
		$result = $w->scanString($text);

		$oldTemplateOptions = $this->mCurrentTemplateOptions;
		$this->mCurrentTemplateOptions = $templateOptions;

		if ($inline) { # Inline rendering off for templates
			if (count($result->children) == 1)
				$result->children[0]->name = 'IGNORE';
		}

		if (1)
			$text = $result->makeXHTML($this); # No debugging info
		else
			$text = $result->makeXHTML($this).'<hr>'.$text.'<hr>'.$result->myPrint();
		$this->mCurrentTemplateOptions = $oldTemplateOptions;
	}

	/** @todo document */
	function parse($text, & $title, $options, $linestart = true, $clearState = true) {
		$this->plain_parse($text);
		$this->mOutput->setText($text);
		return $this->mOutput;
	}

}
?>