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