forked from mugoweb/eep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eepHelpers.php
executable file
·751 lines (685 loc) · 26.8 KB
/
eepHelpers.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
<?php
/*
EEP is a command line tool to support developers using ezpublish
Copyright © 2012 Mugo Web
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
*/
class eep
{
const NOATTRIBUTE = 0;
const REVRELATED = true;
const FORRELATED = false;
static function printTable( $table, $description="" )
{
// calc column widths
$widths = array();
foreach( $table as $r => $row )
{
foreach( $row as $column => $part )
{
// trim the value - suppress the warning if looking at an object
$table[ $r ][ $column ] = @trim( $part );
// and calc the widths - continue to suppress warnings
if( !isset( $widths[$column] ) )
{
$widths[ $column ] = @strlen( $part );
}
elseif( $widths[ $column ] < @strlen( $part ) )
{
$widths[ $column ] = @strlen( $part );
}
}
}
// build the horizontal line
$horParts = array();
foreach( $widths as $width )
{
$horParts[] = str_repeat( "-", $width );
}
$horLine = " +-" . implode( "-+-", $horParts ) . "-+\n";
// do the output
$doneTitles = false;
echo "\n" . $horLine;
$pipe = " I "; // only write pipes on data lines
if( $description )
{
echo $pipe.str_pad( $description, strlen($horLine)-strlen($doneTitles)-6, " ", STR_PAD_RIGHT )." | \n";
echo $horLine;
$pipe = " | ";
}
$pipe = " I "; // only write pipes on data lines
foreach( $table as $row )
{
$align = ""; // two column tables have the second column aligned left
foreach( $row as $column => $part )
{
if( 2==count($row) && 1==$column ) $align = "-";
echo $pipe. sprintf( "% ".$align.$widths[$column]."s", $part);
$pipe = " | ";
}
echo " | \n";
if( !$doneTitles )
{
echo $horLine;
$doneTitles = true;
}
}
echo $horLine;
}
//--------------------------------------------------------------------------
// given an XML string, extract parameters
// depends on attributes:
// required
// validation
// used to validate XML inputs to complex operations
//static function extractParameters( $xml ) no longer used
/*
{
$params = array();
libxml_use_internal_errors( true );
$simpleXML = simplexml_load_string( $xml );
//var_dump( $simpleXML );
if( false === $simpleXML )
{
$errMsg = "Failed to parse the XML\n";
foreach( libxml_get_errors() as $error )
{
$errMsg .= "\t" . $error->message;
throw new Exception( $errMsg );
}
}
foreach( $simpleXML as $index => $element )
{
$value = trim( (string )$element );
if( "nullable" == $element->attributes()->required )
{
if( "null" == $value )
$value = null;
}
elseif( "required" == $element->attributes()->required )
{
if( "" == $value )
throw new Exception( "'" . $index . "' is required in input XML" );
}
$validationType = $element->attributes()->validation;
if( $validationType )
{
$errorMessage = eep::attemptValidationOnParameter( $value, $validationType );
if( $errorMessage )
throw new Exception( "There is a problem with: '" . $index . "': " . $errorMessage );
}
if( $value == "additional_for_specific_datatype" )
{
// currently ignoring this
continue;
}
$params[ $index ] = $value;
}
return $params;
}
*/
//--------------------------------------------------------------------------
// helper for extractParameters()
// simply makes a check on the provided value against a rule associated with
// the validationtype and returns a message if there is a problem
//function attemptValidationOnParameter( $value, $validationType ) no longer used
/*
{
switch( $validationType )
{
default:
echo "There is currently no code for validating: '" . $validationType . "'\n";
break;
case "none":
break;
case "bit":
if( !in_array( $value, array( "0", "1" ) ) )
return "Value should be '0' or '1'";
break;
case "identifier":
$cleaned = preg_replace( "/[^a-z0-9_]/", "", $value );
if( $cleaned != $value )
return "Invalid identifier. Instead of '" .$value. "' use '" .$cleaned. "'";
break;
case "language":
if( !in_array( $value, AttributeFunctions::$someLanguages ) )
return "'" .$value. "' is not a valid language";
break;
}
// signal that there are no problems
return "";
}
*/
//--------------------------------------------------------------------------
static function getListOfAliases()
{
$aliases = array
(
// module shortcuts
"at" => "attribute"
, "cc" => "contentclass"
, "co" => "contentobject"
, "cn" => "contentnode"
, "kb" => "knowledgebase"
, "ccg" => "contentclassgroup"
// method shortcuts
, "ats" => "attributes"
, "ccs" => "contentclasses"
, "cos" => "contentobjects"
, "cns" => "contentnodes"
, "coid" => "contentobjectid"
);
return $aliases;
}
//--------------------------------------------------------------------------
static function expandAliases( $alias )
{
$aliases = eep::getListOfAliases();
if( isset( $aliases[$alias] ))
{
return $aliases[$alias];
}
else
{
return $alias;
}
}
//--------------------------------------------------------------------------
/*
* Fetch the number of (reverse) related objects
*
* @param int $attributeID
* This parameter only makes sense if $params[AllRelations] is unset,
* set to false, or matches eZContentObject::RELATION_ATTRIBUTE
* Possible values:
* - 0 or false:
* Count relations made with any attribute
* - >0
* Count relations made with attribute $attributeID
* @param int|false $reverseRelatedObjects
* Wether to count related objects (false) or reverse related
* objects (false)
* @param array|false $params
* Various params, as an associative array.
* Possible values:
* - AllRelations (bool|int)
* true: count ALL relations, object and attribute level
* false: only count object level relations
* other: bit mask of eZContentObject::RELATION_* constants
* - IgnoreVisibility (bool)
* If true, 'hidden' status will be ignored
*
* @return int The number of (reverse) related objects for the object
*/
// note that this is ripped from ... /kernel/classes/ezcontentobject.php ... relatedObjectCount()
static function fastRelatedObjectCount( $objectId, $objectVersion, $attributeID=0, $reverseRelatedObjects=false, $params=false )
{
$db = eZDB::instance();
$showInvisibleNodesCond = '';
// process params (only IgnoreVisibility currently supported):
if ( is_array( $params ) )
{
if ( isset( $params['IgnoreVisibility'] ) )
{
$showInvisibleNodesCond = eZContentObject::createFilterByVisibilitySQLString( $params['IgnoreVisibility'] );
}
}
$relationTypeMasking = '';
$relationTypeMask = isset( $params['AllRelations'] ) ? $params['AllRelations'] : ( $attributeID === false );
if ( $attributeID && ( $relationTypeMask === false || $relationTypeMask === eZContentObject::RELATION_ATTRIBUTE ) )
{
$attributeID =(int) $attributeID;
$relationTypeMasking .= " AND contentclassattribute_id=$attributeID ";
$relationTypeMask = eZContentObject::RELATION_ATTRIBUTE;
}
elseif ( is_bool( $relationTypeMask ) )
{
$relationTypeMask = eZContentObject::relationTypeMask( $relationTypeMask );
}
if ( $db->databaseName() == 'oracle' )
{
$relationTypeMasking .= " AND bitand( relation_type, $relationTypeMask ) <> 0 ";
}
else
{
$relationTypeMasking .= " AND ( relation_type & $relationTypeMask ) <> 0 ";
}
if ( $reverseRelatedObjects )
{
if ( is_array( $objectId ) )
{
if ( count( $objectId ) > 0 )
{
$objectIDSQL = ' AND ' . $db->generateSQLINStatement( $objectId, 'ezcontentobject_link.to_contentobject_id', false, false, 'int' ) . ' AND
ezcontentobject_link.from_contentobject_version=ezcontentobject.current_version';
}
else
{
$objectIDSQL = '';
}
}
else
{
$objectId = (int) $objectId;
$objectIDSQL = ' AND ezcontentobject_link.to_contentobject_id = ' . $objectId . ' AND
ezcontentobject_link.from_contentobject_version=ezcontentobject.current_version';
}
$select = " count( DISTINCT ezcontentobject.id ) AS count";
}
else
{
$select = " count( ezcontentobject_link.from_contentobject_id ) as count ";
$objectIDSQL = " AND ezcontentobject_link.from_contentobject_id='$objectId'
AND ezcontentobject_link.from_contentobject_version='$objectVersion'";
}
// from the following query, this is the excerpted where condition; it causes
// a BC break in 4.7 and does not seem to do anything ...
// AND ezcontentobject_link.op_code='0'
$query = "SELECT $select
FROM
ezcontentobject, ezcontentobject_link
WHERE
ezcontentobject.id=ezcontentobject_link.from_contentobject_id AND
ezcontentobject.status=" . eZContentObject::STATUS_PUBLISHED . "
$objectIDSQL
$relationTypeMasking
$showInvisibleNodesCond";
$rows = $db->arrayQuery( $query );
return $rows[0]['count'];
}
//--------------------------------------------------------------------------
// eep::displayNodeList( $list, $title )
static function displayNodeList( $list, $title )
{
$results[] = array
(
"Object"
, "Node"
, "Class"
, "Path"
, "Ch'n"
, "Cont"
, "H/I"
, "RO"
, "RRO"
, "P"
, "Name"
);
foreach( $list as $objectNode )
{
$obj = eZContentObject::fetch($objectNode->ContentObjectID);
$results[] = array
(
$objectNode->ContentObjectID
, $objectNode->NodeID
, $objectNode->ClassIdentifier
, $objectNode->PathString
, $objectNode->childrenCount( false )
, $objectNode->classIsContainer()
, $objectNode->IsHidden ."/". $objectNode->IsInvisible
, eep::fastRelatedObjectCount( $objectNode->ContentObjectID, $objectNode->ContentObjectVersion, eep::NOATTRIBUTE, eep::FORRELATED, array( "IgnoreVisibility"=>true, "AllRelations"=>true) )
, eep::fastRelatedObjectCount( $objectNode->ContentObjectID, $objectNode->ContentObjectVersion, eep::NOATTRIBUTE, eep::REVRELATED, array( "IgnoreVisibility"=>true, "AllRelations"=>true) )
, $objectNode->Priority
, (strlen($objectNode->Name)>20)?substr($objectNode->Name,0,17)."...":$objectNode->Name
);
}
eep::printTable( $results, $title );
}
//--------------------------------------------------------------------------
// a non-object is the array of data that you get when you fetch an object
// but say that you don't actually want the object
static function displayNonObjectList( $list, $title )
{
$results = array();
$results[] = array
(
"Object"
, "Sid"
, "V"
, "Remote Id"
, "Name"
);
foreach( $list as $lightObject )
{
$results[] = array
(
$lightObject[ "id" ]
, $lightObject[ "section_id" ]
, $lightObject[ "current_version" ]
, $lightObject[ "remote_id" ]
, (strlen($lightObject[ "name" ])>60)?substr($lightObject[ "name" ],0,57)."...":$lightObject[ "name" ]
);
}
eep::printTable( $results, $title );
}
//--------------------------------------------------------------------------
static function displayObjectList( $list, $title )
{
$results = array();
$results[] = array
(
"Id"
, "NId"
, "SId"
, "V"
, "Remote Id"
, "Class Id"
, "Name"
);
foreach( $list as $n => $object )
{
$results[] = array
(
$object->ID
, $object->mainNodeID()
, $object->SectionID
, $object->CurrentVersion
, $object->RemoteID
, $object->contentClassIdentifier()
, (strlen($object->Name)>60)?substr($object->Name,0,57)."...":$object->Name
);
//unset($object);
//unset( $list[$n] );
//unset( $GLOBALS[ 'eZContentObjectContentObjectCache' ] );
//unset( $GLOBALS[ 'eZContentObjectDataMapCache' ] );
//unset( $GLOBALS[ 'eZContentObjectVersionCache' ] );
}
eep::printTable( $results, $title );
}
//--------------------------------------------------------------------------
// returns key value pairs based on any params to the command line that
// match: --key=value
static function extractAdditionalParams( &$args )
{
$additionalParams = array();
$regex = "/^--([a-zA-Z0-9\-_\[\]]+)=(.*)/";
foreach( $args as $key => $arg )
{
if( preg_match( $regex, $arg, $matches ) )
{
$additionalParams[ $matches[1] ] = $matches[2];
// since this is an 'additional' parameter, remove it from the
// argv list so as to prevent it from being interpreted as a
// regular parameter
unset( $args[$key] );
}
}
return $additionalParams;
}
//--------------------------------------------------------------------------
static function addTask( $taskType, $task, $priority=500 )
{
$priority = (integer )$priority;
if( 0 == $priority ) return false;
$db = eZDB::instance();
// delete any previous instances of this task - this is a performance
// killer
// todo, decide if it is worth exposing a switch for this
/*
$query = "DELETE FROM onix_cron_daemon";
$query .= " WHERE ocd_task='" . $task . "'";
$result = $db->query( $query );
//*/
$task = $db->escapeString( $task );
$taskType = $db->escapeString( $taskType );
$query = "INSERT into onix_cron_daemon";
$query .= " SET ocd_priority=" . $priority;
$query .= " , ocd_task='" . $task . "'";
$query .= " , ocd_tasktype='" . $taskType . "'";
$query .= " , ocd_posteddate='" . date("Y-m-d H:i:s") . "'";
$result = $db->query( $query );
if( false === $result )
{
throw new Exception( "Failed to ad task to cron daemon queue");
}
}
//--------------------------------------------------------------------------
// this protects against accidentally operating on an object with no main
// node, ie, an object that is in the trash
// eep::republishObject( $objectId )
static function republishObject( $objectId )
{
$object = eZContentObject::fetch( $objectId );
if( $object->attribute( 'main_node' ) )
{
$objVersion = $object->currentVersion();
$publish = eZOperationHandler::execute( "content", "publish",
array(
"object_id" => $objectId
, "version" => $objVersion->attribute( "version" )
)
);
}
}
//--------------------------------------------------------------------------
// this is just for testing
static function convertStringToRot13( $str )
{
$str = str_rot13( $str );
return $str;
}
//--------------------------------------------------------------------------
// time is in a colon-separated format hh:mm:ss
// returns the number of seconds
static function convertTimeToInteger( $time )
{
$timeParts = explode( ":", $time );
$integer = ($timeParts[0] * 60*60) + ($timeParts[1] * 60) + $timeParts[2];
if( 0 == strlen( $integer ) )
{
// make sure that we return an integer
$integer = 0;
}
return $integer;
}
//--------------------------------------------------------------------------
static function convertTrim( $str )
{
$str = trim( $str );
return $str;
}
//--------------------------------------------------------------------------
static function dateToTS( $str )
{
$str = strtotime( $str );
return $str;
}
//--------------------------------------------------------------------------
// this cleans many common forms of XML corruption, and ultimately forces
// character encoding - this can render some remaining characters as
// question marks, but many of those can be fixed too
static function fixXML( $xml )
{
$verbose = false;
if( $verbose )
{
echo "\nBEFORE eep::fix()\n";
echo $xml;
echo "\n\n";
}
// hack to deal with escaped CDATA markers
$xml = str_replace( array( "<![CDATA[", "]]>" ), array( "<![CDATA[", "]]>" ), $xml );
// strip the CDATA tags
$xml = str_replace( array( "<![CDATA[", "]]>" ), array( "", "" ), $xml );
// fix double escaped ampersands
$xml = str_replace( "&amp;", "&", $xml );
// fix double escaped carats
$xml = str_replace( "&lt;", "<", $xml );
$xml = str_replace( "&gt;", ">", $xml );
// fix double escaped decimal entities
$xml = preg_replace( "/&#([\d]{2,5});/", "&#$1;", $xml );
// fix double escaped hex entities
$xml = preg_replace( "/&#x([0-9a-fA-F]{2,5});/", "&#x$1;", $xml );
// fix double escaped decimal entities with missing semi-colon -- eg &#146
$xml = preg_replace( "/&#([\d]{2,5})/", "&#$1;", $xml );
// fix double escaped hex entities with missing semi-colon
$xml = preg_replace( "/&#x([0-9a-fA-F]{2,5})/", "&#x$1;", $xml );
// this shows up in NSP data which is important to us
$xml = str_replace( "compact type=\"disc\"", "", $xml );
// fix unterminated linebreaks
$xml = str_replace( "<br>", "<br/>", $xml );
$xml = str_replace( "<BR>", "<br/>", $xml );
// fix paras that have extra space between them - which ez puffs into an extra, empty para
$xml = preg_replace( "/<\/p>[\s]+<p>/", "</p><p>", $xml );
// crazy fancy characters:
$xml = str_replace( "’", "’", $xml );
$xml = str_replace( "•", "•", $xml );
// note: this doesn't account for zero-filled hex instances, eg, !
$replacementRules = array
(
array
( // elipsis
"new" => "..."
, "targets" => array( "…", "&hellip;", "…", chr(133), "…" )
)
, array
( // ndash
"new" => "–"
, "targets" => array( "–", "&ndash;", "–", chr(150), "–", "–" ) /* , "–", "ÔÇô" */
)
, array
( // left single quote
"new" => "‘"
, "targets" => array( "‘", "&lsquo;", "‘", chr(145), "‘" )
)
, array
( // right single quote
"new" => "’"
, "targets" => array( "’", "&rsquo;", "’", chr(146), "’" ) /* , "’" */
)
, array
( // right double quote
"new" => "”"
, "targets" => array( "”", "&rdquo;", "”", chr(148), "”", "“" )
)
, array
( // left double quote
"new" => "“"
, "targets" => array( "“", "&ldquo;", "“", chr(147), "“", "”" )
)
, array
( // mdash
"new" => "—"
, "targets" => array( "—", "&mdash;", "—", chr(151), "—", "—" )
)
, array
( // é
"new" => "é"
, "targets" => array( "é" )
)
, array
( // ö
"new" => "ƪ"
, "targets" => array( "ö" )
)
);
foreach( $replacementRules as $rule )
{
$xml = str_replace( $rule["targets"], $rule["new"], $xml );
}
// and the ultimate: make damn sure that it's UTF8: this harshly trashes
// unusual characters BUT it does convert standard usable characters,
// eg, e ague, into a viable format ALSO, take care to not double encode
// stuff
if( "UTF-8" != mb_detect_encoding( $xml, "UTF-8") )
{
$xml = utf8_encode( $xml );
}
$aDOMDocument = new DOMDocument();
if( $aDOMDocument->loadXML( $xml ) )
{
// pretty sure that we have data that we can work with
}
else
{
// ok, just force it
$xml = utf8_encode( $xml );
}
if( $verbose )
{
echo "\nAFTER eep::fix()\n";
echo $xml;
echo "\n\n";
}
return $xml;
}
//--------------------------------------------------------------------------
// this is how you fix the bad question marks that have been introduced by
// forcing the encoding to utf8 -- fix some of the crappy question-mark
// replacements -- fix the ones that almost certainly mistakes and signs of
// corruption; count the number of replacements made, and if it seems that
// there is some question-mark-corruption going on do the fixes to the
// amibiuous cases
public static function fixBadQuestionMarks( $xml )
{
$count = 0;
$corruptionLevel = 0;
// <character>?s
$xml = preg_replace( "/([a-zA-Z0-9])\?s/", "$1's", $xml, -1, $count );
$corruptionLevel += $count;
// <digit>?<digit>
$xml = preg_replace( "/([\d]+)\?([\d]+)/", "$1–$2", $xml, -1, $count );
$corruptionLevel += $count;
// opening (left) double quote
$xml = preg_replace( "/\>[\?]([^ ])/", ">“$1", $xml, -1, $count );
$corruptionLevel += $count;
$xml = preg_replace( "/[ ][\?]([^ ])/", " “$1", $xml, -1, $count );
$corruptionLevel += $count;
// mdash between spaces
$xml = preg_replace( "/[ ][\?][ ]/", " — ", $xml, -1, $count );
$corruptionLevel += $count;
// closing double quote -- although these might be real question marks ...
if( 4 < $corruptionLevel )
{
$xml = preg_replace( "/([^ ])[\?]\</", "$1”<", $xml, -1, $count );
$xml = preg_replace( "/([^ ])[\?] /", "$1” ", $xml, -1, $count );
}
if( 6 < $corruptionLevel )
{
// mdash between characters -- this might be anything, but almost for sure its not a question mark
$xml = preg_replace( "/([a-zA-Z0-9])[\?]([a-zA-Z0-9])/", "$1—$2", $xml, -1, $count );
}
return $xml;
}
//------------------------------------------------------------------------------
// kind of a multipurpose thing; mainly write an XML tag along with the desired data:
// <tag>blah blah blah</tag>
// by setting $data to null, can also write just an open or close tag:
// <tag>
// the benefit is that that it makes the output homogeneous to call and supports indenting
function writeXMLTag( $indent, $tag, $data )
{
$padding = str_pad( "", $indent );
$data = eep::escapeForXML( $data );
if( strstr( $data, "?xml version=\"1.0\"" ) )
{
$data = preg_replace( "/\s\s+/", " ", $data );
}
echo $padding . "<" . $tag . ">" . trim( $data );
if( null === $data )
{
echo "\n";
}
else
{
echo "</" . $tag . ">\n";
}
}
//------------------------------------------------------------------------------
// Make a string safe for embedding in XML, mostly used for escaping XML so
// that it can be carried in some other XML structure. Can be run on any string,
// doesn't have to originally be XML.
function escapeForXML( $str )
{
// don't accidentally convert a null to a string -- because we care
if( null === $str) return null;
// remove all entities
$str = html_entity_decode( $str );
// do ampersands first, so as to not escape the lt's
$str = str_replace( "&", "&", $str );
$str = str_replace( "<", "<", $str );
return $str;
}
}
?>