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