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