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