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