forked from henck/rtf-html-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtf-html-php.php
676 lines (605 loc) · 20.9 KB
/
rtf-html-php.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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
<?php
/**
* RTF parser/formatter
*
* This code reads RTF files and formats the RTF data to HTML.
*
* PHP version 5
*
* @author Alexander van Oostenrijk
* @copyright 2014 Alexander van Oostenrijk
* @license GNU
* @version 1
* @link http://www.independent-software.com
*
* Sample of use:
*
* $reader = new RtfReader();
* $rtf = file_get_contents("test.rtf"); // or use a string
* if ($reader->Parse($rtf)) {
* //$reader->root->dump(); // to see what the reader read
* $formatter = new RtfHtml();
* echo $formatter->Format($reader->root);
* } else { // Parse error occured.. bad RTF file
* echo "Parse error occured";
* }
*
*/
class RtfElement
{
protected function Indent($level)
{
for($i = 0; $i < $level * 2; $i++) echo " ";
}
}
class RtfGroup extends RtfElement
{
public $parent;
public $children;
public function __construct()
{
$this->parent = null;
$this->children = array();
}
public function GetType()
{
// No children?
if(sizeof($this->children) == 0) return null;
// First child not a control word?
$child = $this->children[0];
if(!$child instanceof RtfControlWord) return null;
return $child->word;
}
public function IsDestination()
{
// No children?
if(sizeof($this->children) == 0) return null;
// First child not a control symbol?
$child = $this->children[0];
if(!$child instanceof RtfControlSymbol) return null;
return $child->symbol == '*';
}
public function dump($level = 0)
{
echo "<div>";
$this->Indent($level);
echo "{";
echo "</div>";
foreach($this->children as $child)
{
if($child instanceof RtfGroup) {
if ($child->GetType() == "fonttbl") continue;
if ($child->GetType() == "colortbl") continue;
if ($child->GetType() == "stylesheet") continue;
if ($child->GetType() == "info") continue;
// Skip any pictures:
if (substr($child->GetType(), 0, 4) == "pict") continue;
if ($child->IsDestination()) continue;
}
$child->dump($level + 2);
}
echo "<div>";
$this->Indent($level);
echo "}";
echo "</div>";
}
}
class RtfControlWord extends RtfElement
{
public $word;
public $parameter;
public function dump($level)
{
echo "<div style='color:green'>";
$this->Indent($level);
echo "WORD {$this->word} ({$this->parameter})";
echo "</div>";
}
}
class RtfControlSymbol extends RtfElement
{
public $symbol;
public $parameter = 0;
public function dump($level)
{
echo "<div style='color:blue'>";
$this->Indent($level);
echo "SYMBOL {$this->symbol} ({$this->parameter})";
echo "</div>";
}
}
class RtfText extends RtfElement
{
public $text;
public function dump($level)
{
echo "<div style='color:red'>";
$this->Indent($level);
echo "TEXT {$this->text}";
echo "</div>";
}
}
class RtfReader
{
public $root = null;
protected function GetChar()
{
$this->char = null;
if ($this->pos < strlen($this->rtf)) {
$this->char = $this->rtf[$this->pos++];
} else {
$this->err = "Tried to read past EOF, RTF is probably truncated";
}
}
protected function ParseStartGroup()
{
// Store state of document on stack.
$group = new RtfGroup();
if($this->group != null) $group->parent = $this->group;
if($this->root == null) {
$this->group = $group;
$this->root = $group;
} else {
array_push($this->group->children, $group);
$this->group = $group;
}
}
protected function is_letter()
{
if(ord($this->char) >= 65 && ord($this->char) <= 90) return True;
if(ord($this->char) >= 97 && ord($this->char) <= 122) return True;
return False;
}
protected function is_digit()
{
if(ord($this->char) >= 48 && ord($this->char) <= 57) return True;
return False;
}
protected function ParseEndGroup()
{
// Retrieve state of document from stack.
$this->group = $this->group->parent;
}
protected function ParseControlWord()
{
$this->GetChar();
$word = "";
while($this->is_letter())
{
$word .= $this->char;
$this->GetChar();
}
// Read parameter (if any) consisting of digits.
// Paramater may be negative.
$parameter = null;
$negative = False;
if($this->char == '-') {
$this->GetChar();
$negative = True;
}
while($this->is_digit())
{
if($parameter == null) $parameter = 0;
$parameter = $parameter * 10 + $this->char;
$this->GetChar();
}
if($parameter === null) $parameter = 1;
// convert to a negative number when applicable
if($negative) $parameter = -$parameter;
// If this is \u, then the parameter will be followed by
// a character.
if($word == "u") {
// Ignore space delimiter
if ($this->char==' ') $this->GetChar();
// if the replacement character is encoded as
// hexadecimal value \'hh then jump over it
if($this->char == '\\' && $this->rtf[$this->pos]=='\'')
$this->pos = $this->pos + 3;
// Convert to UTF unsigned decimal code
if($negative) $parameter = 65536 + $parameter;
}
// If the current character is a space, then
// it is a delimiter. It is consumed.
// If it's not a space, then it's part of the next
// item in the text, so put the character back.
else
{
if($this->char != ' ') $this->pos--;
}
$rtfword = new RtfControlWord();
$rtfword->word = $word;
$rtfword->parameter = $parameter;
array_push($this->group->children, $rtfword);
}
protected function ParseControlSymbol()
{
// Read symbol (one character only).
$this->GetChar();
$symbol = $this->char;
// Symbols ordinarily have no parameter. However,
// if this is \', then it is followed by a 2-digit hex-code:
$parameter = 0;
if($symbol == '\'') {
$this->GetChar();
$parameter = $this->char;
$this->GetChar();
$parameter = hexdec($parameter . $this->char);
}
$rtfsymbol = new RtfControlSymbol();
$rtfsymbol->symbol = $symbol;
$rtfsymbol->parameter = $parameter;
array_push($this->group->children, $rtfsymbol);
}
protected function ParseControl()
{
// Beginning of an RTF control word or control symbol.
// Look ahead by one character to see if it starts with
// a letter (control world) or another symbol (control symbol):
$this->GetChar();
$this->pos--;
if($this->is_letter())
$this->ParseControlWord();
else
$this->ParseControlSymbol();
}
protected function ParseText()
{
// Parse plain text up to backslash or brace,
// unless escaped.
$text = "";
do
{
$terminate = False;
// Is this an escape?
if($this->char == '\\') {
// Perform lookahead to see if this
// is really an escape sequence.
$this->GetChar();
switch($this->char)
{
case '\\': break;
case '{': break;
case '}': break;
default:
// Not an escape. Roll back.
$this->pos = $this->pos - 2;
$terminate = True;
break;
}
} elseif($this->char == '{' || $this->char == '}') {
$this->pos--;
$terminate = True;
}
if(!$terminate) { // store normal text
$text .= $this->char;
$this->GetChar();
}
}
while(!$terminate && $this->pos < $this->len);
$rtftext = new RtfText();
$rtftext->text = $text;
// If group does not exist, then this is not a valid RTF file. Throw an exception.
if($this->group == null) {
$err = "Parse error occured";
trigger_error($err);
throw new Exception("Parse error occured");
}
array_push($this->group->children, $rtftext);
}
/*
* Attempt to parse an RTF string. Parsing returns TRUE on success or FALSE on failure
*/
public function Parse($rtf)
{
try {
$this->rtf = $rtf;
$this->pos = 0;
$this->len = strlen($this->rtf);
$this->group = null;
$this->root = null;
while($this->pos < $this->len)
{
// Read next character:
$this->GetChar();
// Ignore \r and \n
if($this->char == "\n" || $this->char == "\r") continue;
// What type of character is this?
switch($this->char)
{
case '{':
$this->ParseStartGroup();
break;
case '}':
$this->ParseEndGroup();
break;
case '\\':
$this->ParseControl();
break;
default:
$this->ParseText();
break;
}
}
return True;
}
catch(Exception $ex) {
return False;
}
}
}
class RtfState
{
public function __construct()
{
$this->Reset();
}
public function Reset()
{
$this->bold = False;
$this->italic = False;
$this->underline = False;
$this->strike = False;
$this->hidden = False;
$this->fontsize = 0;
$this->fontcolor = null;
$this->background = null;
}
}
class RtfHtml
{
// Initialise Encoding
public function __construct($encoding = 'HTML-ENTITIES')
{
if ($encoding != 'HTML-ENTITIES') {
// Check if mbstring extension is loaded
if (!extension_loaded('mbstring')) {
trigger_error("PHP mbstring extension not enabled, reverting back to HTML-ENTITIES");
$encoding = 'HTML-ENTITIES';
// Check if the encoding is reconized by mbstring extension
} elseif (!in_array($encoding, mb_list_encodings())){
trigger_error("Unrecognized Encoding, reverting back to HTML-ENTITIES");
$encoding = 'HTML-ENTITIES';
}
}
$this->encoding = $encoding;
}
public function Format($root)
{
// Keep track of style modifications
$this->previousState = null;
// and create a stack of states
$this->states = array();
// Put an initial standard state onto the stack
$this->state = new RtfState();
array_push($this->states, $this->state);
// Keep track of opened html tags
$this->openedTags = array('span' => False, 'p' => False);
// Create the first paragraph
$this->OpenTag('p');
// Begin format
$this->FormatGroup($root);
// Remove the last opened <p> tag and return
return substr($this->output ,0, -3);
}
protected function ExtractColorTable($colorTblGrp) {
// {\colortbl;\red0\green0\blue0;}
// Index 0 of the RTF color table is the 'auto' color
$colortbl = array();
$c = count($colorTblGrp);
$color = '';
for ($i=1; $i<$c; $i++) { // Iterate through colors
if($colorTblGrp[$i] instanceof RtfControlWord) {
// Extract RGB color and convert it to hex string
$color = sprintf('#%02x%02x%02x', // hex string format
$colorTblGrp[$i]->parameter, // red
$colorTblGrp[$i+1]->parameter, // green
$colorTblGrp[$i+2]->parameter); // blue
$i+=2;
} elseif($colorTblGrp[$i] instanceof RtfText) {
// This is a delimiter ';' so
if ($i != 1) { // Store the already extracted color
$colortbl[] = $color;
} else { // This is the 'auto' color
$colortbl[] = 0;
}
}
}
$this->colortbl = $colortbl;
}
protected function FormatGroup($group)
{
// Can we ignore this group?
// Font table extraction not yet supported
if($group->GetType() == "fonttbl") return;
// Extract color table
elseif($group->GetType() == "colortbl") {
$this->ExtractColorTable($group->children);
return;
}
// Stylesheet extraction not yet supported
elseif($group->GetType() == "stylesheet") return;
elseif($group->GetType() == "info") return;
// Pictures extraction not yet supported
if(substr($group->GetType(), 0, 4) == "pict") return;
// Ignore Destionations
if($group->IsDestination()) return;
// Push a new state onto the stack:
$this->state = clone $this->state;
array_push($this->states, $this->state);
foreach($group->children as $child)
{
if($child instanceof RtfGroup) $this->FormatGroup($child);
elseif($child instanceof RtfControlWord) $this->FormatControlWord($child);
elseif($child instanceof RtfControlSymbol) $this->FormatControlSymbol($child);
elseif($child instanceof RtfText) $this->FormatText($child);
}
// Pop state from stack
array_pop($this->states);
$this->state = $this->states[sizeof($this->states)-1];
}
protected function FormatControlWord($word)
{
// plain: Reset font formatting properties to default.
// pard: Reset to default paragraph properties.
if($word->word == "plain" || $word->word == "pard"){ $this->state->Reset();
// Font formatting properties:
}elseif($word->word == "b"){ $this->state->bold = $word->parameter; // bold
}elseif($word->word == "i"){ $this->state->italic = $word->parameter; // italic
}elseif($word->word == "ul"){ $this->state->underline = $word->parameter; // underline
}elseif($word->word == "ulnone"){ $this->state->underline = False; // no underline
}elseif($word->word == "strike"){ $this->state->strike = $word->parameter; // strike through
}elseif($word->word == "v"){ $this->state->hidden = $word->parameter; // hidden
}elseif($word->word == "fs"){ $this->state->fontsize = ceil(($word->parameter / 24) * 16); // font size
// Colors:
}elseif ($word->word == "cf") { //|| $word->word == "chcfpat")
$this->state->fontcolor = $word->parameter;
}elseif ($word->word == "cb" || $word->word == "chcbpat" || $word->word == "highlight") {
$this->state->background = $word->parameter;
// RTF special characters:
}elseif($word->word == "lquote"){ $this->output .= "‘"; // ‘ ‘
}elseif($word->word == "rquote"){ $this->output .= "’"; // ’ ’
}elseif($word->word == "ldblquote"){ $this->output .= "“"; // “ “
}elseif($word->word == "rdblquote"){ $this->output .= "”"; // ” ”
}elseif($word->word == "bullet"){ $this->output .= "•"; // • •
}elseif($word->word == "endash"){ $this->output .= "–"; // – –
}elseif($word->word == "emdash"){ $this->output .= "—"; // — —
// more special characters:
}elseif($word->word == "enspace"){ $this->output .= " "; //  
}elseif($word->word == "emspace"){ $this->output .= " "; //  
//}elseif($word->word == "emspace" || $word->word == "enspace"){ $this->output .= " "; //    
}elseif($word->word == "tab"){ $this->output .= " "; // character value 9
}elseif($word->word == "line"){ $this->output .= "<br>"; // character value (line feed = ) (carriage return = )
// Unicode characters:
}elseif($word->word == "u") {
$uchar = $this->DecodeUnicode($word->parameter);
$this->ApplyStyle($uchar);
// End of paragraph:
}elseif($word->word == "par" || $word->word == "row") {
// Close previously opened tags
$this->CloseTags();
// Begin a new paragraph
$this->OpenTag('p');
}
}
protected function DecodeUnicode($code)
{
$htmlentity = "&#{$code};";
if($this->encoding == 'HTML-ENTITIES') return $htmlentity;
else {
// Character codes 128 to 159 (U+0080 to U+009F) are not allowed in HTML
if($code > 127 && $code < 160) {
$utf = mb_convert_encoding(chr($code), 'UTF-8', 'windows-1252');
$htmlentity = htmlentities($utf, ENT_QUOTES, 'UTF-8');
}
$mbChar = mb_convert_encoding($htmlentity, $this->encoding, 'HTML-ENTITIES');
return $mbChar;
}
}
protected function ApplyStyle($txt)
{
// Create a new 'span' element only when a style change occur
// 1st case: style change occured
// 2nd case: there is no change in style but the already created 'span'
// element is somehow closed (ex. because of an end of paragraph)
if ($this->state != $this->previousState ||
($this->state == $this->previousState && !$this->openedTags['span']))
{
$style = "";
if($this->state->bold) $style .= "font-weight:bold;";
if($this->state->italic) $style .= "font-style:italic;";
if($this->state->underline) $style .= "text-decoration:underline;";
// state->underline is a toggle switch variable so no need for
// a dedicated state->end_underline variable
// if($this->state->end_underline) {$span .= "text-decoration:none;";}
if($this->state->strike) $style .= "text-decoration:line-through;";
if($this->state->hidden) $style .= "display:none;";
if($this->state->fontsize != 0) $style .= "font-size:{$this->state->fontsize}px;";
// Font color:
if(isset($this->state->fontcolor)) {
// Check if color is set. in particular when it's the 'auto' color
if ($this->colortbl[$this->state->fontcolor])
$style .= "color:".$this->PrintColor($this->state->fontcolor).";";
}
// Background color:
if (isset($this->state->background)) {
// Check if color is set. in particular when it's the 'auto' color
if ($this->colortbl[$this->state->fontcolor])
$style .= "background-color:".$this->PrintColor($this->state->background).";";
}
// Keep track of preceding style
$this->previousState = clone $this->state;
if ($style != '') {
// If applicable close previously opened 'span' tag
$this->CloseTag('span');
// Create a new 'span' tag
$this->OpenTag('span',"style=\"{$style}\"");
}
}
$this->output .= $txt;
}
protected function PrintColor($index) {
return $this->colortbl[$index];
}
protected function OpenTag($tag, $attr = '')
{
$this->output .= $attr ? "<{$tag} {$attr}>" : "<{$tag}>";
$this->openedTags[$tag] = True;
}
protected function CloseTag($tag)
{
if ($this->openedTags[$tag]) {
// Check for empty html elements
if (substr($this->output ,-strlen("<{$tag}>")) == "<{$tag}>"){
switch ($tag)
{
case 'p': // Replace empty 'p' element with a line break
$this->output = substr($this->output ,0, -3)."<br>";
break;
default: // Delete empty elements
$this->output = substr($this->output ,0, -strlen("<{$tag}>"));
break;
}
} else {
$this->output .= "</{$tag}>";
$this->openedTags[$tag] = False;
}
}
}
protected function CloseTags()
{
// Close all opened tags
foreach ($this->openedTags as $tag => $b)
$this->CloseTag($tag);
}
protected function FormatControlSymbol($symbol)
{
if($symbol->symbol == '\'') {
$uchar = $this->DecodeUnicode($symbol->parameter);
$this->ApplyStyle($uchar);
}
}
protected function FormatText($text)
{
// Convert special characters to HTML entities
$txt = htmlspecialchars($text->text, ENT_NOQUOTES, 'UTF-8');
if($this->encoding == 'HTML-ENTITIES')
$this->ApplyStyle($txt);
else
$this->ApplyStyle(mb_convert_encoding($txt, $this->encoding, 'UTF-8'));
}
}
if (__FILE__ === realpath($_SERVER['SCRIPT_NAME']) && php_sapi_name() === 'cli') {
if (isset($_SERVER['argv'][1]) && ($_SERVER['argv'][1] !== '-')) {
$file = $_SERVER['argv'][1];
} else {
$file = 'php://stdin';
}
$reader = new RtfReader();
$rtf = file_get_contents($file);
if ($reader->Parse($rtf)) {
$formatter = new RtfHtml();
echo $formatter->Format($reader->root);
} else {
echo "Parse error occured";
}
}