summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 9b70e5df053731866c5ad7a494432e6e0b72b4bc (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. return $needsbuild;
  188. }
  189. sub preprocess (@) {
  190. my %params=@_;
  191. foreach my $required (qw{name url}) {
  192. if (! exists $params{$required}) {
  193. error sprintf(gettext("missing %s parameter"), $required)
  194. }
  195. }
  196. my $feed={};
  197. my $name=$params{name};
  198. if (exists $feeds{$name}) {
  199. $feed=$feeds{$name};
  200. }
  201. else {
  202. $feeds{$name}=$feed;
  203. }
  204. $feed->{name}=$name;
  205. $feed->{sourcepage}=$params{page};
  206. $feed->{url}=$params{url};
  207. my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
  208. $dir=~s/^\/+//;
  209. ($dir)=$dir=~/$config{wiki_file_regexp}/;
  210. $feed->{dir}=$dir;
  211. $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
  212. $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
  213. $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
  214. $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
  215. if (exists $params{template}) {
  216. $params{template}=~s/[^-_a-zA-Z0-9]+//g;
  217. }
  218. else {
  219. $params{template} = "aggregatepost"
  220. }
  221. $feed->{template}=$params{template} . ".tmpl";
  222. delete $feed->{unseen};
  223. $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
  224. $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
  225. $feed->{numposts}=0 unless defined $feed->{numposts};
  226. $feed->{newposts}=0 unless defined $feed->{newposts};
  227. $feed->{message}=gettext("new feed") unless defined $feed->{message};
  228. $feed->{error}=0 unless defined $feed->{error};
  229. $feed->{tags}=[];
  230. while (@_) {
  231. my $key=shift;
  232. my $value=shift;
  233. if ($key eq 'tag') {
  234. push @{$feed->{tags}}, $value;
  235. }
  236. }
  237. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  238. ($feed->{error} ? "<em>" : "").$feed->{message}.
  239. ($feed->{error} ? "</em>" : "").
  240. " (".$feed->{numposts}." ".gettext("posts").
  241. ($feed->{newposts} ? "; ".$feed->{newposts}.
  242. " ".gettext("new") : "").
  243. ")";
  244. }
  245. sub delete (@) {
  246. my @files=@_;
  247. # Remove feed data for removed pages.
  248. foreach my $file (@files) {
  249. my $page=pagename($file);
  250. markunseen($page);
  251. }
  252. }
  253. sub markunseen ($) {
  254. my $page=shift;
  255. foreach my $id (keys %feeds) {
  256. if ($feeds{$id}->{sourcepage} eq $page) {
  257. $feeds{$id}->{unseen}=1;
  258. }
  259. }
  260. }
  261. my $state_loaded=0;
  262. sub loadstate () {
  263. return if $state_loaded;
  264. $state_loaded=1;
  265. if (-e "$config{wikistatedir}/aggregate") {
  266. open(IN, "<", "$config{wikistatedir}/aggregate") ||
  267. die "$config{wikistatedir}/aggregate: $!";
  268. while (<IN>) {
  269. $_=IkiWiki::possibly_foolish_untaint($_);
  270. chomp;
  271. my $data={};
  272. foreach my $i (split(/ /, $_)) {
  273. my ($field, $val)=split(/=/, $i, 2);
  274. if ($field eq "name" || $field eq "feed" ||
  275. $field eq "guid" || $field eq "message") {
  276. $data->{$field}=decode_entities($val, " \t\n");
  277. }
  278. elsif ($field eq "tag") {
  279. push @{$data->{tags}}, $val;
  280. }
  281. else {
  282. $data->{$field}=$val;
  283. }
  284. }
  285. if (exists $data->{name}) {
  286. $feeds{$data->{name}}=$data;
  287. }
  288. elsif (exists $data->{guid}) {
  289. $guids{$data->{guid}}=$data;
  290. }
  291. }
  292. close IN;
  293. }
  294. }
  295. sub savestate () {
  296. return unless $state_loaded;
  297. garbage_collect();
  298. my $newfile="$config{wikistatedir}/aggregate.new";
  299. my $cleanup = sub { unlink($newfile) };
  300. open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
  301. foreach my $data (values %feeds, values %guids) {
  302. my @line;
  303. foreach my $field (keys %$data) {
  304. if ($field eq "name" || $field eq "feed" ||
  305. $field eq "guid" || $field eq "message") {
  306. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  307. }
  308. elsif ($field eq "tags") {
  309. push @line, "tag=$_" foreach @{$data->{tags}};
  310. }
  311. else {
  312. push @line, "$field=".$data->{$field}
  313. if defined $data->{$field};
  314. }
  315. }
  316. print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
  317. }
  318. close OUT || error("save $newfile: $!", $cleanup);
  319. rename($newfile, "$config{wikistatedir}/aggregate") ||
  320. error("rename $newfile: $!", $cleanup);
  321. my $timestamp=undef;
  322. foreach my $feed (keys %feeds) {
  323. my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
  324. if (! defined $timestamp || $timestamp > $t) {
  325. $timestamp=$t;
  326. }
  327. }
  328. $newfile=~s/\.new$/time/;
  329. open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
  330. if (defined $timestamp) {
  331. print OUT $timestamp."\n";
  332. }
  333. close OUT || error("save $newfile: $!", $cleanup);
  334. }
  335. sub garbage_collect () {
  336. foreach my $name (keys %feeds) {
  337. # remove any feeds that were not seen while building the pages
  338. # that used to contain them
  339. if ($feeds{$name}->{unseen}) {
  340. delete $feeds{$name};
  341. }
  342. }
  343. foreach my $guid (values %guids) {
  344. # any guid whose feed is gone should be removed
  345. if (! exists $feeds{$guid->{feed}}) {
  346. unlink "$config{srcdir}/".htmlfn($guid->{page})
  347. if exists $guid->{page};
  348. delete $guids{$guid->{guid}};
  349. }
  350. # handle expired guids
  351. elsif ($guid->{expired} && exists $guid->{page}) {
  352. unlink "$config{srcdir}/".htmlfn($guid->{page});
  353. delete $guid->{page};
  354. delete $guid->{md5};
  355. }
  356. }
  357. }
  358. sub mergestate () {
  359. # Load the current state in from disk, and merge into it
  360. # values from the state in memory that might have changed
  361. # during aggregation.
  362. my %myfeeds=%feeds;
  363. my %myguids=%guids;
  364. clearstate();
  365. loadstate();
  366. # All that can change in feed state during aggregation is a few
  367. # fields.
  368. foreach my $name (keys %myfeeds) {
  369. if (exists $feeds{$name}) {
  370. foreach my $field (qw{message lastupdate lasttry
  371. numposts newposts error}) {
  372. $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
  373. }
  374. }
  375. }
  376. # New guids can be created during aggregation.
  377. # Guids have a few fields that may be updated during aggregation.
  378. # It's also possible that guids were removed from the on-disk state
  379. # while the aggregation was in process. That would only happen if
  380. # their feed was also removed, so any removed guids added back here
  381. # will be garbage collected later.
  382. foreach my $guid (keys %myguids) {
  383. if (! exists $guids{$guid}) {
  384. $guids{$guid}=$myguids{$guid};
  385. }
  386. else {
  387. foreach my $field (qw{md5}) {
  388. $guids{$guid}->{$field}=$myguids{$guid}->{$field};
  389. }
  390. }
  391. }
  392. }
  393. sub clearstate () {
  394. %feeds=();
  395. %guids=();
  396. $state_loaded=0;
  397. }
  398. sub expire () {
  399. foreach my $feed (values %feeds) {
  400. next unless $feed->{expireage} || $feed->{expirecount};
  401. my $count=0;
  402. my %seen;
  403. foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
  404. grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
  405. values %guids) {
  406. if ($feed->{expireage}) {
  407. my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
  408. if ($days_old > $feed->{expireage}) {
  409. debug(sprintf(gettext("expiring %s (%s days old)"),
  410. $item->{page}, int($days_old)));
  411. $item->{expired}=1;
  412. }
  413. }
  414. elsif ($feed->{expirecount} &&
  415. $count >= $feed->{expirecount}) {
  416. debug(sprintf(gettext("expiring %s"), $item->{page}));
  417. $item->{expired}=1;
  418. }
  419. else {
  420. if (! $seen{$item->{page}}) {
  421. $seen{$item->{page}}=1;
  422. $count++;
  423. }
  424. }
  425. }
  426. }
  427. }
  428. sub needsaggregate () {
  429. return values %feeds if $config{rebuild};
  430. return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
  431. }
  432. sub aggregate (@) {
  433. eval q{use XML::Feed};
  434. error($@) if $@;
  435. eval q{use URI::Fetch};
  436. error($@) if $@;
  437. foreach my $feed (@_) {
  438. $feed->{lasttry}=time;
  439. $feed->{newposts}=0;
  440. $feed->{message}=sprintf(gettext("last checked %s"),
  441. displaytime($feed->{lasttry}));
  442. $feed->{error}=0;
  443. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  444. if (! length $feed->{feedurl}) {
  445. my @urls=XML::Feed->find_feeds($feed->{url});
  446. if (! @urls) {
  447. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
  448. $feed->{error}=1;
  449. debug($feed->{message});
  450. next;
  451. }
  452. $feed->{feedurl}=pop @urls;
  453. }
  454. my $res=URI::Fetch->fetch($feed->{feedurl});
  455. if (! $res) {
  456. $feed->{message}=URI::Fetch->errstr;
  457. $feed->{error}=1;
  458. debug($feed->{message});
  459. next;
  460. }
  461. # lastupdate is only set if we were able to contact the server
  462. $feed->{lastupdate}=$feed->{lasttry};
  463. if ($res->status == URI::Fetch::URI_GONE()) {
  464. $feed->{message}=gettext("feed not found");
  465. $feed->{error}=1;
  466. debug($feed->{message});
  467. next;
  468. }
  469. my $content=$res->content;
  470. my $f=eval{XML::Feed->parse(\$content)};
  471. if ($@) {
  472. # One common cause of XML::Feed crashing is a feed
  473. # that contains invalid UTF-8 sequences. Convert
  474. # feed to ascii to try to work around.
  475. $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
  476. $f=eval {
  477. $content=Encode::decode_utf8($content, 0);
  478. XML::Feed->parse(\$content)
  479. };
  480. }
  481. if ($@) {
  482. # Another possibility is badly escaped entities.
  483. $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
  484. $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
  485. $f=eval {
  486. $content=Encode::decode_utf8($content, 0);
  487. XML::Feed->parse(\$content)
  488. };
  489. }
  490. if ($@) {
  491. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  492. $feed->{error}=1;
  493. debug($feed->{message});
  494. next;
  495. }
  496. if (! $f) {
  497. $feed->{message}=XML::Feed->errstr;
  498. $feed->{error}=1;
  499. debug($feed->{message});
  500. next;
  501. }
  502. foreach my $entry ($f->entries) {
  503. # XML::Feed doesn't work around XML::Atom's bizarre
  504. # API, so we will. Real unicode strings? Yes please.
  505. # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
  506. local $XML::Atom::ForceUnicode = 1;
  507. my $c=$entry->content;
  508. # atom feeds may have no content, only a summary
  509. if (! defined $c && ref $entry->summary) {
  510. $c=$entry->summary;
  511. }
  512. add_page(
  513. feed => $feed,
  514. copyright => $f->copyright,
  515. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  516. link => $entry->link,
  517. content => (defined $c && defined $c->body) ? $c->body : "",
  518. guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
  519. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  520. base => (defined $c && $c->can("base")) ? $c->base : undef,
  521. );
  522. }
  523. }
  524. }
  525. sub add_page (@) {
  526. my %params=@_;
  527. my $feed=$params{feed};
  528. my $guid={};
  529. my $mtime;
  530. if (exists $guids{$params{guid}}) {
  531. # updating an existing post
  532. $guid=$guids{$params{guid}};
  533. return if $guid->{expired};
  534. }
  535. else {
  536. # new post
  537. $guid->{guid}=$params{guid};
  538. $guids{$params{guid}}=$guid;
  539. $mtime=$params{ctime};
  540. $feed->{numposts}++;
  541. $feed->{newposts}++;
  542. # assign it an unused page
  543. my $page=titlepage($params{title});
  544. # escape slashes and periods in title so it doesn't specify
  545. # directory name or trigger ".." disallowing code.
  546. $page=~s!([/.])!"__".ord($1)."__"!eg;
  547. $page=$feed->{dir}."/".$page;
  548. ($page)=$page=~/$config{wiki_file_regexp}/;
  549. if (! defined $page || ! length $page) {
  550. $page=$feed->{dir}."/item";
  551. }
  552. my $c="";
  553. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  554. -e "$config{srcdir}/".htmlfn($page.$c)) {
  555. $c++
  556. }
  557. # Make sure that the file name isn't too long.
  558. # NB: This doesn't check for path length limits.
  559. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  560. if (defined $max && length(htmlfn($page)) >= $max) {
  561. $c="";
  562. $page=$feed->{dir}."/item";
  563. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  564. -e "$config{srcdir}/".htmlfn($page.$c)) {
  565. $c++
  566. }
  567. }
  568. $guid->{page}=$page;
  569. debug(sprintf(gettext("creating new page %s"), $page));
  570. }
  571. $guid->{feed}=$feed->{name};
  572. # To write or not to write? Need to avoid writing unchanged pages
  573. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  574. # trusted; let's use a digest.
  575. eval q{use Digest::MD5 'md5_hex'};
  576. error($@) if $@;
  577. require Encode;
  578. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  579. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  580. $guid->{md5}=$digest;
  581. # Create the page.
  582. my $template;
  583. eval {
  584. $template=template($feed->{template}, blind_cache => 1);
  585. };
  586. if ($@) {
  587. print STDERR gettext("failed to process template:")." $@";
  588. return;
  589. }
  590. $template->param(title => $params{title})
  591. if defined $params{title} && length($params{title});
  592. $template->param(content => wikiescape(htmlabs($params{content},
  593. defined $params{base} ? $params{base} : $feed->{feedurl})));
  594. $template->param(name => $feed->{name});
  595. $template->param(url => $feed->{url});
  596. $template->param(copyright => $params{copyright})
  597. if defined $params{copyright} && length $params{copyright};
  598. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  599. if defined $params{link};
  600. if (ref $feed->{tags}) {
  601. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  602. }
  603. writefile(htmlfn($guid->{page}), $config{srcdir},
  604. $template->output);
  605. if (defined $mtime && $mtime <= time) {
  606. # Set the mtime, this lets the build process get the right
  607. # creation time on record for the new page.
  608. utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
  609. # Store it in pagectime for expiry code to use also.
  610. $IkiWiki::pagectime{$guid->{page}}=$mtime
  611. unless exists $IkiWiki::pagectime{$guid->{page}};
  612. }
  613. else {
  614. # Dummy value for expiry code.
  615. $IkiWiki::pagectime{$guid->{page}}=time
  616. unless exists $IkiWiki::pagectime{$guid->{page}};
  617. }
  618. }
  619. sub wikiescape ($) {
  620. # escape accidental wikilinks and preprocessor stuff
  621. return encode_entities(shift, '\[\]');
  622. }
  623. sub urlabs ($$) {
  624. my $url=shift;
  625. my $urlbase=shift;
  626. URI->new_abs($url, $urlbase)->as_string;
  627. }
  628. sub htmlabs ($$) {
  629. # Convert links in html from relative to absolute.
  630. # Note that this is a heuristic, which is not specified by the rss
  631. # spec and may not be right for all feeds. Also, see Debian
  632. # bug #381359.
  633. my $html=shift;
  634. my $urlbase=shift;
  635. my $ret="";
  636. my $p = HTML::Parser->new(api_version => 3);
  637. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  638. $p->handler(start => sub {
  639. my ($tagname, $pos, $text) = @_;
  640. if (ref $HTML::Tagset::linkElements{$tagname}) {
  641. while (4 <= @$pos) {
  642. # use attribute sets from right to left
  643. # to avoid invalidating the offsets
  644. # when replacing the values
  645. my($k_offset, $k_len, $v_offset, $v_len) =
  646. splice(@$pos, -4);
  647. my $attrname = lc(substr($text, $k_offset, $k_len));
  648. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  649. next unless $v_offset; # 0 v_offset means no value
  650. my $v = substr($text, $v_offset, $v_len);
  651. $v =~ s/^([\'\"])(.*)\1$/$2/;
  652. my $new_v=urlabs($v, $urlbase);
  653. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  654. substr($text, $v_offset, $v_len) = qq("$new_v");
  655. }
  656. }
  657. $ret.=$text;
  658. }, "tagname, tokenpos, text");
  659. $p->parse($html);
  660. $p->eof;
  661. return $ret;
  662. }
  663. sub htmlfn ($) {
  664. return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
  665. }
  666. my $aggregatelock;
  667. sub lockaggregate () {
  668. # Take an exclusive lock to prevent multiple concurrent aggregators.
  669. # Returns true if the lock was aquired.
  670. if (! -d $config{wikistatedir}) {
  671. mkdir($config{wikistatedir});
  672. }
  673. open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
  674. error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
  675. if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
  676. close($aggregatelock) || error("failed closing aggregatelock: $!");
  677. return 0;
  678. }
  679. return 1;
  680. }
  681. sub unlockaggregate () {
  682. return close($aggregatelock) if $aggregatelock;
  683. return;
  684. }
  685. 1