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