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