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