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