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