summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: d0d7f421798d9dba9ada5107f6e2b58fd517b674 (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 at ".
  211. IkiWiki::displaytime($feed->{lastupdate});
  212. }
  213. # TODO: expiry
  214. } #}}}
  215. sub add_page (@) { #{{{
  216. my %params=@_;
  217. my $feed=$params{feed};
  218. my $guid={};
  219. my $mtime;
  220. if (exists $guids{$params{guid}}) {
  221. # updating an existing post
  222. $guid=$guids{$params{guid}};
  223. }
  224. else {
  225. # new post
  226. $guid->{guid}=$params{guid};
  227. $guids{$params{guid}}=$guid;
  228. $mtime=$params{ctime};
  229. $feed->{numposts}++;
  230. $feed->{newposts}++;
  231. # assign it an unused page
  232. my $page=IkiWiki::titlepage($params{title});
  233. # escape slashes and periods in title so it doesn't specify
  234. # directory name or trigger ".." disallowing code.
  235. $page=~s!([/.])!"__".ord($1)."__"!eg;
  236. $page=$feed->{dir}."/".$page;
  237. ($page)=$page=~/$IkiWiki::config{wiki_file_regexp}/;
  238. if (! defined $page || ! length $page) {
  239. $page=$feed->{dir}."/item";
  240. }
  241. my $c="";
  242. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  243. -e pagefile($page.$c)) {
  244. $c++
  245. }
  246. $guid->{page}=$page;
  247. IkiWiki::debug("creating new page $page");
  248. }
  249. $guid->{feed}=$feed->{name};
  250. # To write or not to write? Need to avoid writing unchanged pages
  251. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  252. # trusted; let's use a digest.
  253. eval q{use Digest::MD5 'md5_hex'};
  254. require Encode;
  255. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  256. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $IkiWiki::config{rebuild};
  257. $guid->{md5}=$digest;
  258. # Create the page.
  259. my $template=IkiWiki::template("aggregatepost.tmpl", blind_cache => 1);
  260. $template->param(title => $params{title})
  261. if defined $params{title} && length($params{title});
  262. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  263. $template->param(name => $feed->{name});
  264. $template->param(url => $feed->{url});
  265. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  266. if defined $params{link};
  267. if (ref $feed->{tags}) {
  268. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  269. }
  270. IkiWiki::writefile(IkiWiki::htmlpage($guid->{page}), $IkiWiki::config{srcdir},
  271. $template->output);
  272. # Set the mtime, this lets the build process get the right creation
  273. # time on record for the new page.
  274. utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
  275. } #}}}
  276. sub htmlescape ($) { #{{{
  277. # escape accidental wikilinks and preprocessor stuff
  278. my $html=shift;
  279. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  280. return $html;
  281. } #}}}
  282. sub urlabs ($$) { #{{{
  283. my $url=shift;
  284. my $urlbase=shift;
  285. URI->new_abs($url, $urlbase)->as_string;
  286. } #}}}
  287. sub htmlabs ($$) { #{{{
  288. # Convert links in html from relative to absolute.
  289. # Note that this is a heuristic, which is not specified by the rss
  290. # spec and may not be right for all feeds. Also, see Debian
  291. # bug #381359.
  292. my $html=shift;
  293. my $urlbase=shift;
  294. my $ret="";
  295. my $p = HTML::Parser->new(api_version => 3);
  296. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  297. $p->handler(start => sub {
  298. my ($tagname, $pos, $text) = @_;
  299. if (ref $HTML::Tagset::linkElements{$tagname}) {
  300. while (4 <= @$pos) {
  301. # use attribute sets from right to left
  302. # to avoid invalidating the offsets
  303. # when replacing the values
  304. my($k_offset, $k_len, $v_offset, $v_len) =
  305. splice(@$pos, -4);
  306. my $attrname = lc(substr($text, $k_offset, $k_len));
  307. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  308. next unless $v_offset; # 0 v_offset means no value
  309. my $v = substr($text, $v_offset, $v_len);
  310. $v =~ s/^([\'\"])(.*)\1$/$2/;
  311. my $new_v=urlabs($v, $urlbase);
  312. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  313. substr($text, $v_offset, $v_len) = qq("$new_v");
  314. }
  315. }
  316. $ret.=$text;
  317. }, "tagname, tokenpos, text");
  318. $p->parse($html);
  319. $p->eof;
  320. return $ret;
  321. } #}}}
  322. sub remove_feeds () { #{{{
  323. my $page=shift;
  324. my %removed;
  325. foreach my $id (keys %feeds) {
  326. if ($feeds{$id}->{sourcepage} eq $page) {
  327. $feeds{$id}->{remove}=1;
  328. $removed{$id}=1;
  329. }
  330. }
  331. } #}}}
  332. sub pagefile ($) { #{{{
  333. my $page=shift;
  334. return "$IkiWiki::config{srcdir}/".IkiWiki::htmlpage($page);
  335. } #}}}
  336. 1