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