Fix mixing and matching of RSS and Atom
[catagits/XML-Feed.git] / lib / XML / Feed.pm
1 # $Id: Feed.pm 1958 2006-08-14 05:31:27Z btrott $
2
3 package XML::Feed;
4 use strict;
5
6 use base qw( Class::ErrorHandler );
7 use Feed::Find;
8 use URI::Fetch;
9 use LWP::UserAgent;
10 use Carp;
11
12 our $VERSION = '0.22';
13
14 sub new {
15     my $class = shift;
16     my $format = shift || 'Atom';
17     my $format_class = 'XML::Feed::' . $format;
18     eval "use $format_class";
19     Carp::croak("Unsupported format $format: $@") if $@;
20     my $feed = bless {}, join('::', __PACKAGE__, $format);
21     $feed->init_empty(@_) or return $class->error($feed->errstr);
22     $feed;
23 }
24
25 sub init_empty { 1 }
26
27 sub parse {
28     my $class = shift;
29     my($stream, $specified_format) = @_;
30     return $class->error("Stream parameter is required") unless $stream;
31     my $feed = bless {}, $class;
32     my $xml = '';
33     if (UNIVERSAL::isa($stream, 'URI')) {
34         my $ua  = LWP::UserAgent->new;
35         $ua->env_proxy; # force allowing of proxies
36         my $res = URI::Fetch->fetch($stream, UserAgent => $ua)
37             or return $class->error(URI::Fetch->errstr);
38         return $class->error("This feed has been permanently removed")
39             if $res->status == URI::Fetch::URI_GONE();
40         $xml = $res->content;
41     } elsif (ref($stream) eq 'SCALAR') {
42         $xml = $$stream;
43     } elsif (ref($stream)) {
44         while (read($stream, my($chunk), 8192)) {
45             $xml .= $chunk;
46         }
47     } else {
48         open my $fh, $stream
49             or return $class->error("Can't open $stream: $!");
50         while (read $fh, my($chunk), 8192) {
51             $xml .= $chunk;
52         }
53         close $fh;
54     }
55     return $class->error("Can't get feed XML content from $stream")
56         unless $xml;
57     my $format;
58     if ($specified_format) {
59         $format = $specified_format;
60     } else {
61         $format = $feed->identify_format(\$xml) or return $class->error($feed->errstr);
62     }
63
64     my $format_class = join '::', __PACKAGE__, $format;
65     eval "use $format_class";
66     return $class->error("Unsupported format $format: $@") if $@;
67     bless $feed, $format_class;
68     $feed->init_string(\$xml) or return $class->error($feed->errstr);
69     $feed;
70 }
71
72 sub identify_format {
73     my $feed = shift;
74     my($xml) = @_;
75     ## Auto-detect feed type based on first element. This is prone
76     ## to breakage, but then again we don't want to parse the whole
77     ## feed ourselves.
78     my $tag;
79     while ($$xml =~ /<(\S+)/sg) {
80         (my $t = $1) =~ tr/a-zA-Z0-9:\-\?!//cd;
81         my $first = substr $t, 0, 1;
82         $tag = $t, last unless $first eq '?' || $first eq '!';
83     }
84     return $feed->error("Cannot find first element") unless $tag;
85     $tag =~ s/^.*://;
86     if ($tag eq 'rss' || $tag eq 'RDF') {
87         return 'RSS';
88     } elsif ($tag eq 'feed') {
89         return 'Atom';
90     } else {
91         return $feed->error("Cannot detect feed type");
92     }
93 }
94
95 sub find_feeds {
96     my $class = shift;
97     my($uri) = @_;
98     my @feeds = Feed::Find->find($uri)
99         or return $class->error(Feed::Find->errstr);
100     @feeds;
101 }
102
103 sub convert {
104     my $feed = shift;
105     my($format) = @_;
106     my $new = __PACKAGE__->new($format);
107     for my $field (qw( title link description language author copyright modified generator )) {
108         my $val = $feed->$field();
109         next unless defined $val;
110         $new->$field($val);
111     }
112     for my $entry ($feed->entries) {
113         $new->add_entry($entry->convert($format));
114     }
115     $new;
116 }
117
118 sub splice {
119     my $feed = shift;
120     my($other) = @_;
121     my %ids = map { $_->id => 1 } $feed->entries;
122     for my $entry ($other->entries) {
123         $feed->add_entry($entry) unless $ids{$entry->id}++;
124     }
125 }
126
127 sub _convert_entry {
128     my $feed   = shift;
129     my $entry  = shift;
130     my $feed_format  = ref($feed);   $feed_format  =~ s!^XML::Feed::!!;
131     my $entry_format = ref($entry);  $entry_format =~ s!^XML::Feed::Entry::!!;
132     return $entry if $entry_format eq $feed_format;
133     return $entry->convert($feed_format); 
134 }
135
136 sub format;
137 sub title;
138 sub link;
139 sub self_link;
140 sub description;
141 sub language;
142 sub author;
143 sub copyright;
144 sub modified;
145 sub generator;
146 sub add_entry;
147 sub entries;
148 sub as_xml;
149 sub id;
150
151 sub tagline { shift->description(@_) }
152 sub items   { $_[0]->entries     }
153
154 1;
155 __END__
156
157 =head1 NAME
158
159 XML::Feed - Syndication feed parser and auto-discovery
160
161 =head1 SYNOPSIS
162
163     use XML::Feed;
164     my $feed = XML::Feed->parse(URI->new('http://example.com/atom.xml'))
165         or die XML::Feed->errstr;
166     print $feed->title, "\n";
167     for my $entry ($feed->entries) {
168     }
169
170     ## Find all of the syndication feeds on a given page, using
171     ## auto-discovery.
172     my @feeds = XML::Feed->find_feeds('http://example.com/');
173
174 =head1 DESCRIPTION
175
176 I<XML::Feed> is a syndication feed parser for both RSS and Atom feeds. It
177 also implements feed auto-discovery for finding feeds, given a URI.
178
179 I<XML::Feed> supports the following syndication feed formats:
180
181 =over 4
182
183 =item * RSS 0.91
184
185 =item * RSS 1.0
186
187 =item * RSS 2.0
188
189 =item * Atom
190
191 =back
192
193 The goal of I<XML::Feed> is to provide a unified API for parsing and using
194 the various syndication formats. The different flavors of RSS and Atom
195 handle data in different ways: date handling; summaries and content;
196 escaping and quoting; etc. This module attempts to remove those differences
197 by providing a wrapper around the formats and the classes implementing
198 those formats (I<XML::RSS> and I<XML::Atom::Feed>). For example, dates are
199 handled differently in each of the above formats. To provide a unified API for
200 date handling, I<XML::Feed> converts all date formats transparently into
201 I<DateTime> objects, which it then returns to the caller.
202
203 =head1 USAGE
204
205 =head2 XML::Feed->new($format)
206
207 Creates a new empty I<XML::Feed> object using the format I<$format>.
208
209     $feed = XML::Feed->new('Atom');
210     $feed = XML::Feed->new('RSS');
211     $feed = XML::Feed->new('RSS', version => '0.91');
212
213 =head2 XML::Feed->parse($stream)
214
215 =head2 XML::Feed->parse($stream, $format)
216
217 Parses a syndication feed identified by I<$stream>. I<$stream> can be any
218 one of the following:
219
220 =over 4
221
222 =item * Scalar reference
223
224 A reference to string containing the XML body of the feed.
225
226 =item * Filehandle
227
228 An open filehandle from which the feed XML will be read.
229
230 =item * File name
231
232 The name of a file containing the feed XML.
233
234 =item * URI object
235
236 A URI from which the feed XML will be retrieved.
237
238 =back
239
240 C<$format> allows you to override format guessing.
241
242 =head2 XML::Feed->find_feeds($uri)
243
244 Given a URI I<$uri>, use auto-discovery to find all of the feeds linked
245 from that page (using I<E<lt>linkE<gt>> tags).
246
247 Returns a list of feed URIs.
248
249 =head2 $feed->convert($format)
250
251 Converts the I<XML::Feed> object into the I<$format> format, and returns
252 the new object.
253
254 =head2 $feed->splice($other_feed)
255
256 Splices in all of the entries from the feed I<$other_feed> into I<$feed>,
257 skipping posts that are already in I<$feed>.
258
259 =head2 $feed->format
260
261 Returns the format of the feed (C<Atom>, or some version of C<RSS>).
262
263 =head2 $feed->title([ $title ])
264
265 The title of the feed/channel.
266
267 =head2 $feed->link([ $uri ])
268
269 The permalink of the feed/channel.
270
271 =head2 $feed->tagline([ $tagline ])
272
273 The description or tagline of the feed/channel.
274
275 =head2 $feed->description([ $description ])
276
277 Alias for I<$feed-E<gt>tagline>.
278
279 =head2 $feed->author([ $author ])
280
281 The author of the feed/channel.
282
283 =head2 $feed->language([ $language ])
284
285 The language of the feed.
286
287 =head2 $feed->copyright([ $copyright ])
288
289 The copyright notice of the feed.
290
291 =head2 $feed->modified([ $modified ])
292
293 A I<DateTime> object representing the last-modified date of the feed.
294
295 If present, I<$modified> should be a I<DateTime> object.
296
297 =head2 $feed->generator([ $generator ])
298
299 The generator of the feed.
300
301 =head2 $feed->self_link ([ $uri ])
302
303 The Atom Self-link of the feed:
304
305 L<http://validator.w3.org/feed/docs/warning/MissingAtomSelfLink.html>
306
307 A string.
308
309 =head2 $feed->entries
310
311 A list of the entries/items in the feed. Returns an array containing
312 I<XML::Feed::Entry> objects.
313
314 =head2 $feed->add_entry($entry)
315
316 Adds an entry to the feed. I<$entry> should be an I<XML::Feed::Entry>
317 object in the correct format for the feed.
318
319 =head2 $feed->as_xml
320
321 Returns an XML representation of the feed, in the format determined by
322 the current format of the I<$feed> object.
323
324 =head1 PACKAGE VARIABLES
325
326 =over 4
327
328 =item C<$XML::Feed::RSS::PREFERRED_PARSER>
329
330 If you want to use another RSS parser class than XML::RSS (default), you can
331 change the class by setting C<$PREFERRED_PARSER> variable in XML::Feed::RSS
332 package.
333
334     $XML::Feed::RSS::PREFERRED_PARSER = "XML::RSS::LibXML";
335
336 B<Note:> this will only work for parsing feeds, not creating feeds.
337
338 =back
339
340 =head1 LICENSE
341
342 I<XML::Feed> is free software; you may redistribute it and/or modify it
343 under the same terms as Perl itself.
344
345 =head1 AUTHOR & COPYRIGHT
346
347 Except where otherwise noted, I<XML::Feed> is Copyright 2004-2008
348 Six Apart, cpan@sixapart.com. All rights reserved.
349
350 =head1 SUBVERSION 
351
352 The latest version of I<XML::Feed> can be found at
353
354     http://code.sixapart.com/svn/XML-Feed/trunk/
355
356 =cut