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