summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: d001760a205864aad7ce78c6d799d06444ffbc2a (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 POSIX;
  9. use open qw{:utf8 :std};
  10. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  11. %pagestate %renderedfiles %oldrenderedfiles %pagesources
  12. %destsources %depends %hooks %forcerebuild $gettext_obj};
  13. use Exporter q{import};
  14. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  15. bestlink htmllink readfile writefile pagetype srcfile pagename
  16. displaytime will_render gettext urlto targetpage
  17. add_underlay
  18. %config %links %pagestate %renderedfiles
  19. %pagesources %destsources);
  20. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  21. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  22. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  23. # Optimisation.
  24. use Memoize;
  25. memoize("abs2rel");
  26. memoize("pagespec_translate");
  27. memoize("file_pruned");
  28. sub defaultconfig () { #{{{
  29. return
  30. wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
  31. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  32. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  33. qr/(^|\/)_MTN\//,
  34. qr/\.dpkg-tmp$/],
  35. wiki_link_regexp => qr{
  36. \[\[ # beginning of link
  37. (?:
  38. ([^\]\|\n\s]+) # 1: link text
  39. \| # followed by '|'
  40. )? # optional
  41. ([^\s\]#]+) # 2: page to link to
  42. (?:
  43. \# # '#', beginning of anchor
  44. ([^\s\]]+) # 3: anchor text
  45. )? # optional
  46. \]\] # end of link
  47. }x,
  48. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  49. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  50. verbose => 0,
  51. syslog => 0,
  52. wikiname => "wiki",
  53. default_pageext => "mdwn",
  54. htmlext => "html",
  55. cgi => 0,
  56. post_commit => 0,
  57. rcs => '',
  58. notify => 0,
  59. url => '',
  60. cgiurl => '',
  61. historyurl => '',
  62. diffurl => '',
  63. rss => 0,
  64. atom => 0,
  65. discussion => 1,
  66. rebuild => 0,
  67. refresh => 0,
  68. getctime => 0,
  69. w3mmode => 0,
  70. wrapper => undef,
  71. wrappermode => undef,
  72. svnrepo => undef,
  73. svnpath => "trunk",
  74. gitorigin_branch => "origin",
  75. gitmaster_branch => "master",
  76. srcdir => undef,
  77. destdir => undef,
  78. pingurl => [],
  79. templatedir => "$installdir/share/ikiwiki/templates",
  80. underlaydir => "$installdir/share/ikiwiki/basewiki",
  81. underlaydirs => [],
  82. setup => undef,
  83. adminuser => undef,
  84. adminemail => undef,
  85. plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
  86. lockedit conditional}],
  87. libdir => undef,
  88. timeformat => '%c',
  89. locale => undef,
  90. sslcookie => 0,
  91. httpauth => 0,
  92. userdir => "",
  93. usedirs => 1,
  94. numbacklinks => 10,
  95. account_creation_password => "",
  96. } #}}}
  97. sub checkconfig () { #{{{
  98. # locale stuff; avoid LC_ALL since it overrides everything
  99. if (defined $ENV{LC_ALL}) {
  100. $ENV{LANG} = $ENV{LC_ALL};
  101. delete $ENV{LC_ALL};
  102. }
  103. if (defined $config{locale}) {
  104. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  105. $ENV{LANG}=$config{locale};
  106. $gettext_obj=undef;
  107. }
  108. }
  109. if ($config{w3mmode}) {
  110. eval q{use Cwd q{abs_path}};
  111. error($@) if $@;
  112. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  113. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  114. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  115. unless $config{cgiurl} =~ m!file:///!;
  116. $config{url}="file://".$config{destdir};
  117. }
  118. if ($config{cgi} && ! length $config{url}) {
  119. error(gettext("Must specify url to wiki with --url when using --cgi"));
  120. }
  121. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  122. unless exists $config{wikistatedir};
  123. if ($config{rcs}) {
  124. eval qq{use IkiWiki::Rcs::$config{rcs}};
  125. if ($@) {
  126. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  127. }
  128. }
  129. else {
  130. require IkiWiki::Rcs::Stub;
  131. }
  132. if (exists $config{umask}) {
  133. umask(possibly_foolish_untaint($config{umask}));
  134. }
  135. run_hooks(checkconfig => sub { shift->() });
  136. return 1;
  137. } #}}}
  138. sub loadplugins () { #{{{
  139. if (defined $config{libdir}) {
  140. unshift @INC, possibly_foolish_untaint($config{libdir});
  141. }
  142. loadplugin($_) foreach @{$config{plugin}};
  143. run_hooks(getopt => sub { shift->() });
  144. if (grep /^-/, @ARGV) {
  145. print STDERR "Unknown option: $_\n"
  146. foreach grep /^-/, @ARGV;
  147. usage();
  148. }
  149. return 1;
  150. } #}}}
  151. sub loadplugin ($) { #{{{
  152. my $plugin=shift;
  153. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  154. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  155. "$installdir/lib/ikiwiki") {
  156. if (defined $dir && -x "$dir/plugins/$plugin") {
  157. require IkiWiki::Plugin::external;
  158. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  159. return 1;
  160. }
  161. }
  162. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  163. eval qq{use $mod};
  164. if ($@) {
  165. error("Failed to load plugin $mod: $@");
  166. }
  167. return 1;
  168. } #}}}
  169. sub error ($;$) { #{{{
  170. my $message=shift;
  171. my $cleaner=shift;
  172. if ($config{cgi}) {
  173. print "Content-type: text/html\n\n";
  174. print misctemplate(gettext("Error"),
  175. "<p>".gettext("Error").": $message</p>");
  176. }
  177. log_message('err' => $message) if $config{syslog};
  178. if (defined $cleaner) {
  179. $cleaner->();
  180. }
  181. die $message."\n";
  182. } #}}}
  183. sub debug ($) { #{{{
  184. return unless $config{verbose};
  185. return log_message(debug => @_);
  186. } #}}}
  187. my $log_open=0;
  188. sub log_message ($$) { #{{{
  189. my $type=shift;
  190. if ($config{syslog}) {
  191. require Sys::Syslog;
  192. if (! $log_open) {
  193. Sys::Syslog::setlogsock('unix');
  194. Sys::Syslog::openlog('ikiwiki', '', 'user');
  195. $log_open=1;
  196. }
  197. return eval {
  198. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  199. };
  200. }
  201. elsif (! $config{cgi}) {
  202. return print "@_\n";
  203. }
  204. else {
  205. return print STDERR "@_\n";
  206. }
  207. } #}}}
  208. sub possibly_foolish_untaint ($) { #{{{
  209. my $tainted=shift;
  210. my ($untainted)=$tainted=~/(.*)/s;
  211. return $untainted;
  212. } #}}}
  213. sub basename ($) { #{{{
  214. my $file=shift;
  215. $file=~s!.*/+!!;
  216. return $file;
  217. } #}}}
  218. sub dirname ($) { #{{{
  219. my $file=shift;
  220. $file=~s!/*[^/]+$!!;
  221. return $file;
  222. } #}}}
  223. sub pagetype ($) { #{{{
  224. my $page=shift;
  225. if ($page =~ /\.([^.]+)$/) {
  226. return $1 if exists $hooks{htmlize}{$1};
  227. }
  228. return;
  229. } #}}}
  230. sub pagename ($) { #{{{
  231. my $file=shift;
  232. my $type=pagetype($file);
  233. my $page=$file;
  234. $page=~s/\Q.$type\E*$// if defined $type;
  235. return $page;
  236. } #}}}
  237. sub targetpage ($$) { #{{{
  238. my $page=shift;
  239. my $ext=shift;
  240. if (! $config{usedirs} || $page =~ /^index$/ ) {
  241. return $page.".".$ext;
  242. } else {
  243. return $page."/index.".$ext;
  244. }
  245. } #}}}
  246. sub htmlpage ($) { #{{{
  247. my $page=shift;
  248. return targetpage($page, $config{htmlext});
  249. } #}}}
  250. sub srcfile ($) { #{{{
  251. my $file=shift;
  252. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  253. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  254. return "$dir/$file" if -e "$dir/$file";
  255. }
  256. error("internal error: $file cannot be found in $config{srcdir} or underlay");
  257. return;
  258. } #}}}
  259. sub add_underlay ($) { #{{{
  260. my $dir=shift;
  261. if ($dir=~/^\//) {
  262. unshift @{$config{underlaydirs}}, $dir;
  263. }
  264. else {
  265. unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
  266. }
  267. return 1;
  268. } #}}}
  269. sub readfile ($;$$) { #{{{
  270. my $file=shift;
  271. my $binary=shift;
  272. my $wantfd=shift;
  273. if (-l $file) {
  274. error("cannot read a symlink ($file)");
  275. }
  276. local $/=undef;
  277. open (my $in, "<", $file) || error("failed to read $file: $!");
  278. binmode($in) if ($binary);
  279. return \*$in if $wantfd;
  280. my $ret=<$in>;
  281. close $in || error("failed to read $file: $!");
  282. return $ret;
  283. } #}}}
  284. sub writefile ($$$;$$) { #{{{
  285. my $file=shift; # can include subdirs
  286. my $destdir=shift; # directory to put file in
  287. my $content=shift;
  288. my $binary=shift;
  289. my $writer=shift;
  290. my $test=$file;
  291. while (length $test) {
  292. if (-l "$destdir/$test") {
  293. error("cannot write to a symlink ($test)");
  294. }
  295. $test=dirname($test);
  296. }
  297. my $newfile="$destdir/$file.ikiwiki-new";
  298. if (-l $newfile) {
  299. error("cannot write to a symlink ($newfile)");
  300. }
  301. my $dir=dirname($newfile);
  302. if (! -d $dir) {
  303. my $d="";
  304. foreach my $s (split(m!/+!, $dir)) {
  305. $d.="$s/";
  306. if (! -d $d) {
  307. mkdir($d) || error("failed to create directory $d: $!");
  308. }
  309. }
  310. }
  311. my $cleanup = sub { unlink($newfile) };
  312. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  313. binmode($out) if ($binary);
  314. if ($writer) {
  315. $writer->(\*$out, $cleanup);
  316. }
  317. else {
  318. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  319. }
  320. close $out || error("failed saving $newfile: $!", $cleanup);
  321. rename($newfile, "$destdir/$file") ||
  322. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  323. return 1;
  324. } #}}}
  325. my %cleared;
  326. sub will_render ($$;$) { #{{{
  327. my $page=shift;
  328. my $dest=shift;
  329. my $clear=shift;
  330. # Important security check.
  331. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  332. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  333. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  334. }
  335. if (! $clear || $cleared{$page}) {
  336. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  337. }
  338. else {
  339. foreach my $old (@{$renderedfiles{$page}}) {
  340. delete $destsources{$old};
  341. }
  342. $renderedfiles{$page}=[$dest];
  343. $cleared{$page}=1;
  344. }
  345. $destsources{$dest}=$page;
  346. return 1;
  347. } #}}}
  348. sub bestlink ($$) { #{{{
  349. my $page=shift;
  350. my $link=shift;
  351. my $cwd=$page;
  352. if ($link=~s/^\/+//) {
  353. # absolute links
  354. $cwd="";
  355. }
  356. $link=~s/\/$//;
  357. do {
  358. my $l=$cwd;
  359. $l.="/" if length $l;
  360. $l.=$link;
  361. if (exists $links{$l}) {
  362. return $l;
  363. }
  364. elsif (exists $pagecase{lc $l}) {
  365. return $pagecase{lc $l};
  366. }
  367. } while $cwd=~s!/?[^/]+$!!;
  368. if (length $config{userdir}) {
  369. my $l = "$config{userdir}/".lc($link);
  370. if (exists $links{$l}) {
  371. return $l;
  372. }
  373. elsif (exists $pagecase{lc $l}) {
  374. return $pagecase{lc $l};
  375. }
  376. }
  377. #print STDERR "warning: page $page, broken link: $link\n";
  378. return "";
  379. } #}}}
  380. sub isinlinableimage ($) { #{{{
  381. my $file=shift;
  382. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  383. } #}}}
  384. sub pagetitle ($;$) { #{{{
  385. my $page=shift;
  386. my $unescaped=shift;
  387. if ($unescaped) {
  388. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  389. }
  390. else {
  391. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  392. }
  393. return $page;
  394. } #}}}
  395. sub titlepage ($) { #{{{
  396. my $title=shift;
  397. $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  398. return $title;
  399. } #}}}
  400. sub linkpage ($) { #{{{
  401. my $link=shift;
  402. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  403. return $link;
  404. } #}}}
  405. sub cgiurl (@) { #{{{
  406. my %params=@_;
  407. return $config{cgiurl}."?".
  408. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  409. } #}}}
  410. sub baseurl (;$) { #{{{
  411. my $page=shift;
  412. return "$config{url}/" if ! defined $page;
  413. $page=htmlpage($page);
  414. $page=~s/[^\/]+$//;
  415. $page=~s/[^\/]+\//..\//g;
  416. return $page;
  417. } #}}}
  418. sub abs2rel ($$) { #{{{
  419. # Work around very innefficient behavior in File::Spec if abs2rel
  420. # is passed two relative paths. It's much faster if paths are
  421. # absolute! (Debian bug #376658; fixed in debian unstable now)
  422. my $path="/".shift;
  423. my $base="/".shift;
  424. require File::Spec;
  425. my $ret=File::Spec->abs2rel($path, $base);
  426. $ret=~s/^// if defined $ret;
  427. return $ret;
  428. } #}}}
  429. sub displaytime ($;$) { #{{{
  430. my $time=shift;
  431. my $format=shift;
  432. if (! defined $format) {
  433. $format=$config{timeformat};
  434. }
  435. # strftime doesn't know about encodings, so make sure
  436. # its output is properly treated as utf8
  437. return decode_utf8(POSIX::strftime($format, localtime($time)));
  438. } #}}}
  439. sub beautify_url ($) { #{{{
  440. my $url=shift;
  441. if ($config{usedirs}) {
  442. $url =~ s!/index.$config{htmlext}$!/!;
  443. }
  444. $url =~ s!^$!./!; # Browsers don't like empty links...
  445. return $url;
  446. } #}}}
  447. sub urlto ($$) { #{{{
  448. my $to=shift;
  449. my $from=shift;
  450. if (! length $to) {
  451. return beautify_url(baseurl($from));
  452. }
  453. if (! $destsources{$to}) {
  454. $to=htmlpage($to);
  455. }
  456. my $link = abs2rel($to, dirname(htmlpage($from)));
  457. return beautify_url($link);
  458. } #}}}
  459. sub htmllink ($$$;@) { #{{{
  460. my $lpage=shift; # the page doing the linking
  461. my $page=shift; # the page that will contain the link (different for inline)
  462. my $link=shift;
  463. my %opts=@_;
  464. $link=~s/\/$//;
  465. my $bestlink;
  466. if (! $opts{forcesubpage}) {
  467. $bestlink=bestlink($lpage, $link);
  468. }
  469. else {
  470. $bestlink="$lpage/".lc($link);
  471. }
  472. my $linktext;
  473. if (defined $opts{linktext}) {
  474. $linktext=$opts{linktext};
  475. }
  476. else {
  477. $linktext=pagetitle(basename($link));
  478. }
  479. return "<span class=\"selflink\">$linktext</span>"
  480. if length $bestlink && $page eq $bestlink &&
  481. ! defined $opts{anchor};
  482. if (! $destsources{$bestlink}) {
  483. $bestlink=htmlpage($bestlink);
  484. if (! $destsources{$bestlink}) {
  485. return $linktext unless length $config{cgiurl};
  486. return "<span class=\"createlink\"><a href=\"".
  487. cgiurl(
  488. do => "create",
  489. page => pagetitle(lc($link), 1),
  490. from => $lpage
  491. ).
  492. "\">?</a>$linktext</span>"
  493. }
  494. }
  495. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  496. $bestlink=beautify_url($bestlink);
  497. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  498. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  499. }
  500. if (defined $opts{anchor}) {
  501. $bestlink.="#".$opts{anchor};
  502. }
  503. my @attrs;
  504. if (defined $opts{rel}) {
  505. push @attrs, ' rel="'.$opts{rel}.'"';
  506. }
  507. if (defined $opts{class}) {
  508. push @attrs, ' class="'.$opts{class}.'"';
  509. }
  510. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  511. } #}}}
  512. sub htmlize ($$$) { #{{{
  513. my $page=shift;
  514. my $type=shift;
  515. my $content=shift;
  516. if (exists $hooks{htmlize}{$type}) {
  517. $content=$hooks{htmlize}{$type}{call}->(
  518. page => $page,
  519. content => $content,
  520. );
  521. }
  522. else {
  523. error("htmlization of $type not supported");
  524. }
  525. run_hooks(sanitize => sub {
  526. $content=shift->(
  527. page => $page,
  528. content => $content,
  529. );
  530. });
  531. return $content;
  532. } #}}}
  533. sub linkify ($$$) { #{{{
  534. my $lpage=shift; # the page containing the links
  535. my $page=shift; # the page the link will end up on (different for inline)
  536. my $content=shift;
  537. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  538. defined $2
  539. ? ( $1
  540. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  541. : htmllink($lpage, $page, linkpage($3),
  542. anchor => $4, linktext => pagetitle($2)))
  543. : ( $1
  544. ? "[[$3".($4 ? "#$4" : "")."]]"
  545. : htmllink($lpage, $page, linkpage($3),
  546. anchor => $4))
  547. }eg;
  548. return $content;
  549. } #}}}
  550. my %preprocessing;
  551. our $preprocess_preview=0;
  552. sub preprocess ($$$;$$) { #{{{
  553. my $page=shift; # the page the data comes from
  554. my $destpage=shift; # the page the data will appear in (different for inline)
  555. my $content=shift;
  556. my $scan=shift;
  557. my $preview=shift;
  558. # Using local because it needs to be set within any nested calls
  559. # of this function.
  560. local $preprocess_preview=$preview if defined $preview;
  561. my $handle=sub {
  562. my $escape=shift;
  563. my $command=shift;
  564. my $params=shift;
  565. if (length $escape) {
  566. return "[[$command $params]]";
  567. }
  568. elsif (exists $hooks{preprocess}{$command}) {
  569. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  570. # Note: preserve order of params, some plugins may
  571. # consider it significant.
  572. my @params;
  573. while ($params =~ m{
  574. (?:([-\w]+)=)? # 1: named parameter key?
  575. (?:
  576. """(.*?)""" # 2: triple-quoted value
  577. |
  578. "([^"]+)" # 3: single-quoted value
  579. |
  580. (\S+) # 4: unquoted value
  581. )
  582. (?:\s+|$) # delimiter to next param
  583. }sgx) {
  584. my $key=$1;
  585. my $val;
  586. if (defined $2) {
  587. $val=$2;
  588. $val=~s/\r\n/\n/mg;
  589. $val=~s/^\n+//g;
  590. $val=~s/\n+$//g;
  591. }
  592. elsif (defined $3) {
  593. $val=$3;
  594. }
  595. elsif (defined $4) {
  596. $val=$4;
  597. }
  598. if (defined $key) {
  599. push @params, $key, $val;
  600. }
  601. else {
  602. push @params, $val, '';
  603. }
  604. }
  605. if ($preprocessing{$page}++ > 3) {
  606. # Avoid loops of preprocessed pages preprocessing
  607. # other pages that preprocess them, etc.
  608. #translators: The first parameter is a
  609. #translators: preprocessor directive name,
  610. #translators: the second a page name, the
  611. #translators: third a number.
  612. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  613. $command, $page, $preprocessing{$page}).
  614. "]]";
  615. }
  616. my $ret;
  617. if (! $scan) {
  618. $ret=$hooks{preprocess}{$command}{call}->(
  619. @params,
  620. page => $page,
  621. destpage => $destpage,
  622. preview => $preprocess_preview,
  623. );
  624. }
  625. else {
  626. # use void context during scan pass
  627. $hooks{preprocess}{$command}{call}->(
  628. @params,
  629. page => $page,
  630. destpage => $destpage,
  631. preview => $preprocess_preview,
  632. );
  633. $ret="";
  634. }
  635. $preprocessing{$page}--;
  636. return $ret;
  637. }
  638. else {
  639. return "[[$command $params]]";
  640. }
  641. };
  642. $content =~ s{
  643. (\\?) # 1: escape?
  644. \[\[ # directive open
  645. ([-\w]+) # 2: command
  646. \s+
  647. ( # 3: the parameters..
  648. (?:
  649. (?:[-\w]+=)? # named parameter key?
  650. (?:
  651. """.*?""" # triple-quoted value
  652. |
  653. "[^"]+" # single-quoted value
  654. |
  655. [^\s\]]+ # unquoted value
  656. )
  657. \s* # whitespace or end
  658. # of directive
  659. )
  660. *) # 0 or more parameters
  661. \]\] # directive closed
  662. }{$handle->($1, $2, $3)}sexg;
  663. return $content;
  664. } #}}}
  665. sub filter ($$$) { #{{{
  666. my $page=shift;
  667. my $destpage=shift;
  668. my $content=shift;
  669. run_hooks(filter => sub {
  670. $content=shift->(page => $page, destpage => $destpage,
  671. content => $content);
  672. });
  673. return $content;
  674. } #}}}
  675. sub indexlink () { #{{{
  676. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  677. } #}}}
  678. my $wikilock;
  679. sub lockwiki (;$) { #{{{
  680. my $wait=@_ ? shift : 1;
  681. # Take an exclusive lock on the wiki to prevent multiple concurrent
  682. # run issues. The lock will be dropped on program exit.
  683. if (! -d $config{wikistatedir}) {
  684. mkdir($config{wikistatedir});
  685. }
  686. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  687. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  688. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  689. if ($wait) {
  690. debug("wiki seems to be locked, waiting for lock");
  691. my $wait=600; # arbitrary, but don't hang forever to
  692. # prevent process pileup
  693. for (1..$wait) {
  694. return if flock($wikilock, 2 | 4);
  695. sleep 1;
  696. }
  697. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  698. }
  699. else {
  700. return 0;
  701. }
  702. }
  703. return 1;
  704. } #}}}
  705. sub unlockwiki () { #{{{
  706. return close($wikilock) if $wikilock;
  707. return;
  708. } #}}}
  709. my $commitlock;
  710. sub commit_hook_enabled () { #{{{
  711. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  712. error("cannot write to $config{wikistatedir}/commitlock: $!");
  713. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  714. close($commitlock) || error("failed closing commitlock: $!");
  715. return 0;
  716. }
  717. close($commitlock) || error("failed closing commitlock: $!");
  718. return 1;
  719. } #}}}
  720. sub disable_commit_hook () { #{{{
  721. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  722. error("cannot write to $config{wikistatedir}/commitlock: $!");
  723. if (! flock($commitlock, 2)) { # LOCK_EX
  724. error("failed to get commit lock");
  725. }
  726. return 1;
  727. } #}}}
  728. sub enable_commit_hook () { #{{{
  729. return close($commitlock) if $commitlock;
  730. return;
  731. } #}}}
  732. sub loadindex () { #{{{
  733. %oldrenderedfiles=%pagectime=();
  734. if (! $config{rebuild}) {
  735. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  736. %destsources=%renderedfiles=%pagecase=();
  737. }
  738. open (my $in, "<", "$config{wikistatedir}/index") || return;
  739. while (<$in>) {
  740. $_=possibly_foolish_untaint($_);
  741. chomp;
  742. my %items;
  743. $items{link}=[];
  744. $items{dest}=[];
  745. foreach my $i (split(/ /, $_)) {
  746. my ($item, $val)=split(/=/, $i, 2);
  747. push @{$items{$item}}, decode_entities($val);
  748. }
  749. next unless exists $items{src}; # skip bad lines for now
  750. my $page=pagename($items{src}[0]);
  751. if (! $config{rebuild}) {
  752. $pagesources{$page}=$items{src}[0];
  753. $pagemtime{$page}=$items{mtime}[0];
  754. $oldlinks{$page}=[@{$items{link}}];
  755. $links{$page}=[@{$items{link}}];
  756. $depends{$page}=$items{depends}[0] if exists $items{depends};
  757. $destsources{$_}=$page foreach @{$items{dest}};
  758. $renderedfiles{$page}=[@{$items{dest}}];
  759. $pagecase{lc $page}=$page;
  760. foreach my $k (grep /_/, keys %items) {
  761. my ($id, $key)=split(/_/, $k, 2);
  762. $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
  763. }
  764. }
  765. $oldrenderedfiles{$page}=[@{$items{dest}}];
  766. $pagectime{$page}=$items{ctime}[0];
  767. }
  768. return close($in);
  769. } #}}}
  770. sub saveindex () { #{{{
  771. run_hooks(savestate => sub { shift->() });
  772. my %hookids;
  773. foreach my $type (keys %hooks) {
  774. $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
  775. }
  776. my @hookids=sort keys %hookids;
  777. if (! -d $config{wikistatedir}) {
  778. mkdir($config{wikistatedir});
  779. }
  780. my $newfile="$config{wikistatedir}/index.new";
  781. my $cleanup = sub { unlink($newfile) };
  782. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  783. foreach my $page (keys %pagemtime) {
  784. next unless $pagemtime{$page};
  785. my $line="mtime=$pagemtime{$page} ".
  786. "ctime=$pagectime{$page} ".
  787. "src=$pagesources{$page}";
  788. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  789. my %count;
  790. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  791. if (exists $depends{$page}) {
  792. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  793. }
  794. if (exists $pagestate{$page}) {
  795. foreach my $id (@hookids) {
  796. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  797. $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key});
  798. }
  799. }
  800. }
  801. print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  802. }
  803. close $out || error("failed saving to $newfile: $!", $cleanup);
  804. rename($newfile, "$config{wikistatedir}/index") ||
  805. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  806. return 1;
  807. } #}}}
  808. sub template_file ($) { #{{{
  809. my $template=shift;
  810. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  811. return "$dir/$template" if -e "$dir/$template";
  812. }
  813. return;
  814. } #}}}
  815. sub template_params (@) { #{{{
  816. my $filename=template_file(shift);
  817. if (! defined $filename) {
  818. return if wantarray;
  819. return "";
  820. }
  821. my @ret=(
  822. filter => sub {
  823. my $text_ref = shift;
  824. ${$text_ref} = decode_utf8(${$text_ref});
  825. },
  826. filename => $filename,
  827. loop_context_vars => 1,
  828. die_on_bad_params => 0,
  829. @_
  830. );
  831. return wantarray ? @ret : {@ret};
  832. } #}}}
  833. sub template ($;@) { #{{{
  834. require HTML::Template;
  835. return HTML::Template->new(template_params(@_));
  836. } #}}}
  837. sub misctemplate ($$;@) { #{{{
  838. my $title=shift;
  839. my $pagebody=shift;
  840. my $template=template("misc.tmpl");
  841. $template->param(
  842. title => $title,
  843. indexlink => indexlink(),
  844. wikiname => $config{wikiname},
  845. pagebody => $pagebody,
  846. baseurl => baseurl(),
  847. @_,
  848. );
  849. run_hooks(pagetemplate => sub {
  850. shift->(page => "", destpage => "", template => $template);
  851. });
  852. return $template->output;
  853. }#}}}
  854. sub hook (@) { # {{{
  855. my %param=@_;
  856. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  857. error 'hook requires type, call, and id parameters';
  858. }
  859. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  860. $hooks{$param{type}}{$param{id}}=\%param;
  861. return 1;
  862. } # }}}
  863. sub run_hooks ($$) { # {{{
  864. # Calls the given sub for each hook of the given type,
  865. # passing it the hook function to call.
  866. my $type=shift;
  867. my $sub=shift;
  868. if (exists $hooks{$type}) {
  869. my @deferred;
  870. foreach my $id (keys %{$hooks{$type}}) {
  871. if ($hooks{$type}{$id}{last}) {
  872. push @deferred, $id;
  873. next;
  874. }
  875. $sub->($hooks{$type}{$id}{call});
  876. }
  877. foreach my $id (@deferred) {
  878. $sub->($hooks{$type}{$id}{call});
  879. }
  880. }
  881. return 1;
  882. } #}}}
  883. sub globlist_to_pagespec ($) { #{{{
  884. my @globlist=split(' ', shift);
  885. my (@spec, @skip);
  886. foreach my $glob (@globlist) {
  887. if ($glob=~/^!(.*)/) {
  888. push @skip, $glob;
  889. }
  890. else {
  891. push @spec, $glob;
  892. }
  893. }
  894. my $spec=join(' or ', @spec);
  895. if (@skip) {
  896. my $skip=join(' and ', @skip);
  897. if (length $spec) {
  898. $spec="$skip and ($spec)";
  899. }
  900. else {
  901. $spec=$skip;
  902. }
  903. }
  904. return $spec;
  905. } #}}}
  906. sub is_globlist ($) { #{{{
  907. my $s=shift;
  908. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  909. } #}}}
  910. sub safequote ($) { #{{{
  911. my $s=shift;
  912. $s=~s/[{}]//g;
  913. return "q{$s}";
  914. } #}}}
  915. sub add_depends ($$) { #{{{
  916. my $page=shift;
  917. my $pagespec=shift;
  918. if (! exists $depends{$page}) {
  919. $depends{$page}=$pagespec;
  920. }
  921. else {
  922. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  923. }
  924. return 1;
  925. } # }}}
  926. sub file_pruned ($$) { #{{{
  927. require File::Spec;
  928. my $file=File::Spec->canonpath(shift);
  929. my $base=File::Spec->canonpath(shift);
  930. $file =~ s#^\Q$base\E/+##;
  931. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  932. return $file =~ m/$regexp/ && $file ne $base;
  933. } #}}}
  934. sub gettext { #{{{
  935. # Only use gettext in the rare cases it's needed.
  936. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  937. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  938. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  939. if (! $gettext_obj) {
  940. $gettext_obj=eval q{
  941. use Locale::gettext q{textdomain};
  942. Locale::gettext->domain('ikiwiki')
  943. };
  944. if ($@) {
  945. print STDERR "$@";
  946. $gettext_obj=undef;
  947. return shift;
  948. }
  949. }
  950. return $gettext_obj->get(shift);
  951. }
  952. else {
  953. return shift;
  954. }
  955. } #}}}
  956. sub pagespec_merge ($$) { #{{{
  957. my $a=shift;
  958. my $b=shift;
  959. return $a if $a eq $b;
  960. # Support for old-style GlobLists.
  961. if (is_globlist($a)) {
  962. $a=globlist_to_pagespec($a);
  963. }
  964. if (is_globlist($b)) {
  965. $b=globlist_to_pagespec($b);
  966. }
  967. return "($a) or ($b)";
  968. } #}}}
  969. sub pagespec_translate ($) { #{{{
  970. # This assumes that $page is in scope in the function
  971. # that evalulates the translated pagespec code.
  972. my $spec=shift;
  973. # Support for old-style GlobLists.
  974. if (is_globlist($spec)) {
  975. $spec=globlist_to_pagespec($spec);
  976. }
  977. # Convert spec to perl code.
  978. my $code="";
  979. while ($spec=~m{
  980. \s* # ignore whitespace
  981. ( # 1: match a single word
  982. \! # !
  983. |
  984. \( # (
  985. |
  986. \) # )
  987. |
  988. \w+\([^\)]*\) # command(params)
  989. |
  990. [^\s()]+ # any other text
  991. )
  992. \s* # ignore whitespace
  993. }igx) {
  994. my $word=$1;
  995. if (lc $word eq 'and') {
  996. $code.=' &&';
  997. }
  998. elsif (lc $word eq 'or') {
  999. $code.=' ||';
  1000. }
  1001. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1002. $code.=' '.$word;
  1003. }
  1004. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1005. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1006. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
  1007. }
  1008. else {
  1009. $code.=' 0';
  1010. }
  1011. }
  1012. else {
  1013. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
  1014. }
  1015. }
  1016. return $code;
  1017. } #}}}
  1018. sub pagespec_match ($$;@) { #{{{
  1019. my $page=shift;
  1020. my $spec=shift;
  1021. my @params=@_;
  1022. # Backwards compatability with old calling convention.
  1023. if (@params == 1) {
  1024. unshift @params, 'location';
  1025. }
  1026. my $ret=eval pagespec_translate($spec);
  1027. return IkiWiki::FailReason->new('syntax error') if $@;
  1028. return $ret;
  1029. } #}}}
  1030. package IkiWiki::FailReason;
  1031. use overload ( #{{{
  1032. '""' => sub { ${$_[0]} },
  1033. '0+' => sub { 0 },
  1034. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1035. fallback => 1,
  1036. ); #}}}
  1037. sub new { #{{{
  1038. return bless \$_[1], $_[0];
  1039. } #}}}
  1040. package IkiWiki::SuccessReason;
  1041. use overload ( #{{{
  1042. '""' => sub { ${$_[0]} },
  1043. '0+' => sub { 1 },
  1044. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1045. fallback => 1,
  1046. ); #}}}
  1047. sub new { #{{{
  1048. return bless \$_[1], $_[0];
  1049. }; #}}}
  1050. package IkiWiki::PageSpec;
  1051. sub match_glob ($$;@) { #{{{
  1052. my $page=shift;
  1053. my $glob=shift;
  1054. my %params=@_;
  1055. my $from=exists $params{location} ? $params{location} : '';
  1056. # relative matching
  1057. if ($glob =~ m!^\./!) {
  1058. $from=~s#/?[^/]+$##;
  1059. $glob=~s#^\./##;
  1060. $glob="$from/$glob" if length $from;
  1061. }
  1062. # turn glob into safe regexp
  1063. $glob=quotemeta($glob);
  1064. $glob=~s/\\\*/.*/g;
  1065. $glob=~s/\\\?/./g;
  1066. if ($page=~/^$glob$/i) {
  1067. return IkiWiki::SuccessReason->new("$glob matches $page");
  1068. }
  1069. else {
  1070. return IkiWiki::FailReason->new("$glob does not match $page");
  1071. }
  1072. } #}}}
  1073. sub match_link ($$;@) { #{{{
  1074. my $page=shift;
  1075. my $link=lc(shift);
  1076. my %params=@_;
  1077. my $from=exists $params{location} ? $params{location} : '';
  1078. # relative matching
  1079. if ($link =~ m!^\.! && defined $from) {
  1080. $from=~s#/?[^/]+$##;
  1081. $link=~s#^\./##;
  1082. $link="$from/$link" if length $from;
  1083. }
  1084. my $links = $IkiWiki::links{$page};
  1085. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1086. my $bestlink = IkiWiki::bestlink($from, $link);
  1087. foreach my $p (@{$links}) {
  1088. if (length $bestlink) {
  1089. return IkiWiki::SuccessReason->new("$page links to $link")
  1090. if $bestlink eq IkiWiki::bestlink($page, $p);
  1091. }
  1092. else {
  1093. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1094. if match_glob($p, $link, %params);
  1095. }
  1096. }
  1097. return IkiWiki::FailReason->new("$page does not link to $link");
  1098. } #}}}
  1099. sub match_backlink ($$;@) { #{{{
  1100. return match_link($_[1], $_[0], @_);
  1101. } #}}}
  1102. sub match_created_before ($$;@) { #{{{
  1103. my $page=shift;
  1104. my $testpage=shift;
  1105. if (exists $IkiWiki::pagectime{$testpage}) {
  1106. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1107. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1108. }
  1109. else {
  1110. return IkiWiki::FailReason->new("$page not created before $testpage");
  1111. }
  1112. }
  1113. else {
  1114. return IkiWiki::FailReason->new("$testpage has no ctime");
  1115. }
  1116. } #}}}
  1117. sub match_created_after ($$;@) { #{{{
  1118. my $page=shift;
  1119. my $testpage=shift;
  1120. if (exists $IkiWiki::pagectime{$testpage}) {
  1121. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1122. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1123. }
  1124. else {
  1125. return IkiWiki::FailReason->new("$page not created after $testpage");
  1126. }
  1127. }
  1128. else {
  1129. return IkiWiki::FailReason->new("$testpage has no ctime");
  1130. }
  1131. } #}}}
  1132. sub match_creation_day ($$;@) { #{{{
  1133. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1134. return IkiWiki::SuccessReason->new('creation_day matched');
  1135. }
  1136. else {
  1137. return IkiWiki::FailReason->new('creation_day did not match');
  1138. }
  1139. } #}}}
  1140. sub match_creation_month ($$;@) { #{{{
  1141. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1142. return IkiWiki::SuccessReason->new('creation_month matched');
  1143. }
  1144. else {
  1145. return IkiWiki::FailReason->new('creation_month did not match');
  1146. }
  1147. } #}}}
  1148. sub match_creation_year ($$;@) { #{{{
  1149. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1150. return IkiWiki::SuccessReason->new('creation_year matched');
  1151. }
  1152. else {
  1153. return IkiWiki::FailReason->new('creation_year did not match');
  1154. }
  1155. } #}}}
  1156. sub match_user ($$;@) { #{{{
  1157. shift;
  1158. my $user=shift;
  1159. my %params=@_;
  1160. return IkiWiki::FailReason->new('cannot match user')
  1161. unless exists $params{user};
  1162. if ($user eq $params{user}) {
  1163. return IkiWiki::SuccessReason->new("user is $user")
  1164. }
  1165. else {
  1166. return IkiWiki::FailReason->new("user is not $user");
  1167. }
  1168. } #}}}
  1169. 1