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