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