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