summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 0da527f25e7bff733b0f64473e6fc7f67d323982 (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. $state_loaded=1;
  116. if (-e "$config{wikistatedir}/aggregate") {
  117. open(IN, "$config{wikistatedir}/aggregate") ||
  118. die "$config{wikistatedir}/aggregate: $!";
  119. while (<IN>) {
  120. $_=IkiWiki::possibly_foolish_untaint($_);
  121. chomp;
  122. my $data={};
  123. foreach my $i (split(/ /, $_)) {
  124. my ($field, $val)=split(/=/, $i, 2);
  125. if ($field eq "name" || $field eq "feed" ||
  126. $field eq "guid" || $field eq "message") {
  127. $data->{$field}=decode_entities($val, " \t\n");
  128. }
  129. elsif ($field eq "tag") {
  130. push @{$data->{tags}}, $val;
  131. }
  132. else {
  133. $data->{$field}=$val;
  134. }
  135. }
  136. if (exists $data->{name}) {
  137. $feeds{$data->{name}}=$data;
  138. }
  139. elsif (exists $data->{guid}) {
  140. $guids{$data->{guid}}=$data;
  141. }
  142. }
  143. close IN;
  144. }
  145. } #}}}
  146. sub savestate () { #{{{
  147. return unless $state_loaded;
  148. eval q{use HTML::Entities};
  149. error($@) if $@;
  150. my $newfile="$config{wikistatedir}/aggregate.new";
  151. my $cleanup = sub { unlink($newfile) };
  152. open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
  153. foreach my $data (values %feeds, values %guids) {
  154. if ($data->{remove}) {
  155. if ($data->{name}) {
  156. foreach my $guid (values %guids) {
  157. if ($guid->{feed} eq $data->{name}) {
  158. $guid->{remove}=1;
  159. }
  160. }
  161. }
  162. else {
  163. unlink pagefile($data->{page})
  164. if exists $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}, int($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. # Another possibility is badly escaped entities.
  279. $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
  280. $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
  281. $content=Encode::decode_utf8($content);
  282. $f=eval{XML::Feed->parse(\$content)};
  283. }
  284. if ($@) {
  285. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  286. $feed->{error}=1;
  287. debug($feed->{message});
  288. next;
  289. }
  290. if (! $f) {
  291. $feed->{message}=XML::Feed->errstr;
  292. $feed->{error}=1;
  293. debug($feed->{message});
  294. next;
  295. }
  296. foreach my $entry ($f->entries) {
  297. add_page(
  298. feed => $feed,
  299. copyright => $f->copyright,
  300. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  301. link => $entry->link,
  302. content => defined $entry->content->body ? $entry->content->body : "",
  303. guid => defined $entry->id ? $entry->id : time."_".$feed->name,
  304. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  305. );
  306. }
  307. }
  308. } #}}}
  309. sub add_page (@) { #{{{
  310. my %params=@_;
  311. my $feed=$params{feed};
  312. my $guid={};
  313. my $mtime;
  314. if (exists $guids{$params{guid}}) {
  315. # updating an existing post
  316. $guid=$guids{$params{guid}};
  317. return if $guid->{expired};
  318. }
  319. else {
  320. # new post
  321. $guid->{guid}=$params{guid};
  322. $guids{$params{guid}}=$guid;
  323. $mtime=$params{ctime};
  324. $feed->{numposts}++;
  325. $feed->{newposts}++;
  326. # assign it an unused page
  327. my $page=IkiWiki::titlepage($params{title});
  328. # escape slashes and periods in title so it doesn't specify
  329. # directory name or trigger ".." disallowing code.
  330. $page=~s!([/.])!"__".ord($1)."__"!eg;
  331. $page=$feed->{dir}."/".$page;
  332. ($page)=$page=~/$config{wiki_file_regexp}/;
  333. if (! defined $page || ! length $page) {
  334. $page=$feed->{dir}."/item";
  335. }
  336. my $c="";
  337. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  338. -e pagefile($page.$c)) {
  339. $c++
  340. }
  341. # Make sure that the file name isn't too long.
  342. # NB: This doesn't check for path length limits.
  343. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  344. if (defined $max && length(htmlfn($page)) >= $max) {
  345. $c="";
  346. $page=$feed->{dir}."/item";
  347. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  348. -e pagefile($page.$c)) {
  349. $c++
  350. }
  351. }
  352. $guid->{page}=$page;
  353. debug(sprintf(gettext("creating new page %s"), $page));
  354. }
  355. $guid->{feed}=$feed->{name};
  356. # To write or not to write? Need to avoid writing unchanged pages
  357. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  358. # trusted; let's use a digest.
  359. eval q{use Digest::MD5 'md5_hex'};
  360. error($@) if $@;
  361. require Encode;
  362. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  363. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  364. $guid->{md5}=$digest;
  365. # Create the page.
  366. my $template=template("aggregatepost.tmpl", blind_cache => 1);
  367. $template->param(title => $params{title})
  368. if defined $params{title} && length($params{title});
  369. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  370. $template->param(name => $feed->{name});
  371. $template->param(url => $feed->{url});
  372. $template->param(copyright => $params{copyright})
  373. if defined $params{copyright} && length $params{copyright};
  374. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  375. if defined $params{link};
  376. if (ref $feed->{tags}) {
  377. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  378. }
  379. writefile(htmlfn($guid->{page}), $config{srcdir},
  380. $template->output);
  381. # Set the mtime, this lets the build process get the right creation
  382. # time on record for the new page.
  383. utime $mtime, $mtime, pagefile($guid->{page})
  384. if defined $mtime && $mtime <= time;
  385. } #}}}
  386. sub htmlescape ($) { #{{{
  387. # escape accidental wikilinks and preprocessor stuff
  388. my $html=shift;
  389. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  390. return $html;
  391. } #}}}
  392. sub urlabs ($$) { #{{{
  393. my $url=shift;
  394. my $urlbase=shift;
  395. URI->new_abs($url, $urlbase)->as_string;
  396. } #}}}
  397. sub htmlabs ($$) { #{{{
  398. # Convert links in html from relative to absolute.
  399. # Note that this is a heuristic, which is not specified by the rss
  400. # spec and may not be right for all feeds. Also, see Debian
  401. # bug #381359.
  402. my $html=shift;
  403. my $urlbase=shift;
  404. my $ret="";
  405. my $p = HTML::Parser->new(api_version => 3);
  406. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  407. $p->handler(start => sub {
  408. my ($tagname, $pos, $text) = @_;
  409. if (ref $HTML::Tagset::linkElements{$tagname}) {
  410. while (4 <= @$pos) {
  411. # use attribute sets from right to left
  412. # to avoid invalidating the offsets
  413. # when replacing the values
  414. my($k_offset, $k_len, $v_offset, $v_len) =
  415. splice(@$pos, -4);
  416. my $attrname = lc(substr($text, $k_offset, $k_len));
  417. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  418. next unless $v_offset; # 0 v_offset means no value
  419. my $v = substr($text, $v_offset, $v_len);
  420. $v =~ s/^([\'\"])(.*)\1$/$2/;
  421. my $new_v=urlabs($v, $urlbase);
  422. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  423. substr($text, $v_offset, $v_len) = qq("$new_v");
  424. }
  425. }
  426. $ret.=$text;
  427. }, "tagname, tokenpos, text");
  428. $p->parse($html);
  429. $p->eof;
  430. return $ret;
  431. } #}}}
  432. sub remove_feeds () { #{{{
  433. my $page=shift;
  434. my %removed;
  435. foreach my $id (keys %feeds) {
  436. if ($feeds{$id}->{sourcepage} eq $page) {
  437. $feeds{$id}->{remove}=1;
  438. $removed{$id}=1;
  439. }
  440. }
  441. } #}}}
  442. sub pagefile ($) { #{{{
  443. my $page=shift;
  444. return "$config{srcdir}/".htmlfn($page);
  445. } #}}}
  446. sub htmlfn ($) { #{{{
  447. return shift().".".$config{htmlext};
  448. } #}}}
  449. 1