summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 78f8b409c1fb01960ba1b66c03989fafd346e08c (plain)
  1. #!/usr/bin/perl
  2. # Blog aggregation plugin.
  3. package IkiWiki::Plugin::aggregate;
  4. use warnings;
  5. use strict;
  6. use IkiWiki 2.00;
  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 URI::Fetch};
  212. error($@) if $@;
  213. eval q{use HTML::Entities};
  214. error($@) if $@;
  215. foreach my $feed (values %feeds) {
  216. next unless $config{rebuild} ||
  217. time - $feed->{lastupdate} >= $feed->{updateinterval};
  218. $feed->{lastupdate}=time;
  219. $feed->{newposts}=0;
  220. $feed->{message}=sprintf(gettext("processed ok at %s"),
  221. displaytime($feed->{lastupdate}));
  222. $feed->{error}=0;
  223. $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
  224. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  225. if (! length $feed->{feedurl}) {
  226. my @urls=XML::Feed->find_feeds($feed->{url});
  227. if (! @urls) {
  228. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
  229. $feed->{error}=1;
  230. debug($feed->{message});
  231. next;
  232. }
  233. $feed->{feedurl}=pop @urls;
  234. }
  235. my $res=URI::Fetch->fetch($feed->{feedurl});
  236. if (! $res) {
  237. $feed->{message}=URI::Fetch->errstr;
  238. $feed->{error}=1;
  239. debug($feed->{message});
  240. next;
  241. }
  242. if ($res->status == URI::Fetch::URI_GONE()) {
  243. $feed->{message}=gettext("feed not found");
  244. $feed->{error}=1;
  245. debug($feed->{message});
  246. next;
  247. }
  248. my $content=$res->content;
  249. my $f=eval{XML::Feed->parse(\$content)};
  250. if ($@) {
  251. # One common cause of XML::Feed crashing is a feed
  252. # that contains invalid UTF-8 sequences. Convert
  253. # feed to ascii to try to work around.
  254. $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
  255. $content=Encode::decode_utf8($content);
  256. $f=eval{XML::Feed->parse(\$content)};
  257. }
  258. if ($@) {
  259. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  260. $feed->{error}=1;
  261. debug($feed->{message});
  262. next;
  263. }
  264. if (! $f) {
  265. $feed->{message}=XML::Feed->errstr;
  266. $feed->{error}=1;
  267. debug($feed->{message});
  268. next;
  269. }
  270. foreach my $entry ($f->entries) {
  271. add_page(
  272. feed => $feed,
  273. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  274. link => $entry->link,
  275. content => defined $entry->content->body ? $entry->content->body : "",
  276. guid => defined $entry->id ? $entry->id : time."_".$feed->name,
  277. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  278. );
  279. }
  280. }
  281. } #}}}
  282. sub add_page (@) { #{{{
  283. my %params=@_;
  284. my $feed=$params{feed};
  285. my $guid={};
  286. my $mtime;
  287. if (exists $guids{$params{guid}}) {
  288. # updating an existing post
  289. $guid=$guids{$params{guid}};
  290. return if $guid->{expired};
  291. }
  292. else {
  293. # new post
  294. $guid->{guid}=$params{guid};
  295. $guids{$params{guid}}=$guid;
  296. $mtime=$params{ctime};
  297. $feed->{numposts}++;
  298. $feed->{newposts}++;
  299. # assign it an unused page
  300. my $page=IkiWiki::titlepage($params{title});
  301. # escape slashes and periods in title so it doesn't specify
  302. # directory name or trigger ".." disallowing code.
  303. $page=~s!([/.])!"__".ord($1)."__"!eg;
  304. $page=$feed->{dir}."/".$page;
  305. ($page)=$page=~/$config{wiki_file_regexp}/;
  306. if (! defined $page || ! length $page) {
  307. $page=$feed->{dir}."/item";
  308. }
  309. my $c="";
  310. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  311. -e pagefile($page.$c)) {
  312. $c++
  313. }
  314. # Make sure that the file name isn't too long.
  315. # NB: This doesn't check for path length limits.
  316. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  317. if (defined $max && length(htmlfn($page)) >= $max) {
  318. $c="";
  319. $page=$feed->{dir}."/item";
  320. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  321. -e pagefile($page.$c)) {
  322. $c++
  323. }
  324. }
  325. $guid->{page}=$page;
  326. debug(sprintf(gettext("creating new page %s"), $page));
  327. }
  328. $guid->{feed}=$feed->{name};
  329. # To write or not to write? Need to avoid writing unchanged pages
  330. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  331. # trusted; let's use a digest.
  332. eval q{use Digest::MD5 'md5_hex'};
  333. error($@) if $@;
  334. require Encode;
  335. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  336. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  337. $guid->{md5}=$digest;
  338. # Create the page.
  339. my $template=template("aggregatepost.tmpl", blind_cache => 1);
  340. $template->param(title => $params{title})
  341. if defined $params{title} && length($params{title});
  342. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  343. $template->param(name => $feed->{name});
  344. $template->param(url => $feed->{url});
  345. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  346. if defined $params{link};
  347. if (ref $feed->{tags}) {
  348. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  349. }
  350. writefile(htmlfn($guid->{page}), $config{srcdir},
  351. $template->output);
  352. # Set the mtime, this lets the build process get the right creation
  353. # time on record for the new page.
  354. utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
  355. } #}}}
  356. sub htmlescape ($) { #{{{
  357. # escape accidental wikilinks and preprocessor stuff
  358. my $html=shift;
  359. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  360. return $html;
  361. } #}}}
  362. sub urlabs ($$) { #{{{
  363. my $url=shift;
  364. my $urlbase=shift;
  365. URI->new_abs($url, $urlbase)->as_string;
  366. } #}}}
  367. sub htmlabs ($$) { #{{{
  368. # Convert links in html from relative to absolute.
  369. # Note that this is a heuristic, which is not specified by the rss
  370. # spec and may not be right for all feeds. Also, see Debian
  371. # bug #381359.
  372. my $html=shift;
  373. my $urlbase=shift;
  374. my $ret="";
  375. my $p = HTML::Parser->new(api_version => 3);
  376. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  377. $p->handler(start => sub {
  378. my ($tagname, $pos, $text) = @_;
  379. if (ref $HTML::Tagset::linkElements{$tagname}) {
  380. while (4 <= @$pos) {
  381. # use attribute sets from right to left
  382. # to avoid invalidating the offsets
  383. # when replacing the values
  384. my($k_offset, $k_len, $v_offset, $v_len) =
  385. splice(@$pos, -4);
  386. my $attrname = lc(substr($text, $k_offset, $k_len));
  387. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  388. next unless $v_offset; # 0 v_offset means no value
  389. my $v = substr($text, $v_offset, $v_len);
  390. $v =~ s/^([\'\"])(.*)\1$/$2/;
  391. my $new_v=urlabs($v, $urlbase);
  392. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  393. substr($text, $v_offset, $v_len) = qq("$new_v");
  394. }
  395. }
  396. $ret.=$text;
  397. }, "tagname, tokenpos, text");
  398. $p->parse($html);
  399. $p->eof;
  400. return $ret;
  401. } #}}}
  402. sub remove_feeds () { #{{{
  403. my $page=shift;
  404. my %removed;
  405. foreach my $id (keys %feeds) {
  406. if ($feeds{$id}->{sourcepage} eq $page) {
  407. $feeds{$id}->{remove}=1;
  408. $removed{$id}=1;
  409. }
  410. }
  411. } #}}}
  412. sub pagefile ($) { #{{{
  413. my $page=shift;
  414. return "$config{srcdir}/".htmlfn($page);
  415. } #}}}
  416. sub htmlfn ($) { #{{{
  417. return shift().".html";
  418. } #}}}
  419. 1