summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 3f8a4bca334debb8a5728b25b258dac50c112f89 (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. return "[[!$command <span class=\"error\">".
  645. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  646. $page, $preprocessing{$page}).
  647. "</span>]]";
  648. }
  649. my $ret;
  650. if (! $scan) {
  651. $ret=eval {
  652. $hooks{preprocess}{$command}{call}->(
  653. @params,
  654. page => $page,
  655. destpage => $destpage,
  656. preview => $preprocess_preview,
  657. );
  658. };
  659. if ($@) {
  660. chomp $@;
  661. $ret="[[!$command <span class=\"error\">".
  662. gettext("Error").": $@"."</span>]]";
  663. }
  664. }
  665. else {
  666. # use void context during scan pass
  667. eval {
  668. $hooks{preprocess}{$command}{call}->(
  669. @params,
  670. page => $page,
  671. destpage => $destpage,
  672. preview => $preprocess_preview,
  673. );
  674. };
  675. $ret="";
  676. }
  677. $preprocessing{$page}--;
  678. return $ret;
  679. }
  680. else {
  681. return "[[$prefix$command $params]]";
  682. }
  683. };
  684. my $regex;
  685. if ($config{prefix_directives}) {
  686. $regex = qr{
  687. (\\?) # 1: escape?
  688. \[\[(!) # directive open; 2: prefix
  689. ([-\w]+) # 3: command
  690. ( # 4: the parameters..
  691. \s+ # Must have space if parameters present
  692. (?:
  693. (?:[-\w]+=)? # named parameter key?
  694. (?:
  695. """.*?""" # triple-quoted value
  696. |
  697. "[^"]+" # single-quoted value
  698. |
  699. [^\s\]]+ # unquoted value
  700. )
  701. \s* # whitespace or end
  702. # of directive
  703. )
  704. *)? # 0 or more parameters
  705. \]\] # directive closed
  706. }sx;
  707. }
  708. else {
  709. $regex = qr{
  710. (\\?) # 1: escape?
  711. \[\[(!?) # directive open; 2: optional prefix
  712. ([-\w]+) # 3: command
  713. \s+
  714. ( # 4: the parameters..
  715. (?:
  716. (?:[-\w]+=)? # named parameter key?
  717. (?:
  718. """.*?""" # triple-quoted value
  719. |
  720. "[^"]+" # single-quoted value
  721. |
  722. [^\s\]]+ # unquoted value
  723. )
  724. \s* # whitespace or end
  725. # of directive
  726. )
  727. *) # 0 or more parameters
  728. \]\] # directive closed
  729. }sx;
  730. }
  731. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  732. return $content;
  733. } #}}}
  734. sub filter ($$$) { #{{{
  735. my $page=shift;
  736. my $destpage=shift;
  737. my $content=shift;
  738. run_hooks(filter => sub {
  739. $content=shift->(page => $page, destpage => $destpage,
  740. content => $content);
  741. });
  742. return $content;
  743. } #}}}
  744. sub indexlink () { #{{{
  745. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  746. } #}}}
  747. my $wikilock;
  748. sub lockwiki (;$) { #{{{
  749. my $wait=@_ ? shift : 1;
  750. # Take an exclusive lock on the wiki to prevent multiple concurrent
  751. # run issues. The lock will be dropped on program exit.
  752. if (! -d $config{wikistatedir}) {
  753. mkdir($config{wikistatedir});
  754. }
  755. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  756. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  757. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  758. if ($wait) {
  759. debug("wiki seems to be locked, waiting for lock");
  760. my $wait=600; # arbitrary, but don't hang forever to
  761. # prevent process pileup
  762. for (1..$wait) {
  763. return if flock($wikilock, 2 | 4);
  764. sleep 1;
  765. }
  766. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  767. }
  768. else {
  769. return 0;
  770. }
  771. }
  772. return 1;
  773. } #}}}
  774. sub unlockwiki () { #{{{
  775. return close($wikilock) if $wikilock;
  776. return;
  777. } #}}}
  778. my $commitlock;
  779. sub commit_hook_enabled () { #{{{
  780. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  781. error("cannot write to $config{wikistatedir}/commitlock: $!");
  782. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  783. close($commitlock) || error("failed closing commitlock: $!");
  784. return 0;
  785. }
  786. close($commitlock) || error("failed closing commitlock: $!");
  787. return 1;
  788. } #}}}
  789. sub disable_commit_hook () { #{{{
  790. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  791. error("cannot write to $config{wikistatedir}/commitlock: $!");
  792. if (! flock($commitlock, 2)) { # LOCK_EX
  793. error("failed to get commit lock");
  794. }
  795. return 1;
  796. } #}}}
  797. sub enable_commit_hook () { #{{{
  798. return close($commitlock) if $commitlock;
  799. return;
  800. } #}}}
  801. sub loadindex () { #{{{
  802. %oldrenderedfiles=%pagectime=();
  803. if (! $config{rebuild}) {
  804. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  805. %destsources=%renderedfiles=%pagecase=%pagestate=();
  806. }
  807. my $in;
  808. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  809. if (-e "$config{wikistatedir}/index") {
  810. system("ikiwiki-transition", "indexdb", $config{srcdir});
  811. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  812. }
  813. else {
  814. return;
  815. }
  816. }
  817. my $ret=Storable::fd_retrieve($in);
  818. if (! defined $ret) {
  819. return 0;
  820. }
  821. my %index=%$ret;
  822. foreach my $src (keys %index) {
  823. my %d=%{$index{$src}};
  824. my $page=pagename($src);
  825. $pagectime{$page}=$d{ctime};
  826. if (! $config{rebuild}) {
  827. $pagesources{$page}=$src;
  828. $pagemtime{$page}=$d{mtime};
  829. $renderedfiles{$page}=$d{dest};
  830. if (exists $d{links} && ref $d{links}) {
  831. $links{$page}=$d{links};
  832. $oldlinks{$page}=[@{$d{links}}];
  833. }
  834. if (exists $d{depends}) {
  835. $depends{$page}=$d{depends};
  836. }
  837. if (exists $d{state}) {
  838. $pagestate{$page}=$d{state};
  839. }
  840. }
  841. $oldrenderedfiles{$page}=[@{$d{dest}}];
  842. }
  843. foreach my $page (keys %pagesources) {
  844. $pagecase{lc $page}=$page;
  845. }
  846. foreach my $page (keys %renderedfiles) {
  847. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  848. }
  849. return close($in);
  850. } #}}}
  851. sub saveindex () { #{{{
  852. run_hooks(savestate => sub { shift->() });
  853. my %hookids;
  854. foreach my $type (keys %hooks) {
  855. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  856. }
  857. my @hookids=keys %hookids;
  858. if (! -d $config{wikistatedir}) {
  859. mkdir($config{wikistatedir});
  860. }
  861. my $newfile="$config{wikistatedir}/indexdb.new";
  862. my $cleanup = sub { unlink($newfile) };
  863. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  864. my %index;
  865. foreach my $page (keys %pagemtime) {
  866. next unless $pagemtime{$page};
  867. my $src=$pagesources{$page};
  868. $index{$src}={
  869. ctime => $pagectime{$page},
  870. mtime => $pagemtime{$page},
  871. dest => $renderedfiles{$page},
  872. links => $links{$page},
  873. };
  874. if (exists $depends{$page}) {
  875. $index{$src}{depends} = $depends{$page};
  876. }
  877. if (exists $pagestate{$page}) {
  878. foreach my $id (@hookids) {
  879. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  880. $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  881. }
  882. }
  883. }
  884. }
  885. my $ret=Storable::nstore_fd(\%index, $out);
  886. return if ! defined $ret || ! $ret;
  887. close $out || error("failed saving to $newfile: $!", $cleanup);
  888. rename($newfile, "$config{wikistatedir}/indexdb") ||
  889. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  890. return 1;
  891. } #}}}
  892. sub template_file ($) { #{{{
  893. my $template=shift;
  894. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  895. return "$dir/$template" if -e "$dir/$template";
  896. }
  897. return;
  898. } #}}}
  899. sub template_params (@) { #{{{
  900. my $filename=template_file(shift);
  901. if (! defined $filename) {
  902. return if wantarray;
  903. return "";
  904. }
  905. my @ret=(
  906. filter => sub {
  907. my $text_ref = shift;
  908. ${$text_ref} = decode_utf8(${$text_ref});
  909. },
  910. filename => $filename,
  911. loop_context_vars => 1,
  912. die_on_bad_params => 0,
  913. @_
  914. );
  915. return wantarray ? @ret : {@ret};
  916. } #}}}
  917. sub template ($;@) { #{{{
  918. require HTML::Template;
  919. return HTML::Template->new(template_params(@_));
  920. } #}}}
  921. sub misctemplate ($$;@) { #{{{
  922. my $title=shift;
  923. my $pagebody=shift;
  924. my $template=template("misc.tmpl");
  925. $template->param(
  926. title => $title,
  927. indexlink => indexlink(),
  928. wikiname => $config{wikiname},
  929. pagebody => $pagebody,
  930. baseurl => baseurl(),
  931. @_,
  932. );
  933. run_hooks(pagetemplate => sub {
  934. shift->(page => "", destpage => "", template => $template);
  935. });
  936. return $template->output;
  937. }#}}}
  938. sub hook (@) { # {{{
  939. my %param=@_;
  940. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  941. error 'hook requires type, call, and id parameters';
  942. }
  943. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  944. $hooks{$param{type}}{$param{id}}=\%param;
  945. return 1;
  946. } # }}}
  947. sub run_hooks ($$) { # {{{
  948. # Calls the given sub for each hook of the given type,
  949. # passing it the hook function to call.
  950. my $type=shift;
  951. my $sub=shift;
  952. if (exists $hooks{$type}) {
  953. my @deferred;
  954. foreach my $id (keys %{$hooks{$type}}) {
  955. if ($hooks{$type}{$id}{last}) {
  956. push @deferred, $id;
  957. next;
  958. }
  959. $sub->($hooks{$type}{$id}{call});
  960. }
  961. foreach my $id (@deferred) {
  962. $sub->($hooks{$type}{$id}{call});
  963. }
  964. }
  965. return 1;
  966. } #}}}
  967. sub globlist_to_pagespec ($) { #{{{
  968. my @globlist=split(' ', shift);
  969. my (@spec, @skip);
  970. foreach my $glob (@globlist) {
  971. if ($glob=~/^!(.*)/) {
  972. push @skip, $glob;
  973. }
  974. else {
  975. push @spec, $glob;
  976. }
  977. }
  978. my $spec=join(' or ', @spec);
  979. if (@skip) {
  980. my $skip=join(' and ', @skip);
  981. if (length $spec) {
  982. $spec="$skip and ($spec)";
  983. }
  984. else {
  985. $spec=$skip;
  986. }
  987. }
  988. return $spec;
  989. } #}}}
  990. sub is_globlist ($) { #{{{
  991. my $s=shift;
  992. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  993. } #}}}
  994. sub safequote ($) { #{{{
  995. my $s=shift;
  996. $s=~s/[{}]//g;
  997. return "q{$s}";
  998. } #}}}
  999. sub add_depends ($$) { #{{{
  1000. my $page=shift;
  1001. my $pagespec=shift;
  1002. return unless pagespec_valid($pagespec);
  1003. if (! exists $depends{$page}) {
  1004. $depends{$page}=$pagespec;
  1005. }
  1006. else {
  1007. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1008. }
  1009. return 1;
  1010. } # }}}
  1011. sub file_pruned ($$) { #{{{
  1012. require File::Spec;
  1013. my $file=File::Spec->canonpath(shift);
  1014. my $base=File::Spec->canonpath(shift);
  1015. $file =~ s#^\Q$base\E/+##;
  1016. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1017. return $file =~ m/$regexp/ && $file ne $base;
  1018. } #}}}
  1019. sub gettext { #{{{
  1020. # Only use gettext in the rare cases it's needed.
  1021. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1022. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1023. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1024. if (! $gettext_obj) {
  1025. $gettext_obj=eval q{
  1026. use Locale::gettext q{textdomain};
  1027. Locale::gettext->domain('ikiwiki')
  1028. };
  1029. if ($@) {
  1030. print STDERR "$@";
  1031. $gettext_obj=undef;
  1032. return shift;
  1033. }
  1034. }
  1035. return $gettext_obj->get(shift);
  1036. }
  1037. else {
  1038. return shift;
  1039. }
  1040. } #}}}
  1041. sub yesno ($) { #{{{
  1042. my $val=shift;
  1043. return (defined $val && lc($val) eq gettext("yes"));
  1044. } #}}}
  1045. sub pagespec_merge ($$) { #{{{
  1046. my $a=shift;
  1047. my $b=shift;
  1048. return $a if $a eq $b;
  1049. # Support for old-style GlobLists.
  1050. if (is_globlist($a)) {
  1051. $a=globlist_to_pagespec($a);
  1052. }
  1053. if (is_globlist($b)) {
  1054. $b=globlist_to_pagespec($b);
  1055. }
  1056. return "($a) or ($b)";
  1057. } #}}}
  1058. sub pagespec_translate ($) { #{{{
  1059. my $spec=shift;
  1060. # Support for old-style GlobLists.
  1061. if (is_globlist($spec)) {
  1062. $spec=globlist_to_pagespec($spec);
  1063. }
  1064. # Convert spec to perl code.
  1065. my $code="";
  1066. while ($spec=~m{
  1067. \s* # ignore whitespace
  1068. ( # 1: match a single word
  1069. \! # !
  1070. |
  1071. \( # (
  1072. |
  1073. \) # )
  1074. |
  1075. \w+\([^\)]*\) # command(params)
  1076. |
  1077. [^\s()]+ # any other text
  1078. )
  1079. \s* # ignore whitespace
  1080. }igx) {
  1081. my $word=$1;
  1082. if (lc $word eq 'and') {
  1083. $code.=' &&';
  1084. }
  1085. elsif (lc $word eq 'or') {
  1086. $code.=' ||';
  1087. }
  1088. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1089. $code.=' '.$word;
  1090. }
  1091. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1092. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1093. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1094. }
  1095. else {
  1096. $code.=' 0';
  1097. }
  1098. }
  1099. else {
  1100. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1101. }
  1102. }
  1103. if (! length $code) {
  1104. $code=0;
  1105. }
  1106. no warnings;
  1107. return eval 'sub { my $page=shift; '.$code.' }';
  1108. } #}}}
  1109. sub pagespec_match ($$;@) { #{{{
  1110. my $page=shift;
  1111. my $spec=shift;
  1112. my @params=@_;
  1113. # Backwards compatability with old calling convention.
  1114. if (@params == 1) {
  1115. unshift @params, 'location';
  1116. }
  1117. my $sub=pagespec_translate($spec);
  1118. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1119. return $sub->($page, @params);
  1120. } #}}}
  1121. sub pagespec_valid ($) { #{{{
  1122. my $spec=shift;
  1123. my $sub=pagespec_translate($spec);
  1124. return ! $@;
  1125. } #}}}
  1126. sub glob2re ($) { #{{{
  1127. my $re=quotemeta(shift);
  1128. $re=~s/\\\*/.*/g;
  1129. $re=~s/\\\?/./g;
  1130. return $re;
  1131. } #}}}
  1132. package IkiWiki::FailReason;
  1133. use overload ( #{{{
  1134. '""' => sub { ${$_[0]} },
  1135. '0+' => sub { 0 },
  1136. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1137. fallback => 1,
  1138. ); #}}}
  1139. sub new { #{{{
  1140. my $class = shift;
  1141. my $value = shift;
  1142. return bless \$value, $class;
  1143. } #}}}
  1144. package IkiWiki::SuccessReason;
  1145. use overload ( #{{{
  1146. '""' => sub { ${$_[0]} },
  1147. '0+' => sub { 1 },
  1148. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1149. fallback => 1,
  1150. ); #}}}
  1151. sub new { #{{{
  1152. my $class = shift;
  1153. my $value = shift;
  1154. return bless \$value, $class;
  1155. }; #}}}
  1156. package IkiWiki::PageSpec;
  1157. sub match_glob ($$;@) { #{{{
  1158. my $page=shift;
  1159. my $glob=shift;
  1160. my %params=@_;
  1161. my $from=exists $params{location} ? $params{location} : '';
  1162. # relative matching
  1163. if ($glob =~ m!^\./!) {
  1164. $from=~s#/?[^/]+$##;
  1165. $glob=~s#^\./##;
  1166. $glob="$from/$glob" if length $from;
  1167. }
  1168. my $regexp=IkiWiki::glob2re($glob);
  1169. if ($page=~/^$regexp$/i) {
  1170. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1171. return IkiWiki::SuccessReason->new("$glob matches $page");
  1172. }
  1173. else {
  1174. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1175. }
  1176. }
  1177. else {
  1178. return IkiWiki::FailReason->new("$glob does not match $page");
  1179. }
  1180. } #}}}
  1181. sub match_internal ($$;@) { #{{{
  1182. return match_glob($_[0], $_[1], @_, internal => 1)
  1183. } #}}}
  1184. sub match_link ($$;@) { #{{{
  1185. my $page=shift;
  1186. my $link=lc(shift);
  1187. my %params=@_;
  1188. my $from=exists $params{location} ? $params{location} : '';
  1189. # relative matching
  1190. if ($link =~ m!^\.! && defined $from) {
  1191. $from=~s#/?[^/]+$##;
  1192. $link=~s#^\./##;
  1193. $link="$from/$link" if length $from;
  1194. }
  1195. my $links = $IkiWiki::links{$page};
  1196. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1197. my $bestlink = IkiWiki::bestlink($from, $link);
  1198. foreach my $p (@{$links}) {
  1199. if (length $bestlink) {
  1200. return IkiWiki::SuccessReason->new("$page links to $link")
  1201. if $bestlink eq IkiWiki::bestlink($page, $p);
  1202. }
  1203. else {
  1204. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1205. if match_glob($p, $link, %params);
  1206. }
  1207. }
  1208. return IkiWiki::FailReason->new("$page does not link to $link");
  1209. } #}}}
  1210. sub match_backlink ($$;@) { #{{{
  1211. return match_link($_[1], $_[0], @_);
  1212. } #}}}
  1213. sub match_created_before ($$;@) { #{{{
  1214. my $page=shift;
  1215. my $testpage=shift;
  1216. if (exists $IkiWiki::pagectime{$testpage}) {
  1217. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1218. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1219. }
  1220. else {
  1221. return IkiWiki::FailReason->new("$page not created before $testpage");
  1222. }
  1223. }
  1224. else {
  1225. return IkiWiki::FailReason->new("$testpage has no ctime");
  1226. }
  1227. } #}}}
  1228. sub match_created_after ($$;@) { #{{{
  1229. my $page=shift;
  1230. my $testpage=shift;
  1231. if (exists $IkiWiki::pagectime{$testpage}) {
  1232. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1233. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1234. }
  1235. else {
  1236. return IkiWiki::FailReason->new("$page not created after $testpage");
  1237. }
  1238. }
  1239. else {
  1240. return IkiWiki::FailReason->new("$testpage has no ctime");
  1241. }
  1242. } #}}}
  1243. sub match_creation_day ($$;@) { #{{{
  1244. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1245. return IkiWiki::SuccessReason->new('creation_day matched');
  1246. }
  1247. else {
  1248. return IkiWiki::FailReason->new('creation_day did not match');
  1249. }
  1250. } #}}}
  1251. sub match_creation_month ($$;@) { #{{{
  1252. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1253. return IkiWiki::SuccessReason->new('creation_month matched');
  1254. }
  1255. else {
  1256. return IkiWiki::FailReason->new('creation_month did not match');
  1257. }
  1258. } #}}}
  1259. sub match_creation_year ($$;@) { #{{{
  1260. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1261. return IkiWiki::SuccessReason->new('creation_year matched');
  1262. }
  1263. else {
  1264. return IkiWiki::FailReason->new('creation_year did not match');
  1265. }
  1266. } #}}}
  1267. 1