summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: a6f8502368bd911558fceaf513d9d020fd0a365d (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 "[[".sprintf(gettext("aggregate plugin missing %s parameter"), $required)."]]";
  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}=gettext("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}." ".gettext("posts").
  92. ($feed->{newposts} ? "; ".$feed->{newposts}.
  93. " ".gettext("new") : "").
  94. ")";
  95. } # }}}
  96. sub delete (@) { #{{{
  97. my @files=@_;
  98. # Remove feed data for removed pages.
  99. foreach my $file (@files) {
  100. my $page=pagename($file);
  101. remove_feeds($page);
  102. }
  103. } #}}}
  104. sub loadstate () { #{{{
  105. if (-e "$config{wikistatedir}/aggregate") {
  106. open (IN, "$config{wikistatedir}/aggregate" ||
  107. die "$config{wikistatedir}/aggregate: $!");
  108. while (<IN>) {
  109. $_=IkiWiki::possibly_foolish_untaint($_);
  110. chomp;
  111. my $data={};
  112. foreach my $i (split(/ /, $_)) {
  113. my ($field, $val)=split(/=/, $i, 2);
  114. if ($field eq "name" || $field eq "feed" ||
  115. $field eq "guid" || $field eq "message") {
  116. $data->{$field}=decode_entities($val, " \t\n");
  117. }
  118. elsif ($field eq "tag") {
  119. push @{$data->{tags}}, $val;
  120. }
  121. else {
  122. $data->{$field}=$val;
  123. }
  124. }
  125. if (exists $data->{name}) {
  126. $feeds{$data->{name}}=$data;
  127. }
  128. elsif (exists $data->{guid}) {
  129. $guids{$data->{guid}}=$data;
  130. }
  131. }
  132. close IN;
  133. }
  134. } #}}}
  135. sub savestate () { #{{{
  136. eval q{use HTML::Entities};
  137. error($@) if $@;
  138. my $newfile="$config{wikistatedir}/aggregate.new";
  139. # TODO: This cleanup function could use improvement. Any newly
  140. # aggregated files are left behind unrecorded, and should be deleted.
  141. my $cleanup = sub { unlink($newfile) };
  142. open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
  143. foreach my $data (values %feeds, values %guids) {
  144. if ($data->{remove}) {
  145. if ($data->{name}) {
  146. foreach my $guid (values %guids) {
  147. if ($guid->{feed} eq $data->{name}) {
  148. $guid->{remove}=1;
  149. }
  150. }
  151. }
  152. else {
  153. unlink pagefile($data->{page});
  154. }
  155. next;
  156. }
  157. elsif ($data->{expired} && exists $data->{page}) {
  158. unlink pagefile($data->{page});
  159. delete $data->{page};
  160. delete $data->{md5};
  161. }
  162. my @line;
  163. foreach my $field (keys %$data) {
  164. if ($field eq "name" || $field eq "feed" ||
  165. $field eq "guid" || $field eq "message") {
  166. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  167. }
  168. elsif ($field eq "tags") {
  169. push @line, "tag=$_" foreach @{$data->{tags}};
  170. }
  171. else {
  172. push @line, "$field=".$data->{$field};
  173. }
  174. }
  175. print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
  176. }
  177. close OUT || error("save $newfile: $!", $cleanup);
  178. rename($newfile, "$config{wikistatedir}/aggregate") ||
  179. error("rename $newfile: $!", $cleanup);
  180. } #}}}
  181. sub expire () { #{{{
  182. foreach my $feed (values %feeds) {
  183. next unless $feed->{expireage} || $feed->{expirecount};
  184. my $count=0;
  185. foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
  186. grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
  187. values %guids) {
  188. if ($feed->{expireage}) {
  189. my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
  190. if ($days_old > $feed->{expireage}) {
  191. debug(sprintf(gettext("expiring %s (%s days old)"),
  192. $item->{page}, $days_old));
  193. $item->{expired}=1;
  194. }
  195. }
  196. elsif ($feed->{expirecount} &&
  197. $count >= $feed->{expirecount}) {
  198. debug(sprintf(gettext("expiring %s"), $item->{page}));
  199. $item->{expired}=1;
  200. }
  201. else {
  202. $count++;
  203. }
  204. }
  205. }
  206. } #}}}
  207. sub aggregate () { #{{{
  208. eval q{use XML::Feed};
  209. error($@) if $@;
  210. eval q{use HTML::Entities};
  211. error($@) if $@;
  212. foreach my $feed (values %feeds) {
  213. next unless $config{rebuild} ||
  214. time - $feed->{lastupdate} >= $feed->{updateinterval};
  215. $feed->{lastupdate}=time;
  216. $feed->{newposts}=0;
  217. $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
  218. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  219. if (! length $feed->{feedurl}) {
  220. my @urls=XML::Feed->find_feeds($feed->{url});
  221. if (! @urls) {
  222. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{feedurl});
  223. $feed->{error}=1;
  224. debug($feed->{message});
  225. next;
  226. }
  227. $feed->{feedurl}=pop @urls;
  228. }
  229. my $f=eval{XML::Feed->parse(URI->new($feed->{feedurl}))};
  230. if ($@) {
  231. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  232. $feed->{error}=1;
  233. debug($feed->{message});
  234. next;
  235. }
  236. if (! $f) {
  237. $feed->{message}=XML::Feed->errstr;
  238. $feed->{error}=1;
  239. debug($feed->{message});
  240. next;
  241. }
  242. foreach my $entry ($f->entries) {
  243. add_page(
  244. feed => $feed,
  245. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  246. link => $entry->link,
  247. content => $entry->content->body,
  248. guid => defined $entry->id ? $entry->id : time."_".$feed->name,
  249. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  250. );
  251. }
  252. $feed->{message}=sprintf(gettext("processed ok at %s"),
  253. displaytime($feed->{lastupdate}));
  254. $feed->{error}=0;
  255. }
  256. } #}}}
  257. sub add_page (@) { #{{{
  258. my %params=@_;
  259. my $feed=$params{feed};
  260. my $guid={};
  261. my $mtime;
  262. if (exists $guids{$params{guid}}) {
  263. # updating an existing post
  264. $guid=$guids{$params{guid}};
  265. return if $guid->{expired};
  266. }
  267. else {
  268. # new post
  269. $guid->{guid}=$params{guid};
  270. $guids{$params{guid}}=$guid;
  271. $mtime=$params{ctime};
  272. $feed->{numposts}++;
  273. $feed->{newposts}++;
  274. # assign it an unused page
  275. my $page=IkiWiki::titlepage($params{title});
  276. # escape slashes and periods in title so it doesn't specify
  277. # directory name or trigger ".." disallowing code.
  278. $page=~s!([/.])!"__".ord($1)."__"!eg;
  279. $page=$feed->{dir}."/".$page;
  280. ($page)=$page=~/$config{wiki_file_regexp}/;
  281. if (! defined $page || ! length $page) {
  282. $page=$feed->{dir}."/item";
  283. }
  284. my $c="";
  285. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  286. -e pagefile($page.$c)) {
  287. $c++
  288. }
  289. # Make sure that the file name isn't too long.
  290. # NB: This doesn't check for path length limits.
  291. eval q{use POSIX};
  292. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  293. if (defined $max && length(htmlpage($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(htmlpage($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}/".htmlpage($page);
  391. } #}}}
  392. 1