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