summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: c1d9119e840662f449d0cd257c0ca1c14df48653 (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_urlpath ($) { #{{{
  451. my $url=shift;
  452. if ($config{usedirs}) {
  453. $url =~ s!/index.$config{htmlext}$!/!;
  454. }
  455. # Ensure url is not an empty link, and
  456. # if it's relative, make that explicit to avoid colon confusion.
  457. if ($url !~ /\//) {
  458. $url="./$url";
  459. }
  460. return $url;
  461. } #}}}
  462. sub urlto ($$) { #{{{
  463. my $to=shift;
  464. my $from=shift;
  465. if (! length $to) {
  466. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  467. }
  468. if (! $destsources{$to}) {
  469. $to=htmlpage($to);
  470. }
  471. my $link = abs2rel($to, dirname(htmlpage($from)));
  472. return beautify_urlpath($link);
  473. } #}}}
  474. sub htmllink ($$$;@) { #{{{
  475. my $lpage=shift; # the page doing the linking
  476. my $page=shift; # the page that will contain the link (different for inline)
  477. my $link=shift;
  478. my %opts=@_;
  479. $link=~s/\/$//;
  480. my $bestlink;
  481. if (! $opts{forcesubpage}) {
  482. $bestlink=bestlink($lpage, $link);
  483. }
  484. else {
  485. $bestlink="$lpage/".lc($link);
  486. }
  487. my $linktext;
  488. if (defined $opts{linktext}) {
  489. $linktext=$opts{linktext};
  490. }
  491. else {
  492. $linktext=pagetitle(basename($link));
  493. }
  494. return "<span class=\"selflink\">$linktext</span>"
  495. if length $bestlink && $page eq $bestlink &&
  496. ! defined $opts{anchor};
  497. if (! $destsources{$bestlink}) {
  498. $bestlink=htmlpage($bestlink);
  499. if (! $destsources{$bestlink}) {
  500. return $linktext unless length $config{cgiurl};
  501. return "<span class=\"createlink\"><a href=\"".
  502. cgiurl(
  503. do => "create",
  504. page => lc($link),
  505. from => $lpage
  506. ).
  507. "\" rel=\"nofollow\">?</a>$linktext</span>"
  508. }
  509. }
  510. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  511. $bestlink=beautify_urlpath($bestlink);
  512. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  513. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  514. }
  515. if (defined $opts{anchor}) {
  516. $bestlink.="#".$opts{anchor};
  517. }
  518. my @attrs;
  519. if (defined $opts{rel}) {
  520. push @attrs, ' rel="'.$opts{rel}.'"';
  521. }
  522. if (defined $opts{class}) {
  523. push @attrs, ' class="'.$opts{class}.'"';
  524. }
  525. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  526. } #}}}
  527. sub userlink ($) { #{{{
  528. my $user=shift;
  529. my $oiduser=eval { openiduser($user) };
  530. if (defined $oiduser) {
  531. return "<a href=\"$user\">$oiduser</a>";
  532. }
  533. else {
  534. eval q{use CGI 'escapeHTML'};
  535. error($@) if $@;
  536. return htmllink("", "", escapeHTML(
  537. length $config{userdir} ? $config{userdir}."/".$user : $user
  538. ), noimageinline => 1);
  539. }
  540. } #}}}
  541. sub htmlize ($$$$) { #{{{
  542. my $page=shift;
  543. my $destpage=shift;
  544. my $type=shift;
  545. my $content=shift;
  546. my $oneline = $content !~ /\n/;
  547. if (exists $hooks{htmlize}{$type}) {
  548. $content=$hooks{htmlize}{$type}{call}->(
  549. page => $page,
  550. content => $content,
  551. );
  552. }
  553. else {
  554. error("htmlization of $type not supported");
  555. }
  556. run_hooks(sanitize => sub {
  557. $content=shift->(
  558. page => $page,
  559. destpage => $destpage,
  560. content => $content,
  561. );
  562. });
  563. if ($oneline) {
  564. # hack to get rid of enclosing junk added by markdown
  565. # and other htmlizers
  566. $content=~s/^<p>//i;
  567. $content=~s/<\/p>$//i;
  568. chomp $content;
  569. }
  570. return $content;
  571. } #}}}
  572. sub linkify ($$$) { #{{{
  573. my $page=shift;
  574. my $destpage=shift;
  575. my $content=shift;
  576. run_hooks(linkify => sub {
  577. $content=shift->(
  578. page => $page,
  579. destpage => $destpage,
  580. content => $content,
  581. );
  582. });
  583. return $content;
  584. } #}}}
  585. our %preprocessing;
  586. our $preprocess_preview=0;
  587. sub preprocess ($$$;$$) { #{{{
  588. my $page=shift; # the page the data comes from
  589. my $destpage=shift; # the page the data will appear in (different for inline)
  590. my $content=shift;
  591. my $scan=shift;
  592. my $preview=shift;
  593. # Using local because it needs to be set within any nested calls
  594. # of this function.
  595. local $preprocess_preview=$preview if defined $preview;
  596. my $handle=sub {
  597. my $escape=shift;
  598. my $prefix=shift;
  599. my $command=shift;
  600. my $params=shift;
  601. if (length $escape) {
  602. return "[[$prefix$command $params]]";
  603. }
  604. elsif (exists $hooks{preprocess}{$command}) {
  605. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  606. # Note: preserve order of params, some plugins may
  607. # consider it significant.
  608. my @params;
  609. while ($params =~ m{
  610. (?:([-\w]+)=)? # 1: named parameter key?
  611. (?:
  612. """(.*?)""" # 2: triple-quoted value
  613. |
  614. "([^"]+)" # 3: single-quoted value
  615. |
  616. (\S+) # 4: unquoted value
  617. )
  618. (?:\s+|$) # delimiter to next param
  619. }sgx) {
  620. my $key=$1;
  621. my $val;
  622. if (defined $2) {
  623. $val=$2;
  624. $val=~s/\r\n/\n/mg;
  625. $val=~s/^\n+//g;
  626. $val=~s/\n+$//g;
  627. }
  628. elsif (defined $3) {
  629. $val=$3;
  630. }
  631. elsif (defined $4) {
  632. $val=$4;
  633. }
  634. if (defined $key) {
  635. push @params, $key, $val;
  636. }
  637. else {
  638. push @params, $val, '';
  639. }
  640. }
  641. if ($preprocessing{$page}++ > 3) {
  642. # Avoid loops of preprocessed pages preprocessing
  643. # other pages that preprocess them, etc.
  644. #translators: The first parameter is a
  645. #translators: preprocessor directive name,
  646. #translators: the second a page name, the
  647. #translators: third a number.
  648. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  649. $command, $page, $preprocessing{$page}).
  650. "]]";
  651. }
  652. my $ret;
  653. if (! $scan) {
  654. $ret=$hooks{preprocess}{$command}{call}->(
  655. @params,
  656. page => $page,
  657. destpage => $destpage,
  658. preview => $preprocess_preview,
  659. );
  660. }
  661. else {
  662. # use void context during scan pass
  663. $hooks{preprocess}{$command}{call}->(
  664. @params,
  665. page => $page,
  666. destpage => $destpage,
  667. preview => $preprocess_preview,
  668. );
  669. $ret="";
  670. }
  671. $preprocessing{$page}--;
  672. return $ret;
  673. }
  674. else {
  675. return "[[$prefix$command $params]]";
  676. }
  677. };
  678. my $regex;
  679. if ($config{prefix_directives}) {
  680. $regex = qr{
  681. (\\?) # 1: escape?
  682. \[\[(!) # directive open; 2: prefix
  683. ([-\w]+) # 3: command
  684. ( # 4: the parameters..
  685. \s+ # Must have space if parameters present
  686. (?:
  687. (?:[-\w]+=)? # named parameter key?
  688. (?:
  689. """.*?""" # triple-quoted value
  690. |
  691. "[^"]+" # single-quoted value
  692. |
  693. [^\s\]]+ # unquoted value
  694. )
  695. \s* # whitespace or end
  696. # of directive
  697. )
  698. *)? # 0 or more parameters
  699. \]\] # directive closed
  700. }sx;
  701. } else {
  702. $regex = qr{
  703. (\\?) # 1: escape?
  704. \[\[(!?) # directive open; 2: optional prefix
  705. ([-\w]+) # 3: command
  706. \s+
  707. ( # 4: the parameters..
  708. (?:
  709. (?:[-\w]+=)? # named parameter key?
  710. (?:
  711. """.*?""" # triple-quoted value
  712. |
  713. "[^"]+" # single-quoted value
  714. |
  715. [^\s\]]+ # unquoted value
  716. )
  717. \s* # whitespace or end
  718. # of directive
  719. )
  720. *) # 0 or more parameters
  721. \]\] # directive closed
  722. }sx;
  723. }
  724. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  725. return $content;
  726. } #}}}
  727. sub filter ($$$) { #{{{
  728. my $page=shift;
  729. my $destpage=shift;
  730. my $content=shift;
  731. run_hooks(filter => sub {
  732. $content=shift->(page => $page, destpage => $destpage,
  733. content => $content);
  734. });
  735. return $content;
  736. } #}}}
  737. sub indexlink () { #{{{
  738. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  739. } #}}}
  740. my $wikilock;
  741. sub lockwiki (;$) { #{{{
  742. my $wait=@_ ? shift : 1;
  743. # Take an exclusive lock on the wiki to prevent multiple concurrent
  744. # run issues. The lock will be dropped on program exit.
  745. if (! -d $config{wikistatedir}) {
  746. mkdir($config{wikistatedir});
  747. }
  748. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  749. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  750. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  751. if ($wait) {
  752. debug("wiki seems to be locked, waiting for lock");
  753. my $wait=600; # arbitrary, but don't hang forever to
  754. # prevent process pileup
  755. for (1..$wait) {
  756. return if flock($wikilock, 2 | 4);
  757. sleep 1;
  758. }
  759. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  760. }
  761. else {
  762. return 0;
  763. }
  764. }
  765. return 1;
  766. } #}}}
  767. sub unlockwiki () { #{{{
  768. return close($wikilock) if $wikilock;
  769. return;
  770. } #}}}
  771. my $commitlock;
  772. sub commit_hook_enabled () { #{{{
  773. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  774. error("cannot write to $config{wikistatedir}/commitlock: $!");
  775. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  776. close($commitlock) || error("failed closing commitlock: $!");
  777. return 0;
  778. }
  779. close($commitlock) || error("failed closing commitlock: $!");
  780. return 1;
  781. } #}}}
  782. sub disable_commit_hook () { #{{{
  783. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  784. error("cannot write to $config{wikistatedir}/commitlock: $!");
  785. if (! flock($commitlock, 2)) { # LOCK_EX
  786. error("failed to get commit lock");
  787. }
  788. return 1;
  789. } #}}}
  790. sub enable_commit_hook () { #{{{
  791. return close($commitlock) if $commitlock;
  792. return;
  793. } #}}}
  794. sub loadindex () { #{{{
  795. %oldrenderedfiles=%pagectime=();
  796. if (! $config{rebuild}) {
  797. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  798. %destsources=%renderedfiles=%pagecase=%pagestate=();
  799. }
  800. my $in;
  801. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  802. if (-e "$config{wikistatedir}/index") {
  803. system("ikiwiki-transition", "indexdb", $config{srcdir});
  804. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  805. }
  806. else {
  807. return;
  808. }
  809. }
  810. my $ret=Storable::fd_retrieve($in);
  811. if (! defined $ret) {
  812. return 0;
  813. }
  814. my %index=%$ret;
  815. foreach my $src (keys %index) {
  816. my %d=%{$index{$src}};
  817. my $page=pagename($src);
  818. $pagectime{$page}=$d{ctime};
  819. if (! $config{rebuild}) {
  820. $pagesources{$page}=$src;
  821. $pagemtime{$page}=$d{mtime};
  822. $renderedfiles{$page}=$d{dest};
  823. if (exists $d{links} && ref $d{links}) {
  824. $links{$page}=$d{links};
  825. $oldlinks{$page}=[@{$d{links}}];
  826. }
  827. if (exists $d{depends}) {
  828. $depends{$page}=$d{depends};
  829. }
  830. if (exists $d{state}) {
  831. $pagestate{$page}=$d{state};
  832. }
  833. }
  834. $oldrenderedfiles{$page}=[@{$d{dest}}];
  835. }
  836. foreach my $page (keys %pagesources) {
  837. $pagecase{lc $page}=$page;
  838. }
  839. foreach my $page (keys %renderedfiles) {
  840. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  841. }
  842. return close($in);
  843. } #}}}
  844. sub saveindex () { #{{{
  845. run_hooks(savestate => sub { shift->() });
  846. my %hookids;
  847. foreach my $type (keys %hooks) {
  848. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  849. }
  850. my @hookids=keys %hookids;
  851. if (! -d $config{wikistatedir}) {
  852. mkdir($config{wikistatedir});
  853. }
  854. my $newfile="$config{wikistatedir}/indexdb.new";
  855. my $cleanup = sub { unlink($newfile) };
  856. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  857. my %index;
  858. foreach my $page (keys %pagemtime) {
  859. next unless $pagemtime{$page};
  860. my $src=$pagesources{$page};
  861. $index{$src}={
  862. ctime => $pagectime{$page},
  863. mtime => $pagemtime{$page},
  864. dest => $renderedfiles{$page},
  865. links => $links{$page},
  866. };
  867. if (exists $depends{$page}) {
  868. $index{$src}{depends} = $depends{$page};
  869. }
  870. if (exists $pagestate{$page}) {
  871. foreach my $id (@hookids) {
  872. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  873. $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  874. }
  875. }
  876. }
  877. }
  878. my $ret=Storable::nstore_fd(\%index, $out);
  879. return if ! defined $ret || ! $ret;
  880. close $out || error("failed saving to $newfile: $!", $cleanup);
  881. rename($newfile, "$config{wikistatedir}/indexdb") ||
  882. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  883. return 1;
  884. } #}}}
  885. sub template_file ($) { #{{{
  886. my $template=shift;
  887. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  888. return "$dir/$template" if -e "$dir/$template";
  889. }
  890. return;
  891. } #}}}
  892. sub template_params (@) { #{{{
  893. my $filename=template_file(shift);
  894. if (! defined $filename) {
  895. return if wantarray;
  896. return "";
  897. }
  898. my @ret=(
  899. filter => sub {
  900. my $text_ref = shift;
  901. ${$text_ref} = decode_utf8(${$text_ref});
  902. },
  903. filename => $filename,
  904. loop_context_vars => 1,
  905. die_on_bad_params => 0,
  906. @_
  907. );
  908. return wantarray ? @ret : {@ret};
  909. } #}}}
  910. sub template ($;@) { #{{{
  911. require HTML::Template;
  912. return HTML::Template->new(template_params(@_));
  913. } #}}}
  914. sub misctemplate ($$;@) { #{{{
  915. my $title=shift;
  916. my $pagebody=shift;
  917. my $template=template("misc.tmpl");
  918. $template->param(
  919. title => $title,
  920. indexlink => indexlink(),
  921. wikiname => $config{wikiname},
  922. pagebody => $pagebody,
  923. baseurl => baseurl(),
  924. @_,
  925. );
  926. run_hooks(pagetemplate => sub {
  927. shift->(page => "", destpage => "", template => $template);
  928. });
  929. return $template->output;
  930. }#}}}
  931. sub hook (@) { # {{{
  932. my %param=@_;
  933. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  934. error 'hook requires type, call, and id parameters';
  935. }
  936. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  937. $hooks{$param{type}}{$param{id}}=\%param;
  938. return 1;
  939. } # }}}
  940. sub run_hooks ($$) { # {{{
  941. # Calls the given sub for each hook of the given type,
  942. # passing it the hook function to call.
  943. my $type=shift;
  944. my $sub=shift;
  945. if (exists $hooks{$type}) {
  946. my @deferred;
  947. foreach my $id (keys %{$hooks{$type}}) {
  948. if ($hooks{$type}{$id}{last}) {
  949. push @deferred, $id;
  950. next;
  951. }
  952. $sub->($hooks{$type}{$id}{call});
  953. }
  954. foreach my $id (@deferred) {
  955. $sub->($hooks{$type}{$id}{call});
  956. }
  957. }
  958. return 1;
  959. } #}}}
  960. sub globlist_to_pagespec ($) { #{{{
  961. my @globlist=split(' ', shift);
  962. my (@spec, @skip);
  963. foreach my $glob (@globlist) {
  964. if ($glob=~/^!(.*)/) {
  965. push @skip, $glob;
  966. }
  967. else {
  968. push @spec, $glob;
  969. }
  970. }
  971. my $spec=join(' or ', @spec);
  972. if (@skip) {
  973. my $skip=join(' and ', @skip);
  974. if (length $spec) {
  975. $spec="$skip and ($spec)";
  976. }
  977. else {
  978. $spec=$skip;
  979. }
  980. }
  981. return $spec;
  982. } #}}}
  983. sub is_globlist ($) { #{{{
  984. my $s=shift;
  985. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  986. } #}}}
  987. sub safequote ($) { #{{{
  988. my $s=shift;
  989. $s=~s/[{}]//g;
  990. return "q{$s}";
  991. } #}}}
  992. sub add_depends ($$) { #{{{
  993. my $page=shift;
  994. my $pagespec=shift;
  995. return unless pagespec_valid($pagespec);
  996. if (! exists $depends{$page}) {
  997. $depends{$page}=$pagespec;
  998. }
  999. else {
  1000. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1001. }
  1002. return 1;
  1003. } # }}}
  1004. sub file_pruned ($$) { #{{{
  1005. require File::Spec;
  1006. my $file=File::Spec->canonpath(shift);
  1007. my $base=File::Spec->canonpath(shift);
  1008. $file =~ s#^\Q$base\E/+##;
  1009. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1010. return $file =~ m/$regexp/ && $file ne $base;
  1011. } #}}}
  1012. sub gettext { #{{{
  1013. # Only use gettext in the rare cases it's needed.
  1014. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1015. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1016. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1017. if (! $gettext_obj) {
  1018. $gettext_obj=eval q{
  1019. use Locale::gettext q{textdomain};
  1020. Locale::gettext->domain('ikiwiki')
  1021. };
  1022. if ($@) {
  1023. print STDERR "$@";
  1024. $gettext_obj=undef;
  1025. return shift;
  1026. }
  1027. }
  1028. return $gettext_obj->get(shift);
  1029. }
  1030. else {
  1031. return shift;
  1032. }
  1033. } #}}}
  1034. sub pagespec_merge ($$) { #{{{
  1035. my $a=shift;
  1036. my $b=shift;
  1037. return $a if $a eq $b;
  1038. # Support for old-style GlobLists.
  1039. if (is_globlist($a)) {
  1040. $a=globlist_to_pagespec($a);
  1041. }
  1042. if (is_globlist($b)) {
  1043. $b=globlist_to_pagespec($b);
  1044. }
  1045. return "($a) or ($b)";
  1046. } #}}}
  1047. sub pagespec_translate ($) { #{{{
  1048. my $spec=shift;
  1049. # Support for old-style GlobLists.
  1050. if (is_globlist($spec)) {
  1051. $spec=globlist_to_pagespec($spec);
  1052. }
  1053. # Convert spec to perl code.
  1054. my $code="";
  1055. while ($spec=~m{
  1056. \s* # ignore whitespace
  1057. ( # 1: match a single word
  1058. \! # !
  1059. |
  1060. \( # (
  1061. |
  1062. \) # )
  1063. |
  1064. \w+\([^\)]*\) # command(params)
  1065. |
  1066. [^\s()]+ # any other text
  1067. )
  1068. \s* # ignore whitespace
  1069. }igx) {
  1070. my $word=$1;
  1071. if (lc $word eq 'and') {
  1072. $code.=' &&';
  1073. }
  1074. elsif (lc $word eq 'or') {
  1075. $code.=' ||';
  1076. }
  1077. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1078. $code.=' '.$word;
  1079. }
  1080. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1081. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1082. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1083. }
  1084. else {
  1085. $code.=' 0';
  1086. }
  1087. }
  1088. else {
  1089. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1090. }
  1091. }
  1092. if (! length $code) {
  1093. $code=0;
  1094. }
  1095. no warnings;
  1096. return eval 'sub { my $page=shift; '.$code.' }';
  1097. } #}}}
  1098. sub pagespec_match ($$;@) { #{{{
  1099. my $page=shift;
  1100. my $spec=shift;
  1101. my @params=@_;
  1102. # Backwards compatability with old calling convention.
  1103. if (@params == 1) {
  1104. unshift @params, 'location';
  1105. }
  1106. my $sub=pagespec_translate($spec);
  1107. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1108. return $sub->($page, @params);
  1109. } #}}}
  1110. sub pagespec_valid ($) { #{{{
  1111. my $spec=shift;
  1112. my $sub=pagespec_translate($spec);
  1113. return ! $@;
  1114. } #}}}
  1115. sub glob2re ($) { #{{{
  1116. my $re=quotemeta(shift);
  1117. $re=~s/\\\*/.*/g;
  1118. $re=~s/\\\?/./g;
  1119. return $re;
  1120. } #}}}
  1121. package IkiWiki::FailReason;
  1122. use overload ( #{{{
  1123. '""' => sub { ${$_[0]} },
  1124. '0+' => sub { 0 },
  1125. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1126. fallback => 1,
  1127. ); #}}}
  1128. sub new { #{{{
  1129. my $class = shift;
  1130. my $value = shift;
  1131. return bless \$value, $class;
  1132. } #}}}
  1133. package IkiWiki::SuccessReason;
  1134. use overload ( #{{{
  1135. '""' => sub { ${$_[0]} },
  1136. '0+' => sub { 1 },
  1137. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1138. fallback => 1,
  1139. ); #}}}
  1140. sub new { #{{{
  1141. my $class = shift;
  1142. my $value = shift;
  1143. return bless \$value, $class;
  1144. }; #}}}
  1145. package IkiWiki::PageSpec;
  1146. sub match_glob ($$;@) { #{{{
  1147. my $page=shift;
  1148. my $glob=shift;
  1149. my %params=@_;
  1150. my $from=exists $params{location} ? $params{location} : '';
  1151. # relative matching
  1152. if ($glob =~ m!^\./!) {
  1153. $from=~s#/?[^/]+$##;
  1154. $glob=~s#^\./##;
  1155. $glob="$from/$glob" if length $from;
  1156. }
  1157. my $regexp=IkiWiki::glob2re($glob);
  1158. if ($page=~/^$regexp$/i) {
  1159. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1160. return IkiWiki::SuccessReason->new("$glob matches $page");
  1161. }
  1162. else {
  1163. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1164. }
  1165. }
  1166. else {
  1167. return IkiWiki::FailReason->new("$glob does not match $page");
  1168. }
  1169. } #}}}
  1170. sub match_internal ($$;@) { #{{{
  1171. return match_glob($_[0], $_[1], @_, internal => 1)
  1172. } #}}}
  1173. sub match_link ($$;@) { #{{{
  1174. my $page=shift;
  1175. my $link=lc(shift);
  1176. my %params=@_;
  1177. my $from=exists $params{location} ? $params{location} : '';
  1178. # relative matching
  1179. if ($link =~ m!^\.! && defined $from) {
  1180. $from=~s#/?[^/]+$##;
  1181. $link=~s#^\./##;
  1182. $link="$from/$link" if length $from;
  1183. }
  1184. my $links = $IkiWiki::links{$page};
  1185. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1186. my $bestlink = IkiWiki::bestlink($from, $link);
  1187. foreach my $p (@{$links}) {
  1188. if (length $bestlink) {
  1189. return IkiWiki::SuccessReason->new("$page links to $link")
  1190. if $bestlink eq IkiWiki::bestlink($page, $p);
  1191. }
  1192. else {
  1193. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1194. if match_glob($p, $link, %params);
  1195. }
  1196. }
  1197. return IkiWiki::FailReason->new("$page does not link to $link");
  1198. } #}}}
  1199. sub match_backlink ($$;@) { #{{{
  1200. return match_link($_[1], $_[0], @_);
  1201. } #}}}
  1202. sub match_created_before ($$;@) { #{{{
  1203. my $page=shift;
  1204. my $testpage=shift;
  1205. if (exists $IkiWiki::pagectime{$testpage}) {
  1206. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1207. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1208. }
  1209. else {
  1210. return IkiWiki::FailReason->new("$page not created before $testpage");
  1211. }
  1212. }
  1213. else {
  1214. return IkiWiki::FailReason->new("$testpage has no ctime");
  1215. }
  1216. } #}}}
  1217. sub match_created_after ($$;@) { #{{{
  1218. my $page=shift;
  1219. my $testpage=shift;
  1220. if (exists $IkiWiki::pagectime{$testpage}) {
  1221. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1222. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1223. }
  1224. else {
  1225. return IkiWiki::FailReason->new("$page not created after $testpage");
  1226. }
  1227. }
  1228. else {
  1229. return IkiWiki::FailReason->new("$testpage has no ctime");
  1230. }
  1231. } #}}}
  1232. sub match_creation_day ($$;@) { #{{{
  1233. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1234. return IkiWiki::SuccessReason->new('creation_day matched');
  1235. }
  1236. else {
  1237. return IkiWiki::FailReason->new('creation_day did not match');
  1238. }
  1239. } #}}}
  1240. sub match_creation_month ($$;@) { #{{{
  1241. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1242. return IkiWiki::SuccessReason->new('creation_month matched');
  1243. }
  1244. else {
  1245. return IkiWiki::FailReason->new('creation_month did not match');
  1246. }
  1247. } #}}}
  1248. sub match_creation_year ($$;@) { #{{{
  1249. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1250. return IkiWiki::SuccessReason->new('creation_year matched');
  1251. }
  1252. else {
  1253. return IkiWiki::FailReason->new('creation_year did not match');
  1254. }
  1255. } #}}}
  1256. 1