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