summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 0ed52aeaec0918224bc166eb7150fdc76e73c88b (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 linkpage ($) { #{{{
  325. my $link=shift;
  326. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  327. return $link;
  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, linkpage($3), anchor => $4, linktext => pagetitle($2)))
  427. : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
  428. }eg;
  429. return $content;
  430. } #}}}
  431. my %preprocessing;
  432. our $preprocess_preview=0;
  433. sub preprocess ($$$;$$) { #{{{
  434. my $page=shift; # the page the data comes from
  435. my $destpage=shift; # the page the data will appear in (different for inline)
  436. my $content=shift;
  437. my $scan=shift;
  438. my $preview=shift;
  439. # Using local because it needs to be set within any nested calls
  440. # of this function.
  441. local $preprocess_preview=$preview if defined $preview;
  442. my $handle=sub {
  443. my $escape=shift;
  444. my $command=shift;
  445. my $params=shift;
  446. if (length $escape) {
  447. return "[[$command $params]]";
  448. }
  449. elsif (exists $hooks{preprocess}{$command}) {
  450. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  451. # Note: preserve order of params, some plugins may
  452. # consider it significant.
  453. my @params;
  454. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  455. my $key=$1;
  456. my $val;
  457. if (defined $2) {
  458. $val=$2;
  459. $val=~s/\r\n/\n/mg;
  460. $val=~s/^\n+//g;
  461. $val=~s/\n+$//g;
  462. }
  463. elsif (defined $3) {
  464. $val=$3;
  465. }
  466. elsif (defined $4) {
  467. $val=$4;
  468. }
  469. if (defined $key) {
  470. push @params, $key, $val;
  471. }
  472. else {
  473. push @params, $val, '';
  474. }
  475. }
  476. if ($preprocessing{$page}++ > 3) {
  477. # Avoid loops of preprocessed pages preprocessing
  478. # other pages that preprocess them, etc.
  479. #translators: The first parameter is a
  480. #translators: preprocessor directive name,
  481. #translators: the second a page name, the
  482. #translators: third a number.
  483. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  484. $command, $page, $preprocessing{$page}).
  485. "]]";
  486. }
  487. my $ret=$hooks{preprocess}{$command}{call}->(
  488. @params,
  489. page => $page,
  490. destpage => $destpage,
  491. preview => $preprocess_preview,
  492. );
  493. $preprocessing{$page}--;
  494. return $ret;
  495. }
  496. else {
  497. return "[[$command $params]]";
  498. }
  499. };
  500. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  501. return $content;
  502. } #}}}
  503. sub filter ($$) { #{{{
  504. my $page=shift;
  505. my $content=shift;
  506. run_hooks(filter => sub {
  507. $content=shift->(page => $page, content => $content);
  508. });
  509. return $content;
  510. } #}}}
  511. sub indexlink () { #{{{
  512. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  513. } #}}}
  514. sub lockwiki () { #{{{
  515. # Take an exclusive lock on the wiki to prevent multiple concurrent
  516. # run issues. The lock will be dropped on program exit.
  517. if (! -d $config{wikistatedir}) {
  518. mkdir($config{wikistatedir});
  519. }
  520. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  521. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  522. if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
  523. debug("wiki seems to be locked, waiting for lock");
  524. my $wait=600; # arbitrary, but don't hang forever to
  525. # prevent process pileup
  526. for (1..$wait) {
  527. return if flock(WIKILOCK, 2 | 4);
  528. sleep 1;
  529. }
  530. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  531. }
  532. } #}}}
  533. sub unlockwiki () { #{{{
  534. close WIKILOCK;
  535. } #}}}
  536. sub commit_hook_enabled () { #{{{
  537. open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
  538. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  539. if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  540. close COMMITLOCK;
  541. return 0;
  542. }
  543. close COMMITLOCK;
  544. return 1;
  545. } #}}}
  546. sub disable_commit_hook () { #{{{
  547. open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
  548. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  549. if (! flock(COMMITLOCK, 2)) { # LOCK_EX
  550. error("failed to get commit lock");
  551. }
  552. } #}}}
  553. sub enable_commit_hook () { #{{{
  554. close COMMITLOCK;
  555. } #}}}
  556. sub loadindex () { #{{{
  557. open (IN, "$config{wikistatedir}/index") || return;
  558. while (<IN>) {
  559. $_=possibly_foolish_untaint($_);
  560. chomp;
  561. my %items;
  562. $items{link}=[];
  563. $items{dest}=[];
  564. foreach my $i (split(/ /, $_)) {
  565. my ($item, $val)=split(/=/, $i, 2);
  566. push @{$items{$item}}, decode_entities($val);
  567. }
  568. next unless exists $items{src}; # skip bad lines for now
  569. my $page=pagename($items{src}[0]);
  570. if (! $config{rebuild}) {
  571. $pagesources{$page}=$items{src}[0];
  572. $oldpagemtime{$page}=$items{mtime}[0];
  573. $oldlinks{$page}=[@{$items{link}}];
  574. $links{$page}=[@{$items{link}}];
  575. $depends{$page}=$items{depends}[0] if exists $items{depends};
  576. $renderedfiles{$page}=[@{$items{dest}}];
  577. $oldrenderedfiles{$page}=[@{$items{dest}}];
  578. $pagecase{lc $page}=$page;
  579. }
  580. $pagectime{$page}=$items{ctime}[0];
  581. }
  582. close IN;
  583. } #}}}
  584. sub saveindex () { #{{{
  585. run_hooks(savestate => sub { shift->() });
  586. if (! -d $config{wikistatedir}) {
  587. mkdir($config{wikistatedir});
  588. }
  589. my $newfile="$config{wikistatedir}/index.new";
  590. my $cleanup = sub { unlink($newfile) };
  591. open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
  592. foreach my $page (keys %oldpagemtime) {
  593. next unless $oldpagemtime{$page};
  594. my $line="mtime=$oldpagemtime{$page} ".
  595. "ctime=$pagectime{$page} ".
  596. "src=$pagesources{$page}";
  597. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  598. my %count;
  599. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  600. if (exists $depends{$page}) {
  601. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  602. }
  603. print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  604. }
  605. close OUT || error("failed saving to $newfile: $!", $cleanup);
  606. rename($newfile, "$config{wikistatedir}/index") ||
  607. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  608. } #}}}
  609. sub template_file ($) { #{{{
  610. my $template=shift;
  611. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  612. return "$dir/$template" if -e "$dir/$template";
  613. }
  614. return undef;
  615. } #}}}
  616. sub template_params (@) { #{{{
  617. my $filename=template_file(shift);
  618. if (! defined $filename) {
  619. return if wantarray;
  620. return "";
  621. }
  622. require HTML::Template;
  623. my @ret=(
  624. filter => sub {
  625. my $text_ref = shift;
  626. $$text_ref=&Encode::decode_utf8($$text_ref);
  627. },
  628. filename => $filename,
  629. loop_context_vars => 1,
  630. die_on_bad_params => 0,
  631. @_
  632. );
  633. return wantarray ? @ret : {@ret};
  634. } #}}}
  635. sub template ($;@) { #{{{
  636. HTML::Template->new(template_params(@_));
  637. } #}}}
  638. sub misctemplate ($$;@) { #{{{
  639. my $title=shift;
  640. my $pagebody=shift;
  641. my $template=template("misc.tmpl");
  642. $template->param(
  643. title => $title,
  644. indexlink => indexlink(),
  645. wikiname => $config{wikiname},
  646. pagebody => $pagebody,
  647. baseurl => baseurl(),
  648. @_,
  649. );
  650. run_hooks(pagetemplate => sub {
  651. shift->(page => "", destpage => "", template => $template);
  652. });
  653. return $template->output;
  654. }#}}}
  655. sub hook (@) { # {{{
  656. my %param=@_;
  657. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  658. error "hook requires type, call, and id parameters";
  659. }
  660. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  661. $hooks{$param{type}}{$param{id}}=\%param;
  662. } # }}}
  663. sub run_hooks ($$) { # {{{
  664. # Calls the given sub for each hook of the given type,
  665. # passing it the hook function to call.
  666. my $type=shift;
  667. my $sub=shift;
  668. if (exists $hooks{$type}) {
  669. my @deferred;
  670. foreach my $id (keys %{$hooks{$type}}) {
  671. if ($hooks{$type}{$id}{last}) {
  672. push @deferred, $id;
  673. next;
  674. }
  675. $sub->($hooks{$type}{$id}{call});
  676. }
  677. foreach my $id (@deferred) {
  678. $sub->($hooks{$type}{$id}{call});
  679. }
  680. }
  681. } #}}}
  682. sub globlist_to_pagespec ($) { #{{{
  683. my @globlist=split(' ', shift);
  684. my (@spec, @skip);
  685. foreach my $glob (@globlist) {
  686. if ($glob=~/^!(.*)/) {
  687. push @skip, $glob;
  688. }
  689. else {
  690. push @spec, $glob;
  691. }
  692. }
  693. my $spec=join(" or ", @spec);
  694. if (@skip) {
  695. my $skip=join(" and ", @skip);
  696. if (length $spec) {
  697. $spec="$skip and ($spec)";
  698. }
  699. else {
  700. $spec=$skip;
  701. }
  702. }
  703. return $spec;
  704. } #}}}
  705. sub is_globlist ($) { #{{{
  706. my $s=shift;
  707. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  708. } #}}}
  709. sub safequote ($) { #{{{
  710. my $s=shift;
  711. $s=~s/[{}]//g;
  712. return "q{$s}";
  713. } #}}}
  714. sub add_depends ($$) { #{{{
  715. my $page=shift;
  716. my $pagespec=shift;
  717. if (! exists $depends{$page}) {
  718. $depends{$page}=$pagespec;
  719. }
  720. else {
  721. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  722. }
  723. } # }}}
  724. sub file_pruned ($$) { #{{{
  725. require File::Spec;
  726. my $file=File::Spec->canonpath(shift);
  727. my $base=File::Spec->canonpath(shift);
  728. $file=~s#^\Q$base\E/*##;
  729. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  730. $file =~ m/$regexp/;
  731. } #}}}
  732. sub gettext { #{{{
  733. # Only use gettext in the rare cases it's needed.
  734. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  735. if (! $gettext_obj) {
  736. $gettext_obj=eval q{
  737. use Locale::gettext q{textdomain};
  738. Locale::gettext->domain('ikiwiki')
  739. };
  740. if ($@) {
  741. print STDERR "$@";
  742. $gettext_obj=undef;
  743. return shift;
  744. }
  745. }
  746. return $gettext_obj->get(shift);
  747. }
  748. else {
  749. return shift;
  750. }
  751. } #}}}
  752. sub pagespec_merge ($$) { #{{{
  753. my $a=shift;
  754. my $b=shift;
  755. return $a if $a eq $b;
  756. # Support for old-style GlobLists.
  757. if (is_globlist($a)) {
  758. $a=globlist_to_pagespec($a);
  759. }
  760. if (is_globlist($b)) {
  761. $b=globlist_to_pagespec($b);
  762. }
  763. return "($a) or ($b)";
  764. } #}}}
  765. sub pagespec_translate ($) { #{{{
  766. # This assumes that $page is in scope in the function
  767. # that evalulates the translated pagespec code.
  768. my $spec=shift;
  769. # Support for old-style GlobLists.
  770. if (is_globlist($spec)) {
  771. $spec=globlist_to_pagespec($spec);
  772. }
  773. # Convert spec to perl code.
  774. my $code="";
  775. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  776. my $word=$1;
  777. if (lc $word eq "and") {
  778. $code.=" &&";
  779. }
  780. elsif (lc $word eq "or") {
  781. $code.=" ||";
  782. }
  783. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  784. $code.=" ".$word;
  785. }
  786. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  787. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  788. $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
  789. }
  790. else {
  791. $code.=" 0";
  792. }
  793. }
  794. else {
  795. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
  796. }
  797. }
  798. return $code;
  799. } #}}}
  800. sub pagespec_match ($$;$) { #{{{
  801. my $page=shift;
  802. my $spec=shift;
  803. my $from=shift;
  804. return eval pagespec_translate($spec);
  805. } #}}}
  806. package IkiWiki::PageSpec;
  807. sub match_glob ($$$) { #{{{
  808. my $page=shift;
  809. my $glob=shift;
  810. my $from=shift;
  811. if (! defined $from){
  812. $from = "";
  813. }
  814. # relative matching
  815. if ($glob =~ m!^\./!) {
  816. $from=~s!/?[^/]+$!!;
  817. $glob=~s!^\./!!;
  818. $glob="$from/$glob" if length $from;
  819. }
  820. # turn glob into safe regexp
  821. $glob=quotemeta($glob);
  822. $glob=~s/\\\*/.*/g;
  823. $glob=~s/\\\?/./g;
  824. return $page=~/^$glob$/i;
  825. } #}}}
  826. sub match_link ($$) { #{{{
  827. my $page=shift;
  828. my $link=lc(shift);
  829. my $links = $IkiWiki::links{$page} or return undef;
  830. foreach my $p (@$links) {
  831. return 1 if lc $p eq $link;
  832. }
  833. return 0;
  834. } #}}}
  835. sub match_backlink ($$) { #{{{
  836. match_link(pop, pop);
  837. } #}}}
  838. sub match_created_before ($$) { #{{{
  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_created_after ($$) { #{{{
  849. my $page=shift;
  850. my $testpage=shift;
  851. if (exists $IkiWiki::pagectime{$testpage}) {
  852. return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
  853. }
  854. else {
  855. return 0;
  856. }
  857. } #}}}
  858. sub match_creation_day ($$) { #{{{
  859. return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
  860. } #}}}
  861. sub match_creation_month ($$) { #{{{
  862. return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
  863. } #}}}
  864. sub match_creation_year ($$) { #{{{
  865. return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
  866. } #}}}
  867. 1