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