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