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