summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: c70307b5f299ae0955e086fd8ebeff937ac895e9 (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 openiduser ($) { #{{{
  511. my $user=shift;
  512. if ($user =~ m!^https?://! &&
  513. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  514. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  515. my $display=$oid->display;
  516. # Convert "user.somehost.com" to "user [somehost.com]".
  517. if ($display !~ /\[/) {
  518. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  519. }
  520. # Convert "http://somehost.com/user" to "user [somehost.com]".
  521. if ($display !~ /\[/) {
  522. $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
  523. }
  524. $display=~s!^https?://!!; # make sure this is removed
  525. eval q{use CGI 'escapeHTML'};
  526. error($@) if $@;
  527. return escapeHTML($display);
  528. }
  529. return;
  530. }
  531. sub userlink ($) { #{{{
  532. my $user=shift;
  533. my $oiduser=openiduser($user);
  534. if (defined $oiduser) {
  535. return "<a href=\"$user\">$oiduser</a>";
  536. }
  537. else {
  538. return htmllink("", "", escapeHTML(
  539. length $config{userdir} ? $config{userdir}."/".$user : $user
  540. ), noimageinline => 1);
  541. }
  542. } #}}}
  543. sub htmlize ($$$) { #{{{
  544. my $page=shift;
  545. my $type=shift;
  546. my $content=shift;
  547. my $oneline = $content !~ /\n/;
  548. if (exists $hooks{htmlize}{$type}) {
  549. $content=$hooks{htmlize}{$type}{call}->(
  550. page => $page,
  551. content => $content,
  552. );
  553. }
  554. else {
  555. error("htmlization of $type not supported");
  556. }
  557. run_hooks(sanitize => sub {
  558. $content=shift->(
  559. page => $page,
  560. content => $content,
  561. );
  562. });
  563. if ($oneline) {
  564. # hack to get rid of enclosing junk added by markdown
  565. # and other htmlizers
  566. $content=~s/^<p>//i;
  567. $content=~s/<\/p>$//i;
  568. chomp $content;
  569. }
  570. return $content;
  571. } #}}}
  572. sub linkify ($$$) { #{{{
  573. my $lpage=shift; # the page containing the links
  574. my $page=shift; # the page the link will end up on (different for inline)
  575. my $content=shift;
  576. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  577. defined $2
  578. ? ( $1
  579. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  580. : htmllink($lpage, $page, linkpage($3),
  581. anchor => $4, linktext => pagetitle($2)))
  582. : ( $1
  583. ? "[[$3".($4 ? "#$4" : "")."]]"
  584. : htmllink($lpage, $page, linkpage($3),
  585. anchor => $4))
  586. }eg;
  587. return $content;
  588. } #}}}
  589. my %preprocessing;
  590. our $preprocess_preview=0;
  591. sub preprocess ($$$;$$) { #{{{
  592. my $page=shift; # the page the data comes from
  593. my $destpage=shift; # the page the data will appear in (different for inline)
  594. my $content=shift;
  595. my $scan=shift;
  596. my $preview=shift;
  597. # Using local because it needs to be set within any nested calls
  598. # of this function.
  599. local $preprocess_preview=$preview if defined $preview;
  600. my $handle=sub {
  601. my $escape=shift;
  602. my $command=shift;
  603. my $params=shift;
  604. if (length $escape) {
  605. return "[[$command $params]]";
  606. }
  607. elsif (exists $hooks{preprocess}{$command}) {
  608. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  609. # Note: preserve order of params, some plugins may
  610. # consider it significant.
  611. my @params;
  612. while ($params =~ m{
  613. (?:([-\w]+)=)? # 1: named parameter key?
  614. (?:
  615. """(.*?)""" # 2: triple-quoted value
  616. |
  617. "([^"]+)" # 3: single-quoted value
  618. |
  619. (\S+) # 4: unquoted value
  620. )
  621. (?:\s+|$) # delimiter to next param
  622. }sgx) {
  623. my $key=$1;
  624. my $val;
  625. if (defined $2) {
  626. $val=$2;
  627. $val=~s/\r\n/\n/mg;
  628. $val=~s/^\n+//g;
  629. $val=~s/\n+$//g;
  630. }
  631. elsif (defined $3) {
  632. $val=$3;
  633. }
  634. elsif (defined $4) {
  635. $val=$4;
  636. }
  637. if (defined $key) {
  638. push @params, $key, $val;
  639. }
  640. else {
  641. push @params, $val, '';
  642. }
  643. }
  644. if ($preprocessing{$page}++ > 3) {
  645. # Avoid loops of preprocessed pages preprocessing
  646. # other pages that preprocess them, etc.
  647. #translators: The first parameter is a
  648. #translators: preprocessor directive name,
  649. #translators: the second a page name, the
  650. #translators: third a number.
  651. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  652. $command, $page, $preprocessing{$page}).
  653. "]]";
  654. }
  655. my $ret;
  656. if (! $scan) {
  657. $ret=$hooks{preprocess}{$command}{call}->(
  658. @params,
  659. page => $page,
  660. destpage => $destpage,
  661. preview => $preprocess_preview,
  662. );
  663. }
  664. else {
  665. # use void context during scan pass
  666. $hooks{preprocess}{$command}{call}->(
  667. @params,
  668. page => $page,
  669. destpage => $destpage,
  670. preview => $preprocess_preview,
  671. );
  672. $ret="";
  673. }
  674. $preprocessing{$page}--;
  675. return $ret;
  676. }
  677. else {
  678. return "[[$command $params]]";
  679. }
  680. };
  681. $content =~ s{
  682. (\\?) # 1: escape?
  683. \[\[ # directive open
  684. ([-\w]+) # 2: command
  685. \s+
  686. ( # 3: the parameters..
  687. (?:
  688. (?:[-\w]+=)? # named parameter key?
  689. (?:
  690. """.*?""" # triple-quoted value
  691. |
  692. "[^"]+" # single-quoted value
  693. |
  694. [^\s\]]+ # unquoted value
  695. )
  696. \s* # whitespace or end
  697. # of directive
  698. )
  699. *) # 0 or more parameters
  700. \]\] # directive closed
  701. }{$handle->($1, $2, $3)}sexg;
  702. return $content;
  703. } #}}}
  704. sub filter ($$$) { #{{{
  705. my $page=shift;
  706. my $destpage=shift;
  707. my $content=shift;
  708. run_hooks(filter => sub {
  709. $content=shift->(page => $page, destpage => $destpage,
  710. content => $content);
  711. });
  712. return $content;
  713. } #}}}
  714. sub indexlink () { #{{{
  715. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  716. } #}}}
  717. my $wikilock;
  718. sub lockwiki (;$) { #{{{
  719. my $wait=@_ ? shift : 1;
  720. # Take an exclusive lock on the wiki to prevent multiple concurrent
  721. # run issues. The lock will be dropped on program exit.
  722. if (! -d $config{wikistatedir}) {
  723. mkdir($config{wikistatedir});
  724. }
  725. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  726. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  727. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  728. if ($wait) {
  729. debug("wiki seems to be locked, waiting for lock");
  730. my $wait=600; # arbitrary, but don't hang forever to
  731. # prevent process pileup
  732. for (1..$wait) {
  733. return if flock($wikilock, 2 | 4);
  734. sleep 1;
  735. }
  736. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  737. }
  738. else {
  739. return 0;
  740. }
  741. }
  742. return 1;
  743. } #}}}
  744. sub unlockwiki () { #{{{
  745. return close($wikilock) if $wikilock;
  746. return;
  747. } #}}}
  748. my $commitlock;
  749. sub commit_hook_enabled () { #{{{
  750. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  751. error("cannot write to $config{wikistatedir}/commitlock: $!");
  752. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  753. close($commitlock) || error("failed closing commitlock: $!");
  754. return 0;
  755. }
  756. close($commitlock) || error("failed closing commitlock: $!");
  757. return 1;
  758. } #}}}
  759. sub disable_commit_hook () { #{{{
  760. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  761. error("cannot write to $config{wikistatedir}/commitlock: $!");
  762. if (! flock($commitlock, 2)) { # LOCK_EX
  763. error("failed to get commit lock");
  764. }
  765. return 1;
  766. } #}}}
  767. sub enable_commit_hook () { #{{{
  768. return close($commitlock) if $commitlock;
  769. return;
  770. } #}}}
  771. sub loadindex () { #{{{
  772. %oldrenderedfiles=%pagectime=();
  773. if (! $config{rebuild}) {
  774. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  775. %destsources=%renderedfiles=%pagecase=();
  776. }
  777. open (my $in, "<", "$config{wikistatedir}/index") || return;
  778. while (<$in>) {
  779. $_=possibly_foolish_untaint($_);
  780. chomp;
  781. my %items;
  782. $items{link}=[];
  783. $items{dest}=[];
  784. foreach my $i (split(/ /, $_)) {
  785. my ($item, $val)=split(/=/, $i, 2);
  786. push @{$items{$item}}, decode_entities($val);
  787. }
  788. next unless exists $items{src}; # skip bad lines for now
  789. my $page=pagename($items{src}[0]);
  790. if (! $config{rebuild}) {
  791. $pagesources{$page}=$items{src}[0];
  792. $pagemtime{$page}=$items{mtime}[0];
  793. $oldlinks{$page}=[@{$items{link}}];
  794. $links{$page}=[@{$items{link}}];
  795. $depends{$page}=$items{depends}[0] if exists $items{depends};
  796. $destsources{$_}=$page foreach @{$items{dest}};
  797. $renderedfiles{$page}=[@{$items{dest}}];
  798. $pagecase{lc $page}=$page;
  799. foreach my $k (grep /_/, keys %items) {
  800. my ($id, $key)=split(/_/, $k, 2);
  801. $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
  802. }
  803. }
  804. $oldrenderedfiles{$page}=[@{$items{dest}}];
  805. $pagectime{$page}=$items{ctime}[0];
  806. }
  807. return close($in);
  808. } #}}}
  809. sub saveindex () { #{{{
  810. run_hooks(savestate => sub { shift->() });
  811. my %hookids;
  812. foreach my $type (keys %hooks) {
  813. $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
  814. }
  815. my @hookids=sort keys %hookids;
  816. if (! -d $config{wikistatedir}) {
  817. mkdir($config{wikistatedir});
  818. }
  819. my $newfile="$config{wikistatedir}/index.new";
  820. my $cleanup = sub { unlink($newfile) };
  821. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  822. foreach my $page (keys %pagemtime) {
  823. next unless $pagemtime{$page};
  824. my $line="mtime=$pagemtime{$page} ".
  825. "ctime=$pagectime{$page} ".
  826. "src=$pagesources{$page}";
  827. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  828. my %count;
  829. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  830. if (exists $depends{$page}) {
  831. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  832. }
  833. if (exists $pagestate{$page}) {
  834. foreach my $id (@hookids) {
  835. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  836. $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key});
  837. }
  838. }
  839. }
  840. print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  841. }
  842. close $out || error("failed saving to $newfile: $!", $cleanup);
  843. rename($newfile, "$config{wikistatedir}/index") ||
  844. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  845. return 1;
  846. } #}}}
  847. sub template_file ($) { #{{{
  848. my $template=shift;
  849. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  850. return "$dir/$template" if -e "$dir/$template";
  851. }
  852. return;
  853. } #}}}
  854. sub template_params (@) { #{{{
  855. my $filename=template_file(shift);
  856. if (! defined $filename) {
  857. return if wantarray;
  858. return "";
  859. }
  860. my @ret=(
  861. filter => sub {
  862. my $text_ref = shift;
  863. ${$text_ref} = decode_utf8(${$text_ref});
  864. },
  865. filename => $filename,
  866. loop_context_vars => 1,
  867. die_on_bad_params => 0,
  868. @_
  869. );
  870. return wantarray ? @ret : {@ret};
  871. } #}}}
  872. sub template ($;@) { #{{{
  873. require HTML::Template;
  874. return HTML::Template->new(template_params(@_));
  875. } #}}}
  876. sub misctemplate ($$;@) { #{{{
  877. my $title=shift;
  878. my $pagebody=shift;
  879. my $template=template("misc.tmpl");
  880. $template->param(
  881. title => $title,
  882. indexlink => indexlink(),
  883. wikiname => $config{wikiname},
  884. pagebody => $pagebody,
  885. baseurl => baseurl(),
  886. @_,
  887. );
  888. run_hooks(pagetemplate => sub {
  889. shift->(page => "", destpage => "", template => $template);
  890. });
  891. return $template->output;
  892. }#}}}
  893. sub hook (@) { # {{{
  894. my %param=@_;
  895. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  896. error 'hook requires type, call, and id parameters';
  897. }
  898. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  899. $hooks{$param{type}}{$param{id}}=\%param;
  900. return 1;
  901. } # }}}
  902. sub run_hooks ($$) { # {{{
  903. # Calls the given sub for each hook of the given type,
  904. # passing it the hook function to call.
  905. my $type=shift;
  906. my $sub=shift;
  907. if (exists $hooks{$type}) {
  908. my @deferred;
  909. foreach my $id (keys %{$hooks{$type}}) {
  910. if ($hooks{$type}{$id}{last}) {
  911. push @deferred, $id;
  912. next;
  913. }
  914. $sub->($hooks{$type}{$id}{call});
  915. }
  916. foreach my $id (@deferred) {
  917. $sub->($hooks{$type}{$id}{call});
  918. }
  919. }
  920. return 1;
  921. } #}}}
  922. sub globlist_to_pagespec ($) { #{{{
  923. my @globlist=split(' ', shift);
  924. my (@spec, @skip);
  925. foreach my $glob (@globlist) {
  926. if ($glob=~/^!(.*)/) {
  927. push @skip, $glob;
  928. }
  929. else {
  930. push @spec, $glob;
  931. }
  932. }
  933. my $spec=join(' or ', @spec);
  934. if (@skip) {
  935. my $skip=join(' and ', @skip);
  936. if (length $spec) {
  937. $spec="$skip and ($spec)";
  938. }
  939. else {
  940. $spec=$skip;
  941. }
  942. }
  943. return $spec;
  944. } #}}}
  945. sub is_globlist ($) { #{{{
  946. my $s=shift;
  947. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  948. } #}}}
  949. sub safequote ($) { #{{{
  950. my $s=shift;
  951. $s=~s/[{}]//g;
  952. return "q{$s}";
  953. } #}}}
  954. sub add_depends ($$) { #{{{
  955. my $page=shift;
  956. my $pagespec=shift;
  957. if (! exists $depends{$page}) {
  958. $depends{$page}=$pagespec;
  959. }
  960. else {
  961. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  962. }
  963. return 1;
  964. } # }}}
  965. sub file_pruned ($$) { #{{{
  966. require File::Spec;
  967. my $file=File::Spec->canonpath(shift);
  968. my $base=File::Spec->canonpath(shift);
  969. $file =~ s#^\Q$base\E/+##;
  970. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  971. return $file =~ m/$regexp/ && $file ne $base;
  972. } #}}}
  973. sub gettext { #{{{
  974. # Only use gettext in the rare cases it's needed.
  975. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  976. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  977. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  978. if (! $gettext_obj) {
  979. $gettext_obj=eval q{
  980. use Locale::gettext q{textdomain};
  981. Locale::gettext->domain('ikiwiki')
  982. };
  983. if ($@) {
  984. print STDERR "$@";
  985. $gettext_obj=undef;
  986. return shift;
  987. }
  988. }
  989. return $gettext_obj->get(shift);
  990. }
  991. else {
  992. return shift;
  993. }
  994. } #}}}
  995. sub pagespec_merge ($$) { #{{{
  996. my $a=shift;
  997. my $b=shift;
  998. return $a if $a eq $b;
  999. # Support for old-style GlobLists.
  1000. if (is_globlist($a)) {
  1001. $a=globlist_to_pagespec($a);
  1002. }
  1003. if (is_globlist($b)) {
  1004. $b=globlist_to_pagespec($b);
  1005. }
  1006. return "($a) or ($b)";
  1007. } #}}}
  1008. sub pagespec_translate ($) { #{{{
  1009. # This assumes that $page is in scope in the function
  1010. # that evalulates the translated pagespec code.
  1011. my $spec=shift;
  1012. # Support for old-style GlobLists.
  1013. if (is_globlist($spec)) {
  1014. $spec=globlist_to_pagespec($spec);
  1015. }
  1016. # Convert spec to perl code.
  1017. my $code="";
  1018. while ($spec=~m{
  1019. \s* # ignore whitespace
  1020. ( # 1: match a single word
  1021. \! # !
  1022. |
  1023. \( # (
  1024. |
  1025. \) # )
  1026. |
  1027. \w+\([^\)]*\) # command(params)
  1028. |
  1029. [^\s()]+ # any other text
  1030. )
  1031. \s* # ignore whitespace
  1032. }igx) {
  1033. my $word=$1;
  1034. if (lc $word eq 'and') {
  1035. $code.=' &&';
  1036. }
  1037. elsif (lc $word eq 'or') {
  1038. $code.=' ||';
  1039. }
  1040. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1041. $code.=' '.$word;
  1042. }
  1043. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1044. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1045. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
  1046. }
  1047. else {
  1048. $code.=' 0';
  1049. }
  1050. }
  1051. else {
  1052. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
  1053. }
  1054. }
  1055. return $code;
  1056. } #}}}
  1057. sub pagespec_match ($$;@) { #{{{
  1058. my $page=shift;
  1059. my $spec=shift;
  1060. my @params=@_;
  1061. # Backwards compatability with old calling convention.
  1062. if (@params == 1) {
  1063. unshift @params, 'location';
  1064. }
  1065. my $ret=eval pagespec_translate($spec);
  1066. return IkiWiki::FailReason->new('syntax error') if $@;
  1067. return $ret;
  1068. } #}}}
  1069. package IkiWiki::FailReason;
  1070. use overload ( #{{{
  1071. '""' => sub { ${$_[0]} },
  1072. '0+' => sub { 0 },
  1073. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1074. fallback => 1,
  1075. ); #}}}
  1076. sub new { #{{{
  1077. return bless \$_[1], $_[0];
  1078. } #}}}
  1079. package IkiWiki::SuccessReason;
  1080. use overload ( #{{{
  1081. '""' => sub { ${$_[0]} },
  1082. '0+' => sub { 1 },
  1083. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1084. fallback => 1,
  1085. ); #}}}
  1086. sub new { #{{{
  1087. return bless \$_[1], $_[0];
  1088. }; #}}}
  1089. package IkiWiki::PageSpec;
  1090. sub match_glob ($$;@) { #{{{
  1091. my $page=shift;
  1092. my $glob=shift;
  1093. my %params=@_;
  1094. my $from=exists $params{location} ? $params{location} : '';
  1095. # relative matching
  1096. if ($glob =~ m!^\./!) {
  1097. $from=~s#/?[^/]+$##;
  1098. $glob=~s#^\./##;
  1099. $glob="$from/$glob" if length $from;
  1100. }
  1101. # turn glob into safe regexp
  1102. $glob=quotemeta($glob);
  1103. $glob=~s/\\\*/.*/g;
  1104. $glob=~s/\\\?/./g;
  1105. if ($page=~/^$glob$/i) {
  1106. return IkiWiki::SuccessReason->new("$glob matches $page");
  1107. }
  1108. else {
  1109. return IkiWiki::FailReason->new("$glob does not match $page");
  1110. }
  1111. } #}}}
  1112. sub match_link ($$;@) { #{{{
  1113. my $page=shift;
  1114. my $link=lc(shift);
  1115. my %params=@_;
  1116. my $from=exists $params{location} ? $params{location} : '';
  1117. # relative matching
  1118. if ($link =~ m!^\.! && defined $from) {
  1119. $from=~s#/?[^/]+$##;
  1120. $link=~s#^\./##;
  1121. $link="$from/$link" if length $from;
  1122. }
  1123. my $links = $IkiWiki::links{$page};
  1124. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1125. my $bestlink = IkiWiki::bestlink($from, $link);
  1126. foreach my $p (@{$links}) {
  1127. if (length $bestlink) {
  1128. return IkiWiki::SuccessReason->new("$page links to $link")
  1129. if $bestlink eq IkiWiki::bestlink($page, $p);
  1130. }
  1131. else {
  1132. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1133. if match_glob($p, $link, %params);
  1134. }
  1135. }
  1136. return IkiWiki::FailReason->new("$page does not link to $link");
  1137. } #}}}
  1138. sub match_backlink ($$;@) { #{{{
  1139. return match_link($_[1], $_[0], @_);
  1140. } #}}}
  1141. sub match_created_before ($$;@) { #{{{
  1142. my $page=shift;
  1143. my $testpage=shift;
  1144. if (exists $IkiWiki::pagectime{$testpage}) {
  1145. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1146. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1147. }
  1148. else {
  1149. return IkiWiki::FailReason->new("$page not created before $testpage");
  1150. }
  1151. }
  1152. else {
  1153. return IkiWiki::FailReason->new("$testpage has no ctime");
  1154. }
  1155. } #}}}
  1156. sub match_created_after ($$;@) { #{{{
  1157. my $page=shift;
  1158. my $testpage=shift;
  1159. if (exists $IkiWiki::pagectime{$testpage}) {
  1160. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1161. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1162. }
  1163. else {
  1164. return IkiWiki::FailReason->new("$page not created after $testpage");
  1165. }
  1166. }
  1167. else {
  1168. return IkiWiki::FailReason->new("$testpage has no ctime");
  1169. }
  1170. } #}}}
  1171. sub match_creation_day ($$;@) { #{{{
  1172. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1173. return IkiWiki::SuccessReason->new('creation_day matched');
  1174. }
  1175. else {
  1176. return IkiWiki::FailReason->new('creation_day did not match');
  1177. }
  1178. } #}}}
  1179. sub match_creation_month ($$;@) { #{{{
  1180. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1181. return IkiWiki::SuccessReason->new('creation_month matched');
  1182. }
  1183. else {
  1184. return IkiWiki::FailReason->new('creation_month did not match');
  1185. }
  1186. } #}}}
  1187. sub match_creation_year ($$;@) { #{{{
  1188. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1189. return IkiWiki::SuccessReason->new('creation_year matched');
  1190. }
  1191. else {
  1192. return IkiWiki::FailReason->new('creation_year did not match');
  1193. }
  1194. } #}}}
  1195. sub match_user ($$;@) { #{{{
  1196. shift;
  1197. my $user=shift;
  1198. my %params=@_;
  1199. return IkiWiki::FailReason->new('cannot match user')
  1200. unless exists $params{user};
  1201. if ($user eq $params{user}) {
  1202. return IkiWiki::SuccessReason->new("user is $user")
  1203. }
  1204. else {
  1205. return IkiWiki::FailReason->new("user is not $user");
  1206. }
  1207. } #}}}
  1208. 1