3 package XML::Atom::Content;
5 use base qw( XML::Atom::Base );
7 __PACKAGE__->mk_attr_accessors(qw( type mode ));
8 __PACKAGE__->mk_xml_attr_accessors(qw( lang base ));
12 use MIME::Base64 qw( encode_base64 decode_base64 );
14 sub element_name { 'content' }
18 my %param = @_ == 1 ? (Body => $_[0]) : @_;
19 $content->SUPER::init(%param);
21 $content->body($param{Body});
24 $content->type($param{Type});
31 my $elem = $content->elem;
35 $elem->removeChildNodes;
37 $elem->removeChild($_) for $elem->getChildNodes;
39 if (!_is_printable($data)) {
40 Encode::_utf8_off($data);
42 $elem->appendChild(XML::LibXML::Text->new(encode_base64($data, '')));
44 $elem->appendChild(XML::XPath::Node::Text->new(encode_base64($data, '')));
47 if ($content->version == 0.3) {
48 $content->mode('base64');
51 my $copy = '<div xmlns="http://www.w3.org/1999/xhtml">' .
57 my $parser = XML::LibXML->new;
58 my $tree = $parser->parse_string($copy);
59 $node = $tree->getDocumentElement;
61 my $xp = XML::XPath->new(xml => $copy);
62 $node = (($xp->find('/')->get_nodelist)[0]->getChildNodes)[0]
67 $elem->appendChild($node);
68 if ($content->version == 0.3) {
69 $content->mode('xml');
71 $content->type('xhtml');
75 $elem->appendChild(XML::LibXML::Text->new($data));
77 $elem->appendChild(XML::XPath::Node::Text->new($data));
80 if ($content->version == 0.3) {
81 $content->mode('escaped');
83 $content->type($data =~ /^\s*</ ? 'html' : 'text');
88 unless (exists $content->{__body}) {
91 if ($content->version == 0.3) {
92 $mode = $content->mode || 'xml';
95 $content->type eq 'xhtml' ? 'xml'
96 : $content->type =~ m![/\+]xml$! ? 'xml'
97 : $content->type eq 'html' ? 'escaped'
98 : $content->type eq 'text' ? 'escaped'
99 : $content->type =~ m!^text/! ? 'escaped'
103 if ($mode eq 'xml') {
104 my @children = grep ref($_) =~ /Element/,
105 LIBXML ? $elem->childNodes : $elem->getChildNodes;
107 if (@children == 1 && $children[0]->getLocalName eq 'div') {
109 LIBXML ? $children[0]->childNodes :
110 $children[0]->getChildNodes
112 $content->{__body} = '';
113 for my $n (@children) {
114 $content->{__body} .= $n->toString(LIBXML ? 1 : 0);
117 $content->{__body} = LIBXML ? $elem->textContent : $elem->string_value;
120 Encode::_utf8_off($content->{__body}) unless $XML::Atom::ForceUnicode;
122 } elsif ($mode eq 'base64') {
123 my $raw = decode_base64(LIBXML ? $elem->textContent : $elem->string_value);
124 if ($content->type && $content->type =~ m!^text/!) {
125 $content->{__body} = eval { Encode::decode("utf-8", $raw) } || $raw;
126 Encode::_utf8_off($content->{__body}) unless $XML::Atom::ForceUnicode;
128 $content->{__body} = $raw;
130 } elsif ($mode eq 'escaped') {
131 $content->{__body} = LIBXML ? $elem->textContent : $elem->string_value;
133 $content->{__body} = undef;
144 # try decoding this $data with UTF-8
146 ( Encode::is_utf8($data)
148 : eval { Encode::decode("utf-8", $data, Encode::FB_CROAK) } );
150 return ! $@ && $decoded =~ /^\p{IsPrint}*$/;