summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 2ee27ac3e7cf1fa6ac5d38a6a4917fd9eb00c770 (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. #print STDERR "warning: page $page, broken link: $link\n";
  274. return "";
  275. } #}}}
  276. sub isinlinableimage ($) { #{{{
  277. my $file=shift;
  278. $file=~/\.(png|gif|jpg|jpeg)$/i;
  279. } #}}}
  280. sub pagetitle ($;$) { #{{{
  281. my $page=shift;
  282. my $unescaped=shift;
  283. if ($unescaped) {
  284. $page=~s/__(\d+)__/chr($1)/eg;
  285. }
  286. else {
  287. $page=~s/__(\d+)__/&#$1;/g;
  288. }
  289. $page=~y/_/ /;
  290. return $page;
  291. } #}}}
  292. sub titlepage ($) { #{{{
  293. my $title=shift;
  294. $title=~y/ /_/;
  295. $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
  296. return $title;
  297. } #}}}
  298. sub cgiurl (@) { #{{{
  299. my %params=@_;
  300. return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
  301. } #}}}
  302. sub baseurl (;$) { #{{{
  303. my $page=shift;
  304. return "$config{url}/" if ! defined $page;
  305. $page=~s/[^\/]+$//;
  306. $page=~s/[^\/]+\//..\//g;
  307. return $page;
  308. } #}}}
  309. sub abs2rel ($$) { #{{{
  310. # Work around very innefficient behavior in File::Spec if abs2rel
  311. # is passed two relative paths. It's much faster if paths are
  312. # absolute! (Debian bug #376658; fixed in debian unstable now)
  313. my $path="/".shift;
  314. my $base="/".shift;
  315. require File::Spec;
  316. my $ret=File::Spec->abs2rel($path, $base);
  317. $ret=~s/^// if defined $ret;
  318. return $ret;
  319. } #}}}
  320. sub displaytime ($) { #{{{
  321. my $time=shift;
  322. eval q{use POSIX};
  323. error($@) if $@;
  324. # strftime doesn't know about encodings, so make sure
  325. # its output is properly treated as utf8
  326. return decode_utf8(POSIX::strftime(
  327. $config{timeformat}, localtime($time)));
  328. } #}}}
  329. sub htmllink ($$$;$$$) { #{{{
  330. my $lpage=shift; # the page doing the linking
  331. my $page=shift; # the page that will contain the link (different for inline)
  332. my $link=shift;
  333. my $noimageinline=shift; # don't turn links into inline html images
  334. my $forcesubpage=shift; # force a link to a subpage
  335. my $linktext=shift; # set to force the link text to something
  336. my $bestlink;
  337. if (! $forcesubpage) {
  338. $bestlink=bestlink($lpage, $link);
  339. }
  340. else {
  341. $bestlink="$lpage/".lc($link);
  342. }
  343. $linktext=pagetitle(basename($link)) unless defined $linktext;
  344. return "<span class=\"selflink\">$linktext</span>"
  345. if length $bestlink && $page eq $bestlink;
  346. if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
  347. $bestlink=htmlpage($bestlink);
  348. }
  349. if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
  350. return $linktext unless length $config{cgiurl};
  351. return "<span><a href=\"".
  352. cgiurl(do => "create", page => lc($link), from => $page).
  353. "\">?</a>$linktext</span>"
  354. }
  355. $bestlink=abs2rel($bestlink, dirname($page));
  356. if (! $noimageinline && isinlinableimage($bestlink)) {
  357. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  358. }
  359. return "<a href=\"$bestlink\">$linktext</a>";
  360. } #}}}
  361. sub htmlize ($$$) { #{{{
  362. my $page=shift;
  363. my $type=shift;
  364. my $content=shift;
  365. if (exists $hooks{htmlize}{$type}) {
  366. $content=$hooks{htmlize}{$type}{call}->(
  367. page => $page,
  368. content => $content,
  369. );
  370. }
  371. else {
  372. error("htmlization of $type not supported");
  373. }
  374. run_hooks(sanitize => sub {
  375. $content=shift->(
  376. page => $page,
  377. content => $content,
  378. );
  379. });
  380. return $content;
  381. } #}}}
  382. sub linkify ($$$) { #{{{
  383. my $lpage=shift; # the page containing the links
  384. my $page=shift; # the page the link will end up on (different for inline)
  385. my $content=shift;
  386. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  387. $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
  388. : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
  389. }eg;
  390. return $content;
  391. } #}}}
  392. my %preprocessing;
  393. sub preprocess ($$$;$) { #{{{
  394. my $page=shift; # the page the data comes from
  395. my $destpage=shift; # the page the data will appear in (different for inline)
  396. my $content=shift;
  397. my $scan=shift;
  398. my $handle=sub {
  399. my $escape=shift;
  400. my $command=shift;
  401. my $params=shift;
  402. if (length $escape) {
  403. return "[[$command $params]]";
  404. }
  405. elsif (exists $hooks{preprocess}{$command}) {
  406. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  407. # Note: preserve order of params, some plugins may
  408. # consider it significant.
  409. my @params;
  410. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  411. my $key=$1;
  412. my $val;
  413. if (defined $2) {
  414. $val=$2;
  415. $val=~s/\r\n/\n/mg;
  416. $val=~s/^\n+//g;
  417. $val=~s/\n+$//g;
  418. }
  419. elsif (defined $3) {
  420. $val=$3;
  421. }
  422. elsif (defined $4) {
  423. $val=$4;
  424. }
  425. if (defined $key) {
  426. push @params, $key, $val;
  427. }
  428. else {
  429. push @params, $val, '';
  430. }
  431. }
  432. if ($preprocessing{$page}++ > 3) {
  433. # Avoid loops of preprocessed pages preprocessing
  434. # other pages that preprocess them, etc.
  435. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  436. $command, $page, $preprocessing{$page}).
  437. "]]";
  438. }
  439. my $ret=$hooks{preprocess}{$command}{call}->(
  440. @params,
  441. page => $page,
  442. destpage => $destpage,
  443. );
  444. $preprocessing{$page}--;
  445. return $ret;
  446. }
  447. else {
  448. return "[[$command $params]]";
  449. }
  450. };
  451. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  452. return $content;
  453. } #}}}
  454. sub filter ($$) { #{{{
  455. my $page=shift;
  456. my $content=shift;
  457. run_hooks(filter => sub {
  458. $content=shift->(page => $page, content => $content);
  459. });
  460. return $content;
  461. } #}}}
  462. sub indexlink () { #{{{
  463. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  464. } #}}}
  465. sub lockwiki () { #{{{
  466. # Take an exclusive lock on the wiki to prevent multiple concurrent
  467. # run issues. The lock will be dropped on program exit.
  468. if (! -d $config{wikistatedir}) {
  469. mkdir($config{wikistatedir});
  470. }
  471. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  472. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  473. if (! flock(WIKILOCK, 2 | 4)) {
  474. debug("wiki seems to be locked, waiting for lock");
  475. my $wait=600; # arbitrary, but don't hang forever to
  476. # prevent process pileup
  477. for (1..600) {
  478. return if flock(WIKILOCK, 2 | 4);
  479. sleep 1;
  480. }
  481. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  482. }
  483. } #}}}
  484. sub unlockwiki () { #{{{
  485. close WIKILOCK;
  486. } #}}}
  487. sub loadindex () { #{{{
  488. open (IN, "$config{wikistatedir}/index") || return;
  489. while (<IN>) {
  490. $_=possibly_foolish_untaint($_);
  491. chomp;
  492. my %items;
  493. $items{link}=[];
  494. $items{dest}=[];
  495. foreach my $i (split(/ /, $_)) {
  496. my ($item, $val)=split(/=/, $i, 2);
  497. push @{$items{$item}}, decode_entities($val);
  498. }
  499. next unless exists $items{src}; # skip bad lines for now
  500. my $page=pagename($items{src}[0]);
  501. if (! $config{rebuild}) {
  502. $pagesources{$page}=$items{src}[0];
  503. $oldpagemtime{$page}=$items{mtime}[0];
  504. $oldlinks{$page}=[@{$items{link}}];
  505. $links{$page}=[@{$items{link}}];
  506. $depends{$page}=$items{depends}[0] if exists $items{depends};
  507. $renderedfiles{$page}=[@{$items{dest}}];
  508. $oldrenderedfiles{$page}=[@{$items{dest}}];
  509. $pagecase{lc $page}=$page;
  510. }
  511. $pagectime{$page}=$items{ctime}[0];
  512. }
  513. close IN;
  514. } #}}}
  515. sub saveindex () { #{{{
  516. run_hooks(savestate => sub { shift->() });
  517. if (! -d $config{wikistatedir}) {
  518. mkdir($config{wikistatedir});
  519. }
  520. open (OUT, ">$config{wikistatedir}/index") ||
  521. error("cannot write to $config{wikistatedir}/index: $!");
  522. foreach my $page (keys %oldpagemtime) {
  523. next unless $oldpagemtime{$page};
  524. my $line="mtime=$oldpagemtime{$page} ".
  525. "ctime=$pagectime{$page} ".
  526. "src=$pagesources{$page}";
  527. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  528. my %count;
  529. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  530. if (exists $depends{$page}) {
  531. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  532. }
  533. print OUT $line."\n";
  534. }
  535. close OUT;
  536. } #}}}
  537. sub template_params (@) { #{{{
  538. my $filename=shift;
  539. require HTML::Template;
  540. return filter => sub {
  541. my $text_ref = shift;
  542. $$text_ref=&Encode::decode_utf8($$text_ref);
  543. },
  544. filename => "$config{templatedir}/$filename",
  545. loop_context_vars => 1,
  546. die_on_bad_params => 0,
  547. @_;
  548. } #}}}
  549. sub template ($;@) { #{{{
  550. HTML::Template->new(template_params(@_));
  551. } #}}}
  552. sub misctemplate ($$;@) { #{{{
  553. my $title=shift;
  554. my $pagebody=shift;
  555. my $template=template("misc.tmpl");
  556. $template->param(
  557. title => $title,
  558. indexlink => indexlink(),
  559. wikiname => $config{wikiname},
  560. pagebody => $pagebody,
  561. baseurl => baseurl(),
  562. @_,
  563. );
  564. run_hooks(pagetemplate => sub {
  565. shift->(page => "", destpage => "", template => $template);
  566. });
  567. return $template->output;
  568. }#}}}
  569. sub hook (@) { # {{{
  570. my %param=@_;
  571. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  572. error "hook requires type, call, and id parameters";
  573. }
  574. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  575. $hooks{$param{type}}{$param{id}}=\%param;
  576. } # }}}
  577. sub run_hooks ($$) { # {{{
  578. # Calls the given sub for each hook of the given type,
  579. # passing it the hook function to call.
  580. my $type=shift;
  581. my $sub=shift;
  582. if (exists $hooks{$type}) {
  583. my @deferred;
  584. foreach my $id (keys %{$hooks{$type}}) {
  585. if ($hooks{$type}{$id}{last}) {
  586. push @deferred, $id;
  587. next;
  588. }
  589. $sub->($hooks{$type}{$id}{call});
  590. }
  591. foreach my $id (@deferred) {
  592. $sub->($hooks{$type}{$id}{call});
  593. }
  594. }
  595. } #}}}
  596. sub globlist_to_pagespec ($) { #{{{
  597. my @globlist=split(' ', shift);
  598. my (@spec, @skip);
  599. foreach my $glob (@globlist) {
  600. if ($glob=~/^!(.*)/) {
  601. push @skip, $glob;
  602. }
  603. else {
  604. push @spec, $glob;
  605. }
  606. }
  607. my $spec=join(" or ", @spec);
  608. if (@skip) {
  609. my $skip=join(" and ", @skip);
  610. if (length $spec) {
  611. $spec="$skip and ($spec)";
  612. }
  613. else {
  614. $spec=$skip;
  615. }
  616. }
  617. return $spec;
  618. } #}}}
  619. sub is_globlist ($) { #{{{
  620. my $s=shift;
  621. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  622. } #}}}
  623. sub safequote ($) { #{{{
  624. my $s=shift;
  625. $s=~s/[{}]//g;
  626. return "q{$s}";
  627. } #}}}
  628. sub pagespec_merge ($$) { #{{{
  629. my $a=shift;
  630. my $b=shift;
  631. return $a if $a eq $b;
  632. # Support for old-style GlobLists.
  633. if (is_globlist($a)) {
  634. $a=globlist_to_pagespec($a);
  635. }
  636. if (is_globlist($b)) {
  637. $b=globlist_to_pagespec($b);
  638. }
  639. return "($a) or ($b)";
  640. } #}}}
  641. sub pagespec_translate ($) { #{{{
  642. # This assumes that $page is in scope in the function
  643. # that evalulates the translated pagespec code.
  644. my $spec=shift;
  645. # Support for old-style GlobLists.
  646. if (is_globlist($spec)) {
  647. $spec=globlist_to_pagespec($spec);
  648. }
  649. # Convert spec to perl code.
  650. my $code="";
  651. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  652. my $word=$1;
  653. if (lc $word eq "and") {
  654. $code.=" &&";
  655. }
  656. elsif (lc $word eq "or") {
  657. $code.=" ||";
  658. }
  659. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  660. $code.=" ".$word;
  661. }
  662. elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
  663. $code.=" match_$1(\$page, ".safequote($2).")";
  664. }
  665. else {
  666. $code.=" match_glob(\$page, ".safequote($word).")";
  667. }
  668. }
  669. return $code;
  670. } #}}}
  671. sub add_depends ($$) { #{{{
  672. my $page=shift;
  673. my $pagespec=shift;
  674. if (! exists $depends{$page}) {
  675. $depends{$page}=$pagespec;
  676. }
  677. else {
  678. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  679. }
  680. } # }}}
  681. sub file_pruned ($$) { #{{{
  682. require File::Spec;
  683. my $file=File::Spec->canonpath(shift);
  684. my $base=File::Spec->canonpath(shift);
  685. $file=~s#^\Q$base\E/*##;
  686. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  687. $file =~ m/$regexp/;
  688. } #}}}
  689. sub gettext { #{{{
  690. # Only use gettext in the rare cases it's needed.
  691. # This overrides future calls of this function.
  692. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  693. eval q{use Locale::gettext};
  694. textdomain('ikiwiki');
  695. return Locale::gettext::gettext(shift);
  696. }
  697. else {
  698. return shift;
  699. }
  700. } #}}}
  701. sub pagespec_match ($$) { #{{{
  702. my $page=shift;
  703. my $spec=shift;
  704. return eval pagespec_translate($spec);
  705. } #}}}
  706. sub match_glob ($$) { #{{{
  707. my $page=shift;
  708. my $glob=shift;
  709. # turn glob into safe regexp
  710. $glob=quotemeta($glob);
  711. $glob=~s/\\\*/.*/g;
  712. $glob=~s/\\\?/./g;
  713. return $page=~/^$glob$/i;
  714. } #}}}
  715. sub match_link ($$) { #{{{
  716. my $page=shift;
  717. my $link=lc(shift);
  718. my $links = $links{$page} or return undef;
  719. foreach my $p (@$links) {
  720. return 1 if lc $p eq $link;
  721. }
  722. return 0;
  723. } #}}}
  724. sub match_backlink ($$) { #{{{
  725. match_link(pop, pop);
  726. } #}}}
  727. sub match_created_before ($$) { #{{{
  728. my $page=shift;
  729. my $testpage=shift;
  730. if (exists $pagectime{$testpage}) {
  731. return $pagectime{$page} < $pagectime{$testpage};
  732. }
  733. else {
  734. return 0;
  735. }
  736. } #}}}
  737. sub match_created_after ($$) { #{{{
  738. my $page=shift;
  739. my $testpage=shift;
  740. if (exists $pagectime{$testpage}) {
  741. return $pagectime{$page} > $pagectime{$testpage};
  742. }
  743. else {
  744. return 0;
  745. }
  746. } #}}}
  747. sub match_creation_day ($$) { #{{{
  748. return ((gmtime($pagectime{shift()}))[3] == shift);
  749. } #}}}
  750. sub match_creation_month ($$) { #{{{
  751. return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
  752. } #}}}
  753. sub match_creation_year ($$) { #{{{
  754. return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
  755. } #}}}
  756. 1