summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 6f9c78075f88509524314feea170e48e50377398 (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. if ($config{aggregate} && ! ($config{post_commit} &&
  30. IkiWiki::commit_hook_enabled())) {
  31. if (! IkiWiki::lockwiki(0)) {
  32. debug("wiki is locked by another process, not aggregating");
  33. exit 1;
  34. }
  35. loadstate();
  36. IkiWiki::loadindex();
  37. aggregate();
  38. expire();
  39. savestate();
  40. clearstate();
  41. IkiWiki::unlockwiki();
  42. }
  43. } #}}}
  44. sub filter (@) { #{{{
  45. my %params=@_;
  46. my $page=$params{page};
  47. loadstate(); # if not already loaded
  48. # Mark all feeds originating on this page as removable;
  49. # preprocess will unmark those that still exist.
  50. remove_feeds($page);
  51. return $params{content};
  52. } # }}}
  53. sub preprocess (@) { #{{{
  54. my %params=@_;
  55. foreach my $required (qw{name url}) {
  56. if (! exists $params{$required}) {
  57. return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
  58. }
  59. }
  60. my $feed={};
  61. my $name=$params{name};
  62. if (exists $feeds{$name}) {
  63. $feed=$feeds{$name};
  64. }
  65. else {
  66. $feeds{$name}=$feed;
  67. }
  68. $feed->{name}=$name;
  69. $feed->{sourcepage}=$params{page};
  70. $feed->{url}=$params{url};
  71. my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
  72. $dir=~s/^\/+//;
  73. ($dir)=$dir=~/$config{wiki_file_regexp}/;
  74. $feed->{dir}=$dir;
  75. $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
  76. $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
  77. $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
  78. $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
  79. delete $feed->{remove};
  80. delete $feed->{expired};
  81. $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
  82. $feed->{numposts}=0 unless defined $feed->{numposts};
  83. $feed->{newposts}=0 unless defined $feed->{newposts};
  84. $feed->{message}=gettext("new feed") unless defined $feed->{message};
  85. $feed->{error}=0 unless defined $feed->{error};
  86. $feed->{tags}=[];
  87. while (@_) {
  88. my $key=shift;
  89. my $value=shift;
  90. if ($key eq 'tag') {
  91. push @{$feed->{tags}}, $value;
  92. }
  93. }
  94. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  95. ($feed->{error} ? "<em>" : "").$feed->{message}.
  96. ($feed->{error} ? "</em>" : "").
  97. " (".$feed->{numposts}." ".gettext("posts").
  98. ($feed->{newposts} ? "; ".$feed->{newposts}.
  99. " ".gettext("new") : "").
  100. ")";
  101. } # }}}
  102. sub delete (@) { #{{{
  103. my @files=@_;
  104. # Remove feed data for removed pages.
  105. foreach my $file (@files) {
  106. my $page=pagename($file);
  107. remove_feeds($page);
  108. }
  109. } #}}}
  110. my $state_loaded=0;
  111. sub loadstate () { #{{{
  112. return if $state_loaded;
  113. if (-e "$config{wikistatedir}/aggregate") {
  114. open(IN, "$config{wikistatedir}/aggregate") ||
  115. die "$config{wikistatedir}/aggregate: $!";
  116. while (<IN>) {
  117. $_=IkiWiki::possibly_foolish_untaint($_);
  118. chomp;
  119. my $data={};
  120. foreach my $i (split(/ /, $_)) {
  121. my ($field, $val)=split(/=/, $i, 2);
  122. if ($field eq "name" || $field eq "feed" ||
  123. $field eq "guid" || $field eq "message") {
  124. $data->{$field}=decode_entities($val, " \t\n");
  125. }
  126. elsif ($field eq "tag") {
  127. push @{$data->{tags}}, $val;
  128. }
  129. else {
  130. $data->{$field}=$val;
  131. }
  132. }
  133. if (exists $data->{name}) {
  134. $feeds{$data->{name}}=$data;
  135. }
  136. elsif (exists $data->{guid}) {
  137. $guids{$data->{guid}}=$data;
  138. }
  139. }
  140. close IN;
  141. $state_loaded=1;
  142. }
  143. } #}}}
  144. sub savestate () { #{{{
  145. eval q{use HTML::Entities};
  146. error($@) if $@;
  147. my $newfile="$config{wikistatedir}/aggregate.new";
  148. # TODO: This cleanup function could use improvement. Any newly
  149. # aggregated files are left behind unrecorded, and should be deleted.
  150. my $cleanup = sub { unlink($newfile) };
  151. open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
  152. foreach my $data (values %feeds, values %guids) {
  153. if ($data->{remove}) {
  154. if ($data->{name}) {
  155. foreach my $guid (values %guids) {
  156. if ($guid->{feed} eq $data->{name}) {
  157. $guid->{remove}=1;
  158. }
  159. }
  160. }
  161. else {
  162. unlink pagefile($data->{page});
  163. }
  164. next;
  165. }
  166. elsif ($data->{expired} && exists $data->{page}) {
  167. unlink pagefile($data->{page});
  168. delete $data->{page};
  169. delete $data->{md5};
  170. }
  171. my @line;
  172. foreach my $field (keys %$data) {
  173. if ($field eq "name" || $field eq "feed" ||
  174. $field eq "guid" || $field eq "message") {
  175. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  176. }
  177. elsif ($field eq "tags") {
  178. push @line, "tag=$_" foreach @{$data->{tags}};
  179. }
  180. else {
  181. push @line, "$field=".$data->{$field};
  182. }
  183. }
  184. print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
  185. }
  186. close OUT || error("save $newfile: $!", $cleanup);
  187. rename($newfile, "$config{wikistatedir}/aggregate") ||
  188. error("rename $newfile: $!", $cleanup);
  189. } #}}}
  190. sub clearstate () { #{{{
  191. %feeds=();
  192. %guids=();
  193. $state_loaded=0;
  194. } #}}}
  195. sub expire () { #{{{
  196. foreach my $feed (values %feeds) {
  197. next unless $feed->{expireage} || $feed->{expirecount};
  198. my $count=0;
  199. foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
  200. grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
  201. values %guids) {
  202. if ($feed->{expireage}) {
  203. my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
  204. if ($days_old > $feed->{expireage}) {
  205. debug(sprintf(gettext("expiring %s (%s days old)"),
  206. $item->{page}, $days_old));
  207. $item->{expired}=1;
  208. }
  209. }
  210. elsif ($feed->{expirecount} &&
  211. $count >= $feed->{expirecount}) {
  212. debug(sprintf(gettext("expiring %s"), $item->{page}));
  213. $item->{expired}=1;
  214. }
  215. else {
  216. $count++;
  217. }
  218. }
  219. }
  220. } #}}}
  221. sub aggregate () { #{{{
  222. eval q{use XML::Feed};
  223. error($@) if $@;
  224. eval q{use URI::Fetch};
  225. error($@) if $@;
  226. eval q{use HTML::Entities};
  227. error($@) if $@;
  228. foreach my $feed (values %feeds) {
  229. next unless $config{rebuild} ||
  230. time - $feed->{lastupdate} >= $feed->{updateinterval};
  231. $feed->{lastupdate}=time;
  232. $feed->{newposts}=0;
  233. $feed->{message}=sprintf(gettext("processed ok at %s"),
  234. displaytime($feed->{lastupdate}));
  235. $feed->{error}=0;
  236. $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
  237. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  238. if (! length $feed->{feedurl}) {
  239. my @urls=XML::Feed->find_feeds($feed->{url});
  240. if (! @urls) {
  241. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
  242. $feed->{error}=1;
  243. debug($feed->{message});
  244. next;
  245. }
  246. $feed->{feedurl}=pop @urls;
  247. }
  248. my $res=URI::Fetch->fetch($feed->{feedurl});
  249. if (! $res) {
  250. $feed->{message}=URI::Fetch->errstr;
  251. $feed->{error}=1;
  252. debug($feed->{message});
  253. next;
  254. }
  255. if ($res->status == URI::Fetch::URI_GONE()) {
  256. $feed->{message}=gettext("feed not found");
  257. $feed->{error}=1;
  258. debug($feed->{message});
  259. next;
  260. }
  261. my $content=$res->content;
  262. my $f=eval{XML::Feed->parse(\$content)};
  263. if ($@) {
  264. # One common cause of XML::Feed crashing is a feed
  265. # that contains invalid UTF-8 sequences. Convert
  266. # feed to ascii to try to work around.
  267. $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
  268. $content=Encode::decode_utf8($content);
  269. $f=eval{XML::Feed->parse(\$content)};
  270. }
  271. if ($@) {
  272. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  273. $feed->{error}=1;
  274. debug($feed->{message});
  275. next;
  276. }
  277. if (! $f) {
  278. $feed->{message}=XML::Feed->errstr;
  279. $feed->{error}=1;
  280. debug($feed->{message});
  281. next;
  282. }
  283. foreach my $entry ($f->entries) {
  284. add_page(
  285. feed => $feed,
  286. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  287. link => $entry->link,
  288. content => defined $entry->content->body ? $entry->content->body : "",
  289. guid => defined $entry->id ? $entry->id : time."_".$feed->name,
  290. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  291. );
  292. }
  293. }
  294. } #}}}
  295. sub add_page (@) { #{{{
  296. my %params=@_;
  297. my $feed=$params{feed};
  298. my $guid={};
  299. my $mtime;
  300. if (exists $guids{$params{guid}}) {
  301. # updating an existing post
  302. $guid=$guids{$params{guid}};
  303. return if $guid->{expired};
  304. }
  305. else {
  306. # new post
  307. $guid->{guid}=$params{guid};
  308. $guids{$params{guid}}=$guid;
  309. $mtime=$params{ctime};
  310. $feed->{numposts}++;
  311. $feed->{newposts}++;
  312. # assign it an unused page
  313. my $page=IkiWiki::titlepage($params{title});
  314. # escape slashes and periods in title so it doesn't specify
  315. # directory name or trigger ".." disallowing code.
  316. $page=~s!([/.])!"__".ord($1)."__"!eg;
  317. $page=$feed->{dir}."/".$page;
  318. ($page)=$page=~/$config{wiki_file_regexp}/;
  319. if (! defined $page || ! length $page) {
  320. $page=$feed->{dir}."/item";
  321. }
  322. my $c="";
  323. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  324. -e pagefile($page.$c)) {
  325. $c++
  326. }
  327. # Make sure that the file name isn't too long.
  328. # NB: This doesn't check for path length limits.
  329. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  330. if (defined $max && length(htmlfn($page)) >= $max) {
  331. $c="";
  332. $page=$feed->{dir}."/item";
  333. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  334. -e pagefile($page.$c)) {
  335. $c++
  336. }
  337. }
  338. $guid->{page}=$page;
  339. debug(sprintf(gettext("creating new page %s"), $page));
  340. }
  341. $guid->{feed}=$feed->{name};
  342. # To write or not to write? Need to avoid writing unchanged pages
  343. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  344. # trusted; let's use a digest.
  345. eval q{use Digest::MD5 'md5_hex'};
  346. error($@) if $@;
  347. require Encode;
  348. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  349. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  350. $guid->{md5}=$digest;
  351. # Create the page.
  352. my $template=template("aggregatepost.tmpl", blind_cache => 1);
  353. $template->param(title => $params{title})
  354. if defined $params{title} && length($params{title});
  355. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  356. $template->param(name => $feed->{name});
  357. $template->param(url => $feed->{url});
  358. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  359. if defined $params{link};
  360. if (ref $feed->{tags}) {
  361. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  362. }
  363. writefile(htmlfn($guid->{page}), $config{srcdir},
  364. $template->output);
  365. # Set the mtime, this lets the build process get the right creation
  366. # time on record for the new page.
  367. utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
  368. } #}}}
  369. sub htmlescape ($) { #{{{
  370. # escape accidental wikilinks and preprocessor stuff
  371. my $html=shift;
  372. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  373. return $html;
  374. } #}}}
  375. sub urlabs ($$) { #{{{
  376. my $url=shift;
  377. my $urlbase=shift;
  378. URI->new_abs($url, $urlbase)->as_string;
  379. } #}}}
  380. sub htmlabs ($$) { #{{{
  381. # Convert links in html from relative to absolute.
  382. # Note that this is a heuristic, which is not specified by the rss
  383. # spec and may not be right for all feeds. Also, see Debian
  384. # bug #381359.
  385. my $html=shift;
  386. my $urlbase=shift;
  387. my $ret="";
  388. my $p = HTML::Parser->new(api_version => 3);
  389. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  390. $p->handler(start => sub {
  391. my ($tagname, $pos, $text) = @_;
  392. if (ref $HTML::Tagset::linkElements{$tagname}) {
  393. while (4 <= @$pos) {
  394. # use attribute sets from right to left
  395. # to avoid invalidating the offsets
  396. # when replacing the values
  397. my($k_offset, $k_len, $v_offset, $v_len) =
  398. splice(@$pos, -4);
  399. my $attrname = lc(substr($text, $k_offset, $k_len));
  400. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  401. next unless $v_offset; # 0 v_offset means no value
  402. my $v = substr($text, $v_offset, $v_len);
  403. $v =~ s/^([\'\"])(.*)\1$/$2/;
  404. my $new_v=urlabs($v, $urlbase);
  405. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  406. substr($text, $v_offset, $v_len) = qq("$new_v");
  407. }
  408. }
  409. $ret.=$text;
  410. }, "tagname, tokenpos, text");
  411. $p->parse($html);
  412. $p->eof;
  413. return $ret;
  414. } #}}}
  415. sub remove_feeds () { #{{{
  416. my $page=shift;
  417. my %removed;
  418. foreach my $id (keys %feeds) {
  419. if ($feeds{$id}->{sourcepage} eq $page) {
  420. $feeds{$id}->{remove}=1;
  421. $removed{$id}=1;
  422. }
  423. }
  424. } #}}}
  425. sub pagefile ($) { #{{{
  426. my $page=shift;
  427. return "$config{srcdir}/".htmlfn($page);
  428. } #}}}
  429. sub htmlfn ($) { #{{{
  430. return shift().".".$config{htmlext};
  431. } #}}}
  432. 1