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