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