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