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