-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathODTUtility.php
More file actions
1099 lines (1004 loc) · 46.1 KB
/
Copy pathODTUtility.php
File metadata and controls
1099 lines (1004 loc) · 46.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
/**
* Utility functions.
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author LarsDW223
*/
/** Include csscolors */
require_once DOKU_PLUGIN . 'odt/ODT/css/csscolors.php';
/** Include cssborder */
require_once DOKU_PLUGIN . 'odt/ODT/css/cssborder.php';
/**
* ODTUtility:
* Class containing some internal utility functions.
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author LarsDW223
* @package ODT\Utility
*/
class ODTUtility
{
/**
* Replace local links with bookmark references or text
*
* @param string $content The document content
* @param array $toc The table of contents
* @param array $bookmarks List of bookmarks
* @param string $styleName Link style name
* @param string $visitedStyleName Visited link style name
*/
public static function replaceLocalLinkPlaceholders(&$content, array $toc, array $bookmarks, $styleName, $visitedStyleName) {
$matches = array();
$position = 0;
$max = strlen ($content);
$length = strlen ('<locallink>');
$lengthWithName = strlen ('<locallink name=');
while ( $position < $max ) {
$first = strpos ($content, '<locallink', $position);
if ( $first === false ) {
break;
}
$endFirst = strpos ($content, '>', $first);
if ( $endFirst === false ) {
break;
}
$second = strpos ($content, '</locallink>', $endFirst);
if ( $second === false ) {
break;
}
// $match includes the whole tag '<locallink name="...">text</locallink>'
// The attribute 'name' is optional!
$match = substr ($content, $first, $second - $first + $length + 1);
$text = substr ($match, $endFirst-$first+1, -($length + 1));
$text = trim ($text, ' ');
$text = strtolower ($text);
$page = str_replace (' ', '_', $text);
$opentag = substr ($match, 0, $endFirst-$first);
$name = substr ($opentag, $lengthWithName);
$name = trim ($name, '">');
$linkStyle = 'text:style-name="'.$styleName.'"';
$linkStyle .= ' text:visited-style-name="'.$visitedStyleName.'"';
$found = false;
foreach ($toc as $item) {
$params = explode (',', $item);
if ( $page == $params [1] ) {
$found = true;
$link = '<text:a xlink:type="simple" xlink:href="#'.$params [0].'" '.$linkStyle.'>';
if ( !empty($name) ) {
$link .= $name;
} else {
$link .= $text;
}
$link .= '</text:a>';
$content = str_replace ($match, $link, $content);
$position = $first + strlen ($link);
}
}
if ( $found == false ) {
// Nothing found yet, check the bookmarks too.
foreach ($bookmarks as $item) {
if ( $page == $item ) {
$found = true;
$link = '<text:a xlink:type="simple" xlink:href="#'.$item.'" '.$linkStyle.'>';
if ( !empty($name) ) {
$link .= $name;
} else {
$link .= $text;
}
$link .= '</text:a>';
$content = str_replace ($match, $link, $content);
$position = $first + strlen ($link);
}
}
}
if ( $found == false ) {
// If we get here, then the referenced target was not found.
// There must be a bug manging the bookmarks or links!
// At least remove the locallink element and insert text.
if ( !empty($name) ) {
$content = str_replace ($match, $name, $content);
} else {
$content = str_replace ($match, $text, $content);
}
$position = $first + strlen ($text);
}
}
}
/**
* This function deletes the useless elements. Right now, these are empty paragraphs
* or paragraphs that only include whitespace.
*
* IMPORTANT:
* Paragraphs can be used for pagebreaks/changing page format.
* Such paragraphs may not be deleted!
*
* @param string $docContent The document content
* @param array $preventDeletetionStyles Array of style names which may not be deleted
*/
public static function deleteUselessElements(&$docContent, array $preventDeletetionStyles) {
$length_open = strlen ('<text:p');
$length_close = strlen ('</text:p>');
$max = strlen ($docContent);
$pos = 0;
while ($pos < $max) {
$start_open = strpos ($docContent, '<text:p', $pos);
if ( $start_open === false ) {
break;
}
$start_close = strpos ($docContent, '>', $start_open + $length_open);
if ( $start_close === false ) {
break;
}
$end = strpos ($docContent, '</text:p>', $start_close + 1);
if ( $end === false ) {
break;
}
$deleted = false;
$length = $end - $start_open + $length_close;
$content = substr ($docContent, $start_close + 1, $end - ($start_close + 1));
if ( empty($content) || ctype_space ($content) ) {
// Paragraph is empty or consists of whitespace only. Check style name.
$style_start = strpos ($docContent, '"', $start_open);
if ( $style_start === false ) {
// No '"' found??? Ignore this paragraph.
break;
}
$style_end = strpos ($docContent, '"', $style_start+1);
if ( $style_end === false ) {
// No '"' found??? Ignore this paragraph.
break;
}
$style_name = substr ($docContent, $style_start+1, $style_end - ($style_start+1));
// Only delete empty paragraph if not listed in 'Do not delete' array!
if ( !in_array($style_name, $preventDeletetionStyles) )
{
$docContent = substr_replace($docContent, '', $start_open, $length);
$deleted = true;
$max -= $length;
$pos = $start_open;
}
}
if ( $deleted == false ) {
$pos = $start_close;
}
}
}
/**
* The function tries to examine the width and height
* of the image stored in file $src.
*
* @param string $src The file name of image
* @param int $maxwidth The maximum width the image shall have
* @param int $maxheight The maximum height the image shall have
* @return array Width and height of the image in centimeters or
* both 0 if file doesn't exist.
* Just the integer value, no units included.
*/
public static function getImageSize($src, $maxwidth=NULL, $maxheight=NULL){
if(file_exists($src)) {
$info = getimagesize($src);
} else {
// FIXME: Add cache support for downloaded images.
$fetch = @(new DokuHTTPClient())->get($src);
if(!$fetch) {
return array(0, 0);
}
$info = getimagesizefromstring($fetch);
}
if(!$info)
{
if(file_exists($src)) {
$svgfile = @simplexml_load_file($src);
} else {
$svgfile = @simplexml_load_file($fetch);
}
if(isset($svgfile["width"]) && isset($svgfile["height"]))
{
$info = array(substr($svgfile["width"],0,-2), substr($svgfile["height"],0,-2));
}
elseif (isset($svgfile["viewBox"]))
{
/* preg_match("#viewbox=[\"']\d* \d* (\d*+(\.?+\d*)) (\d*+(\.?+\d*))#i", file_get_contents($src), $info);
$info = array($info[1], $info[3]); */
$info = explode(' ', $svgfile["viewBox"]);
$info = array($info[2], $info[3]);
}
else
{
return array(0, 0);
}
}
if(!isset($width)){
$width = $info[0];
$height = $info[1];
} else {
$height = round(($width * $info[1]) / $info[0]);
}
if ($maxwidth && $width > $maxwidth) {
$height = $height * ($maxwidth/$width);
$width = $maxwidth;
}
if ($maxheight && $height > $maxheight) {
$width = $width * ($maxheight/$height);
$height = $maxheight;
}
// Convert from pixel to centimeters
if ($width) $width = (($width/96.0)*2.54);
if ($height) $height = (($height/96.0)*2.54);
return array($width, $height);
}
/**
* Return the size of an image in centimeters.
*
* @param string $src Filepath of the image
* @param string|null $width Alternative width
* @param string|null $height Alternative height
* @param boolean|true $preferImage Prefer original image size
* @param ODTUnits $units $ODTUnits object for unit conversion
* @return array
*/
public static function getImageSizeString($src, $width = NULL, $height = NULL, $preferImage=true, ODTUnits $units){
list($width_file, $height_file) = self::getImageSize($src);
// Get original ratio if possible
$ratio = 1;
if ($width_file != 0 && $height_file != 0) {
$ratio = $height_file/$width_file;
}
if ($width_file != 0 && $preferImage) {
$width = $width_file.'cm';
$height = $height_file.'cm';
} else {
// convert from pixel to centimeters only if no unit is
// specified or if unit is 'px'
$unit_width = $units->stripDigits ($width);
$unit_height = $units->stripDigits ($height);
if ((empty($unit_width) && empty($unit_height)) ||
($unit_width == 'px' && $unit_height == 'px')) {
if (!$height) {
$height = $width * $ratio;
}
$height = (($height/96.0)*2.54).'cm';
if ($width) $width = (($width/96.0)*2.54).'cm';
}
}
// At this point $width and $height should include a unit
$width = str_replace(',', '.', $width);
$height = str_replace(',', '.', $height);
if ($width && $height) {
// Don't be wider than the page
if ($width_file >= 17){ // FIXME : this assumes A4 page format with 2cm margins
$width = $width.'" style:rel-width="100%';
$height = $height.'" style:rel-height="scale';
} else {
$width = $width;
$height = $height;
}
} else {
// external image and unable to download, fallback
if (!$width) {
$width = '" svg:rel-width="100%';
}
if (!$height) {
$height = '" svg:rel-height="100%';
}
}
return array($width, $height);
}
/**
* Split $value by whitespace and convert any relative values (%)
* into an absolute value. This is done by taking the percentage of
* $maxWidthInPt.
*
* @param string $value String (Property value)
* @param integer $maxWidthInPt Maximum width in points
* @param ODTUnits $units $ODTUnits object for unit conversion
* @return string
*/
protected static function adjustPercentageValueParts ($value, $maxWidthInPt, $units) {
$values = preg_split ('/\s+/', $value);
$value = '';
foreach ($values as $part) {
$length = strlen ($part);
if ( $length > 1 && $part [$length-1] == '%' ) {
$percentageValue = $units->getDigits($part);
$part = (($percentageValue * $maxWidthInPt)/100) . 'pt';
//$part = '5pt ';
}
$value .= ' '.$part;
}
$value = trim($value);
$value = trim($value, '"');
return $value;
}
/**
* The function adjusts the properties values for ODT:
* - 'em' units are converted to 'pt' units
* - CSS color names are converted to its RGB value
* - short color values like #fff are converted to the long format, e.g #ffffff
* - some relative values are converted to absoulte depending on other
* values e.g. 'line-height' an 'font-size'
*
* @author LarsDW223
*
* @param array $properties Array with property value pairs
* @param ODTUnits $units Units object to use for conversion
* @param integer $maxWidth Units object to use for conversion
*/
public static function adjustValuesForODT (&$properties, ODTUnits $units, $maxWidth=NULL) {
$adjustToMaxWidth = array('margin', 'margin-left', 'margin-right', 'margin-top', 'margin-bottom');
// Convert 'text-decoration'.
if(!empty($properties['text-decoration']))
{
if ($properties['text-decoration'] == 'line-through') {
$properties ['text-line-through-style'] = 'solid';
} elseif ($properties['text-decoration'] == 'underline') {
$properties ['text-underline-style'] = 'solid';
} elseif ($properties['text-decoration'] == 'overline') {
$properties ['text-overline-style'] = 'solid';
}
}
// Normalize border properties
cssborder::normalize($properties);
// First do simple adjustments per property
foreach ($properties as $property => $value) {
$properties [$property] = self::adjustValueForODT ($property, $value, $units);
}
// Adjust relative margins if $maxWidth is given.
// $maxWidth is expected to be the width of the surrounding element.
if (isset($maxWidth)) {
$maxWidthInPt = $units->toPoints($maxWidth, 'y');
$maxWidthInPt = $units->getDigits($maxWidthInPt);
foreach ($adjustToMaxWidth as $property) {
if (!empty($properties [$property])) {
$properties [$property] = self::adjustPercentageValueParts ($properties [$property], $maxWidthInPt, $units);
}
}
}
// Now we do the adjustments for which one value depends on another
// Do we have font-size or line-height set?
if (isset($properties ['font-size']) || isset($properties ['line-height'])) {
// First get absolute font-size in points
$base_font_size_in_pt = $units->getPixelPerEm ().'px';
$base_font_size_in_pt = $units->toPoints($base_font_size_in_pt, 'y');
$base_font_size_in_pt = $units->getDigits($base_font_size_in_pt);
if (isset($properties ['font-size'])) {
$font_size_unit = $units->stripDigits($properties ['font-size']);
$font_size_digits = $units->getDigits($properties ['font-size']);
if ($font_size_unit == '%') {
$base_font_size_in_pt = ($font_size_digits * $base_font_size_in_pt)/100;
$properties ['font-size'] = $base_font_size_in_pt.'pt';
} elseif ($font_size_unit != 'pt') {
$properties ['font-size'] = $units->toPoints($properties ['font-size'], 'y');
$base_font_size_in_pt = $units->getDigits($properties ['font-size']);
} else {
$base_font_size_in_pt = $units->getDigits($properties ['font-size']);
}
}
// Convert relative line-heights to absolute
if (isset($properties ['line-height'])) {
$line_height_unit = $units->stripDigits($properties ['line-height']);
$line_height_digits = $units->getDigits($properties ['line-height']);
if ($line_height_unit == '%') {
$properties ['line-height'] = (($line_height_digits * $base_font_size_in_pt)/100).'pt';
} elseif (empty($line_height_unit)) {
$properties ['line-height'] = ($line_height_digits * $base_font_size_in_pt).'pt';
}
}
}
}
/**
* The function adjusts the property value for ODT:
* - 'em' units are converted to 'pt' units
* - CSS color names are converted to its RGB value
* - short color values like #fff are converted to the long format, e.g #ffffff
*
* @author LarsDW223
*
* @param string $property The property name
* @param string $value The value
* @param ODTUnits $units Units object to use for conversion
* @return string Converted value
*/
public static function adjustValueForODT ($property, $value, ODTUnits $units) {
if ($property == 'font-family') {
// There might be several font/font-families included.
// Only take the first one.
$value = trim($value, '"');
if (strpos($value, ',') !== false) {
$values = explode(',', $value);
$value = trim ($values [0], '"');
$value = trim ($value, "'");
$value = trim ($value);
}
} else {
$values = preg_split ('/\s+/', $value);
$value = '';
foreach ($values as $part) {
// If it is a short color value (#xxx) then convert it to long value (#xxxxxx)
// (ODT does not support the short form)
if (isset($part[0]) && $part[0] == '#' && strlen($part) == 4 ) {
$part = '#'.$part [1].$part [1].$part [2].$part [2].$part [3].$part [3];
} else {
// If it is a CSS color name, get it's real color value
$color = csscolors::getColorValue ($part);
if ( $part == 'black' || $color != '#000000' ) {
$part = $color;
}
}
if ( strlen($part) > 2 && substr($part, -2, -1) == 'e' && substr($part, -1) == 'm' ) {
$part = $units->toPoints($part, 'y');
}
if ( strlen($part) > 2 && (substr($part, -2, -1) != 'p' || substr($part, -1) != 't') &&
strpos($property, 'border')!==false ) {
$part = $units->toPoints($part, 'y');
}
// Some values can have '"' in it. These need to be converted to '''
// e.g. 'font-family' tp specify that '"Courier New"' is one font name not two
$part = str_replace('"', ''', $part);
$value .= ' '.$part;
}
$value = trim($value);
$value = trim($value, '"');
}
return $value;
}
/**
* This function processes the CSS style declarations in $style and saves them in $properties
* as key - value pairs, e.g. $properties ['color'] = 'red'. It also adjusts the values
* for the ODT format and changes URLs to local paths if required, using $baseURL).
*
* @author LarsDW223
* @param array $properties
* @param string $style The CSS style e.g. 'color:red;'
* @param string|null $baseURL
* @param ODTUnits $units Units object to use for conversion
* @param integer $maxWidth MaximumWidth
*/
public static function getCSSStylePropertiesForODT(&$properties, $style, $baseURL = NULL, ODTUnits $units, $maxWidth=NULL){
// Create rule with selector '*' (doesn't matter) and declarations as set in $style
$rule = new css_rule ('*', $style);
$rule->getProperties ($properties);
//foreach ($properties as $property => $value) {
// $properties [$property] = self::adjustValueForODT ($property, $value, $units);
//}
self::adjustValuesForODT ($properties, $units, $maxWidth);
if ( !empty ($properties ['background-image']) ) {
if ( !empty ($baseURL) ) {
// Replace 'url(...)' with $baseURL
$properties ['background-image'] = cssimportnew::replaceURLPrefix ($properties ['background-image'], $baseURL);
}
}
}
/**
* The function opens/puts a new element on the HTML stack in $params->htmlStack.
* The element name will be $element and it will be created with the attributes $attributes.
* Then CSS matching is performed and the CSS properties are returned in $dest.
* Finally the CSS properties are converted to ODT format if neccessary.
*
* @author LarsDW223
* @param ODTInternalParams $params Commom params.
* @param array $dest Target array for properties storage
* @param string $element The element's name
* @param string $attributes The element's attributes
* @param integer $maxWidth Maximum Width
*/
public static function openHTMLElement (ODTInternalParams $params, array &$dest, $element, $attributes, $maxWidth=NULL) {
// Push/create our element to import on the stack
$params->htmlStack->open($element, $attributes);
$toMatch = $params->htmlStack->getCurrentElement();
$params->import->getPropertiesForElement($dest, $toMatch, $params->units);
// Adjust values for ODT
self::adjustValuesForODT($dest, $params->units, $maxWidth);
}
/**
* The function closes element with name $element on the HTML stack in $params->htmlStack.
*
* @author LarsDW223
* @param ODTInternalParams $params Commom params.
* @param string $element The element's name
*/
public static function closeHTMLElement (ODTInternalParams $params, $element) {
$params->htmlStack->close($element);
}
/**
* The function temporarily opens/puts a new element on the HTML stack in $params->htmlStack.
* Before leaving the function the element is removed from the stack.
*
* The element name will be $element and it will be created with the attributes $attributes.
* After opening the element CSS matching is performed and the CSS properties are returned in $dest.
* Finally the CSS properties are converted to ODT format if neccessary.
*
* @author LarsDW223
* @param ODTInternalParams $params Commom params.
* @param array $dest Target array for properties storage
* @param string $element The element's name
* @param string $attributes The element's attributes
* @param integer $maxWidth Maximum Width
* @param boolean $inherit Enable/disable CSS inheritance
*/
public static function getHTMLElementProperties (ODTInternalParams $params, array &$dest, $element, $attributes, $maxWidth=NULL, $inherit=true) {
// Push/create our element to import on the stack
$params->htmlStack->open($element, $attributes);
$toMatch = $params->htmlStack->getCurrentElement();
$params->import->getPropertiesForElement($dest, $toMatch, $params->units, $inherit);
// Adjust values for ODT
self::adjustValuesForODT($dest, $params->units, $maxWidth);
// Remove element from stack
$params->htmlStack->removeCurrent();
}
/**
* Small helper function for finding the next tag enclosed in <angle> brackets.
* Returns beginning and end of the tag as an array [0] = start, [1] = end.
*
* @author LarsDW223
* @param string $content Code to search in.
* @param string $pos Start position for searching.
* @return array
*/
public static function getNextTag (&$content, $pos) {
$start = strpos ($content, '<', $pos);
if ($start === false) {
return false;
}
$end = strpos ($content, '>', $pos);
if ($end === false) {
return false;
}
return array($start, $end);
}
/**
* The function returns $value as a valid IRI and replaces some signs
* if neccessary, e.g. '&' will be replaced by '&'.
* The function will not do double replacements, e.g. if the string
* already includes a '&' it will NOT become '&amp;'.
*
* @author LarsDW223
* @param string $value String to be converted to IRI
* @return string
*/
public static function stringToIRI ($value) {
$max = strlen ($value);
for ($pos = 0 ; $pos < $max ; $pos++) {
switch ($value [$pos]) {
case '&':
if ($max - $pos >= 4 &&
$value [$pos+1] == '#' &&
$value [$pos+2] == '3' &&
$value [$pos+3] == '8' &&
$value [$pos+4] == ';') {
// '&' must be replaced with "&"
$value [$pos+1] = 'a';
$value [$pos+2] = 'm';
$value [$pos+3] = 'p';
$pos += 4;
} else if ($max - $pos < 4 ||
$value [$pos+1] != 'a' ||
$value [$pos+2] != 'm' ||
$value [$pos+3] != 'p' ||
$value [$pos+4] != ';' ) {
// '&' must be replaced with "&"
$new = substr($value, 0, $pos+1);
$new .= 'amp;';
$new .= substr($value, $pos+1);
$value = $new;
$max += 4;
$pos += 4;
}
break;
}
}
return $value;
}
protected static function getLinkURL ($search) {
preg_match ('/href="[^"]*"/', $search, $matches);
$url = substr ($matches[0], 5);
$url = trim($url, '"');
// Keep '&' and ':' in the link URL unescaped, otherwise url parameter passing will not work
$url = str_replace('&', '&', $url);
$url = str_replace('%3A', ':', $url);
return $url;
}
/**
* static call back to replace spaces
*
* @param array $matches
* @return string
*/
protected static function _preserveSpace($matches){
$spaces = $matches[1];
$len = strlen($spaces);
return '<text:s text:c="'.$len.'"/>';
}
protected static function createTextStyle (ODTInternalParams $params, $element, $attributes, $styleName=NULL) {
// Create automatic style
if (!isset($styleName) || !$params->document->styleExists($styleName)) {
// Get properties
$properties = array();
self::getHTMLElementProperties ($params, $properties, $element, $attributes);
if (!isset($styleName)) {
$properties ['style-name'] = ODTStyle::getNewStylename ('span');
} else {
// Use callers style name. He needs to be sure that it's unique!
$properties ['style-name'] = $styleName;
}
$params->document->createTextStyle($properties, false);
// Return style name
return $properties ['style-name'];
} else {
// Style already exists
return $styleName;
}
}
protected static function createParagraphStyle (ODTInternalParams $params, $element, $attributes, $styleName=NULL) {
// Create automatic style
if (!isset($styleName) || !$params->document->styleExists($styleName)) {
// Get properties
$properties = array();
self::getHTMLElementProperties ($params, $properties, $element, $attributes);
if (!isset($styleName)) {
$properties ['style-name'] = ODTStyle::getNewStylename ('span');
} else {
// Use callers style name. He needs to be sure that it's unique!
$properties ['style-name'] = $styleName;
}
$params->document->createParagraphStyle($properties, false);
// Return style name
return $properties ['style-name'];
} else {
// Style already exists
return $styleName;
}
}
/**
* Convenience function for converting some HTML code to ODT format.
* The function will try to automatically create any needed ODT styles
* from the CSS code found in the HTML code.
*
* Also some special settings can be passed in the options array:
*
* $options ['p_style']:
* The default paragraph style. If empty 'body' will be used.
*
* $options ['list_p_style']:
* The default paragraph style in lists. If empty 'body' will be used.
*
* $options ['list_ol_style']:
* The default style for ordered lists. If empty 'numbering' will be used.
*
* $options ['list_ul_style']:
* The default style for un-ordered lists. If empty 'list' will be used.
*
* $options ['media_selector']:
* The media selector used for CSS handling (e.g. 'screen' or 'print').
* If empty the current/configured one will be used.
*
* $options ['element']:
* If not empty an HTML tag named '$options ['element']' will be pushed
* on the internal HTML stack before converting the $HTMLCode.
* This influences CSS handling.
*
* $options ['attributes']:
* The attributes to set for '$options ['element']'.
*
* $options ['escape_content']:
* Should have the value 'true' or 'false' (as string!). If 'true'
* XML entities will be escaped. Otherwise it is assumed that it
* already has been done.
*
* $options ['class']:
* Optional CSS class to add to found 'class="..."' attributes in
* the HTML code.
*
* $options ['style_names']:
* If set to 'prefix_and_class' then ODT style names will not be
* generated dynamically but are constructed from '$options ['style_names_prefix']'
* following the CSS class name(s).
*
* $options ['linebreaks']:
* If set to 'remove' then linebreaks will be ignored. Otherwise
* they will be kept and converted to proper ODT linebreaks.
*
* $options ['tabs']:
* If set to 'remove' then tabs will be ignored. Otherwise they
* will be kept and converted to proper ODT tabs.
*
* $options ['space']:
* If set to 'preserve' then space is preserved like for preformatted
* code blocks. Otherwise space is not preserved and multiple spaces
* will apear as only one space.
*
* @author LarsDW223
* @param ODTInternalParams $params The internal params
* @param string $HTMLCode The HTML code to convert
* @param array $options Array of options
*/
public static function generateODTfromHTMLCode(ODTInternalParams $params, $HTMLCode, array $options){
$elements = array ('sup' => array ('open' => '<text:span text:style-name="sup">',
'close' => '</text:span>'),
'sub' => array ('open' => '<text:span text:style-name="sub">',
'close' => '</text:span>'),
'u' => array ('open' => '<text:span text:style-name="underline">',
'close' => '</text:span>'),
'em' => array ('open' => '<text:span text:style-name="Emphasis">',
'close' => '</text:span>'),
'strong' => array ('open' => '<text:span text:style-name="Strong_20_Emphasis">',
'close' => '</text:span>'),
'del' => array ('open' => '<text:span text:style-name="del">',
'close' => '</text:span>'),
'span' => array ('open' => '',
'close' => ''),
'a' => array ('open' => '',
'close' => ''),
'ol' => array ('open' => '',
'close' => ''),
'ul' => array ('open' => '',
'close' => ''),
'li' => array ('open' => '<text:list-item><text:p text:style-name="Text_20_body">',
'close' => '</text:p></text:list-item>'),
// In the moment only remove divs
'div' => array ('open' => '', 'close' => ''),
);
$parsed = array();
// remove useless leading and trailing whitespace-newlines
$HTMLCode = preg_replace('/^ \n/', '', $HTMLCode);
$HTMLCode = preg_replace('/\n $/', '', $HTMLCode);
$HTMLCode = str_replace(' ', ' ', $HTMLCode);
// Get default paragraph style
if (!empty($options ['p_style'])) {
$p_style = $options ['p_style'];
} else {
$p_style = $params->document->getStyleName('body');
}
// Get default list style names
if (!empty($options ['list_p_style'])) {
$p_list_style = $options ['list_p_style'];
} else {
$p_list_style = $params->document->getStyleName('body');
}
if (!empty($options ['list_ol_style'])) {
$ol_list_style = $options ['list_ol_style'];
} else {
$ol_list_style = $params->document->getStyleName('numbering');
}
if (!empty($options ['list_ul_style'])) {
$ul_list_style = $options ['list_ul_style'];
} else {
$ul_list_style = $params->document->getStyleName('list');
}
// Set new media selector (remember old one)
$media = $params->import->getMedia ();
if (!empty($options['media_selector'])) {
$params->import->setMedia($options['media_selector']);
}
if (!empty($options ['element'])) {
$params->htmlStack->open($options ['element'], $options ['attributes']);
}
// First examine $HTMLCode and differ between normal content,
// opening tags and closing tags.
$max = strlen ($HTMLCode);
$pos = 0;
while ($pos < $max) {
$found = self::getNextTag($HTMLCode, $pos);
if ($found !== false) {
$entry = array();
$entry ['content'] = substr($HTMLCode, $pos, $found [0]-$pos);
if ($entry ['content'] === false) {
$entry ['content'] = '';
}
$parsed [] = $entry;
$tagged = substr($HTMLCode, $found [0], $found [1]-$found [0]+1);
$entry = array();
if ($HTMLCode [$found[1]-1] == '/') {
// Element without content <abc/>, doesn'T make sense, save as content
$entry ['content'] = $tagged;
} else {
if ($HTMLCode [$found[0]+1] != '/') {
$parts = explode(' ', trim($tagged, '<> '), 2);
$entry ['tag-open'] = $parts [0];
if ( isset($parts [1]) ) {
$entry ['attributes'] = $parts [1];
}
$entry ['tag-orig'] = $tagged;
} else {
$entry ['tag-close'] = trim ($tagged, '<>/ ');
$entry ['tag-orig'] = $tagged;
}
}
$entry ['matched'] = false;
$parsed [] = $entry;
$pos = $found [1]+1;
} else {
$entry = array();
$entry ['content'] = substr($HTMLCode, $pos);
$parsed [] = $entry;
break;
}
}
// Check each array entry.
$checked = array();
$first = true;
$firstTag = '';
$olStartValue = NULL;
for ($out = 0 ; $out < count($parsed) ; $out++) {
if (isset($checked [$out])) {
continue;
}
$found = &$parsed [$out];
if (isset($found ['content'])) {
if ($options ['escape_content'] !== 'false') {
$checked [$out] = $params->document->replaceXMLEntities($found ['content']);
} else {
$checked [$out] = $found ['content'];
}
} else if (isset($found ['tag-open'])) {
$closed = false;
for ($in = $out+1 ; $in < count($parsed) ; $in++) {
$search = &$parsed [$in];
if (isset($search ['tag-close']) &&
$found ['tag-open'] == $search ['tag-close'] &&
$search ['matched'] === false &&
array_key_exists($found ['tag-open'], $elements)) {
$closed = true;
$search ['matched'] = true;
// Remeber the first element
if ($first) {
$first = false;
$firstTag = $found ['tag-open'];
}
// Known and closed tag, convert to ODT
switch ($found ['tag-open']) {
case 'span':
// Create ODT span using CSS style from attributes
if (!empty($options ['class'])) {
if (preg_match('/class="[^"]*"/', $found ['attributes'], $matches) == 1) {
$class_attr = substr($matches [0], 7);
$class_attr = trim($class_attr, '"');
$class_attr = 'class="'.$options ['class'].' '.$class_attr.'"';
$found ['attributes'] = str_replace($matches [0], $class_attr, $found ['attributes']);
}
}
$style_name = NULL;
if ($options ['style_names'] == 'prefix_and_class') {
if (preg_match('/class="[^"]*"/', $found ['attributes'], $matches) == 1) {
$class_attr = substr($matches [0], 7);
$class_attr = trim($class_attr, '"');
$style_name = $options ['style_names_prefix'].$class_attr;
}
}
$style_name = self::createTextStyle ($params, 'span', $found ['attributes'], $style_name);
$checked [$out] = '<text:span text:style-name="'.$style_name.'">';
$checked [$in] = '</text:span>';
break;
case 'a':
$url = self::getLinkURL($found ['attributes']);
if (empty($url)) {
$url = 'URLNotFoundInXHTMLLink';
}
$checked [$out] = $params->document->openHyperlink ($url, NULL, NULL, true);
$checked [$in] = $params->document->closeHyperlink (true);
break;
case 'ul':
$checked [$out] = '<text:list text:style-name="'.$ul_list_style.'" text:continue-numbering="false">';
$checked [$in] = '</text:list>';
break;
case 'ol':
$checked [$out] = '<text:list text:style-name="'.$ol_list_style.'" text:continue-numbering="false">';
$checked [$in] = '</text:list>';
if (preg_match('/start="[^"]*"/', $found ['attributes'], $matches) == 1) {
$olStartValue = substr($matches [0], 7);
$olStartValue = trim($olStartValue, '"');
}
break;
case 'li':
// Create ODT span using CSS style from attributes
$haveClass = false;
if (!empty($options ['class'])) {
if (preg_match('/class="[^"]*"/', $found ['attributes'], $matches) == 1) {
$class_attr = substr($matches [0], 7);
$class_attr = trim($class_attr, '"');
$class_attr = 'class="'.$options ['class'].' '.$class_attr.'"';
$found ['attributes'] = str_replace($matches [0], $class_attr, $found ['attributes']);
$haveClass = true;
}
}
$style_name = NULL;
if ($options ['style_names'] == 'prefix_and_class') {
if (preg_match('/class="[^"]*"/', $found ['attributes'], $matches) == 1) {
$class_attr = substr($matches [0], 7);
$class_attr = trim($class_attr, '"');
$style_name = $options ['style_names_prefix'].$class_attr;
$haveClass = true;
}
}
if ($haveClass) {
$style_name = self::createParagraphStyle ($params, 'li', $found ['attributes'], $style_name);
} else {
$style_name = $p_list_style;
}