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