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