summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 960d4da990e767837daea2bcfa9de0ff850e6a09 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use open qw{:utf8 :std};
  8. use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
  9. %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
  10. %forcerebuild};
  11. use Exporter q{import};
  12. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  13. bestlink htmllink readfile writefile pagetype srcfile pagename
  14. displaytime will_render gettext
  15. %config %links %renderedfiles %pagesources);
  16. our $VERSION = 1.01; # plugin interface version
  17. # Optimisation.
  18. use Memoize;
  19. memoize("abs2rel");
  20. memoize("pagespec_translate");
  21. memoize("file_pruned");
  22. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  23. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  24. sub defaultconfig () { #{{{
  25. wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./, qr/\.x?html?$/,
  26. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
  27. wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
  28. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  29. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  30. verbose => 0,
  31. syslog => 0,
  32. wikiname => "wiki",
  33. default_pageext => "mdwn",
  34. cgi => 0,
  35. rcs => '',
  36. notify => 0,
  37. url => '',
  38. cgiurl => '',
  39. historyurl => '',
  40. diffurl => '',
  41. anonok => 0,
  42. rss => 0,
  43. atom => 0,
  44. discussion => 1,
  45. rebuild => 0,
  46. refresh => 0,
  47. getctime => 0,
  48. w3mmode => 0,
  49. wrapper => undef,
  50. wrappermode => undef,
  51. svnrepo => undef,
  52. svnpath => "trunk",
  53. srcdir => undef,
  54. destdir => undef,
  55. pingurl => [],
  56. templatedir => "$installdir/share/ikiwiki/templates",
  57. underlaydir => "$installdir/share/ikiwiki/basewiki",
  58. setup => undef,
  59. adminuser => undef,
  60. adminemail => undef,
  61. plugin => [qw{mdwn inline htmlscrubber passwordauth}],
  62. timeformat => '%c',
  63. locale => undef,
  64. sslcookie => 0,
  65. httpauth => 0,
  66. userdir => "",
  67. } #}}}
  68. sub checkconfig () { #{{{
  69. # locale stuff; avoid LC_ALL since it overrides everything
  70. if (defined $ENV{LC_ALL}) {
  71. $ENV{LANG} = $ENV{LC_ALL};
  72. delete $ENV{LC_ALL};
  73. }
  74. if (defined $config{locale}) {
  75. eval q{use POSIX};
  76. error($@) if $@;
  77. $ENV{LANG} = $config{locale}
  78. if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
  79. }
  80. if ($config{w3mmode}) {
  81. eval q{use Cwd q{abs_path}};
  82. error($@) if $@;
  83. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  84. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  85. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  86. unless $config{cgiurl} =~ m!file:///!;
  87. $config{url}="file://".$config{destdir};
  88. }
  89. if ($config{cgi} && ! length $config{url}) {
  90. error(gettext("Must specify url to wiki with --url when using --cgi"));
  91. }
  92. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  93. unless exists $config{wikistatedir};
  94. if ($config{rcs}) {
  95. eval qq{require IkiWiki::Rcs::$config{rcs}};
  96. if ($@) {
  97. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  98. }
  99. }
  100. else {
  101. require IkiWiki::Rcs::Stub;
  102. }
  103. run_hooks(checkconfig => sub { shift->() });
  104. } #}}}
  105. sub loadplugins () { #{{{
  106. loadplugin($_) foreach @{$config{plugin}};
  107. run_hooks(getopt => sub { shift->() });
  108. if (grep /^-/, @ARGV) {
  109. print STDERR "Unknown option: $_\n"
  110. foreach grep /^-/, @ARGV;
  111. usage();
  112. }
  113. } #}}}
  114. sub loadplugin ($) { #{{{
  115. my $plugin=shift;
  116. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  117. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  118. eval qq{use $mod};
  119. if ($@) {
  120. error("Failed to load plugin $mod: $@");
  121. }
  122. } #}}}
  123. sub error ($) { #{{{
  124. if ($config{cgi}) {
  125. print "Content-type: text/html\n\n";
  126. print misctemplate(gettext("Error"),
  127. "<p>".gettext("Error").": @_</p>");
  128. }
  129. log_message(error => @_);
  130. exit(1);
  131. } #}}}
  132. sub debug ($) { #{{{
  133. return unless $config{verbose};
  134. log_message(debug => @_);
  135. } #}}}
  136. my $log_open=0;
  137. sub log_message ($$) { #{{{
  138. my $type=shift;
  139. if ($config{syslog}) {
  140. require Sys::Syslog;
  141. unless ($log_open) {
  142. Sys::Syslog::setlogsock('unix');
  143. Sys::Syslog::openlog('ikiwiki', '', 'user');
  144. $log_open=1;
  145. }
  146. eval {
  147. Sys::Syslog::syslog($type, join(" ", @_));
  148. }
  149. }
  150. elsif (! $config{cgi}) {
  151. print "@_\n";
  152. }
  153. else {
  154. print STDERR "@_\n";
  155. }
  156. } #}}}
  157. sub possibly_foolish_untaint ($) { #{{{
  158. my $tainted=shift;
  159. my ($untainted)=$tainted=~/(.*)/;
  160. return $untainted;
  161. } #}}}
  162. sub basename ($) { #{{{
  163. my $file=shift;
  164. $file=~s!.*/+!!;
  165. return $file;
  166. } #}}}
  167. sub dirname ($) { #{{{
  168. my $file=shift;
  169. $file=~s!/*[^/]+$!!;
  170. return $file;
  171. } #}}}
  172. sub pagetype ($) { #{{{
  173. my $page=shift;
  174. if ($page =~ /\.([^.]+)$/) {
  175. return $1 if exists $hooks{htmlize}{$1};
  176. }
  177. return undef;
  178. } #}}}
  179. sub pagename ($) { #{{{
  180. my $file=shift;
  181. my $type=pagetype($file);
  182. my $page=$file;
  183. $page=~s/\Q.$type\E*$// if defined $type;
  184. return $page;
  185. } #}}}
  186. sub htmlpage ($) { #{{{
  187. my $page=shift;
  188. return $page.".html";
  189. } #}}}
  190. sub srcfile ($) { #{{{
  191. my $file=shift;
  192. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  193. return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
  194. error("internal error: $file cannot be found");
  195. } #}}}
  196. sub readfile ($;$) { #{{{
  197. my $file=shift;
  198. my $binary=shift;
  199. if (-l $file) {
  200. error("cannot read a symlink ($file)");
  201. }
  202. local $/=undef;
  203. open (IN, $file) || error("failed to read $file: $!");
  204. binmode(IN) if ($binary);
  205. my $ret=<IN>;
  206. close IN;
  207. return $ret;
  208. } #}}}
  209. sub writefile ($$$;$) { #{{{
  210. my $file=shift; # can include subdirs
  211. my $destdir=shift; # directory to put file in
  212. my $content=shift;
  213. my $binary=shift;
  214. my $test=$file;
  215. while (length $test) {
  216. if (-l "$destdir/$test") {
  217. error("cannot write to a symlink ($test)");
  218. }
  219. $test=dirname($test);
  220. }
  221. my $dir=dirname("$destdir/$file");
  222. if (! -d $dir) {
  223. my $d="";
  224. foreach my $s (split(m!/+!, $dir)) {
  225. $d.="$s/";
  226. if (! -d $d) {
  227. mkdir($d) || error("failed to create directory $d: $!");
  228. }
  229. }
  230. }
  231. open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
  232. binmode(OUT) if ($binary);
  233. print OUT $content;
  234. close OUT;
  235. } #}}}
  236. my %cleared;
  237. sub will_render ($$;$) { #{{{
  238. my $page=shift;
  239. my $dest=shift;
  240. my $clear=shift;
  241. # Important security check.
  242. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  243. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  244. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  245. }
  246. if (! $clear || $cleared{$page}) {
  247. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  248. }
  249. else {
  250. $renderedfiles{$page}=[$dest];
  251. $cleared{$page}=1;
  252. }
  253. } #}}}
  254. sub bestlink ($$) { #{{{
  255. my $page=shift;
  256. my $link=shift;
  257. my $cwd=$page;
  258. if ($link=~s/^\/+//) {
  259. # absolute links
  260. $cwd="";
  261. }
  262. do {
  263. my $l=$cwd;
  264. $l.="/" if length $l;
  265. $l.=$link;
  266. if (exists $links{$l}) {
  267. return $l;
  268. }
  269. elsif (exists $pagecase{lc $l}) {
  270. return $pagecase{lc $l};
  271. }
  272. } while $cwd=~s!/?[^/]+$!!;
  273. if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
  274. return $links{"$config{userdir}/".lc($link)};
  275. }
  276. #print STDERR "warning: page $page, broken link: $link\n";
  277. return "";
  278. } #}}}
  279. sub isinlinableimage ($) { #{{{
  280. my $file=shift;
  281. $file=~/\.(png|gif|jpg|jpeg)$/i;
  282. } #}}}
  283. sub pagetitle ($;$) { #{{{
  284. my $page=shift;
  285. my $unescaped=shift;
  286. if ($unescaped) {
  287. $page=~s/__(\d+)__/chr($1)/eg;
  288. }
  289. else {
  290. $page=~s/__(\d+)__/&#$1;/g;
  291. }
  292. $page=~y/_/ /;
  293. return $page;
  294. } #}}}
  295. sub titlepage ($) { #{{{
  296. my $title=shift;
  297. $title=~y/ /_/;
  298. $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
  299. return $title;
  300. } #}}}
  301. sub cgiurl (@) { #{{{
  302. my %params=@_;
  303. return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
  304. } #}}}
  305. sub baseurl (;$) { #{{{
  306. my $page=shift;
  307. return "$config{url}/" if ! defined $page;
  308. $page=~s/[^\/]+$//;
  309. $page=~s/[^\/]+\//..\//g;
  310. return $page;
  311. } #}}}
  312. sub abs2rel ($$) { #{{{
  313. # Work around very innefficient behavior in File::Spec if abs2rel
  314. # is passed two relative paths. It's much faster if paths are
  315. # absolute! (Debian bug #376658; fixed in debian unstable now)
  316. my $path="/".shift;
  317. my $base="/".shift;
  318. require File::Spec;
  319. my $ret=File::Spec->abs2rel($path, $base);
  320. $ret=~s/^// if defined $ret;
  321. return $ret;
  322. } #}}}
  323. sub displaytime ($) { #{{{
  324. my $time=shift;
  325. eval q{use POSIX};
  326. error($@) if $@;
  327. # strftime doesn't know about encodings, so make sure
  328. # its output is properly treated as utf8
  329. return decode_utf8(POSIX::strftime(
  330. $config{timeformat}, localtime($time)));
  331. } #}}}
  332. sub htmllink ($$$;$$$) { #{{{
  333. my $lpage=shift; # the page doing the linking
  334. my $page=shift; # the page that will contain the link (different for inline)
  335. my $link=shift;
  336. my $noimageinline=shift; # don't turn links into inline html images
  337. my $forcesubpage=shift; # force a link to a subpage
  338. my $linktext=shift; # set to force the link text to something
  339. my $bestlink;
  340. if (! $forcesubpage) {
  341. $bestlink=bestlink($lpage, $link);
  342. }
  343. else {
  344. $bestlink="$lpage/".lc($link);
  345. }
  346. $linktext=pagetitle(basename($link)) unless defined $linktext;
  347. return "<span class=\"selflink\">$linktext</span>"
  348. if length $bestlink && $page eq $bestlink;
  349. if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
  350. $bestlink=htmlpage($bestlink);
  351. }
  352. if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
  353. return $linktext unless length $config{cgiurl};
  354. return "<span><a href=\"".
  355. cgiurl(do => "create", page => lc($link), from => $page).
  356. "\">?</a>$linktext</span>"
  357. }
  358. $bestlink=abs2rel($bestlink, dirname($page));
  359. if (! $noimageinline && isinlinableimage($bestlink)) {
  360. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  361. }
  362. return "<a href=\"$bestlink\">$linktext</a>";
  363. } #}}}
  364. sub htmlize ($$$) { #{{{
  365. my $page=shift;
  366. my $type=shift;
  367. my $content=shift;
  368. if (exists $hooks{htmlize}{$type}) {
  369. $content=$hooks{htmlize}{$type}{call}->(
  370. page => $page,
  371. content => $content,
  372. );
  373. }
  374. else {
  375. error("htmlization of $type not supported");
  376. }
  377. run_hooks(sanitize => sub {
  378. $content=shift->(
  379. page => $page,
  380. content => $content,
  381. );
  382. });
  383. return $content;
  384. } #}}}
  385. sub linkify ($$$) { #{{{
  386. my $lpage=shift; # the page containing the links
  387. my $page=shift; # the page the link will end up on (different for inline)
  388. my $content=shift;
  389. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  390. $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
  391. : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
  392. }eg;
  393. return $content;
  394. } #}}}
  395. my %preprocessing;
  396. sub preprocess ($$$;$) { #{{{
  397. my $page=shift; # the page the data comes from
  398. my $destpage=shift; # the page the data will appear in (different for inline)
  399. my $content=shift;
  400. my $scan=shift;
  401. my $handle=sub {
  402. my $escape=shift;
  403. my $command=shift;
  404. my $params=shift;
  405. if (length $escape) {
  406. return "[[$command $params]]";
  407. }
  408. elsif (exists $hooks{preprocess}{$command}) {
  409. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  410. # Note: preserve order of params, some plugins may
  411. # consider it significant.
  412. my @params;
  413. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  414. my $key=$1;
  415. my $val;
  416. if (defined $2) {
  417. $val=$2;
  418. $val=~s/\r\n/\n/mg;
  419. $val=~s/^\n+//g;
  420. $val=~s/\n+$//g;
  421. }
  422. elsif (defined $3) {
  423. $val=$3;
  424. }
  425. elsif (defined $4) {
  426. $val=$4;
  427. }
  428. if (defined $key) {
  429. push @params, $key, $val;
  430. }
  431. else {
  432. push @params, $val, '';
  433. }
  434. }
  435. if ($preprocessing{$page}++ > 3) {
  436. # Avoid loops of preprocessed pages preprocessing
  437. # other pages that preprocess them, etc.
  438. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  439. $command, $page, $preprocessing{$page}).
  440. "]]";
  441. }
  442. my $ret=$hooks{preprocess}{$command}{call}->(
  443. @params,
  444. page => $page,
  445. destpage => $destpage,
  446. );
  447. $preprocessing{$page}--;
  448. return $ret;
  449. }
  450. else {
  451. return "[[$command $params]]";
  452. }
  453. };
  454. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  455. return $content;
  456. } #}}}
  457. sub filter ($$) { #{{{
  458. my $page=shift;
  459. my $content=shift;
  460. run_hooks(filter => sub {
  461. $content=shift->(page => $page, content => $content);
  462. });
  463. return $content;
  464. } #}}}
  465. sub indexlink () { #{{{
  466. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  467. } #}}}
  468. sub lockwiki () { #{{{
  469. # Take an exclusive lock on the wiki to prevent multiple concurrent
  470. # run issues. The lock will be dropped on program exit.
  471. if (! -d $config{wikistatedir}) {
  472. mkdir($config{wikistatedir});
  473. }
  474. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  475. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  476. if (! flock(WIKILOCK, 2 | 4)) {
  477. debug("wiki seems to be locked, waiting for lock");
  478. my $wait=600; # arbitrary, but don't hang forever to
  479. # prevent process pileup
  480. for (1..600) {
  481. return if flock(WIKILOCK, 2 | 4);
  482. sleep 1;
  483. }
  484. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  485. }
  486. } #}}}
  487. sub unlockwiki () { #{{{
  488. close WIKILOCK;
  489. } #}}}
  490. sub loadindex () { #{{{
  491. open (IN, "$config{wikistatedir}/index") || return;
  492. while (<IN>) {
  493. $_=possibly_foolish_untaint($_);
  494. chomp;
  495. my %items;
  496. $items{link}=[];
  497. $items{dest}=[];
  498. foreach my $i (split(/ /, $_)) {
  499. my ($item, $val)=split(/=/, $i, 2);
  500. push @{$items{$item}}, decode_entities($val);
  501. }
  502. next unless exists $items{src}; # skip bad lines for now
  503. my $page=pagename($items{src}[0]);
  504. if (! $config{rebuild}) {
  505. $pagesources{$page}=$items{src}[0];
  506. $oldpagemtime{$page}=$items{mtime}[0];
  507. $oldlinks{$page}=[@{$items{link}}];
  508. $links{$page}=[@{$items{link}}];
  509. $depends{$page}=$items{depends}[0] if exists $items{depends};
  510. $renderedfiles{$page}=[@{$items{dest}}];
  511. $oldrenderedfiles{$page}=[@{$items{dest}}];
  512. $pagecase{lc $page}=$page;
  513. }
  514. $pagectime{$page}=$items{ctime}[0];
  515. }
  516. close IN;
  517. } #}}}
  518. sub saveindex () { #{{{
  519. run_hooks(savestate => sub { shift->() });
  520. if (! -d $config{wikistatedir}) {
  521. mkdir($config{wikistatedir});
  522. }
  523. open (OUT, ">$config{wikistatedir}/index") ||
  524. error("cannot write to $config{wikistatedir}/index: $!");
  525. foreach my $page (keys %oldpagemtime) {
  526. next unless $oldpagemtime{$page};
  527. my $line="mtime=$oldpagemtime{$page} ".
  528. "ctime=$pagectime{$page} ".
  529. "src=$pagesources{$page}";
  530. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  531. my %count;
  532. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  533. if (exists $depends{$page}) {
  534. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  535. }
  536. print OUT $line."\n";
  537. }
  538. close OUT;
  539. } #}}}
  540. sub template_params (@) { #{{{
  541. my $filename=shift;
  542. require HTML::Template;
  543. return filter => sub {
  544. my $text_ref = shift;
  545. $$text_ref=&Encode::decode_utf8($$text_ref);
  546. },
  547. filename => "$config{templatedir}/$filename",
  548. loop_context_vars => 1,
  549. die_on_bad_params => 0,
  550. @_;
  551. } #}}}
  552. sub template ($;@) { #{{{
  553. HTML::Template->new(template_params(@_));
  554. } #}}}
  555. sub misctemplate ($$;@) { #{{{
  556. my $title=shift;
  557. my $pagebody=shift;
  558. my $template=template("misc.tmpl");
  559. $template->param(
  560. title => $title,
  561. indexlink => indexlink(),
  562. wikiname => $config{wikiname},
  563. pagebody => $pagebody,
  564. baseurl => baseurl(),
  565. @_,
  566. );
  567. run_hooks(pagetemplate => sub {
  568. shift->(page => "", destpage => "", template => $template);
  569. });
  570. return $template->output;
  571. }#}}}
  572. sub hook (@) { # {{{
  573. my %param=@_;
  574. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  575. error "hook requires type, call, and id parameters";
  576. }
  577. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  578. $hooks{$param{type}}{$param{id}}=\%param;
  579. } # }}}
  580. sub run_hooks ($$) { # {{{
  581. # Calls the given sub for each hook of the given type,
  582. # passing it the hook function to call.
  583. my $type=shift;
  584. my $sub=shift;
  585. if (exists $hooks{$type}) {
  586. my @deferred;
  587. foreach my $id (keys %{$hooks{$type}}) {
  588. if ($hooks{$type}{$id}{last}) {
  589. push @deferred, $id;
  590. next;
  591. }
  592. $sub->($hooks{$type}{$id}{call});
  593. }
  594. foreach my $id (@deferred) {
  595. $sub->($hooks{$type}{$id}{call});
  596. }
  597. }
  598. } #}}}
  599. sub globlist_to_pagespec ($) { #{{{
  600. my @globlist=split(' ', shift);
  601. my (@spec, @skip);
  602. foreach my $glob (@globlist) {
  603. if ($glob=~/^!(.*)/) {
  604. push @skip, $glob;
  605. }
  606. else {
  607. push @spec, $glob;
  608. }
  609. }
  610. my $spec=join(" or ", @spec);
  611. if (@skip) {
  612. my $skip=join(" and ", @skip);
  613. if (length $spec) {
  614. $spec="$skip and ($spec)";
  615. }
  616. else {
  617. $spec=$skip;
  618. }
  619. }
  620. return $spec;
  621. } #}}}
  622. sub is_globlist ($) { #{{{
  623. my $s=shift;
  624. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  625. } #}}}
  626. sub safequote ($) { #{{{
  627. my $s=shift;
  628. $s=~s/[{}]//g;
  629. return "q{$s}";
  630. } #}}}
  631. sub pagespec_merge ($$) { #{{{
  632. my $a=shift;
  633. my $b=shift;
  634. return $a if $a eq $b;
  635. # Support for old-style GlobLists.
  636. if (is_globlist($a)) {
  637. $a=globlist_to_pagespec($a);
  638. }
  639. if (is_globlist($b)) {
  640. $b=globlist_to_pagespec($b);
  641. }
  642. return "($a) or ($b)";
  643. } #}}}
  644. sub pagespec_translate ($) { #{{{
  645. # This assumes that $page is in scope in the function
  646. # that evalulates the translated pagespec code.
  647. my $spec=shift;
  648. # Support for old-style GlobLists.
  649. if (is_globlist($spec)) {
  650. $spec=globlist_to_pagespec($spec);
  651. }
  652. # Convert spec to perl code.
  653. my $code="";
  654. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  655. my $word=$1;
  656. if (lc $word eq "and") {
  657. $code.=" &&";
  658. }
  659. elsif (lc $word eq "or") {
  660. $code.=" ||";
  661. }
  662. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  663. $code.=" ".$word;
  664. }
  665. elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
  666. $code.=" match_$1(\$page, ".safequote($2).")";
  667. }
  668. else {
  669. $code.=" match_glob(\$page, ".safequote($word).")";
  670. }
  671. }
  672. return $code;
  673. } #}}}
  674. sub add_depends ($$) { #{{{
  675. my $page=shift;
  676. my $pagespec=shift;
  677. if (! exists $depends{$page}) {
  678. $depends{$page}=$pagespec;
  679. }
  680. else {
  681. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  682. }
  683. } # }}}
  684. sub file_pruned ($$) { #{{{
  685. require File::Spec;
  686. my $file=File::Spec->canonpath(shift);
  687. my $base=File::Spec->canonpath(shift);
  688. $file=~s#^\Q$base\E/*##;
  689. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  690. $file =~ m/$regexp/;
  691. } #}}}
  692. sub gettext { #{{{
  693. # Only use gettext in the rare cases it's needed.
  694. # This overrides future calls of this function.
  695. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  696. eval q{use Locale::gettext};
  697. textdomain('ikiwiki');
  698. return Locale::gettext::gettext(shift);
  699. }
  700. else {
  701. return shift;
  702. }
  703. } #}}}
  704. sub pagespec_match ($$) { #{{{
  705. my $page=shift;
  706. my $spec=shift;
  707. return eval pagespec_translate($spec);
  708. } #}}}
  709. sub match_glob ($$) { #{{{
  710. my $page=shift;
  711. my $glob=shift;
  712. # turn glob into safe regexp
  713. $glob=quotemeta($glob);
  714. $glob=~s/\\\*/.*/g;
  715. $glob=~s/\\\?/./g;
  716. return $page=~/^$glob$/i;
  717. } #}}}
  718. sub match_link ($$) { #{{{
  719. my $page=shift;
  720. my $link=lc(shift);
  721. my $links = $links{$page} or return undef;
  722. foreach my $p (@$links) {
  723. return 1 if lc $p eq $link;
  724. }
  725. return 0;
  726. } #}}}
  727. sub match_backlink ($$) { #{{{
  728. match_link(pop, pop);
  729. } #}}}
  730. sub match_created_before ($$) { #{{{
  731. my $page=shift;
  732. my $testpage=shift;
  733. if (exists $pagectime{$testpage}) {
  734. return $pagectime{$page} < $pagectime{$testpage};
  735. }
  736. else {
  737. return 0;
  738. }
  739. } #}}}
  740. sub match_created_after ($$) { #{{{
  741. my $page=shift;
  742. my $testpage=shift;
  743. if (exists $pagectime{$testpage}) {
  744. return $pagectime{$page} > $pagectime{$testpage};
  745. }
  746. else {
  747. return 0;
  748. }
  749. } #}}}
  750. sub match_creation_day ($$) { #{{{
  751. return ((gmtime($pagectime{shift()}))[3] == shift);
  752. } #}}}
  753. sub match_creation_month ($$) { #{{{
  754. return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
  755. } #}}}
  756. sub match_creation_year ($$) { #{{{
  757. return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
  758. } #}}}
  759. 1