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