summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: 7789c4c2a9d38b7e616d9d3b4df8e4d96fe74ec6 (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. 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=template($feed->{template}, blind_cache => 1);
  582. $template->param(title => $params{title})
  583. if defined $params{title} && length($params{title});
  584. $template->param(content => wikiescape(htmlabs($params{content},
  585. defined $params{base} ? $params{base} : $feed->{feedurl})));
  586. $template->param(name => $feed->{name});
  587. $template->param(url => $feed->{url});
  588. $template->param(copyright => $params{copyright})
  589. if defined $params{copyright} && length $params{copyright};
  590. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  591. if defined $params{link};
  592. if (ref $feed->{tags}) {
  593. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  594. }
  595. writefile(htmlfn($guid->{page}), $config{srcdir},
  596. $template->output);
  597. if (defined $mtime && $mtime <= time) {
  598. # Set the mtime, this lets the build process get the right
  599. # creation time on record for the new page.
  600. utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
  601. # Store it in pagectime for expiry code to use also.
  602. $IkiWiki::pagectime{$guid->{page}}=$mtime
  603. unless exists $IkiWiki::pagectime{$guid->{page}};
  604. }
  605. else {
  606. # Dummy value for expiry code.
  607. $IkiWiki::pagectime{$guid->{page}}=time
  608. unless exists $IkiWiki::pagectime{$guid->{page}};
  609. }
  610. }
  611. sub wikiescape ($) {
  612. # escape accidental wikilinks and preprocessor stuff
  613. return encode_entities(shift, '\[\]');
  614. }
  615. sub urlabs ($$) {
  616. my $url=shift;
  617. my $urlbase=shift;
  618. URI->new_abs($url, $urlbase)->as_string;
  619. }
  620. sub htmlabs ($$) {
  621. # Convert links in html from relative to absolute.
  622. # Note that this is a heuristic, which is not specified by the rss
  623. # spec and may not be right for all feeds. Also, see Debian
  624. # bug #381359.
  625. my $html=shift;
  626. my $urlbase=shift;
  627. my $ret="";
  628. my $p = HTML::Parser->new(api_version => 3);
  629. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  630. $p->handler(start => sub {
  631. my ($tagname, $pos, $text) = @_;
  632. if (ref $HTML::Tagset::linkElements{$tagname}) {
  633. while (4 <= @$pos) {
  634. # use attribute sets from right to left
  635. # to avoid invalidating the offsets
  636. # when replacing the values
  637. my($k_offset, $k_len, $v_offset, $v_len) =
  638. splice(@$pos, -4);
  639. my $attrname = lc(substr($text, $k_offset, $k_len));
  640. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  641. next unless $v_offset; # 0 v_offset means no value
  642. my $v = substr($text, $v_offset, $v_len);
  643. $v =~ s/^([\'\"])(.*)\1$/$2/;
  644. my $new_v=urlabs($v, $urlbase);
  645. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  646. substr($text, $v_offset, $v_len) = qq("$new_v");
  647. }
  648. }
  649. $ret.=$text;
  650. }, "tagname, tokenpos, text");
  651. $p->parse($html);
  652. $p->eof;
  653. return $ret;
  654. }
  655. sub htmlfn ($) {
  656. return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
  657. }
  658. my $aggregatelock;
  659. sub lockaggregate () {
  660. # Take an exclusive lock to prevent multiple concurrent aggregators.
  661. # Returns true if the lock was aquired.
  662. if (! -d $config{wikistatedir}) {
  663. mkdir($config{wikistatedir});
  664. }
  665. open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
  666. error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
  667. if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
  668. close($aggregatelock) || error("failed closing aggregatelock: $!");
  669. return 0;
  670. }
  671. return 1;
  672. }
  673. sub unlockaggregate () {
  674. return close($aggregatelock) if $aggregatelock;
  675. return;
  676. }
  677. 1