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