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