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