summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 614c3fa5510ef09f10750a2639b6a4ad03aa6731 (plain)
  1. #!/usr/bin/perl
  2. # Feed aggregation plugin.
  3. package IkiWiki::Plugin::aggregate;
  4. use warnings;
  5. use strict;
  6. use IkiWiki 3.00;
  7. use HTML::Parser;
  8. use HTML::Tagset;
  9. use HTML::Entities;
  10. use open qw{:utf8 :std};
  11. my %feeds;
  12. my %guids;
  13. sub import {
  14. hook(type => "getopt", id => "aggregate", call => \&getopt);
  15. hook(type => "getsetup", id => "aggregate", call => \&getsetup);
  16. hook(type => "checkconfig", id => "aggregate", call => \&checkconfig,
  17. last => 1);
  18. hook(type => "needsbuild", id => "aggregate", call => \&needsbuild);
  19. hook(type => "preprocess", id => "aggregate", call => \&preprocess);
  20. hook(type => "delete", id => "aggregate", call => \&delete);
  21. hook(type => "savestate", id => "aggregate", call => \&savestate);
  22. hook(type => "htmlize", id => "_aggregated", call => \&htmlize);
  23. if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
  24. hook(type => "cgi", id => "aggregate", call => \&cgi);
  25. }
  26. }
  27. sub getopt () {
  28. eval q{use Getopt::Long};
  29. error($@) if $@;
  30. Getopt::Long::Configure('pass_through');
  31. GetOptions(
  32. "aggregate" => \$config{aggregate},
  33. "aggregateinternal!" => \$config{aggregateinternal},
  34. );
  35. }
  36. sub getsetup () {
  37. return
  38. plugin => {
  39. safe => 1,
  40. rebuild => undef,
  41. },
  42. aggregateinternal => {
  43. type => "boolean",
  44. example => 1,
  45. description => "enable aggregation to internal pages?",
  46. safe => 0, # enabling needs manual transition
  47. rebuild => 0,
  48. },
  49. aggregate_webtrigger => {
  50. type => "boolean",
  51. example => 0,
  52. description => "allow aggregation to be triggered via the web?",
  53. safe => 1,
  54. rebuild => 0,
  55. },
  56. cookiejar => {
  57. type => "string",
  58. example => { file => "$ENV{HOME}/.ikiwiki/cookies" },
  59. safe => 0, # hooks into perl module internals
  60. description => "cookie control",
  61. },
  62. }
  63. sub checkconfig () {
  64. if (! defined $config{aggregateinternal}) {
  65. $config{aggregateinternal}=1;
  66. }
  67. if (! defined $config{cookies}) {
  68. $config{cookies}={ file => "$ENV{HOME}/.ikiwiki/cookies" };
  69. }
  70. if ($config{aggregate} && ! ($config{post_commit} &&
  71. IkiWiki::commit_hook_enabled())) {
  72. launchaggregation();
  73. }
  74. }
  75. sub cgi ($) {
  76. my $cgi=shift;
  77. if (defined $cgi->param('do') &&
  78. $cgi->param("do") eq "aggregate_webtrigger") {
  79. $|=1;
  80. print "Content-Type: text/plain\n\n";
  81. $config{cgi}=0;
  82. $config{verbose}=1;
  83. $config{syslog}=0;
  84. print gettext("Aggregation triggered via web.")."\n\n";
  85. if (launchaggregation()) {
  86. IkiWiki::lockwiki();
  87. IkiWiki::loadindex();
  88. require IkiWiki::Render;
  89. IkiWiki::refresh();
  90. IkiWiki::saveindex();
  91. }
  92. else {
  93. print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
  94. }
  95. exit 0;
  96. }
  97. }
  98. sub launchaggregation () {
  99. # See if any feeds need aggregation.
  100. loadstate();
  101. my @feeds=needsaggregate();
  102. return unless @feeds;
  103. if (! lockaggregate()) {
  104. debug("an aggregation process is already running");
  105. return;
  106. }
  107. # force a later rebuild of source pages
  108. $IkiWiki::forcerebuild{$_->{sourcepage}}=1
  109. foreach @feeds;
  110. # Fork a child process to handle the aggregation.
  111. # The parent process will then handle building the
  112. # result. This avoids messy code to clear state
  113. # accumulated while aggregating.
  114. defined(my $pid = fork) or error("Can't fork: $!");
  115. if (! $pid) {
  116. IkiWiki::loadindex();
  117. # Aggregation happens without the main wiki lock
  118. # being held. This allows editing pages etc while
  119. # aggregation is running.
  120. aggregate(@feeds);
  121. IkiWiki::lockwiki;
  122. # Merge changes, since aggregation state may have
  123. # changed on disk while the aggregation was happening.
  124. mergestate();
  125. expire();
  126. savestate();
  127. IkiWiki::unlockwiki;
  128. exit 0;
  129. }
  130. waitpid($pid,0);
  131. if ($?) {
  132. error "aggregation failed with code $?";
  133. }
  134. clearstate();
  135. unlockaggregate();
  136. return 1;
  137. }
  138. # Pages with extension _aggregated have plain html markup, pass through.
  139. sub htmlize (@) {
  140. my %params=@_;
  141. return $params{content};
  142. }
  143. # Used by ikiwiki-transition aggregateinternal.
  144. sub migrate_to_internal {
  145. if (! lockaggregate()) {
  146. error("an aggregation process is currently running");
  147. }
  148. IkiWiki::lockwiki();
  149. loadstate();
  150. $config{verbose}=1;
  151. foreach my $data (values %guids) {
  152. next unless $data->{page};
  153. next if $data->{expired};
  154. $config{aggregateinternal} = 0;
  155. my $oldname = "$config{srcdir}/".htmlfn($data->{page});
  156. if (! -e $oldname) {
  157. $oldname = $IkiWiki::Plugin::transient::transientdir."/".htmlfn($data->{page});
  158. }
  159. my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
  160. $config{aggregateinternal} = 1;
  161. my $newname = $IkiWiki::Plugin::transient::transientdir."/".htmlfn($data->{page});
  162. debug "moving $oldname -> $newname";
  163. if (-e $newname) {
  164. if (-e $oldname) {
  165. error("$newname already exists");
  166. }
  167. else {
  168. debug("already renamed to $newname?");
  169. }
  170. }
  171. elsif (-e $oldname) {
  172. rename($oldname, $newname) || error("$!");
  173. }
  174. else {
  175. debug("$oldname not found");
  176. }
  177. if (-e $oldoutput) {
  178. require IkiWiki::Render;
  179. debug("removing output file $oldoutput");
  180. IkiWiki::prune($oldoutput);
  181. }
  182. }
  183. savestate();
  184. IkiWiki::unlockwiki;
  185. unlockaggregate();
  186. }
  187. sub needsbuild (@) {
  188. my $needsbuild=shift;
  189. loadstate();
  190. foreach my $feed (values %feeds) {
  191. if (exists $pagesources{$feed->{sourcepage}} &&
  192. grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
  193. # Mark all feeds originating on this page as
  194. # not yet seen; preprocess will unmark those that
  195. # still exist.
  196. markunseen($feed->{sourcepage});
  197. }
  198. }
  199. return $needsbuild;
  200. }
  201. sub preprocess (@) {
  202. my %params=@_;
  203. foreach my $required (qw{name url}) {
  204. if (! exists $params{$required}) {
  205. error sprintf(gettext("missing %s parameter"), $required)
  206. }
  207. }
  208. my $feed={};
  209. my $name=$params{name};
  210. if (exists $feeds{$name}) {
  211. $feed=$feeds{$name};
  212. }
  213. else {
  214. $feeds{$name}=$feed;
  215. }
  216. $feed->{name}=$name;
  217. $feed->{sourcepage}=$params{page};
  218. $feed->{url}=$params{url};
  219. my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
  220. $dir=~s/^\/+//;
  221. ($dir)=$dir=~/$config{wiki_file_regexp}/;
  222. $feed->{dir}=$dir;
  223. $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
  224. $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
  225. $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
  226. $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
  227. if (exists $params{template}) {
  228. $params{template}=~s/[^-_a-zA-Z0-9]+//g;
  229. }
  230. else {
  231. $params{template} = "aggregatepost"
  232. }
  233. $feed->{template}=$params{template} . ".tmpl";
  234. delete $feed->{unseen};
  235. $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
  236. $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
  237. $feed->{numposts}=0 unless defined $feed->{numposts};
  238. $feed->{newposts}=0 unless defined $feed->{newposts};
  239. $feed->{message}=gettext("new feed") unless defined $feed->{message};
  240. $feed->{error}=0 unless defined $feed->{error};
  241. $feed->{tags}=[];
  242. while (@_) {
  243. my $key=shift;
  244. my $value=shift;
  245. if ($key eq 'tag') {
  246. push @{$feed->{tags}}, $value;
  247. }
  248. }
  249. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  250. ($feed->{error} ? "<em>" : "").$feed->{message}.
  251. ($feed->{error} ? "</em>" : "").
  252. " (".$feed->{numposts}." ".gettext("posts").
  253. ($feed->{newposts} ? "; ".$feed->{newposts}.
  254. " ".gettext("new") : "").
  255. ")";
  256. }
  257. sub delete (@) {
  258. my @files=@_;
  259. # Remove feed data for removed pages.
  260. foreach my $file (@files) {
  261. my $page=pagename($file);
  262. markunseen($page);
  263. }
  264. }
  265. sub markunseen ($) {
  266. my $page=shift;
  267. foreach my $id (keys %feeds) {
  268. if ($feeds{$id}->{sourcepage} eq $page) {
  269. $feeds{$id}->{unseen}=1;
  270. }
  271. }
  272. }
  273. my $state_loaded=0;
  274. sub loadstate () {
  275. return if $state_loaded;
  276. $state_loaded=1;
  277. if (-e "$config{wikistatedir}/aggregate") {
  278. open(IN, "<", "$config{wikistatedir}/aggregate") ||
  279. die "$config{wikistatedir}/aggregate: $!";
  280. while (<IN>) {
  281. $_=IkiWiki::possibly_foolish_untaint($_);
  282. chomp;
  283. my $data={};
  284. foreach my $i (split(/ /, $_)) {
  285. my ($field, $val)=split(/=/, $i, 2);
  286. if ($field eq "name" || $field eq "feed" ||
  287. $field eq "guid" || $field eq "message") {
  288. $data->{$field}=decode_entities($val, " \t\n");
  289. }
  290. elsif ($field eq "tag") {
  291. push @{$data->{tags}}, $val;
  292. }
  293. else {
  294. $data->{$field}=$val;
  295. }
  296. }
  297. if (exists $data->{name}) {
  298. $feeds{$data->{name}}=$data;
  299. }
  300. elsif (exists $data->{guid}) {
  301. $guids{$data->{guid}}=$data;
  302. }
  303. }
  304. close IN;
  305. }
  306. }
  307. sub savestate () {
  308. return unless $state_loaded;
  309. garbage_collect();
  310. my $newfile="$config{wikistatedir}/aggregate.new";
  311. my $cleanup = sub { unlink($newfile) };
  312. open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
  313. foreach my $data (values %feeds, values %guids) {
  314. my @line;
  315. foreach my $field (keys %$data) {
  316. if ($field eq "name" || $field eq "feed" ||
  317. $field eq "guid" || $field eq "message") {
  318. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  319. }
  320. elsif ($field eq "tags") {
  321. push @line, "tag=$_" foreach @{$data->{tags}};
  322. }
  323. else {
  324. push @line, "$field=".$data->{$field}
  325. if defined $data->{$field};
  326. }
  327. }
  328. print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
  329. }
  330. close OUT || error("save $newfile: $!", $cleanup);
  331. rename($newfile, "$config{wikistatedir}/aggregate") ||
  332. error("rename $newfile: $!", $cleanup);
  333. my $timestamp=undef;
  334. foreach my $feed (keys %feeds) {
  335. my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
  336. if (! defined $timestamp || $timestamp > $t) {
  337. $timestamp=$t;
  338. }
  339. }
  340. $newfile=~s/\.new$/time/;
  341. open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
  342. if (defined $timestamp) {
  343. print OUT $timestamp."\n";
  344. }
  345. close OUT || error("save $newfile: $!", $cleanup);
  346. }
  347. sub garbage_collect () {
  348. foreach my $name (keys %feeds) {
  349. # remove any feeds that were not seen while building the pages
  350. # that used to contain them
  351. if ($feeds{$name}->{unseen}) {
  352. delete $feeds{$name};
  353. }
  354. }
  355. foreach my $guid (values %guids) {
  356. # any guid whose feed is gone should be removed
  357. if (! exists $feeds{$guid->{feed}}) {
  358. if (exists $guid->{page}) {
  359. unlink $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page})
  360. || unlink "$config{srcdir}/".htmlfn($guid->{page});
  361. }
  362. delete $guids{$guid->{guid}};
  363. }
  364. # handle expired guids
  365. elsif ($guid->{expired} && exists $guid->{page}) {
  366. unlink "$config{srcdir}/".htmlfn($guid->{page});
  367. unlink $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page});
  368. delete $guid->{page};
  369. delete $guid->{md5};
  370. }
  371. }
  372. }
  373. sub mergestate () {
  374. # Load the current state in from disk, and merge into it
  375. # values from the state in memory that might have changed
  376. # during aggregation.
  377. my %myfeeds=%feeds;
  378. my %myguids=%guids;
  379. clearstate();
  380. loadstate();
  381. # All that can change in feed state during aggregation is a few
  382. # fields.
  383. foreach my $name (keys %myfeeds) {
  384. if (exists $feeds{$name}) {
  385. foreach my $field (qw{message lastupdate lasttry
  386. numposts newposts error}) {
  387. $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
  388. }
  389. }
  390. }
  391. # New guids can be created during aggregation.
  392. # Guids have a few fields that may be updated during aggregation.
  393. # It's also possible that guids were removed from the on-disk state
  394. # while the aggregation was in process. That would only happen if
  395. # their feed was also removed, so any removed guids added back here
  396. # will be garbage collected later.
  397. foreach my $guid (keys %myguids) {
  398. if (! exists $guids{$guid}) {
  399. $guids{$guid}=$myguids{$guid};
  400. }
  401. else {
  402. foreach my $field (qw{md5}) {
  403. $guids{$guid}->{$field}=$myguids{$guid}->{$field};
  404. }
  405. }
  406. }
  407. }
  408. sub clearstate () {
  409. %feeds=();
  410. %guids=();
  411. $state_loaded=0;
  412. }
  413. sub expire () {
  414. foreach my $feed (values %feeds) {
  415. next unless $feed->{expireage} || $feed->{expirecount};
  416. my $count=0;
  417. my %seen;
  418. foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
  419. grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
  420. values %guids) {
  421. if ($feed->{expireage}) {
  422. my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
  423. if ($days_old > $feed->{expireage}) {
  424. debug(sprintf(gettext("expiring %s (%s days old)"),
  425. $item->{page}, int($days_old)));
  426. $item->{expired}=1;
  427. }
  428. }
  429. elsif ($feed->{expirecount} &&
  430. $count >= $feed->{expirecount}) {
  431. debug(sprintf(gettext("expiring %s"), $item->{page}));
  432. $item->{expired}=1;
  433. }
  434. else {
  435. if (! $seen{$item->{page}}) {
  436. $seen{$item->{page}}=1;
  437. $count++;
  438. }
  439. }
  440. }
  441. }
  442. }
  443. sub needsaggregate () {
  444. return values %feeds if $config{rebuild};
  445. return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
  446. }
  447. sub aggregate (@) {
  448. eval q{use XML::Feed};
  449. error($@) if $@;
  450. eval q{use URI::Fetch};
  451. error($@) if $@;
  452. foreach my $feed (@_) {
  453. $feed->{lasttry}=time;
  454. $feed->{newposts}=0;
  455. $feed->{message}=sprintf(gettext("last checked %s"),
  456. displaytime($feed->{lasttry}));
  457. $feed->{error}=0;
  458. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  459. if (! length $feed->{feedurl}) {
  460. my @urls=XML::Feed->find_feeds($feed->{url});
  461. if (! @urls) {
  462. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
  463. $feed->{error}=1;
  464. debug($feed->{message});
  465. next;
  466. }
  467. $feed->{feedurl}=pop @urls;
  468. }
  469. my $res=URI::Fetch->fetch($feed->{feedurl},
  470. UserAgent => LWP::UserAgent->new(
  471. cookie_jar => $config{cookiejar},
  472. ),
  473. );
  474. if (! $res) {
  475. $feed->{message}=URI::Fetch->errstr;
  476. $feed->{error}=1;
  477. debug($feed->{message});
  478. next;
  479. }
  480. # lastupdate is only set if we were able to contact the server
  481. $feed->{lastupdate}=$feed->{lasttry};
  482. if ($res->status == URI::Fetch::URI_GONE()) {
  483. $feed->{message}=gettext("feed not found");
  484. $feed->{error}=1;
  485. debug($feed->{message});
  486. next;
  487. }
  488. my $content=$res->content;
  489. my $f=eval{XML::Feed->parse(\$content)};
  490. if ($@) {
  491. # One common cause of XML::Feed crashing is a feed
  492. # that contains invalid UTF-8 sequences. Convert
  493. # feed to ascii to try to work around.
  494. $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
  495. $f=eval {
  496. $content=Encode::decode_utf8($content, 0);
  497. XML::Feed->parse(\$content)
  498. };
  499. }
  500. if ($@) {
  501. # Another possibility is badly escaped entities.
  502. $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
  503. $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
  504. $f=eval {
  505. $content=Encode::decode_utf8($content, 0);
  506. XML::Feed->parse(\$content)
  507. };
  508. }
  509. if ($@) {
  510. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  511. $feed->{error}=1;
  512. debug($feed->{message});
  513. next;
  514. }
  515. if (! $f) {
  516. $feed->{message}=XML::Feed->errstr;
  517. $feed->{error}=1;
  518. debug($feed->{message});
  519. next;
  520. }
  521. foreach my $entry ($f->entries) {
  522. # XML::Feed doesn't work around XML::Atom's bizarre
  523. # API, so we will. Real unicode strings? Yes please.
  524. # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
  525. local $XML::Atom::ForceUnicode = 1;
  526. my $c=$entry->content;
  527. # atom feeds may have no content, only a summary
  528. if (! defined $c && ref $entry->summary) {
  529. $c=$entry->summary;
  530. }
  531. add_page(
  532. feed => $feed,
  533. copyright => $f->copyright,
  534. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  535. link => $entry->link,
  536. content => (defined $c && defined $c->body) ? $c->body : "",
  537. guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
  538. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  539. base => (defined $c && $c->can("base")) ? $c->base : undef,
  540. );
  541. }
  542. }
  543. }
  544. sub add_page (@) {
  545. my %params=@_;
  546. my $feed=$params{feed};
  547. my $guid={};
  548. my $mtime;
  549. if (exists $guids{$params{guid}}) {
  550. # updating an existing post
  551. $guid=$guids{$params{guid}};
  552. return if $guid->{expired};
  553. }
  554. else {
  555. # new post
  556. $guid->{guid}=$params{guid};
  557. $guids{$params{guid}}=$guid;
  558. $mtime=$params{ctime};
  559. $feed->{numposts}++;
  560. $feed->{newposts}++;
  561. # assign it an unused page
  562. my $page=titlepage($params{title});
  563. # escape slashes and periods in title so it doesn't specify
  564. # directory name or trigger ".." disallowing code.
  565. $page=~s!([/.])!"__".ord($1)."__"!eg;
  566. $page=$feed->{dir}."/".$page;
  567. ($page)=$page=~/$config{wiki_file_regexp}/;
  568. if (! defined $page || ! length $page) {
  569. $page=$feed->{dir}."/item";
  570. }
  571. my $c="";
  572. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  573. -e $IkiWiki::Plugin::transient::transientdir."/".htmlfn($page.$c) ||
  574. -e "$config{srcdir}/".htmlfn($page.$c)) {
  575. $c++
  576. }
  577. # Make sure that the file name isn't too long.
  578. # NB: This doesn't check for path length limits.
  579. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  580. if (defined $max && length(htmlfn($page)) >= $max) {
  581. $c="";
  582. $page=$feed->{dir}."/item";
  583. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  584. -e $IkiWiki::Plugin::transient::transientdir."/".htmlfn($page.$c) ||
  585. -e "$config{srcdir}/".htmlfn($page.$c)) {
  586. $c++
  587. }
  588. }
  589. $guid->{page}=$page;
  590. debug(sprintf(gettext("creating new page %s"), $page));
  591. }
  592. $guid->{feed}=$feed->{name};
  593. # To write or not to write? Need to avoid writing unchanged pages
  594. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  595. # trusted; let's use a digest.
  596. eval q{use Digest::MD5 'md5_hex'};
  597. error($@) if $@;
  598. require Encode;
  599. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  600. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  601. $guid->{md5}=$digest;
  602. # Create the page.
  603. my $template;
  604. eval {
  605. $template=template($feed->{template}, blind_cache => 1);
  606. };
  607. if ($@) {
  608. print STDERR gettext("failed to process template:")." $@";
  609. return;
  610. }
  611. $template->param(title => $params{title})
  612. if defined $params{title} && length($params{title});
  613. $template->param(content => wikiescape(htmlabs($params{content},
  614. defined $params{base} ? $params{base} : $feed->{feedurl})));
  615. $template->param(name => $feed->{name});
  616. $template->param(url => $feed->{url});
  617. $template->param(copyright => $params{copyright})
  618. if defined $params{copyright} && length $params{copyright};
  619. $template->param(permalink => IkiWiki::urlabs($params{link}, $feed->{feedurl}))
  620. if defined $params{link};
  621. if (ref $feed->{tags}) {
  622. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  623. }
  624. writefile(htmlfn($guid->{page}),
  625. $IkiWiki::Plugin::transient::transientdir, $template->output);
  626. if (defined $mtime && $mtime <= time) {
  627. # Set the mtime, this lets the build process get the right
  628. # creation time on record for the new page.
  629. utime $mtime, $mtime,
  630. $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page});
  631. # Store it in pagectime for expiry code to use also.
  632. $IkiWiki::pagectime{$guid->{page}}=$mtime
  633. unless exists $IkiWiki::pagectime{$guid->{page}};
  634. }
  635. else {
  636. # Dummy value for expiry code.
  637. $IkiWiki::pagectime{$guid->{page}}=time
  638. unless exists $IkiWiki::pagectime{$guid->{page}};
  639. }
  640. }
  641. sub wikiescape ($) {
  642. # escape accidental wikilinks and preprocessor stuff
  643. return encode_entities(shift, '\[\]');
  644. }
  645. sub htmlabs ($$) {
  646. # Convert links in html from relative to absolute.
  647. # Note that this is a heuristic, which is not specified by the rss
  648. # spec and may not be right for all feeds. Also, see Debian
  649. # bug #381359.
  650. my $html=shift;
  651. my $urlbase=shift;
  652. my $ret="";
  653. my $p = HTML::Parser->new(api_version => 3);
  654. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  655. $p->handler(start => sub {
  656. my ($tagname, $pos, $text) = @_;
  657. if (ref $HTML::Tagset::linkElements{$tagname}) {
  658. while (4 <= @$pos) {
  659. # use attribute sets from right to left
  660. # to avoid invalidating the offsets
  661. # when replacing the values
  662. my($k_offset, $k_len, $v_offset, $v_len) =
  663. splice(@$pos, -4);
  664. my $attrname = lc(substr($text, $k_offset, $k_len));
  665. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  666. next unless $v_offset; # 0 v_offset means no value
  667. my $v = substr($text, $v_offset, $v_len);
  668. $v =~ s/^([\'\"])(.*)\1$/$2/;
  669. my $new_v=IkiWiki::urlabs($v, $urlbase);
  670. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  671. substr($text, $v_offset, $v_len) = qq("$new_v");
  672. }
  673. }
  674. $ret.=$text;
  675. }, "tagname, tokenpos, text");
  676. $p->parse($html);
  677. $p->eof;
  678. return $ret;
  679. }
  680. sub htmlfn ($) {
  681. return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
  682. }
  683. my $aggregatelock;
  684. sub lockaggregate () {
  685. # Take an exclusive lock to prevent multiple concurrent aggregators.
  686. # Returns true if the lock was aquired.
  687. if (! -d $config{wikistatedir}) {
  688. mkdir($config{wikistatedir});
  689. }
  690. open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
  691. error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
  692. if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
  693. close($aggregatelock) || error("failed closing aggregatelock: $!");
  694. return 0;
  695. }
  696. return 1;
  697. }
  698. sub unlockaggregate () {
  699. return close($aggregatelock) if $aggregatelock;
  700. return;
  701. }
  702. 1