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