summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 2295691aa85cfd672a11e05b73e397519dc55622 (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. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  293. if (defined $max && length(htmlfn($page)) >= $max) {
  294. $c="";
  295. $page=$feed->{dir}."/item";
  296. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  297. -e pagefile($page.$c)) {
  298. $c++
  299. }
  300. }
  301. $guid->{page}=$page;
  302. debug(sprintf(gettext("creating new page %s"), $page));
  303. }
  304. $guid->{feed}=$feed->{name};
  305. # To write or not to write? Need to avoid writing unchanged pages
  306. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  307. # trusted; let's use a digest.
  308. eval q{use Digest::MD5 'md5_hex'};
  309. error($@) if $@;
  310. require Encode;
  311. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  312. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  313. $guid->{md5}=$digest;
  314. # Create the page.
  315. my $template=template("aggregatepost.tmpl", blind_cache => 1);
  316. $template->param(title => $params{title})
  317. if defined $params{title} && length($params{title});
  318. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  319. $template->param(name => $feed->{name});
  320. $template->param(url => $feed->{url});
  321. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  322. if defined $params{link};
  323. if (ref $feed->{tags}) {
  324. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  325. }
  326. writefile(htmlfn($guid->{page}), $config{srcdir},
  327. $template->output);
  328. # Set the mtime, this lets the build process get the right creation
  329. # time on record for the new page.
  330. utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
  331. } #}}}
  332. sub htmlescape ($) { #{{{
  333. # escape accidental wikilinks and preprocessor stuff
  334. my $html=shift;
  335. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  336. return $html;
  337. } #}}}
  338. sub urlabs ($$) { #{{{
  339. my $url=shift;
  340. my $urlbase=shift;
  341. URI->new_abs($url, $urlbase)->as_string;
  342. } #}}}
  343. sub htmlabs ($$) { #{{{
  344. # Convert links in html from relative to absolute.
  345. # Note that this is a heuristic, which is not specified by the rss
  346. # spec and may not be right for all feeds. Also, see Debian
  347. # bug #381359.
  348. my $html=shift;
  349. my $urlbase=shift;
  350. my $ret="";
  351. my $p = HTML::Parser->new(api_version => 3);
  352. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  353. $p->handler(start => sub {
  354. my ($tagname, $pos, $text) = @_;
  355. if (ref $HTML::Tagset::linkElements{$tagname}) {
  356. while (4 <= @$pos) {
  357. # use attribute sets from right to left
  358. # to avoid invalidating the offsets
  359. # when replacing the values
  360. my($k_offset, $k_len, $v_offset, $v_len) =
  361. splice(@$pos, -4);
  362. my $attrname = lc(substr($text, $k_offset, $k_len));
  363. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  364. next unless $v_offset; # 0 v_offset means no value
  365. my $v = substr($text, $v_offset, $v_len);
  366. $v =~ s/^([\'\"])(.*)\1$/$2/;
  367. my $new_v=urlabs($v, $urlbase);
  368. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  369. substr($text, $v_offset, $v_len) = qq("$new_v");
  370. }
  371. }
  372. $ret.=$text;
  373. }, "tagname, tokenpos, text");
  374. $p->parse($html);
  375. $p->eof;
  376. return $ret;
  377. } #}}}
  378. sub remove_feeds () { #{{{
  379. my $page=shift;
  380. my %removed;
  381. foreach my $id (keys %feeds) {
  382. if ($feeds{$id}->{sourcepage} eq $page) {
  383. $feeds{$id}->{remove}=1;
  384. $removed{$id}=1;
  385. }
  386. }
  387. } #}}}
  388. sub pagefile ($) { #{{{
  389. my $page=shift;
  390. return "$config{srcdir}/".htmlfn($page);
  391. } #}}}
  392. sub htmlfn ($) { #{{{
  393. return shift().".html";
  394. } #}}}
  395. 1