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