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