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