forked from ezsystems/ezpublish-legacy
/
ezxmlinputparser.php
1384 lines (1193 loc) · 47.8 KB
/
ezxmlinputparser.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
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
/**
* File containing the eZXMLInputParser class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
* @package kernel
*/
/*
Base class for the input parser.
The goal of the parser is XML/HTML analyzing, fixing and transforming.
The input is processed in 2 passes:
- 1st pass: Parsing input, check for syntax errors, build DOM tree.
- 2nd pass: Walking through DOM tree, checking validity by XML schema,
calling tag handlers to transform the tree.
Both passes are controlled by the arrays described bellow and user handler functions.
*/
// if ( !class_exists( 'eZXMLSchema' ) ) // AS 21-09-2007: commented out because of include_once being commented out
class eZXMLInputParser
{
/// \deprecated (back-compatibility)
const SHOW_NO_ERRORS = 0;
const SHOW_SCHEMA_ERRORS = 1;
const SHOW_ALL_ERRORS = 2;
/// Use these constants for error types
const ERROR_NONE = 0;
const ERROR_SYNTAX = 4;
const ERROR_SCHEMA = 8;
const ERROR_DATA = 16;
const ERROR_ALL = 28; // 4+8+16
/* $InputTags array contains properties of elements that come from the input.
Each array element describes a tag that comes from the input. Arrays index is
a tag's name. Each element is an array that may contain the following members:
'name' - a string representing a new name of the tag,
'nameHandler' - a name of the function that returns new tag name. Function format:
function tagNameHandler( $tagName, &$attributes )
If no of those elements are defined the original tag's name is used.
'noChildren' - boolean value that determines if this tag could have child tags,
default value is false.
Example:
public $InputTags = array(
'original-name' => array( 'name' => 'new-name' ),
'original-name2' => array( 'nameHandler' => 'tagNameHandler',
'noChildren' => true ),
...
);
*/
public $InputTags = array();
/*
$OutputTags array contains properties of elements that are produced in the output.
Each array element describes a tag presented in the output. Arrays index is
a tag's name. Each element is an array that may contain the following members:
'parsingHandler' - "Parsing handler" called at parse pass 1 before processing tag's children.
'initHandler' - "Init handler" called at pass 2 before proccessing tag's children.
'structHandler' - "Structure handler" called at pass 2 after proccessing tag's children,
but before schema validity check. It can be used to implement structure
transformations.
'publishHandler' - "Publish handler" called at pass 2 after schema validity check, so it is called
in case the element has it's guaranteed place in the DOM tree.
'attributes' - an array that describes attributes transformations. Array's index is the
original name of an attribute, and the value is the new name.
'requiredInputAttributes' - attributes that are required in the input tag. If they are not presented
it raises invalid input flag.
Example:
public $OutputTags = array(
'custom' => array( 'parsingHandler' => 'parsingHandlerCustom',
'initHandler' => 'initHandlerCustom',
'structHandler' => 'structHandlerCustom',
'publishHandler' => 'publishHandlerCustom',
'attributes' => array( 'title' => 'name' ) ),
...
);
*/
public $OutputTags = array();
public $Namespaces = array( 'image' => 'http://ez.no/namespaces/ezpublish3/image/',
'xhtml' => 'http://ez.no/namespaces/ezpublish3/xhtml/',
'custom' => 'http://ez.no/namespaces/ezpublish3/custom/',
'tmp' => 'http://ez.no/namespaces/ezpublish3/temporary/' );
/*!
The constructor.
\param $validate
\param $validateErrorLevel Determines types of errors that break input processing
It's possible to combine any error types, by creating a bitmask of EZ_XMLINPUTPARSER_ERROR_* constants.
\c true value means that all errors defined by $detectErrorLevel parameter will break further processing
\param $detectErrorLevel Determines types of errors that will be detected and added to error log ($Messages).
*/
function eZXMLInputParser( $validateErrorLevel = self::ERROR_NONE, $detectErrorLevel = self::ERROR_NONE, $parseLineBreaks = false,
$removeDefaultAttrs = false )
{
// Back-compatibility fixes:
if ( $detectErrorLevel === self::SHOW_SCHEMA_ERRORS )
{
$detectErrorLevel = self::ERROR_SCHEMA;
}
elseif ( $detectErrorLevel === self::SHOW_ALL_ERRORS )
{
$detectErrorLevel = self::ERROR_ALL;
}
if ( $validateErrorLevel === false )
{
$validateErrorLevel = self::ERROR_NONE;
}
elseif ( $validateErrorLevel === true )
{
$validateErrorLevel = $detectErrorLevel;
}
$this->ValidateErrorLevel = $validateErrorLevel;
$this->DetectErrorLevel = $detectErrorLevel;
$this->RemoveDefaultAttrs = $removeDefaultAttrs;
$this->ParseLineBreaks = $parseLineBreaks;
$this->XMLSchema = eZXMLSchema::instance();
$this->eZPublishVersion = eZPublishSDK::majorVersion() + eZPublishSDK::minorVersion() * 0.1;
$ini = eZINI::instance( 'ezxml.ini' );
if ( $ini->hasVariable( 'InputSettings', 'TrimSpaces' ) )
{
$trimSpaces = $ini->variable( 'InputSettings', 'TrimSpaces' );
$this->TrimSpaces = $trimSpaces == 'true' ? true : false;
}
if ( $ini->hasVariable( 'InputSettings', 'AllowMultipleSpaces' ) )
{
$allowMultipleSpaces = $ini->variable( 'InputSettings', 'AllowMultipleSpaces' );
$this->AllowMultipleSpaces = $allowMultipleSpaces == 'true' ? true : false;
}
if ( $ini->hasVariable( 'InputSettings', 'AllowNumericEntities' ) )
{
$allowNumericEntities = $ini->variable( 'InputSettings', 'AllowNumericEntities' );
$this->AllowNumericEntities = $allowNumericEntities == 'true' ? true : false;
}
$contentIni = eZINI::instance( 'content.ini' );
$useStrictHeaderRule = $contentIni->variable( 'header', 'UseStrictHeaderRule' );
$this->StrictHeaders = $useStrictHeaderRule == 'true' ? true : false;
}
/// \public
function setDOMDocumentClass( $DOMDocumentClass )
{
$this->DOMDocumentClass = $DOMDocumentClass;
}
/// \public
function setParseLineBreaks( $value )
{
$this->ParseLineBreaks = $value;
}
/// \public
function setRemoveDefaultAttrs( $value )
{
$this->RemoveDefaultAttrs = $value;
}
/// \public
function createRootNode()
{
if ( !$this->Document )
{
$this->Document = new $this->DOMDocumentClass( '1.0', 'utf-8' );
}
// Creating root section with namespaces definitions
$mainSection = $this->Document->createElement( 'section' );
$this->Document->appendChild( $mainSection );
foreach( array( 'image', 'xhtml', 'custom' ) as $prefix )
{
$mainSection->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:' . $prefix, $this->Namespaces[$prefix] );
}
return $this->Document;
}
/*!
\public
Call this function to process your input
*/
function process( $text, $createRootNode = true )
{
$text = str_replace( "\r", '', $text);
$text = str_replace( "\t", ' ', $text);
// replace unicode chars that will break the XML validity
// see http://www.w3.org/TR/REC-xml/#charsets
$text = preg_replace( '/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $text, -1, $count );
if ( $count > 0 )
{
$this->Messages[] = ezpI18n::tr(
'kernel/classes/datatypes/ezxmltext',
"%count invalid character(s) have been found and replaced by a space",
false,
array( '%count' => $count )
);
}
if ( !$this->ParseLineBreaks )
{
$text = str_replace( "\n", '', $text);
}
$this->Document = new $this->DOMDocumentClass( '1.0', 'utf-8' );
if ( $createRootNode )
{
$this->createRootNode();
}
// Perform pass 1
// Parsing the source string
$this->performPass1( $text );
//$this->Document->formatOutput = true;
$debug = eZDebugSetting::isConditionTrue( 'kernel-datatype-ezxmltext', eZDebug::LEVEL_DEBUG );
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(), eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext', 'XML after pass 1' ) );
}
if ( $this->QuitProcess )
{
return false;
}
// Perform pass 2
$this->performPass2();
//$this->Document->formatOutput = true;
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(), eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext', 'XML after pass 2' ) );
}
if ( $this->QuitProcess )
{
return false;
}
return $this->Document;
}
/*
\public
Pass 1: Parsing the source HTML string.
*/
function performPass1( &$data )
{
$ret = true;
$pos = 0;
if ( $this->Document->documentElement )
{
do
{
$this->parseTag( $data, $pos, $this->Document->documentElement );
if ( $this->QuitProcess )
{
$ret = false;
break;
}
}
while( $pos < strlen( $data ) );
}
else
{
$tmp = null;
$this->parseTag( $data, $pos, $tmp );
if ( $this->QuitProcess )
{
$ret = false;
}
}
return $ret;
}
// The main recursive function for pass 1
function parseTag( &$data, &$pos, &$parent )
{
// Find tag, determine it's type, name and attributes.
$initialPos = $pos;
if ( $pos >= strlen( $data ) )
{
return true;
}
$tagBeginPos = strpos( $data, '<', $pos );
if ( $this->ParseLineBreaks )
{
// Regard line break as a start tag position
$lineBreakPos = strpos( $data, "\n", $pos );
if ( $lineBreakPos !== false )
{
$tagBeginPos = $tagBeginPos === false ? $lineBreakPos : min( $tagBeginPos, $lineBreakPos );
}
}
$tagName = '';
$attributes = null;
// If it doesn't begin with '<' then its a text node.
if ( $tagBeginPos != $pos || $tagBeginPos === false )
{
$pos = $initialPos;
$tagName = $newTagName = '#text';
$noChildren = true;
if ( !$tagBeginPos )
{
$tagBeginPos = strlen( $data );
}
$textContent = substr( $data, $pos, $tagBeginPos - $pos );
$textContent = $this->washText( $textContent );
$pos = $tagBeginPos;
if ( $textContent === '' )
{
return false;
}
}
// Process closing tag.
elseif ( $data[$tagBeginPos] == '<' && $tagBeginPos + 1 < strlen( $data ) &&
$data[$tagBeginPos + 1] == '/' )
{
$tagEndPos = strpos( $data, '>', $tagBeginPos + 1 );
if ( $tagEndPos === false )
{
$pos = $tagBeginPos + 1;
$this->handleError( self::ERROR_SYNTAX, ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', 'Wrong closing tag' ) );
return false;
}
$pos = $tagEndPos + 1;
$closedTagName = strtolower( trim( substr( $data, $tagBeginPos + 2, $tagEndPos - $tagBeginPos - 2 ) ) );
// Find matching tag in ParentStack array
$firstLoop = true;
for( $i = count( $this->ParentStack ) - 1; $i >= 0; $i-- )
{
$parentNames = $this->ParentStack[$i];
if ( $parentNames[0] == $closedTagName )
{
array_pop( $this->ParentStack );
if ( !$firstLoop )
{
$pos = $tagBeginPos;
return true;
}
// If newTagName was '' we don't break children loop
elseif ( $parentNames[1] !== '' )
{
return true;
}
else
{
return false;
}
}
$firstLoop = false;
}
$this->handleError( self::ERROR_SYNTAX, ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', 'Wrong closing tag : </%1>.', false, array( $closedTagName ) ) );
return false;
}
// Insert <br/> instead of linebreaks
elseif ( $this->ParseLineBreaks && $data[$tagBeginPos] == "\n" )
{
$newTagName = 'br';
$noChildren = true;
$pos = $tagBeginPos + 1;
}
// Regular tag: get tag's name and attributes.
else
{
$tagEndPos = $this->findEndOpeningTagPosition( $data, $tagBeginPos );
if ( $tagEndPos === false )
{
$pos = $tagBeginPos + 1;
$this->handleError( self::ERROR_SYNTAX, ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', 'Wrong opening tag' ) );
return false;
}
$pos = $tagEndPos + 1;
$tagString = substr( $data, $tagBeginPos + 1, $tagEndPos - $tagBeginPos - 1 );
// Check for final backslash
$noChildren = substr( $tagString, -1, 1 ) == '/' ? true : false;
// Remove final backslash and spaces
$tagString = preg_replace( "/\s*\/$/", "", $tagString );
$firstSpacePos = strpos( $tagString, ' ' );
if ( $firstSpacePos === false )
{
$tagName = strtolower( trim( $tagString ) );
$attributeString = '';
}
else
{
$tagName = strtolower( substr( $tagString, 0, $firstSpacePos ) );
$attributeString = substr( $tagString, $firstSpacePos + 1 );
$attributeString = trim( $attributeString );
// Parse attribute string
if ( $attributeString )
{
$attributes = $this->parseAttributes( $attributeString );
}
}
// Determine tag's name
if ( isset( $this->InputTags[$tagName] ) )
{
$thisInputTag = $this->InputTags[$tagName];
if ( isset( $thisInputTag['name'] ) )
{
$newTagName = $thisInputTag['name'];
}
else
{
$newTagName = $this->callInputHandler( 'nameHandler', $tagName, $attributes );
}
}
else
{
if ( $this->XMLSchema->exists( $tagName ) )
{
$newTagName = $tagName;
}
else
{
$this->handleError( self::ERROR_SYNTAX, ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', 'Unknown tag: <%1>.', false, array( $tagName ) ) );
return false;
}
}
// Check 'noChildren' property
if ( isset( $thisInputTag['noChildren'] ) )
{
$noChildren = true;
}
$thisOutputTag = isset( $this->OutputTags[$newTagName] ) ? $this->OutputTags[$newTagName] : null;
// Implementation of 'autoCloseOn' rule ( Handling of unclosed tags, ex.: <p>, <li> )
if ( isset( $thisOutputTag['autoCloseOn'] ) &&
$parent &&
$parent->parentNode instanceof DOMElement &&
in_array( $parent->nodeName, $thisOutputTag['autoCloseOn'] ) )
{
// Wrong nesting: auto-close parent and try to re-parse this tag at higher level
array_pop( $this->ParentStack );
$pos = $tagBeginPos;
return true;
}
// Append to parent stack
if ( !$noChildren && $newTagName !== false )
{
$this->ParentStack[] = array( $tagName, $newTagName, $attributeString );
}
if ( !$newTagName )
{
// If $newTagName is an empty string then it's not a error
if ( $newTagName === false )
$this->handleError( self::ERROR_SYNTAX, ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Can't convert tag's name: <%1>.", false, array( $tagName ) ) );
return false;
}
// wordmatch.ini support
if ( $attributeString )
{
$attributes = $this->wordMatchSupport( $newTagName, $attributes, $attributeString );
}
}
// Create text or normal node.
if ( $newTagName == '#text' )
{
$element = $this->Document->createTextNode( $textContent );
}
else
{
$element = $this->Document->createElement( $newTagName );
}
if ( $attributes )
{
$this->setAttributes( $element, $attributes );
}
// Append element as a child or set it as root if there is no parent.
if ( $parent )
{
$parent->appendChild( $element );
}
else
{
$this->Document->appendChild( $element );
}
$params = array();
$params[] =& $data;
$params[] =& $pos;
$params[] =& $tagBeginPos;
$result = $this->callOutputHandler( 'parsingHandler', $element, $params );
if ( $result === false )
{
// This tag is already parsed in handler
if ( !$noChildren )
{
array_pop( $this->ParentStack );
}
return false;
}
if ( $this->QuitProcess )
{
return false;
}
// Process children
if ( !$noChildren )
{
do
{
$parseResult = $this->parseTag( $data, $pos, $element );
if ( $this->QuitProcess )
{
return false;
}
}
while( $parseResult !== true );
}
return false;
}
/*
Helper functions for pass 1
*/
/**
* Finds the postion of the > character which marks the end of the opening
* tag that starts at $tagBeginPos in $data.
* It's not as easy as it seems, because some '>' can also appear in attributes.
* So we need to iterate over the next '>' characters to find the correct one.
* See https://jira.ez.no/browse/EZP-26096
*
* @param string $data
* @param integer $tagBeginPos
* @param integer $offset used for recursive call when a > is found in an attribute.
* @return integer|false
*/
private function findEndOpeningTagPosition( $data, $tagBeginPos, $offset = 0 )
{
$endPos = strpos( $data, '>', $tagBeginPos + $offset );
if ( $endPos === false )
{
return false;
}
$tagCode = substr( $data, $tagBeginPos, $endPos - $tagBeginPos );
if ( strpos( $tagCode, '=' ) === false )
{
// this tag has no attribute, so the next '>' is the right one.
return $endPos;
}
if ( $this->isValidXmlTag( $tagCode ) )
{
return $endPos;
}
return $this->findEndOpeningTagPosition( $data, $tagBeginPos, $endPos - $tagBeginPos + 1 );
}
/**
* Checks whether $code can be considered as a valid XML excerpt. If not,
* it's probably because we found a '>' in the middle of an attribute.
*
* @param string $code
* @return boolean
*/
private function isValidXmlTag( $code )
{
if ( $code[strlen( $code ) - 1] !== '/' )
{
$code .= '/';
}
$code .= '>';
$code = '<' . str_replace(
array( '<', '&' ),
array( '<', '&' ),
substr( $code, 1 )
);
$errorHanding = libxml_use_internal_errors( true );
$simpleXml = simplexml_load_string( $code );
libxml_use_internal_errors( $errorHanding );
return ( $simpleXml !== false );
}
function parseAttributes( $attributeString )
{
$attributes = array();
// Valid characters for XML attributes
// @see http://www.w3.org/TR/xml/#NT-Name
$nameStartChar = ':A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x{2FF}\\x{370}-\\x{37D}\\x{37F}-\\x{1FFF}\\x{200C}-\\x{200D}\\x{2070}-\\x{218F}\\x{2C00}-\\x{2FEF}\\x{3001}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFFD}\\x{10000}-\\x{EFFFF}';
if (
preg_match_all(
"/\s+([$nameStartChar][$nameStartChar\-.0-9\\xB7\\x{0300}-\\x{036F}\\x{203F}-\\x{2040}]*)\s*=\s*(?:(?:\"([^\"]+?)\")|(?:'([^']+?)')|(?: *([^\"'\s]+)))/u",
" " . $attributeString,
$attributeArray,
PREG_SET_ORDER
)
) {
foreach ( $attributeArray as $attribute )
{
// Value will always be at the last position
$value = trim( array_pop( $attribute ) );
// Value of '0' is valid ( eg. border='0' )
if ( $value !== '' && $value !== false && $value !== null )
{
$attributes[$attribute[1]] = $value;
}
}
}
return $attributes;
}
function setAttributes( $element, $attributes )
{
$thisOutputTag = $this->OutputTags[$element->nodeName];
foreach( $attributes as $key => $value )
{
// Convert attribute names
if ( isset( $thisOutputTag['attributes'] ) &&
isset( $thisOutputTag['attributes'][$key] ) )
{
$qualifiedName = $thisOutputTag['attributes'][$key];
}
else
{
$qualifiedName = $key;
}
// Filter classes
if ( $qualifiedName == 'class' )
{
$classesList = $this->XMLSchema->getClassesList( $element->nodeName );
if ( !in_array( $value, $classesList ) )
{
$this->handleError( self::ERROR_DATA,
ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Class '%1' is not allowed for element <%2> (check content.ini).",
false, array( $value, $element->nodeName ) ) );
continue;
}
}
// Create attribute nodes
if ( $qualifiedName )
{
if ( strpos( $qualifiedName, ':' ) )
{
list( $prefix, $name ) = explode( ':', $qualifiedName );
if ( isset( $this->Namespaces[$prefix] ) )
{
$URI = $this->Namespaces[$prefix];
$element->setAttributeNS( $URI, $qualifiedName, htmlspecialchars_decode( $value ) );
}
else
{
eZDebug::writeWarning( "No namespace defined for prefix '$prefix'.", 'eZXML input parser' );
}
}
else
{
$element->setAttribute( $qualifiedName, htmlspecialchars_decode( $value ) );
}
}
}
// Check for required attrs are present
if ( isset( $this->OutputTags[$element->nodeName]['requiredInputAttributes'] ) )
{
foreach( $this->OutputTags[$element->nodeName]['requiredInputAttributes'] as $reqAttrName )
{
$presented = false;
foreach( $attributes as $key => $value )
{
if ( $key == $reqAttrName )
{
$presented = true;
break;
}
}
if ( !$presented )
{
$this->handleError( self::ERROR_SCHEMA,
ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Required attribute '%1' is not presented in tag <%2>.",
false, array( $reqAttrName, $element->nodeName ) ) );
}
}
}
}
function washText( $textContent )
{
$textContent = $this->entitiesDecode( $textContent );
if ( !$this->AllowNumericEntities )
{
$textContent = $this->convertNumericEntities( $textContent );
}
if ( !$this->AllowMultipleSpaces )
{
$textContent = preg_replace( "/ {2,}/", " ", $textContent );
}
return $textContent;
}
function entitiesDecode( $text )
{
$text = str_replace( ''', "'", $text );
$text = str_replace( '>', '>', $text );
$text = str_replace( '<', '<', $text );
$text = str_replace( ''', "'", $text );
$text = str_replace( '"', '"', $text );
$text = str_replace( '&', '&', $text );
return $text;
}
function convertNumericEntities( $text )
{
if ( strlen( $text ) < 4 )
{
return $text;
}
// Convert other HTML entities to the current charset characters.
$codec = eZTextCodec::instance( 'unicode', false );
$pos = 0;
$domString = "";
while ( $pos < strlen( $text ) - 1 )
{
$startPos = $pos;
while( !( $text[$pos] == '&' && isset($text[$pos + 1]) && $text[$pos + 1] == '#' ) && $pos < strlen( $text ) - 1 )
{
$pos++;
}
$domString .= substr( $text, $startPos, $pos - $startPos );
if ( $pos < strlen( $text ) - 1 )
{
$endPos = strpos( $text, ';', $pos + 2 );
if ( $endPos === false )
{
$pos += 2;
continue;
}
$code = substr( $text, $pos + 2, $endPos - ( $pos + 2 ) );
$char = $codec->convertString( array( $code ) );
$pos = $endPos + 1;
$domString .= $char;
}
else
{
$domString .= substr( $text, $pos, 2 );
}
}
return $domString;
}
/*!
Returns modified attributes parameter
*/
protected function wordMatchSupport( $newTagName, $attributes, $attributeString )
{
$ini = eZINI::instance( 'wordmatch.ini' );
if ( $ini->hasVariable( $newTagName, 'MatchString' ) )
{
$matchArray = $ini->variable( $newTagName, 'MatchString' );
if ( $matchArray )
{
foreach ( array_keys( $matchArray ) as $key )
{
$matchString = $matchArray[$key];
if ( preg_match( "/$matchString/i", $attributeString ) )
{
$attributes['class'] = $key;
unset( $attributes['style'] );
}
}
}
}
return $attributes;
}
/*!
\public
Pass 2: Process the tree, run handlers, rebuild and validate.
*/
function performPass2()
{
$tmp = null;
$this->processSubtree( $this->Document->documentElement, $tmp );
}
// main recursive function for pass 2
function processSubtree( $element, &$lastHandlerResult )
{
$ret = null;
$tmp = null;
// Call "Init handler"
$this->callOutputHandler( 'initHandler', $element, $tmp );
$debug = eZDebugSetting::isConditionTrue( 'kernel-datatype-ezxmltext', eZDebug::LEVEL_DEBUG );
// Process children
if ( $element->hasChildNodes() )
{
// Make another copy of children to save primary structure
$childNodes = $element->childNodes;
$childrenCount = $childNodes->length;
// we can not loop directly over the childNodes property, because this will change while we are working on it's parent's children
$children = array();
foreach ( $childNodes as $childNode )
{
$children[] = $childNode;
}
$lastResult = null;
$newElements = array();
foreach ( $children as $child )
{
if ( $debug )
{
eZDebug::writeDebug( 'processing children, current child: ' . $child->nodeName, eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext', __METHOD__ ) );
}
$childReturn = $this->processSubtree( $child, $lastResult );
unset( $lastResult );
if ( isset( $childReturn['result'] ) )
{
if ( $debug )
{
eZDebug::writeDebug( 'return result is set for child ' . $child->nodeName, eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext', __METHOD__ ) );
}
$lastResult = $childReturn['result'];
}
if ( isset( $childReturn['new_elements'] ) )
{
$newElements = array_merge( $newElements, $childReturn['new_elements'] );
}
if ( $this->QuitProcess )
{
return $ret;
}
}
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML before processNewElements for element ' . $element->nodeName ) );
}
// process elements created in children handlers
$this->processNewElements( $newElements );
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML after processNewElements for element ' . $element->nodeName ) );
}
}
// Call "Structure handler"
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML before callOutputHandler structHandler for element ' . $element->nodeName ) );
}
$ret = $this->callOutputHandler( 'structHandler', $element, $lastHandlerResult );
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML after callOutputHandler structHandler for element ' . $element->nodeName ) );
eZDebug::writeDebug( $ret,
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'return value of callOutputHandler structHandler for element ' . $element->nodeName ) );
}
// Process by schema (check if element is allowed to exist)
if ( !$this->processBySchemaPresence( $element ) )
{
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML after failed processBySchemaPresence for element ' . $element->nodeName ) );
}
return $ret;
}
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML after processBySchemaPresence for element ' . $element->nodeName ) );
}
// Process by schema (check place in the tree)
if ( !$this->processBySchemaTree( $element ) )
{
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML after failed processBySchemaTree for element ' . $element->nodeName ) );
}
return $ret;
}
if ( $debug )
{
eZDebug::writeDebug( $this->Document->saveXML(),
eZDebugSetting::changeLabel( 'kernel-datatype-ezxmltext',
'XML after processBySchemaTree for element ' . $element->nodeName ) );
}
$tmp = null;
// Call "Publish handler"
$this->callOutputHandler( 'publishHandler', $element, $tmp );
// Process attributes according to the schema
if ( $element->hasAttributes() )