summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 2e1ab66e644775faad5b0bcbc231bb5fbd1e0e95 (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->{error}=0 unless defined $feed->{error};
  76. $feed->{tags}=[];
  77. while (@_) {
  78. my $key=shift;
  79. my $value=shift;
  80. if ($key eq 'tag') {
  81. push @{$feed->{tags}}, $value;
  82. }
  83. }
  84. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  85. ($feed->{error} ? "<em>" : "").$feed->{message}.
  86. ($feed->{error} ? "</em>" : "").
  87. " (".$feed->{numposts}." posts".
  88. ($feed->{newposts} ? "; ".$feed->{newposts}." new" : "").
  89. ")";
  90. } # }}}
  91. sub delete (@) { #{{{
  92. my @files=@_;
  93. # Remove feed data for removed pages.
  94. foreach my $file (@files) {
  95. my $page=pagename($file);
  96. remove_feeds($page);
  97. }
  98. } #}}}
  99. sub loadstate () { #{{{
  100. if (-e "$config{wikistatedir}/aggregate") {
  101. open (IN, "$config{wikistatedir}/aggregate" ||
  102. die "$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, ">$config{wikistatedir}/aggregate" ||
  134. die "$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 $config{rebuild} ||
  173. time - $feed->{lastupdate} >= $feed->{updateinterval};
  174. $feed->{lastupdate}=time;
  175. $feed->{newposts}=0;
  176. $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
  177. 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. $feed->{error}=1;
  183. debug($feed->{message});
  184. next;
  185. }
  186. $feed->{feedurl}=pop @urls;
  187. }
  188. my $f=eval{XML::Feed->parse(URI->new($feed->{feedurl}))};
  189. if ($@) {
  190. $feed->{message}="feed crashed XML::Feed! $@";
  191. $feed->{error}=1;
  192. debug($feed->{message});
  193. next;
  194. }
  195. if (! $f) {
  196. $feed->{message}=XML::Feed->errstr;
  197. $feed->{error}=1;
  198. debug($feed->{message});
  199. next;
  200. }
  201. foreach my $entry ($f->entries) {
  202. add_page(
  203. feed => $feed,
  204. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  205. link => $entry->link,
  206. content => $entry->content->body,
  207. guid => defined $entry->id ? $entry->id : time."_".$feed->name,
  208. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  209. );
  210. }
  211. $feed->{message}="processed ok at ".
  212. displaytime($feed->{lastupdate});
  213. $feed->{error}=0;
  214. }
  215. # TODO: expiry
  216. } #}}}
  217. sub add_page (@) { #{{{
  218. my %params=@_;
  219. my $feed=$params{feed};
  220. my $guid={};
  221. my $mtime;
  222. if (exists $guids{$params{guid}}) {
  223. # updating an existing post
  224. $guid=$guids{$params{guid}};
  225. }
  226. else {
  227. # new post
  228. $guid->{guid}=$params{guid};
  229. $guids{$params{guid}}=$guid;
  230. $mtime=$params{ctime};
  231. $feed->{numposts}++;
  232. $feed->{newposts}++;
  233. # assign it an unused page
  234. my $page=IkiWiki::titlepage($params{title});
  235. # escape slashes and periods in title so it doesn't specify
  236. # directory name or trigger ".." disallowing code.
  237. $page=~s!([/.])!"__".ord($1)."__"!eg;
  238. $page=$feed->{dir}."/".$page;
  239. ($page)=$page=~/$config{wiki_file_regexp}/;
  240. if (! defined $page || ! length $page) {
  241. $page=$feed->{dir}."/item";
  242. }
  243. my $c="";
  244. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  245. -e pagefile($page.$c)) {
  246. $c++
  247. }
  248. $guid->{page}=$page;
  249. debug("creating new page $page");
  250. }
  251. $guid->{feed}=$feed->{name};
  252. # To write or not to write? Need to avoid writing unchanged pages
  253. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  254. # trusted; let's use a digest.
  255. eval q{use Digest::MD5 'md5_hex'};
  256. require Encode;
  257. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  258. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  259. $guid->{md5}=$digest;
  260. # Create the page.
  261. my $template=template("aggregatepost.tmpl", blind_cache => 1);
  262. $template->param(title => $params{title})
  263. if defined $params{title} && length($params{title});
  264. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  265. $template->param(name => $feed->{name});
  266. $template->param(url => $feed->{url});
  267. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  268. if defined $params{link};
  269. if (ref $feed->{tags}) {
  270. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  271. }
  272. writefile(htmlpage($guid->{page}), $config{srcdir},
  273. $template->output);
  274. # Set the mtime, this lets the build process get the right creation
  275. # time on record for the new page.
  276. utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
  277. } #}}}
  278. sub htmlescape ($) { #{{{
  279. # escape accidental wikilinks and preprocessor stuff
  280. my $html=shift;
  281. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  282. return $html;
  283. } #}}}
  284. sub urlabs ($$) { #{{{
  285. my $url=shift;
  286. my $urlbase=shift;
  287. URI->new_abs($url, $urlbase)->as_string;
  288. } #}}}
  289. sub htmlabs ($$) { #{{{
  290. # Convert links in html from relative to absolute.
  291. # Note that this is a heuristic, which is not specified by the rss
  292. # spec and may not be right for all feeds. Also, see Debian
  293. # bug #381359.
  294. my $html=shift;
  295. my $urlbase=shift;
  296. my $ret="";
  297. my $p = HTML::Parser->new(api_version => 3);
  298. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  299. $p->handler(start => sub {
  300. my ($tagname, $pos, $text) = @_;
  301. if (ref $HTML::Tagset::linkElements{$tagname}) {
  302. while (4 <= @$pos) {
  303. # use attribute sets from right to left
  304. # to avoid invalidating the offsets
  305. # when replacing the values
  306. my($k_offset, $k_len, $v_offset, $v_len) =
  307. splice(@$pos, -4);
  308. my $attrname = lc(substr($text, $k_offset, $k_len));
  309. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  310. next unless $v_offset; # 0 v_offset means no value
  311. my $v = substr($text, $v_offset, $v_len);
  312. $v =~ s/^([\'\"])(.*)\1$/$2/;
  313. my $new_v=urlabs($v, $urlbase);
  314. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  315. substr($text, $v_offset, $v_len) = qq("$new_v");
  316. }
  317. }
  318. $ret.=$text;
  319. }, "tagname, tokenpos, text");
  320. $p->parse($html);
  321. $p->eof;
  322. return $ret;
  323. } #}}}
  324. sub remove_feeds () { #{{{
  325. my $page=shift;
  326. my %removed;
  327. foreach my $id (keys %feeds) {
  328. if ($feeds{$id}->{sourcepage} eq $page) {
  329. $feeds{$id}->{remove}=1;
  330. $removed{$id}=1;
  331. }
  332. }
  333. } #}}}
  334. sub pagefile ($) { #{{{
  335. my $page=shift;
  336. return "$config{srcdir}/".htmlpage($page);
  337. } #}}}
  338. 1