summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 7c4ab3d106b87bf5cc4ce834bad15e7aaba7c7e1 (plain)
  1. #!/usr/bin/perl
  2. # Blog aggregation plugin.
  3. package IkiWiki::Plugin::aggregate;
  4. use warnings;
  5. use strict;
  6. use IkiWiki;
  7. use HTML::Entities;
  8. use HTML::Parser;
  9. use HTML::Tagset;
  10. use URI;
  11. my %feeds;
  12. my %guids;
  13. sub import { #{{{
  14. IkiWiki::hook(type => "getopt", id => "aggregate",
  15. call => \&getopt);
  16. IkiWiki::hook(type => "checkconfig", id => "aggregate",
  17. call => \&checkconfig);
  18. IkiWiki::hook(type => "filter", id => "aggregate",
  19. call => \&filter);
  20. IkiWiki::hook(type => "preprocess", id => "aggregate",
  21. call => \&preprocess);
  22. IkiWiki::hook(type => "delete", id => "aggregate",
  23. call => \&delete);
  24. IkiWiki::hook(type => "savestate", id => "aggregate",
  25. call => \&savestate);
  26. } # }}}
  27. sub getopt () { #{{{
  28. eval q{use Getopt::Long};
  29. Getopt::Long::Configure('pass_through');
  30. GetOptions("aggregate" => \$IkiWiki::config{aggregate});
  31. } #}}}
  32. sub checkconfig () { #{{{
  33. loadstate();
  34. if ($IkiWiki::config{aggregate}) {
  35. IkiWiki::loadindex();
  36. aggregate();
  37. savestate();
  38. }
  39. } #}}}
  40. sub filter (@) { #{{{
  41. my %params=@_;
  42. my $page=$params{page};
  43. # Mark all feeds originating on this page as removable;
  44. # preprocess will unmark those that still exist.
  45. remove_feeds($page);
  46. return $params{content};
  47. } # }}}
  48. sub preprocess (@) { #{{{
  49. my %params=@_;
  50. foreach my $required (qw{name url}) {
  51. if (! exists $params{$required}) {
  52. return "[[aggregate plugin missing $required parameter]]";
  53. }
  54. }
  55. my $feed={};
  56. my $name=$params{name};
  57. if (exists $feeds{$name}) {
  58. $feed=$feeds{$name};
  59. }
  60. else {
  61. $feeds{$name}=$feed;
  62. }
  63. $feed->{name}=$name;
  64. $feed->{sourcepage}=$params{page};
  65. $feed->{url}=$params{url};
  66. my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
  67. $dir=~s/^\/+//;
  68. ($dir)=$dir=~/$IkiWiki::config{wiki_file_regexp}/;
  69. $feed->{dir}=$dir;
  70. $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
  71. $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
  72. $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
  73. $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
  74. delete $feed->{remove};
  75. $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
  76. $feed->{numposts}=0 unless defined $feed->{numposts};
  77. $feed->{newposts}=0 unless defined $feed->{newposts};
  78. $feed->{message}="new feed" unless defined $feed->{message};
  79. $feed->{tags}=[];
  80. while (@_) {
  81. my $key=shift;
  82. my $value=shift;
  83. if ($key eq 'tag') {
  84. push @{$feed->{tags}}, $value;
  85. }
  86. }
  87. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  88. "<i>".$feed->{message}."</i> (".$feed->{numposts}.
  89. " stored posts; ".$feed->{newposts}." new)<br />";
  90. } # }}}
  91. sub delete (@) { #{{{
  92. my @files=@_;
  93. # Remove feed data for removed pages.
  94. foreach my $file (@files) {
  95. my $page=IkiWiki::pagename($file);
  96. remove_feeds($page);
  97. }
  98. } #}}}
  99. sub loadstate () { #{{{
  100. if (-e "$IkiWiki::config{wikistatedir}/aggregate") {
  101. open (IN, "$IkiWiki::config{wikistatedir}/aggregate" ||
  102. die "$IkiWiki::config{wikistatedir}/aggregate: $!");
  103. while (<IN>) {
  104. $_=IkiWiki::possibly_foolish_untaint($_);
  105. chomp;
  106. my $data={};
  107. foreach my $i (split(/ /, $_)) {
  108. my ($field, $val)=split(/=/, $i, 2);
  109. if ($field eq "name" || $field eq "feed" ||
  110. $field eq "guid" || $field eq "message") {
  111. $data->{$field}=decode_entities($val, " \t\n");
  112. }
  113. elsif ($field eq "tag") {
  114. push @{$data->{tags}}, $val;
  115. }
  116. else {
  117. $data->{$field}=$val;
  118. }
  119. }
  120. if (exists $data->{name}) {
  121. $feeds{$data->{name}}=$data;
  122. }
  123. elsif (exists $data->{guid}) {
  124. $guids{$data->{guid}}=$data;
  125. }
  126. }
  127. close IN;
  128. }
  129. } #}}}
  130. sub savestate () { #{{{
  131. eval q{use HTML::Entities};
  132. die $@ if $@;
  133. open (OUT, ">$IkiWiki::config{wikistatedir}/aggregate" ||
  134. die "$IkiWiki::config{wikistatedir}/aggregate: $!");
  135. foreach my $data (values %feeds, values %guids) {
  136. if ($data->{remove}) {
  137. if ($data->{name}) {
  138. foreach my $guid (values %guids) {
  139. if ($guid->{feed} eq $data->{name}) {
  140. $guid->{remove}=1;
  141. }
  142. }
  143. }
  144. else {
  145. unlink pagefile($data->{page});
  146. }
  147. next;
  148. }
  149. my @line;
  150. foreach my $field (keys %$data) {
  151. if ($field eq "name" || $field eq "feed" ||
  152. $field eq "guid" || $field eq "message") {
  153. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  154. }
  155. elsif ($field eq "tags") {
  156. push @line, "tag=$_" foreach @{$data->{tags}};
  157. }
  158. else {
  159. push @line, "$field=".$data->{$field};
  160. }
  161. }
  162. print OUT join(" ", @line)."\n";
  163. }
  164. close OUT;
  165. } #}}}
  166. sub aggregate () { #{{{
  167. eval q{use XML::Feed};
  168. die $@ if $@;
  169. eval q{use HTML::Entities};
  170. die $@ if $@;
  171. foreach my $feed (values %feeds) {
  172. next unless $IkiWiki::config{rebuild} ||
  173. time - $feed->{lastupdate} >= $feed->{updateinterval};
  174. $feed->{lastupdate}=time;
  175. $feed->{newposts}=0;
  176. $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
  177. IkiWiki::debug("checking feed ".$feed->{name}." ...");
  178. if (! length $feed->{feedurl}) {
  179. my @urls=XML::Feed->find_feeds($feed->{url});
  180. if (! @urls) {
  181. $feed->{message}="could not find feed at ".$feed->{feedurl};
  182. IkiWiki::debug($feed->{message});
  183. next;
  184. }
  185. $feed->{feedurl}=pop @urls;
  186. }
  187. my $f=eval{XML::Feed->parse(URI->new($feed->{feedurl}))};
  188. if ($@) {
  189. $feed->{message}="feed crashed XML::Feed! $@";
  190. IkiWiki::debug($feed->{message});
  191. next;
  192. }
  193. if (! $f) {
  194. $feed->{message}=XML::Feed->errstr;
  195. IkiWiki::debug($feed->{message});
  196. next;
  197. }
  198. foreach my $entry ($f->entries) {
  199. add_page(
  200. feed => $feed,
  201. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  202. link => $entry->link,
  203. content => $entry->content->body,
  204. guid => defined $entry->id ? $entry->id : time."_".$feed->name,
  205. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  206. );
  207. }
  208. $feed->{message}="processed ok";
  209. }
  210. # TODO: expiry
  211. } #}}}
  212. sub add_page (@) { #{{{
  213. my %params=@_;
  214. my $feed=$params{feed};
  215. my $guid={};
  216. my $mtime;
  217. if (exists $guids{$params{guid}}) {
  218. # updating an existing post
  219. $guid=$guids{$params{guid}};
  220. }
  221. else {
  222. # new post
  223. $guid->{guid}=$params{guid};
  224. $guids{$params{guid}}=$guid;
  225. $mtime=$params{ctime};
  226. $feed->{numposts}++;
  227. $feed->{newposts}++;
  228. # assign it an unused page
  229. my $page=IkiWiki::titlepage($params{title});
  230. # escape slashes and periods in title so it doesn't specify
  231. # directory name or trigger ".." disallowing code.
  232. $page=~s!([/.])!"__".ord($1)."__"!eg;
  233. $page=$feed->{dir}."/".$page;
  234. $page=lc($page);
  235. ($page)=$page=~/$IkiWiki::config{wiki_file_regexp}/;
  236. if (! defined $page || ! length $page) {
  237. $page=$feed->{dir}."/item";
  238. }
  239. my $c="";
  240. while (exists $IkiWiki::pagesources{$page.$c} ||
  241. -e pagefile($page.$c)) {
  242. $c++
  243. }
  244. $guid->{page}=$page;
  245. IkiWiki::debug("creating new page $page");
  246. }
  247. $guid->{feed}=$feed->{name};
  248. # To write or not to write? Need to avoid writing unchanged pages
  249. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  250. # trusted; let's use a digest.
  251. eval q{use Digest::MD5 'md5_hex'};
  252. require Encode;
  253. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  254. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $IkiWiki::config{rebuild};
  255. $guid->{md5}=$digest;
  256. # Create the page.
  257. my $template=IkiWiki::template("aggregatepost.tmpl", blind_cache => 1);
  258. $template->param(title => $params{title})
  259. if defined $params{title} && length($params{title});
  260. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  261. $template->param(name => $feed->{name});
  262. $template->param(url => $feed->{url});
  263. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  264. if defined $params{link};
  265. if (ref $feed->{tags}) {
  266. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  267. }
  268. IkiWiki::writefile($guid->{page}.".html", $IkiWiki::config{srcdir},
  269. $template->output);
  270. # Set the mtime, this lets the build process get the right creation
  271. # time on record for the new page.
  272. utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
  273. } #}}}
  274. sub htmlescape ($) { #{{{
  275. # escape accidental wikilinks and preprocessor stuff
  276. my $html=shift;
  277. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  278. return $html;
  279. } #}}}
  280. sub urlabs ($$) { #{{{
  281. my $url=shift;
  282. my $urlbase=shift;
  283. URI->new_abs($url, $urlbase)->as_string;
  284. } #}}}
  285. sub htmlabs ($$) { #{{{
  286. # Convert links in html from relative to absolute.
  287. # Note that this is a heuristic, which is not specified by the rss
  288. # spec and may not be right for all feeds. Also, see Debian
  289. # bug #XXXX TODO: get bug.
  290. my $html=shift;
  291. my $urlbase=shift;
  292. my $ret="";
  293. my $p = HTML::Parser->new(api_version => 3);
  294. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  295. $p->handler(start => sub {
  296. my ($tagname, $pos, $text) = @_;
  297. if (ref $HTML::Tagset::linkElements{$tagname}) {
  298. while (4 <= @$pos) {
  299. # use attribute sets from right to left
  300. # to avoid invalidating the offsets
  301. # when replacing the values
  302. my($k_offset, $k_len, $v_offset, $v_len) =
  303. splice(@$pos, -4);
  304. my $attrname = lc(substr($text, $k_offset, $k_len));
  305. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  306. next unless $v_offset; # 0 v_offset means no value
  307. my $v = substr($text, $v_offset, $v_len);
  308. $v =~ s/^([\'\"])(.*)\1$/$2/;
  309. my $new_v=urlabs($v, $urlbase);
  310. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  311. substr($text, $v_offset, $v_len) = qq("$new_v");
  312. }
  313. }
  314. $ret.=$text;
  315. }, "tagname, tokenpos, text");
  316. $p->parse($html);
  317. $p->eof;
  318. return $ret;
  319. } #}}}
  320. sub remove_feeds () { #{{{
  321. my $page=shift;
  322. my %removed;
  323. foreach my $id (keys %feeds) {
  324. if ($feeds{$id}->{sourcepage} eq $page) {
  325. $feeds{$id}->{remove}=1;
  326. $removed{$id}=1;
  327. }
  328. }
  329. } #}}}
  330. sub pagefile ($) { #{{{
  331. my $page=shift;
  332. return "$IkiWiki::config{srcdir}/$page.html";
  333. } #}}}
  334. 1