summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: f618042374acc4e561be7be446b4fd0c918db316 (plain)
  1. #!/usr/bin/perl
  2. # Feed aggregation plugin.
  3. package IkiWiki::Plugin::aggregate;
  4. use warnings;
  5. use strict;
  6. use IkiWiki 2.00;
  7. use HTML::Parser;
  8. use HTML::Tagset;
  9. use HTML::Entities;
  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. if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
  22. hook(type => "cgi", id => "aggregate", call => \&cgi);
  23. }
  24. } # }}}
  25. sub getopt () { #{{{
  26. eval q{use Getopt::Long};
  27. error($@) if $@;
  28. Getopt::Long::Configure('pass_through');
  29. GetOptions("aggregate" => \$config{aggregate});
  30. } #}}}
  31. sub checkconfig () { #{{{
  32. if ($config{aggregate} && ! ($config{post_commit} &&
  33. IkiWiki::commit_hook_enabled())) {
  34. launchaggregation();
  35. }
  36. } #}}}
  37. sub cgi ($) { #{{{
  38. my $cgi=shift;
  39. if (defined $cgi->param('do') &&
  40. $cgi->param("do") eq "aggregate_webtrigger") {
  41. $|=1;
  42. print "Content-Type: text/plain\n\n";
  43. $config{cgi}=0;
  44. $config{verbose}=1;
  45. $config{syslog}=0;
  46. print gettext("Aggregation triggered via web.")."\n\n";
  47. if (launchaggregation()) {
  48. IkiWiki::lockwiki();
  49. IkiWiki::loadindex();
  50. require IkiWiki::Render;
  51. IkiWiki::refresh();
  52. IkiWiki::saveindex();
  53. }
  54. else {
  55. print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
  56. }
  57. exit 0;
  58. }
  59. } #}}}
  60. sub launchaggregation () { #{{{
  61. # See if any feeds need aggregation.
  62. loadstate();
  63. my @feeds=needsaggregate();
  64. return unless @feeds;
  65. if (! lockaggregate()) {
  66. debug("an aggregation process is already running");
  67. return;
  68. }
  69. # force a later rebuild of source pages
  70. $IkiWiki::forcerebuild{$_->{sourcepage}}=1
  71. foreach @feeds;
  72. # Fork a child process to handle the aggregation.
  73. # The parent process will then handle building the
  74. # result. This avoids messy code to clear state
  75. # accumulated while aggregating.
  76. defined(my $pid = fork) or error("Can't fork: $!");
  77. if (! $pid) {
  78. IkiWiki::loadindex();
  79. # Aggregation happens without the main wiki lock
  80. # being held. This allows editing pages etc while
  81. # aggregation is running.
  82. aggregate(@feeds);
  83. IkiWiki::lockwiki;
  84. # Merge changes, since aggregation state may have
  85. # changed on disk while the aggregation was happening.
  86. mergestate();
  87. expire();
  88. savestate();
  89. IkiWiki::unlockwiki;
  90. exit 0;
  91. }
  92. waitpid($pid,0);
  93. if ($?) {
  94. error "aggregation failed with code $?";
  95. }
  96. clearstate();
  97. unlockaggregate();
  98. return 1;
  99. } #}}}
  100. sub needsbuild (@) { #{{{
  101. my $needsbuild=shift;
  102. loadstate();
  103. foreach my $feed (values %feeds) {
  104. if (exists $pagesources{$feed->{sourcepage}} &&
  105. grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
  106. # Mark all feeds originating on this page as
  107. # not yet seen; preprocess will unmark those that
  108. # still exist.
  109. markunseen($feed->{sourcepage});
  110. }
  111. }
  112. } # }}}
  113. sub preprocess (@) { #{{{
  114. my %params=@_;
  115. foreach my $required (qw{name url}) {
  116. if (! exists $params{$required}) {
  117. error sprintf(gettext("missing %s parameter"), $required)
  118. }
  119. }
  120. my $feed={};
  121. my $name=$params{name};
  122. if (exists $feeds{$name}) {
  123. $feed=$feeds{$name};
  124. }
  125. else {
  126. $feeds{$name}=$feed;
  127. }
  128. $feed->{name}=$name;
  129. $feed->{sourcepage}=$params{page};
  130. $feed->{url}=$params{url};
  131. my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
  132. $dir=~s/^\/+//;
  133. ($dir)=$dir=~/$config{wiki_file_regexp}/;
  134. $feed->{dir}=$dir;
  135. $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
  136. $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
  137. $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
  138. $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
  139. if (exists $params{template}) {
  140. $params{template}=~s/[^-_a-zA-Z0-9]+//g;
  141. }
  142. else {
  143. $params{template} = "aggregatepost"
  144. }
  145. $feed->{template}=$params{template} . ".tmpl";
  146. delete $feed->{unseen};
  147. $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
  148. $feed->{numposts}=0 unless defined $feed->{numposts};
  149. $feed->{newposts}=0 unless defined $feed->{newposts};
  150. $feed->{message}=gettext("new feed") unless defined $feed->{message};
  151. $feed->{error}=0 unless defined $feed->{error};
  152. $feed->{tags}=[];
  153. while (@_) {
  154. my $key=shift;
  155. my $value=shift;
  156. if ($key eq 'tag') {
  157. push @{$feed->{tags}}, $value;
  158. }
  159. }
  160. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  161. ($feed->{error} ? "<em>" : "").$feed->{message}.
  162. ($feed->{error} ? "</em>" : "").
  163. " (".$feed->{numposts}." ".gettext("posts").
  164. ($feed->{newposts} ? "; ".$feed->{newposts}.
  165. " ".gettext("new") : "").
  166. ")";
  167. } # }}}
  168. sub delete (@) { #{{{
  169. my @files=@_;
  170. # Remove feed data for removed pages.
  171. foreach my $file (@files) {
  172. my $page=pagename($file);
  173. markunseen($page);
  174. }
  175. } #}}}
  176. sub markunseen ($) { #{{{
  177. my $page=shift;
  178. foreach my $id (keys %feeds) {
  179. if ($feeds{$id}->{sourcepage} eq $page) {
  180. $feeds{$id}->{unseen}=1;
  181. }
  182. }
  183. } #}}}
  184. my $state_loaded=0;
  185. sub loadstate () { #{{{
  186. return if $state_loaded;
  187. $state_loaded=1;
  188. if (-e "$config{wikistatedir}/aggregate") {
  189. open(IN, "$config{wikistatedir}/aggregate") ||
  190. die "$config{wikistatedir}/aggregate: $!";
  191. while (<IN>) {
  192. $_=IkiWiki::possibly_foolish_untaint($_);
  193. chomp;
  194. my $data={};
  195. foreach my $i (split(/ /, $_)) {
  196. my ($field, $val)=split(/=/, $i, 2);
  197. if ($field eq "name" || $field eq "feed" ||
  198. $field eq "guid" || $field eq "message") {
  199. $data->{$field}=decode_entities($val, " \t\n");
  200. }
  201. elsif ($field eq "tag") {
  202. push @{$data->{tags}}, $val;
  203. }
  204. else {
  205. $data->{$field}=$val;
  206. }
  207. }
  208. if (exists $data->{name}) {
  209. $feeds{$data->{name}}=$data;
  210. }
  211. elsif (exists $data->{guid}) {
  212. $guids{$data->{guid}}=$data;
  213. }
  214. }
  215. close IN;
  216. }
  217. } #}}}
  218. sub savestate () { #{{{
  219. return unless $state_loaded;
  220. garbage_collect();
  221. my $newfile="$config{wikistatedir}/aggregate.new";
  222. my $cleanup = sub { unlink($newfile) };
  223. open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
  224. foreach my $data (values %feeds, values %guids) {
  225. my @line;
  226. foreach my $field (keys %$data) {
  227. if ($field eq "name" || $field eq "feed" ||
  228. $field eq "guid" || $field eq "message") {
  229. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  230. }
  231. elsif ($field eq "tags") {
  232. push @line, "tag=$_" foreach @{$data->{tags}};
  233. }
  234. else {
  235. push @line, "$field=".$data->{$field};
  236. }
  237. }
  238. print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
  239. }
  240. close OUT || error("save $newfile: $!", $cleanup);
  241. rename($newfile, "$config{wikistatedir}/aggregate") ||
  242. error("rename $newfile: $!", $cleanup);
  243. } #}}}
  244. sub garbage_collect () { #{{{
  245. foreach my $name (keys %feeds) {
  246. # remove any feeds that were not seen while building the pages
  247. # that used to contain them
  248. if ($feeds{$name}->{unseen}) {
  249. delete $feeds{$name};
  250. }
  251. }
  252. foreach my $guid (values %guids) {
  253. # any guid whose feed is gone should be removed
  254. if (! exists $feeds{$guid->{feed}}) {
  255. unlink pagefile($guid->{page})
  256. if exists $guid->{page};
  257. delete $guids{$guid->{guid}};
  258. }
  259. # handle expired guids
  260. elsif ($guid->{expired} && exists $guid->{page}) {
  261. unlink pagefile($guid->{page});
  262. delete $guid->{page};
  263. delete $guid->{md5};
  264. }
  265. }
  266. } #}}}
  267. sub mergestate () { #{{{
  268. # Load the current state in from disk, and merge into it
  269. # values from the state in memory that might have changed
  270. # during aggregation.
  271. my %myfeeds=%feeds;
  272. my %myguids=%guids;
  273. clearstate();
  274. loadstate();
  275. # All that can change in feed state during aggregation is a few
  276. # fields.
  277. foreach my $name (keys %myfeeds) {
  278. if (exists $feeds{$name}) {
  279. foreach my $field (qw{message lastupdate numposts
  280. newposts error}) {
  281. $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
  282. }
  283. }
  284. }
  285. # New guids can be created during aggregation.
  286. # It's also possible that guids were removed from the on-disk state
  287. # while the aggregation was in process. That would only happen if
  288. # their feed was also removed, so any removed guids added back here
  289. # will be garbage collected later.
  290. foreach my $guid (keys %myguids) {
  291. if (! exists $guids{$guid}) {
  292. $guids{$guid}=$myguids{$guid};
  293. }
  294. }
  295. } #}}}
  296. sub clearstate () { #{{{
  297. %feeds=();
  298. %guids=();
  299. $state_loaded=0;
  300. } #}}}
  301. sub expire () { #{{{
  302. foreach my $feed (values %feeds) {
  303. next unless $feed->{expireage} || $feed->{expirecount};
  304. my $count=0;
  305. my %seen;
  306. foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
  307. grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
  308. values %guids) {
  309. if ($feed->{expireage}) {
  310. my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
  311. if ($days_old > $feed->{expireage}) {
  312. debug(sprintf(gettext("expiring %s (%s days old)"),
  313. $item->{page}, int($days_old)));
  314. $item->{expired}=1;
  315. }
  316. }
  317. elsif ($feed->{expirecount} &&
  318. $count >= $feed->{expirecount}) {
  319. debug(sprintf(gettext("expiring %s"), $item->{page}));
  320. $item->{expired}=1;
  321. }
  322. else {
  323. if (! $seen{$item->{page}}) {
  324. $seen{$item->{page}}=1;
  325. $count++;
  326. }
  327. }
  328. }
  329. }
  330. } #}}}
  331. sub needsaggregate () { #{{{
  332. return values %feeds if $config{rebuild};
  333. return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
  334. } #}}}
  335. sub aggregate (@) { #{{{
  336. eval q{use XML::Feed};
  337. error($@) if $@;
  338. eval q{use URI::Fetch};
  339. error($@) if $@;
  340. foreach my $feed (@_) {
  341. $feed->{lastupdate}=time;
  342. $feed->{newposts}=0;
  343. $feed->{message}=sprintf(gettext("processed ok at %s"),
  344. displaytime($feed->{lastupdate}));
  345. $feed->{error}=0;
  346. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  347. if (! length $feed->{feedurl}) {
  348. my @urls=XML::Feed->find_feeds($feed->{url});
  349. if (! @urls) {
  350. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
  351. $feed->{error}=1;
  352. debug($feed->{message});
  353. next;
  354. }
  355. $feed->{feedurl}=pop @urls;
  356. }
  357. my $res=URI::Fetch->fetch($feed->{feedurl});
  358. if (! $res) {
  359. $feed->{message}=URI::Fetch->errstr;
  360. $feed->{error}=1;
  361. debug($feed->{message});
  362. next;
  363. }
  364. if ($res->status == URI::Fetch::URI_GONE()) {
  365. $feed->{message}=gettext("feed not found");
  366. $feed->{error}=1;
  367. debug($feed->{message});
  368. next;
  369. }
  370. my $content=$res->content;
  371. my $f=eval{XML::Feed->parse(\$content)};
  372. if ($@) {
  373. # One common cause of XML::Feed crashing is a feed
  374. # that contains invalid UTF-8 sequences. Convert
  375. # feed to ascii to try to work around.
  376. $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
  377. $content=Encode::decode_utf8($content, 0);
  378. $f=eval{XML::Feed->parse(\$content)};
  379. }
  380. if ($@) {
  381. # Another possibility is badly escaped entities.
  382. $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
  383. $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
  384. $content=Encode::decode_utf8($content, 0);
  385. $f=eval{XML::Feed->parse(\$content)};
  386. }
  387. if ($@) {
  388. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  389. $feed->{error}=1;
  390. debug($feed->{message});
  391. next;
  392. }
  393. if (! $f) {
  394. $feed->{message}=XML::Feed->errstr;
  395. $feed->{error}=1;
  396. debug($feed->{message});
  397. next;
  398. }
  399. foreach my $entry ($f->entries) {
  400. add_page(
  401. feed => $feed,
  402. copyright => $f->copyright,
  403. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  404. link => $entry->link,
  405. content => defined $entry->content->body ? $entry->content->body : "",
  406. guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
  407. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  408. );
  409. }
  410. }
  411. } #}}}
  412. sub add_page (@) { #{{{
  413. my %params=@_;
  414. my $feed=$params{feed};
  415. my $guid={};
  416. my $mtime;
  417. if (exists $guids{$params{guid}}) {
  418. # updating an existing post
  419. $guid=$guids{$params{guid}};
  420. return if $guid->{expired};
  421. }
  422. else {
  423. # new post
  424. $guid->{guid}=$params{guid};
  425. $guids{$params{guid}}=$guid;
  426. $mtime=$params{ctime};
  427. $feed->{numposts}++;
  428. $feed->{newposts}++;
  429. # assign it an unused page
  430. my $page=IkiWiki::titlepage($params{title});
  431. # escape slashes and periods in title so it doesn't specify
  432. # directory name or trigger ".." disallowing code.
  433. $page=~s!([/.])!"__".ord($1)."__"!eg;
  434. $page=$feed->{dir}."/".$page;
  435. ($page)=$page=~/$config{wiki_file_regexp}/;
  436. if (! defined $page || ! length $page) {
  437. $page=$feed->{dir}."/item";
  438. }
  439. my $c="";
  440. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  441. -e pagefile($page.$c)) {
  442. $c++
  443. }
  444. # Make sure that the file name isn't too long.
  445. # NB: This doesn't check for path length limits.
  446. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  447. if (defined $max && length(htmlfn($page)) >= $max) {
  448. $c="";
  449. $page=$feed->{dir}."/item";
  450. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  451. -e pagefile($page.$c)) {
  452. $c++
  453. }
  454. }
  455. $guid->{page}=$page;
  456. debug(sprintf(gettext("creating new page %s"), $page));
  457. }
  458. $guid->{feed}=$feed->{name};
  459. # To write or not to write? Need to avoid writing unchanged pages
  460. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  461. # trusted; let's use a digest.
  462. eval q{use Digest::MD5 'md5_hex'};
  463. error($@) if $@;
  464. require Encode;
  465. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  466. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  467. $guid->{md5}=$digest;
  468. # Create the page.
  469. my $template=template($feed->{template}, blind_cache => 1);
  470. $template->param(title => $params{title})
  471. if defined $params{title} && length($params{title});
  472. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  473. $template->param(name => $feed->{name});
  474. $template->param(url => $feed->{url});
  475. $template->param(copyright => $params{copyright})
  476. if defined $params{copyright} && length $params{copyright};
  477. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  478. if defined $params{link};
  479. if (ref $feed->{tags}) {
  480. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  481. }
  482. writefile(htmlfn($guid->{page}), $config{srcdir},
  483. $template->output);
  484. # Set the mtime, this lets the build process get the right creation
  485. # time on record for the new page.
  486. utime $mtime, $mtime, pagefile($guid->{page})
  487. if defined $mtime && $mtime <= time;
  488. } #}}}
  489. sub htmlescape ($) { #{{{
  490. # escape accidental wikilinks and preprocessor stuff
  491. my $html=shift;
  492. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  493. return $html;
  494. } #}}}
  495. sub urlabs ($$) { #{{{
  496. my $url=shift;
  497. my $urlbase=shift;
  498. URI->new_abs($url, $urlbase)->as_string;
  499. } #}}}
  500. sub htmlabs ($$) { #{{{
  501. # Convert links in html from relative to absolute.
  502. # Note that this is a heuristic, which is not specified by the rss
  503. # spec and may not be right for all feeds. Also, see Debian
  504. # bug #381359.
  505. my $html=shift;
  506. my $urlbase=shift;
  507. my $ret="";
  508. my $p = HTML::Parser->new(api_version => 3);
  509. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  510. $p->handler(start => sub {
  511. my ($tagname, $pos, $text) = @_;
  512. if (ref $HTML::Tagset::linkElements{$tagname}) {
  513. while (4 <= @$pos) {
  514. # use attribute sets from right to left
  515. # to avoid invalidating the offsets
  516. # when replacing the values
  517. my($k_offset, $k_len, $v_offset, $v_len) =
  518. splice(@$pos, -4);
  519. my $attrname = lc(substr($text, $k_offset, $k_len));
  520. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  521. next unless $v_offset; # 0 v_offset means no value
  522. my $v = substr($text, $v_offset, $v_len);
  523. $v =~ s/^([\'\"])(.*)\1$/$2/;
  524. my $new_v=urlabs($v, $urlbase);
  525. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  526. substr($text, $v_offset, $v_len) = qq("$new_v");
  527. }
  528. }
  529. $ret.=$text;
  530. }, "tagname, tokenpos, text");
  531. $p->parse($html);
  532. $p->eof;
  533. return $ret;
  534. } #}}}
  535. sub pagefile ($) { #{{{
  536. my $page=shift;
  537. return "$config{srcdir}/".htmlfn($page);
  538. } #}}}
  539. sub htmlfn ($) { #{{{
  540. return shift().".".$config{htmlext};
  541. } #}}}
  542. my $aggregatelock;
  543. sub lockaggregate () { #{{{
  544. # Take an exclusive lock to prevent multiple concurrent aggregators.
  545. # Returns true if the lock was aquired.
  546. if (! -d $config{wikistatedir}) {
  547. mkdir($config{wikistatedir});
  548. }
  549. open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
  550. error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
  551. if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
  552. close($aggregatelock) || error("failed closing aggregatelock: $!");
  553. return 0;
  554. }
  555. return 1;
  556. } #}}}
  557. sub unlockaggregate () { #{{{
  558. return close($aggregatelock) if $aggregatelock;
  559. return;
  560. } #}}}
  561. 1