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