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