forked from henck/rtf-html-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtf-html-php.php
More file actions
1162 lines (1036 loc) · 37.1 KB
/
rtf-html-php.php
File metadata and controls
1162 lines (1036 loc) · 37.1 KB
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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 $child->word;
elseif ($child instanceof RtfControlSymbol)
return ($child->symbol == '*') ? '*' : null;
return null;
}
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) {
// First group of the RTF document
$this->group = $group;
$this->root = $group;
// Create uc stack and insert the first default value
$this->uc = array(1);
} else {
array_push($this->uc, end($this->uc));
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;
}
/*
* Checks for end of line (EOL)
*/
protected function is_endofline()
{
if ($this->char == "\r" || $this->char == "\n") {
// Checks for a Windows/Acron type EOL
if( $this->rtf[$this->pos] == "\n" || $this->rtf[$this->pos] == "\r" ) {
$this->GetChar();
}
return TRUE;
}
return FALSE;
}
/*
* Checks for a space delimiter
*/
protected function is_space_delimiter()
{
if ($this->char == " " || $this->is_endofline()) return TRUE;
return FALSE;
}
protected function ParseEndGroup()
{
// Retrieve state of document from stack.
$this->group = $this->group->parent;
// Retrieve last uc value from stack
array_pop($this->uc);
}
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 no parameter assume control word's default (usually 1)
// if no default then assign 0 to the parameter
if($parameter === null) $parameter = 1;
// convert to a negative number when applicable
if($negative) $parameter = -$parameter;
// Update uc value
if ($word == "uc") {
array_pop($this->uc);
$this->uc[] = $parameter;
}
// Skip space delimiter
if(!$this->is_space_delimiter()) $this->pos--;
// If this is \u, then the parameter will be followed
// by {$this->uc} characters.
if($word == "u") {
// Convert parameter to unsigned decimal unicode
if($negative) $parameter = 65536 + $parameter;
// Will ignore replacement characters $uc times
$uc = end($this->uc);
while ($uc > 0) {
$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;
// Break if it's an RTF scope delimiter
elseif ($this->char == '{' || $this->char == '{')
break;
// - To include an RTF delimiter in skippable data, it must be
// represented using the appropriate control symbol (that is,
// escaped with a backslash,) as in plain text.
// - Any RTF control word or symbol is considered a single character
// for the purposes of counting skippable characters. For this reason
// it's more appropriate to create à $skip flag and let the Parse()
// function take care of the skippable characters.
$uc--;
}
}
$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;
// Treat EOL symbols as \par control word
if ($this->is_endofline()) {
$rtfword = new RtfControlWord();
$rtfword->word = 'par';
$rtfword->parameter = $parameter;
array_push($this->group->children, $rtfword);
return;
} elseif($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 = "";
$terminate = False;
do
{
// Ignore EOL characters
if($this->char == "\r" || $this->char == "\n") {
$this->GetChar();
continue;
}
// 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) {
// Save plain 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($err);
}
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 RtfImage
{
public function __construct()
{
$this->Reset();
}
public function Reset()
{
$this->format = 'bmp';
$this->width = 0; // in xExt if wmetafile otherwise in px
$this->height = 0; // in yExt if wmetafile otherwise in px
$this->goalWidth = 0; // in twips
$this->goalHeight = 0; // in twips
$this->pcScaleX = 100; // 100%
$this->pcScaleY = 100; // 100%
$this->binarySize = null; // Number of bytes of the binary data
$this->ImageData = null; // Binary or Hexadecimal Data
}
public function PrintImage()
{
// <img src="data:image/{FORMAT};base64,{#BDATA}" />
$output = "<img src=\"data:image/{$this->format};base64,";
if (isset($this->binarySize)) { // process binary data
return;
} else { // process hexadecimal data
$output .= base64_encode(pack('H*',$this->ImageData));
}
$output .= "\" />";
return $output;
}
}
class RtfFont
{
public $fontfamily;
public $fontname;
public $charset;
public $codepage;
}
class RtfState
{
public static $fonttbl = array();
public static $colortbl = array();
private static $highlight = array(
1 => 'Black',
2 => 'Blue',
3 => 'Cyan',
4 => 'Green',
5 => 'Magenta',
6 => 'Red',
7 => 'Yellow',
8 => 'Unused',
9 => 'DarkBlue',
10 => 'DarkCyan',
11 => 'DarkGreen',
12 => 'DarkMagenta',
13 => 'DarkRed',
14 => 'DarkYellow',
15 => 'DarkGray',
16 => 'LightGray'
);
public function __construct()
{
$this->Reset();
}
public function Reset($defaultFont = null)
{
$this->bold = False;
$this->italic = False;
$this->underline = False;
$this->strike = False;
$this->hidden = False;
$this->fontsize = 0;
$this->fontcolor = null;
$this->background = null;
$this->font = isset($defaultFont) ? $defaultFont : null;
}
public function PrintStyle()
{
$style = "";
if($this->bold) $style .= "font-weight:bold;";
if($this->italic) $style .= "font-style:italic;";
if($this->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->strike) $style .= "text-decoration:line-through;";
if($this->hidden) $style .= "display:none;";
if(isset($this->font)) {
if (isset(self::$fonttbl[$this->font]->fontfamily))
$style .= "font-family:" . self::$fonttbl[$this->font]->fontfamily . ";";
}
if($this->fontsize != 0) $style .= "font-size:{$this->fontsize}px;";
// Font color:
if(isset($this->fontcolor)) {
// Check if color is set. in particular when it's the 'auto' color
if (self::$colortbl[$this->fontcolor])
$style .= "color:" . self::$colortbl[$this->fontcolor] . ";";
}
// Background color:
if (isset($this->background)) {
// Check if color is set. in particular when it's the 'auto' color
if (self::$colortbl[$this->background])
$style .= "background-color:" . self::$colortbl[$this->background] . ";";
// Highlight color:
} elseif (isset($this->hcolor)) {
if (isset(self::$highlight[$this->hcolor]))
$style .= "background-color:" . self::$highlight[$this->hcolor] . ";";
}
return $style;
}
public function isLike($state)
{
if (!($state instanceof RtfState))
return False;
if ($this->bold != $state->bold)
return False;
if ($this->italic != $state->italic)
return False;
if ($this->underline != $state->underline)
return False;
if ($this->strike != $state->strike)
return False;
if ($this->hidden != $state->hidden)
return False;
if ($this->fontsize != $state->fontsize)
return False;
// Compare Font Color
if (isset($this->fontcolor)) {
if (!isset($state->fontcolor))
return False;
elseif ($this->fontcolor != $state->fontcolor)
return False;
} elseif (isset($state->fontcolor))
return False;
// Compare Background-color
if (isset($this->background)) {
if (!isset($state->background))
return False;
elseif ($this->background != $state->background)
return False;
} elseif (isset($state->background))
return False;
// Compare Background-color
if (isset($this->hcolor)) {
if (!isset($state->hcolor))
return False;
elseif ($this->hcolor != $state->hcolor)
return False;
} elseif (isset($state->hcolor))
return False;
if (isset($this->font)) {
if (!isset($state->font))
return False;
elseif ( self::$fonttbl[$this->font]->fontfamily !=
self::$fonttbl[$state->font]->fontfamily)
return False;
} elseif (isset($state->font))
return False;
return True;
}
}
class RtfHtml
{
private $output = '';
private $encoding;
// 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->ProcessGroup($root);
// Remove the last opened <p> tag and return
return substr($this->output ,0, -3);
}
protected function ExtractFontTable($fontTblGrp)
{
// {' \fonttbl (<fontinfo> | ('{' <fontinfo> '}'))+ '}'
// <fontnum><fontfamily><fcharset>?<fprq>?<panose>?
// <nontaggedname>?<fontemb>?<codepage>? <fontname><fontaltname>? ';'
$fonttbl = array();
$c = count($fontTblGrp);
for ($i=1;$i<$c;$i++){
$fname = '';
$fN = null;
foreach ($fontTblGrp[$i]->children as $child){
if ($child instanceof RtfControlWord){
switch ($child->word) {
case 'f':
$fN = $child->parameter;
$fonttbl[$fN] = new RtfFont();
break;
// Font family names
case 'froman': $fonttbl[$fN]->fontfamily = "serif"; break;
case 'fswiss': $fonttbl[$fN]->fontfamily = "sans-serif"; break;
case 'fmodern': $fonttbl[$fN]->fontfamily = "monospace"; break;
case 'fscript': $fonttbl[$fN]->fontfamily = "cursive"; break;
case 'fdecor': $fonttbl[$fN]->fontfamily = "fantasy"; break;
// case 'fnil': break; // default font
// case 'ftech': break; // symbol
// case 'fbidi': break; // bidirectional font
case 'fcharset': // charset
$fonttbl[$fN]->charset =
$this->GetEncodingFromCharset($child->parameter);
break;
case 'cpg': // code page
$fonttbl[$fN]->codepage =
$this->GetEncodingFromCodepage($child->parameter);
break;
case 'fprq': // Font pitch
$fonttbl[$fN]->fprq = $child->parameter;
break;
default: break;
}
} elseif ($child instanceof RtfText) {
// Save font name
$fname .= $child->text;
}
/*
elseif ($child instanceof RtfGroup) {
// possible subgroups:
// '{\*' \falt #PCDATA '}' = alternate font name
// '{\*' \fontemb <fonttype> <fontfname>? <data>? '}'
// '{\*' \fontfile <codepage>? #PCDATA '}'
// '{\*' \panose <data> '}'
continue;
} elseif ($child instanceof RtfControlSymbol) {
// the only authorized symbol here is '*':
// \*\fname = non tagged file name (only WordPad uses it)
continue;
}
*/
}
// Remove end ; delimiter from font name
$fonttbl[$fN]->fontname = substr($fname,0,-1);
// Save extracted Font
RtfState::$fonttbl = $fonttbl;
}
}
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;
}
}
}
RtfState::$colortbl = $colortbl;
}
protected function ExtractImage($pictGrp)
{
$Image = new RtfImage();
foreach ($pictGrp as $child) {
if ($child instanceof RtfControlWord) {
switch ($child->word) {
// Picture Format
case "emfblip": $Image->format = 'emf'; break;
case "pngblip": $Image->format = 'png'; break;
case "jpegblip": $Image->format = 'jpeg'; break;
case "macpict": $Image->format = 'pict'; break;
// case "wmetafile": $Image->format = 'bmp'; break;
// Picture size and scaling
case "picw": $Image->width = $child->parameter; break;
case "pich": $Image->height = $child->parameter; break;
case "picwgoal": $Image->goalWidth = $child->parameter; break;
case "pichgoal": $Image->goalHeight = $child->parameter; break;
case "picscalex": $Image->pcScaleX = $child->parameter; break;
case "picscaley": $Image->pcScaleY = $child->parameter; break;
// Binary or Hexadecimal Data ?
case "bin": $Image->binarySize = $child->parameter; break;
default: break;
}
} elseif ($child instanceof RtfText) { // store Data
$Image->ImageData = $child->text;
}
}
// output Image
$this->output .= $Image->PrintImage();
unset($Image);
}
protected function ProcessGroup($group)
{
// Can we ignore this group?
switch ($group->GetType())
{
case "fonttbl": // Extract Font table
$this->ExtractFontTable($group->children);
return;
case "colortbl": // Extract color table
$this->ExtractColorTable($group->children);
return;
case "stylesheet":
// Stylesheet extraction not yet supported
return;
case "info":
// Ignore Document information
return;
case "pict":
$this->ExtractImage($group->children);
return;
case "nonshppict":
// Ignore alternative images
return;
case "*": // Process destionation
$this->ProcessDestination($group->children);
return;
}
// Pictures extraction not yet supported
//if(substr($group->GetType(), 0, 4) == "pict") return;
// Push a new state onto the stack:
$this->state = clone $this->state;
array_push($this->states, $this->state);
foreach($group->children as $child)
$this->FormatEntry($child);
// Pop state from stack
array_pop($this->states);
$this->state = $this->states[sizeof($this->states)-1];
}
protected function ProcessDestination($dest)
{
if (!$dest[1] instanceof RtfControlWord) return;
// Check if this is a Word 97 picture
if ($dest[1]->word == "shppict") {
$c = count($dest);
for ($i=2;$i<$c;$i++)
$this->FormatEntry($dest[$i]);
}
}
protected function FormatEntry($entry)
{
if($entry instanceof RtfGroup) $this->ProcessGroup($entry);
elseif($entry instanceof RtfControlWord) $this->FormatControlWord($entry);
elseif($entry instanceof RtfControlSymbol) $this->FormatControlSymbol($entry);
elseif($entry instanceof RtfText) $this->FormatText($entry);
}
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($this->defaultFont);
// 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
}elseif($word->word == "f"){ $this->state->font = $word->parameter;
// Colors:
}elseif ($word->word == "cf" || $word->word == "chcfpat") {
$this->state->fontcolor = $word->parameter;
}elseif ($word->word == "cb" || $word->word == "chcbpat") {
$this->state->background = $word->parameter;
}elseif ($word->word == "highlight") {
$this->state->hcolor = $word->parameter;
// RTF special characters:
}elseif($word->word == "lquote"){ $this->Write("‘"); // ‘ ‘
}elseif($word->word == "rquote"){ $this->Write("’"); // ’ ’
}elseif($word->word == "ldblquote"){ $this->Write("“"); // “ “
}elseif($word->word == "rdblquote"){ $this->Write("”"); // ” ”
}elseif($word->word == "bullet"){ $this->Write("•"); // • •
}elseif($word->word == "endash"){ $this->Write("–"); // – –
}elseif($word->word == "emdash"){ $this->Write("—"); // — —
// more special characters:
}elseif($word->word == "enspace"){ $this->Write(" "); //  
}elseif($word->word == "emspace"){ $this->Write(" "); //  
//}elseif($word->word == "emspace" || $word->word == "enspace"){ $this->Write(" "); //    
}elseif($word->word == "tab"){ $this->Write(" "); // 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->Write($uchar);
// End of paragraph:
}elseif($word->word == "par" || $word->word == "row") {
// Close previously opened tags
$this->CloseTags();
// Begin a new paragraph
$this->OpenTag('p');
// Store defaults
}elseif($word->word == "deff") {
$this->defaultFont = $word->parameter;
}elseif(in_array($word->word, array('ansi','mac','pc','pca'))){
$this->RTFencoding = $this->GetEncodingFromCodepage($word->word);
}elseif ($word->word == "ansicpg" && $word->parameter) {
$this->RTFencoding = $this->GetEncodingFromCodepage($word->parameter);
}
}
protected function DecodeUnicode($code, $srcEnc = 'UTF-8')
{
$utf8 = '';
if ($srcEnc != 'UTF-8') { // convert character to Unicode
$utf8 = iconv(mb_detect_encoding($code, mb_detect_order(), false), "UTF-8", $code);
}
if ($this->encoding == 'HTML-ENTITIES') {
return $utf8 ? "&#{$this->ord_utf8($utf8)};" : "&#{$code};";
} elseif ($this->encoding == 'UTF-8') {
return $utf8 ? $utf8 : mb_convert_encoding("&#{$code};", $this->encoding, 'HTML-ENTITIES');
} else {
return $utf8 ? mb_convert_encoding($utf8, $this->encoding, 'UTF-8') :
mb_convert_encoding("&#{$code};", $this->encoding, 'HTML-ENTITIES');
}
}
protected function Write($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->isLike($this->previousState) ||
($this->state->isLike($this->previousState) && !$this->openedTags['span']))
{
// If applicable close previously opened 'span' tag
$this->CloseTag('span');
$style = $this->state->PrintStyle();
// Keep track of preceding style
$this->previousState = clone $this->state;
// Create style attribute and open span
$attr = $style ? "style=\"{$style}\"" : "";
$this->OpenTag('span', $attr);
}
$this->output .= $txt;
}
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 == '\'') {
$enc = $this->GetSourceEncoding();
$uchar = $this->DecodeUnicode($symbol->parameter, $enc);