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