summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 8a3c817558781433931e4dd15b3a2bb5e3745df0 (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_file ($) { #{{{
  545. my $template=shift;
  546. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  547. return "$dir/$template" if -e "$dir/$template";
  548. }
  549. return undef;
  550. } #}}}
  551. sub template_params (@) { #{{{
  552. my $filename=template_file(shift);
  553. if (! defined $filename) {
  554. return if wantarray;
  555. return "";
  556. }
  557. require HTML::Template;
  558. my @ret=(
  559. filter => sub {
  560. my $text_ref = shift;
  561. $$text_ref=&Encode::decode_utf8($$text_ref);
  562. },
  563. filename => $filename,
  564. loop_context_vars => 1,
  565. die_on_bad_params => 0,
  566. @_
  567. );
  568. return wantarray ? @ret : {@ret};
  569. } #}}}
  570. sub template ($;@) { #{{{
  571. HTML::Template->new(template_params(@_));
  572. } #}}}
  573. sub misctemplate ($$;@) { #{{{
  574. my $title=shift;
  575. my $pagebody=shift;
  576. my $template=template("misc.tmpl");
  577. $template->param(
  578. title => $title,
  579. indexlink => indexlink(),
  580. wikiname => $config{wikiname},
  581. pagebody => $pagebody,
  582. baseurl => baseurl(),
  583. @_,
  584. );
  585. run_hooks(pagetemplate => sub {
  586. shift->(page => "", destpage => "", template => $template);
  587. });
  588. return $template->output;
  589. }#}}}
  590. sub hook (@) { # {{{
  591. my %param=@_;
  592. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  593. error "hook requires type, call, and id parameters";
  594. }
  595. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  596. $hooks{$param{type}}{$param{id}}=\%param;
  597. } # }}}
  598. sub run_hooks ($$) { # {{{
  599. # Calls the given sub for each hook of the given type,
  600. # passing it the hook function to call.
  601. my $type=shift;
  602. my $sub=shift;
  603. if (exists $hooks{$type}) {
  604. my @deferred;
  605. foreach my $id (keys %{$hooks{$type}}) {
  606. if ($hooks{$type}{$id}{last}) {
  607. push @deferred, $id;
  608. next;
  609. }
  610. $sub->($hooks{$type}{$id}{call});
  611. }
  612. foreach my $id (@deferred) {
  613. $sub->($hooks{$type}{$id}{call});
  614. }
  615. }
  616. } #}}}
  617. sub globlist_to_pagespec ($) { #{{{
  618. my @globlist=split(' ', shift);
  619. my (@spec, @skip);
  620. foreach my $glob (@globlist) {
  621. if ($glob=~/^!(.*)/) {
  622. push @skip, $glob;
  623. }
  624. else {
  625. push @spec, $glob;
  626. }
  627. }
  628. my $spec=join(" or ", @spec);
  629. if (@skip) {
  630. my $skip=join(" and ", @skip);
  631. if (length $spec) {
  632. $spec="$skip and ($spec)";
  633. }
  634. else {
  635. $spec=$skip;
  636. }
  637. }
  638. return $spec;
  639. } #}}}
  640. sub is_globlist ($) { #{{{
  641. my $s=shift;
  642. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  643. } #}}}
  644. sub safequote ($) { #{{{
  645. my $s=shift;
  646. $s=~s/[{}]//g;
  647. return "q{$s}";
  648. } #}}}
  649. sub pagespec_merge ($$) { #{{{
  650. my $a=shift;
  651. my $b=shift;
  652. return $a if $a eq $b;
  653. # Support for old-style GlobLists.
  654. if (is_globlist($a)) {
  655. $a=globlist_to_pagespec($a);
  656. }
  657. if (is_globlist($b)) {
  658. $b=globlist_to_pagespec($b);
  659. }
  660. return "($a) or ($b)";
  661. } #}}}
  662. sub pagespec_translate ($) { #{{{
  663. # This assumes that $page is in scope in the function
  664. # that evalulates the translated pagespec code.
  665. my $spec=shift;
  666. # Support for old-style GlobLists.
  667. if (is_globlist($spec)) {
  668. $spec=globlist_to_pagespec($spec);
  669. }
  670. # Convert spec to perl code.
  671. my $code="";
  672. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  673. my $word=$1;
  674. if (lc $word eq "and") {
  675. $code.=" &&";
  676. }
  677. elsif (lc $word eq "or") {
  678. $code.=" ||";
  679. }
  680. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  681. $code.=" ".$word;
  682. }
  683. elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
  684. $code.=" match_$1(\$page, ".safequote($2).")";
  685. }
  686. else {
  687. $code.=" match_glob(\$page, ".safequote($word).")";
  688. }
  689. }
  690. return $code;
  691. } #}}}
  692. sub add_depends ($$) { #{{{
  693. my $page=shift;
  694. my $pagespec=shift;
  695. if (! exists $depends{$page}) {
  696. $depends{$page}=$pagespec;
  697. }
  698. else {
  699. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  700. }
  701. } # }}}
  702. sub file_pruned ($$) { #{{{
  703. require File::Spec;
  704. my $file=File::Spec->canonpath(shift);
  705. my $base=File::Spec->canonpath(shift);
  706. $file=~s#^\Q$base\E/*##;
  707. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  708. $file =~ m/$regexp/;
  709. } #}}}
  710. my $gettext_obj;
  711. sub gettext { #{{{
  712. # Only use gettext in the rare cases it's needed.
  713. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  714. if (! $gettext_obj) {
  715. eval q{use Locale::gettext ''};
  716. $gettext_obj=Locale::gettext->domain('ikiwiki');
  717. }
  718. return $gettext_obj->get(shift);
  719. }
  720. else {
  721. return shift;
  722. }
  723. } #}}}
  724. sub pagespec_match ($$) { #{{{
  725. my $page=shift;
  726. my $spec=shift;
  727. return eval pagespec_translate($spec);
  728. } #}}}
  729. sub match_glob ($$) { #{{{
  730. my $page=shift;
  731. my $glob=shift;
  732. # turn glob into safe regexp
  733. $glob=quotemeta($glob);
  734. $glob=~s/\\\*/.*/g;
  735. $glob=~s/\\\?/./g;
  736. return $page=~/^$glob$/i;
  737. } #}}}
  738. sub match_link ($$) { #{{{
  739. my $page=shift;
  740. my $link=lc(shift);
  741. my $links = $links{$page} or return undef;
  742. foreach my $p (@$links) {
  743. return 1 if lc $p eq $link;
  744. }
  745. return 0;
  746. } #}}}
  747. sub match_backlink ($$) { #{{{
  748. match_link(pop, pop);
  749. } #}}}
  750. sub match_created_before ($$) { #{{{
  751. my $page=shift;
  752. my $testpage=shift;
  753. if (exists $pagectime{$testpage}) {
  754. return $pagectime{$page} < $pagectime{$testpage};
  755. }
  756. else {
  757. return 0;
  758. }
  759. } #}}}
  760. sub match_created_after ($$) { #{{{
  761. my $page=shift;
  762. my $testpage=shift;
  763. if (exists $pagectime{$testpage}) {
  764. return $pagectime{$page} > $pagectime{$testpage};
  765. }
  766. else {
  767. return 0;
  768. }
  769. } #}}}
  770. sub match_creation_day ($$) { #{{{
  771. return ((gmtime($pagectime{shift()}))[3] == shift);
  772. } #}}}
  773. sub match_creation_month ($$) { #{{{
  774. return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
  775. } #}}}
  776. sub match_creation_year ($$) { #{{{
  777. return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
  778. } #}}}
  779. 1