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