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