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