summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 43ef67e8c9ce6ea4824977528a602533962cd47c (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_ALL, $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 "$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. #translators: The first parameter is a
  439. #translators: preprocessor directive name,
  440. #translators: the second a page name, the
  441. #translators: third a number.
  442. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  443. $command, $page, $preprocessing{$page}).
  444. "]]";
  445. }
  446. my $ret=$hooks{preprocess}{$command}{call}->(
  447. @params,
  448. page => $page,
  449. destpage => $destpage,
  450. );
  451. $preprocessing{$page}--;
  452. return $ret;
  453. }
  454. else {
  455. return "[[$command $params]]";
  456. }
  457. };
  458. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  459. return $content;
  460. } #}}}
  461. sub filter ($$) { #{{{
  462. my $page=shift;
  463. my $content=shift;
  464. run_hooks(filter => sub {
  465. $content=shift->(page => $page, content => $content);
  466. });
  467. return $content;
  468. } #}}}
  469. sub indexlink () { #{{{
  470. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  471. } #}}}
  472. sub lockwiki () { #{{{
  473. # Take an exclusive lock on the wiki to prevent multiple concurrent
  474. # run issues. The lock will be dropped on program exit.
  475. if (! -d $config{wikistatedir}) {
  476. mkdir($config{wikistatedir});
  477. }
  478. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  479. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  480. if (! flock(WIKILOCK, 2 | 4)) {
  481. debug("wiki seems to be locked, waiting for lock");
  482. my $wait=600; # arbitrary, but don't hang forever to
  483. # prevent process pileup
  484. for (1..600) {
  485. return if flock(WIKILOCK, 2 | 4);
  486. sleep 1;
  487. }
  488. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  489. }
  490. } #}}}
  491. sub unlockwiki () { #{{{
  492. close WIKILOCK;
  493. } #}}}
  494. sub loadindex () { #{{{
  495. open (IN, "$config{wikistatedir}/index") || return;
  496. while (<IN>) {
  497. $_=possibly_foolish_untaint($_);
  498. chomp;
  499. my %items;
  500. $items{link}=[];
  501. $items{dest}=[];
  502. foreach my $i (split(/ /, $_)) {
  503. my ($item, $val)=split(/=/, $i, 2);
  504. push @{$items{$item}}, decode_entities($val);
  505. }
  506. next unless exists $items{src}; # skip bad lines for now
  507. my $page=pagename($items{src}[0]);
  508. if (! $config{rebuild}) {
  509. $pagesources{$page}=$items{src}[0];
  510. $oldpagemtime{$page}=$items{mtime}[0];
  511. $oldlinks{$page}=[@{$items{link}}];
  512. $links{$page}=[@{$items{link}}];
  513. $depends{$page}=$items{depends}[0] if exists $items{depends};
  514. $renderedfiles{$page}=[@{$items{dest}}];
  515. $oldrenderedfiles{$page}=[@{$items{dest}}];
  516. $pagecase{lc $page}=$page;
  517. }
  518. $pagectime{$page}=$items{ctime}[0];
  519. }
  520. close IN;
  521. } #}}}
  522. sub saveindex () { #{{{
  523. run_hooks(savestate => sub { shift->() });
  524. if (! -d $config{wikistatedir}) {
  525. mkdir($config{wikistatedir});
  526. }
  527. open (OUT, ">$config{wikistatedir}/index") ||
  528. error("cannot write to $config{wikistatedir}/index: $!");
  529. foreach my $page (keys %oldpagemtime) {
  530. next unless $oldpagemtime{$page};
  531. my $line="mtime=$oldpagemtime{$page} ".
  532. "ctime=$pagectime{$page} ".
  533. "src=$pagesources{$page}";
  534. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  535. my %count;
  536. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  537. if (exists $depends{$page}) {
  538. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  539. }
  540. print OUT $line."\n";
  541. }
  542. close OUT;
  543. } #}}}
  544. sub template_params (@) { #{{{
  545. my $filename=shift;
  546. require HTML::Template;
  547. return filter => sub {
  548. my $text_ref = shift;
  549. $$text_ref=&Encode::decode_utf8($$text_ref);
  550. },
  551. filename => "$config{templatedir}/$filename",
  552. loop_context_vars => 1,
  553. die_on_bad_params => 0,
  554. @_;
  555. } #}}}
  556. sub template ($;@) { #{{{
  557. HTML::Template->new(template_params(@_));
  558. } #}}}
  559. sub misctemplate ($$;@) { #{{{
  560. my $title=shift;
  561. my $pagebody=shift;
  562. my $template=template("misc.tmpl");
  563. $template->param(
  564. title => $title,
  565. indexlink => indexlink(),
  566. wikiname => $config{wikiname},
  567. pagebody => $pagebody,
  568. baseurl => baseurl(),
  569. @_,
  570. );
  571. run_hooks(pagetemplate => sub {
  572. shift->(page => "", destpage => "", template => $template);
  573. });
  574. return $template->output;
  575. }#}}}
  576. sub hook (@) { # {{{
  577. my %param=@_;
  578. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  579. error "hook requires type, call, and id parameters";
  580. }
  581. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  582. $hooks{$param{type}}{$param{id}}=\%param;
  583. } # }}}
  584. sub run_hooks ($$) { # {{{
  585. # Calls the given sub for each hook of the given type,
  586. # passing it the hook function to call.
  587. my $type=shift;
  588. my $sub=shift;
  589. if (exists $hooks{$type}) {
  590. my @deferred;
  591. foreach my $id (keys %{$hooks{$type}}) {
  592. if ($hooks{$type}{$id}{last}) {
  593. push @deferred, $id;
  594. next;
  595. }
  596. $sub->($hooks{$type}{$id}{call});
  597. }
  598. foreach my $id (@deferred) {
  599. $sub->($hooks{$type}{$id}{call});
  600. }
  601. }
  602. } #}}}
  603. sub globlist_to_pagespec ($) { #{{{
  604. my @globlist=split(' ', shift);
  605. my (@spec, @skip);
  606. foreach my $glob (@globlist) {
  607. if ($glob=~/^!(.*)/) {
  608. push @skip, $glob;
  609. }
  610. else {
  611. push @spec, $glob;
  612. }
  613. }
  614. my $spec=join(" or ", @spec);
  615. if (@skip) {
  616. my $skip=join(" and ", @skip);
  617. if (length $spec) {
  618. $spec="$skip and ($spec)";
  619. }
  620. else {
  621. $spec=$skip;
  622. }
  623. }
  624. return $spec;
  625. } #}}}
  626. sub is_globlist ($) { #{{{
  627. my $s=shift;
  628. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  629. } #}}}
  630. sub safequote ($) { #{{{
  631. my $s=shift;
  632. $s=~s/[{}]//g;
  633. return "q{$s}";
  634. } #}}}
  635. sub pagespec_merge ($$) { #{{{
  636. my $a=shift;
  637. my $b=shift;
  638. return $a if $a eq $b;
  639. # Support for old-style GlobLists.
  640. if (is_globlist($a)) {
  641. $a=globlist_to_pagespec($a);
  642. }
  643. if (is_globlist($b)) {
  644. $b=globlist_to_pagespec($b);
  645. }
  646. return "($a) or ($b)";
  647. } #}}}
  648. sub pagespec_translate ($) { #{{{
  649. # This assumes that $page is in scope in the function
  650. # that evalulates the translated pagespec code.
  651. my $spec=shift;
  652. # Support for old-style GlobLists.
  653. if (is_globlist($spec)) {
  654. $spec=globlist_to_pagespec($spec);
  655. }
  656. # Convert spec to perl code.
  657. my $code="";
  658. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  659. my $word=$1;
  660. if (lc $word eq "and") {
  661. $code.=" &&";
  662. }
  663. elsif (lc $word eq "or") {
  664. $code.=" ||";
  665. }
  666. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  667. $code.=" ".$word;
  668. }
  669. elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
  670. $code.=" match_$1(\$page, ".safequote($2).")";
  671. }
  672. else {
  673. $code.=" match_glob(\$page, ".safequote($word).")";
  674. }
  675. }
  676. return $code;
  677. } #}}}
  678. sub add_depends ($$) { #{{{
  679. my $page=shift;
  680. my $pagespec=shift;
  681. if (! exists $depends{$page}) {
  682. $depends{$page}=$pagespec;
  683. }
  684. else {
  685. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  686. }
  687. } # }}}
  688. sub file_pruned ($$) { #{{{
  689. require File::Spec;
  690. my $file=File::Spec->canonpath(shift);
  691. my $base=File::Spec->canonpath(shift);
  692. $file=~s#^\Q$base\E/*##;
  693. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  694. $file =~ m/$regexp/;
  695. } #}}}
  696. my $gettext_obj;
  697. sub gettext { #{{{
  698. # Only use gettext in the rare cases it's needed.
  699. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  700. if (! $gettext_obj) {
  701. eval q{use Locale::gettext ''};
  702. $gettext_obj=Locale::gettext->domain('ikiwiki');
  703. }
  704. return $gettext_obj->get(shift);
  705. }
  706. else {
  707. return shift;
  708. }
  709. } #}}}
  710. sub pagespec_match ($$) { #{{{
  711. my $page=shift;
  712. my $spec=shift;
  713. return eval pagespec_translate($spec);
  714. } #}}}
  715. sub match_glob ($$) { #{{{
  716. my $page=shift;
  717. my $glob=shift;
  718. # turn glob into safe regexp
  719. $glob=quotemeta($glob);
  720. $glob=~s/\\\*/.*/g;
  721. $glob=~s/\\\?/./g;
  722. return $page=~/^$glob$/i;
  723. } #}}}
  724. sub match_link ($$) { #{{{
  725. my $page=shift;
  726. my $link=lc(shift);
  727. my $links = $links{$page} or return undef;
  728. foreach my $p (@$links) {
  729. return 1 if lc $p eq $link;
  730. }
  731. return 0;
  732. } #}}}
  733. sub match_backlink ($$) { #{{{
  734. match_link(pop, pop);
  735. } #}}}
  736. sub match_created_before ($$) { #{{{
  737. my $page=shift;
  738. my $testpage=shift;
  739. if (exists $pagectime{$testpage}) {
  740. return $pagectime{$page} < $pagectime{$testpage};
  741. }
  742. else {
  743. return 0;
  744. }
  745. } #}}}
  746. sub match_created_after ($$) { #{{{
  747. my $page=shift;
  748. my $testpage=shift;
  749. if (exists $pagectime{$testpage}) {
  750. return $pagectime{$page} > $pagectime{$testpage};
  751. }
  752. else {
  753. return 0;
  754. }
  755. } #}}}
  756. sub match_creation_day ($$) { #{{{
  757. return ((gmtime($pagectime{shift()}))[3] == shift);
  758. } #}}}
  759. sub match_creation_month ($$) { #{{{
  760. return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
  761. } #}}}
  762. sub match_creation_year ($$) { #{{{
  763. return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
  764. } #}}}
  765. 1