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