summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: a9debfb7dc86f3ba51be46a1f4ba011703017b54 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use URI::Escape q{uri_escape_utf8};
  8. use POSIX;
  9. use Storable;
  10. use open qw{:utf8 :std};
  11. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  12. %pagestate %renderedfiles %oldrenderedfiles %pagesources
  13. %destsources %depends %hooks %forcerebuild $gettext_obj};
  14. use Exporter q{import};
  15. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  16. bestlink htmllink readfile writefile pagetype srcfile pagename
  17. displaytime will_render gettext urlto targetpage
  18. add_underlay
  19. %config %links %pagestate %renderedfiles
  20. %pagesources %destsources);
  21. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  22. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  23. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  24. # Optimisation.
  25. use Memoize;
  26. memoize("abs2rel");
  27. memoize("pagespec_translate");
  28. memoize("file_pruned");
  29. sub defaultconfig () { #{{{
  30. return
  31. wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
  32. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  33. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  34. qr/(^|\/)_MTN\//,
  35. qr/\.dpkg-tmp$/],
  36. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  37. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  38. verbose => 0,
  39. syslog => 0,
  40. wikiname => "wiki",
  41. default_pageext => "mdwn",
  42. htmlext => "html",
  43. cgi => 0,
  44. post_commit => 0,
  45. rcs => '',
  46. url => '',
  47. cgiurl => '',
  48. historyurl => '',
  49. diffurl => '',
  50. rss => 0,
  51. atom => 0,
  52. allowrss => 0,
  53. allowatom => 0,
  54. discussion => 1,
  55. rebuild => 0,
  56. refresh => 0,
  57. getctime => 0,
  58. w3mmode => 0,
  59. wrapper => undef,
  60. wrappermode => undef,
  61. svnpath => "trunk",
  62. gitorigin_branch => "origin",
  63. gitmaster_branch => "master",
  64. srcdir => undef,
  65. destdir => undef,
  66. pingurl => [],
  67. templatedir => "$installdir/share/ikiwiki/templates",
  68. underlaydir => "$installdir/share/ikiwiki/basewiki",
  69. underlaydirs => [],
  70. setup => undef,
  71. adminuser => undef,
  72. adminemail => undef,
  73. plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
  74. signinedit lockedit conditional recentchanges}],
  75. libdir => undef,
  76. timeformat => '%c',
  77. locale => undef,
  78. sslcookie => 0,
  79. httpauth => 0,
  80. userdir => "",
  81. usedirs => 1,
  82. numbacklinks => 10,
  83. account_creation_password => "",
  84. prefix_directives => 0,
  85. hardlink => 0,
  86. } #}}}
  87. sub checkconfig () { #{{{
  88. # locale stuff; avoid LC_ALL since it overrides everything
  89. if (defined $ENV{LC_ALL}) {
  90. $ENV{LANG} = $ENV{LC_ALL};
  91. delete $ENV{LC_ALL};
  92. }
  93. if (defined $config{locale}) {
  94. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  95. $ENV{LANG}=$config{locale};
  96. $gettext_obj=undef;
  97. }
  98. }
  99. if (ref $config{ENV} eq 'HASH') {
  100. foreach my $val (keys %{$config{ENV}}) {
  101. $ENV{$val}=$config{ENV}{$val};
  102. }
  103. }
  104. if ($config{w3mmode}) {
  105. eval q{use Cwd q{abs_path}};
  106. error($@) if $@;
  107. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  108. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  109. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  110. unless $config{cgiurl} =~ m!file:///!;
  111. $config{url}="file://".$config{destdir};
  112. }
  113. if ($config{cgi} && ! length $config{url}) {
  114. error(gettext("Must specify url to wiki with --url when using --cgi"));
  115. }
  116. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  117. unless exists $config{wikistatedir};
  118. if ($config{rcs}) {
  119. eval qq{use IkiWiki::Rcs::$config{rcs}};
  120. if ($@) {
  121. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  122. }
  123. }
  124. else {
  125. require IkiWiki::Rcs::Stub;
  126. }
  127. if (exists $config{umask}) {
  128. umask(possibly_foolish_untaint($config{umask}));
  129. }
  130. run_hooks(checkconfig => sub { shift->() });
  131. return 1;
  132. } #}}}
  133. sub loadplugins () { #{{{
  134. if (defined $config{libdir}) {
  135. unshift @INC, possibly_foolish_untaint($config{libdir});
  136. }
  137. loadplugin($_) foreach @{$config{plugin}};
  138. run_hooks(getopt => sub { shift->() });
  139. if (grep /^-/, @ARGV) {
  140. print STDERR "Unknown option: $_\n"
  141. foreach grep /^-/, @ARGV;
  142. usage();
  143. }
  144. return 1;
  145. } #}}}
  146. sub loadplugin ($) { #{{{
  147. my $plugin=shift;
  148. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  149. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  150. "$installdir/lib/ikiwiki") {
  151. if (defined $dir && -x "$dir/plugins/$plugin") {
  152. require IkiWiki::Plugin::external;
  153. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  154. return 1;
  155. }
  156. }
  157. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  158. eval qq{use $mod};
  159. if ($@) {
  160. error("Failed to load plugin $mod: $@");
  161. }
  162. return 1;
  163. } #}}}
  164. sub error ($;$) { #{{{
  165. my $message=shift;
  166. my $cleaner=shift;
  167. if ($config{cgi}) {
  168. print "Content-type: text/html\n\n";
  169. print misctemplate(gettext("Error"),
  170. "<p>".gettext("Error").": $message</p>");
  171. }
  172. log_message('err' => $message) if $config{syslog};
  173. if (defined $cleaner) {
  174. $cleaner->();
  175. }
  176. die $message."\n";
  177. } #}}}
  178. sub debug ($) { #{{{
  179. return unless $config{verbose};
  180. return log_message(debug => @_);
  181. } #}}}
  182. my $log_open=0;
  183. sub log_message ($$) { #{{{
  184. my $type=shift;
  185. if ($config{syslog}) {
  186. require Sys::Syslog;
  187. if (! $log_open) {
  188. Sys::Syslog::setlogsock('unix');
  189. Sys::Syslog::openlog('ikiwiki', '', 'user');
  190. $log_open=1;
  191. }
  192. return eval {
  193. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  194. };
  195. }
  196. elsif (! $config{cgi}) {
  197. return print "@_\n";
  198. }
  199. else {
  200. return print STDERR "@_\n";
  201. }
  202. } #}}}
  203. sub possibly_foolish_untaint ($) { #{{{
  204. my $tainted=shift;
  205. my ($untainted)=$tainted=~/(.*)/s;
  206. return $untainted;
  207. } #}}}
  208. sub basename ($) { #{{{
  209. my $file=shift;
  210. $file=~s!.*/+!!;
  211. return $file;
  212. } #}}}
  213. sub dirname ($) { #{{{
  214. my $file=shift;
  215. $file=~s!/*[^/]+$!!;
  216. return $file;
  217. } #}}}
  218. sub pagetype ($) { #{{{
  219. my $page=shift;
  220. if ($page =~ /\.([^.]+)$/) {
  221. return $1 if exists $hooks{htmlize}{$1};
  222. }
  223. return;
  224. } #}}}
  225. sub isinternal ($) { #{{{
  226. my $page=shift;
  227. return exists $pagesources{$page} &&
  228. $pagesources{$page} =~ /\._([^.]+)$/;
  229. } #}}}
  230. sub pagename ($) { #{{{
  231. my $file=shift;
  232. my $type=pagetype($file);
  233. my $page=$file;
  234. $page=~s/\Q.$type\E*$// if defined $type;
  235. return $page;
  236. } #}}}
  237. sub targetpage ($$) { #{{{
  238. my $page=shift;
  239. my $ext=shift;
  240. if (! $config{usedirs} || $page =~ /^index$/ ) {
  241. return $page.".".$ext;
  242. } else {
  243. return $page."/index.".$ext;
  244. }
  245. } #}}}
  246. sub htmlpage ($) { #{{{
  247. my $page=shift;
  248. return targetpage($page, $config{htmlext});
  249. } #}}}
  250. sub srcfile_stat { #{{{
  251. my $file=shift;
  252. my $nothrow=shift;
  253. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  254. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  255. return "$dir/$file", stat(_) if -e "$dir/$file";
  256. }
  257. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  258. return;
  259. } #}}}
  260. sub srcfile ($;$) { #{{{
  261. return (srcfile_stat(@_))[0];
  262. } #}}}
  263. sub add_underlay ($) { #{{{
  264. my $dir=shift;
  265. if ($dir=~/^\//) {
  266. unshift @{$config{underlaydirs}}, $dir;
  267. }
  268. else {
  269. unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
  270. }
  271. return 1;
  272. } #}}}
  273. sub readfile ($;$$) { #{{{
  274. my $file=shift;
  275. my $binary=shift;
  276. my $wantfd=shift;
  277. if (-l $file) {
  278. error("cannot read a symlink ($file)");
  279. }
  280. local $/=undef;
  281. open (my $in, "<", $file) || error("failed to read $file: $!");
  282. binmode($in) if ($binary);
  283. return \*$in if $wantfd;
  284. my $ret=<$in>;
  285. close $in || error("failed to read $file: $!");
  286. return $ret;
  287. } #}}}
  288. sub prep_writefile ($$) {
  289. my $file=shift;
  290. my $destdir=shift;
  291. my $test=$file;
  292. while (length $test) {
  293. if (-l "$destdir/$test") {
  294. error("cannot write to a symlink ($test)");
  295. }
  296. $test=dirname($test);
  297. }
  298. my $dir=dirname("$destdir/$file");
  299. if (! -d $dir) {
  300. my $d="";
  301. foreach my $s (split(m!/+!, $dir)) {
  302. $d.="$s/";
  303. if (! -d $d) {
  304. mkdir($d) || error("failed to create directory $d: $!");
  305. }
  306. }
  307. }
  308. return 1;
  309. }
  310. sub writefile ($$$;$$) { #{{{
  311. my $file=shift; # can include subdirs
  312. my $destdir=shift; # directory to put file in
  313. my $content=shift;
  314. my $binary=shift;
  315. my $writer=shift;
  316. prep_writefile($file, $destdir);
  317. my $newfile="$destdir/$file.ikiwiki-new";
  318. if (-l $newfile) {
  319. error("cannot write to a symlink ($newfile)");
  320. }
  321. my $cleanup = sub { unlink($newfile) };
  322. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  323. binmode($out) if ($binary);
  324. if ($writer) {
  325. $writer->(\*$out, $cleanup);
  326. }
  327. else {
  328. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  329. }
  330. close $out || error("failed saving $newfile: $!", $cleanup);
  331. rename($newfile, "$destdir/$file") ||
  332. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  333. return 1;
  334. } #}}}
  335. my %cleared;
  336. sub will_render ($$;$) { #{{{
  337. my $page=shift;
  338. my $dest=shift;
  339. my $clear=shift;
  340. # Important security check.
  341. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  342. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  343. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  344. }
  345. if (! $clear || $cleared{$page}) {
  346. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  347. }
  348. else {
  349. foreach my $old (@{$renderedfiles{$page}}) {
  350. delete $destsources{$old};
  351. }
  352. $renderedfiles{$page}=[$dest];
  353. $cleared{$page}=1;
  354. }
  355. $destsources{$dest}=$page;
  356. return 1;
  357. } #}}}
  358. sub bestlink ($$) { #{{{
  359. my $page=shift;
  360. my $link=shift;
  361. my $cwd=$page;
  362. if ($link=~s/^\/+//) {
  363. # absolute links
  364. $cwd="";
  365. }
  366. $link=~s/\/$//;
  367. do {
  368. my $l=$cwd;
  369. $l.="/" if length $l;
  370. $l.=$link;
  371. if (exists $links{$l}) {
  372. return $l;
  373. }
  374. elsif (exists $pagecase{lc $l}) {
  375. return $pagecase{lc $l};
  376. }
  377. } while $cwd=~s!/?[^/]+$!!;
  378. if (length $config{userdir}) {
  379. my $l = "$config{userdir}/".lc($link);
  380. if (exists $links{$l}) {
  381. return $l;
  382. }
  383. elsif (exists $pagecase{lc $l}) {
  384. return $pagecase{lc $l};
  385. }
  386. }
  387. #print STDERR "warning: page $page, broken link: $link\n";
  388. return "";
  389. } #}}}
  390. sub isinlinableimage ($) { #{{{
  391. my $file=shift;
  392. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  393. } #}}}
  394. sub pagetitle ($;$) { #{{{
  395. my $page=shift;
  396. my $unescaped=shift;
  397. if ($unescaped) {
  398. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  399. }
  400. else {
  401. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  402. }
  403. return $page;
  404. } #}}}
  405. sub titlepage ($) { #{{{
  406. my $title=shift;
  407. $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  408. return $title;
  409. } #}}}
  410. sub linkpage ($) { #{{{
  411. my $link=shift;
  412. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  413. return $link;
  414. } #}}}
  415. sub cgiurl (@) { #{{{
  416. my %params=@_;
  417. return $config{cgiurl}."?".
  418. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  419. } #}}}
  420. sub baseurl (;$) { #{{{
  421. my $page=shift;
  422. return "$config{url}/" if ! defined $page;
  423. $page=htmlpage($page);
  424. $page=~s/[^\/]+$//;
  425. $page=~s/[^\/]+\//..\//g;
  426. return $page;
  427. } #}}}
  428. sub abs2rel ($$) { #{{{
  429. # Work around very innefficient behavior in File::Spec if abs2rel
  430. # is passed two relative paths. It's much faster if paths are
  431. # absolute! (Debian bug #376658; fixed in debian unstable now)
  432. my $path="/".shift;
  433. my $base="/".shift;
  434. require File::Spec;
  435. my $ret=File::Spec->abs2rel($path, $base);
  436. $ret=~s/^// if defined $ret;
  437. return $ret;
  438. } #}}}
  439. sub displaytime ($;$) { #{{{
  440. my $time=shift;
  441. my $format=shift;
  442. if (! defined $format) {
  443. $format=$config{timeformat};
  444. }
  445. # strftime doesn't know about encodings, so make sure
  446. # its output is properly treated as utf8
  447. return decode_utf8(POSIX::strftime($format, localtime($time)));
  448. } #}}}
  449. sub beautify_url ($) { #{{{
  450. my $url=shift;
  451. if ($config{usedirs}) {
  452. $url =~ s!/index.$config{htmlext}$!/!;
  453. }
  454. $url =~ s!^$!./!; # Browsers don't like empty links...
  455. return $url;
  456. } #}}}
  457. sub urlto ($$) { #{{{
  458. my $to=shift;
  459. my $from=shift;
  460. if (! length $to) {
  461. return beautify_url(baseurl($from));
  462. }
  463. if (! $destsources{$to}) {
  464. $to=htmlpage($to);
  465. }
  466. my $link = abs2rel($to, dirname(htmlpage($from)));
  467. return beautify_url($link);
  468. } #}}}
  469. sub htmllink ($$$;@) { #{{{
  470. my $lpage=shift; # the page doing the linking
  471. my $page=shift; # the page that will contain the link (different for inline)
  472. my $link=shift;
  473. my %opts=@_;
  474. $link=~s/\/$//;
  475. my $bestlink;
  476. if (! $opts{forcesubpage}) {
  477. $bestlink=bestlink($lpage, $link);
  478. }
  479. else {
  480. $bestlink="$lpage/".lc($link);
  481. }
  482. my $linktext;
  483. if (defined $opts{linktext}) {
  484. $linktext=$opts{linktext};
  485. }
  486. else {
  487. $linktext=pagetitle(basename($link));
  488. }
  489. return "<span class=\"selflink\">$linktext</span>"
  490. if length $bestlink && $page eq $bestlink &&
  491. ! defined $opts{anchor};
  492. if (! $destsources{$bestlink}) {
  493. $bestlink=htmlpage($bestlink);
  494. if (! $destsources{$bestlink}) {
  495. return $linktext unless length $config{cgiurl};
  496. return "<span class=\"createlink\"><a href=\"".
  497. cgiurl(
  498. do => "create",
  499. page => pagetitle(lc($link), 1),
  500. from => $lpage
  501. ).
  502. "\" rel=\"nofollow\">?</a>$linktext</span>"
  503. }
  504. }
  505. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  506. $bestlink=beautify_url($bestlink);
  507. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  508. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  509. }
  510. if (defined $opts{anchor}) {
  511. $bestlink.="#".$opts{anchor};
  512. }
  513. my @attrs;
  514. if (defined $opts{rel}) {
  515. push @attrs, ' rel="'.$opts{rel}.'"';
  516. }
  517. if (defined $opts{class}) {
  518. push @attrs, ' class="'.$opts{class}.'"';
  519. }
  520. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  521. } #}}}
  522. sub userlink ($) { #{{{
  523. my $user=shift;
  524. my $oiduser=eval { openiduser($user) };
  525. if (defined $oiduser) {
  526. return "<a href=\"$user\">$oiduser</a>";
  527. }
  528. else {
  529. eval q{use CGI 'escapeHTML'};
  530. error($@) if $@;
  531. return htmllink("", "", escapeHTML(
  532. length $config{userdir} ? $config{userdir}."/".$user : $user
  533. ), noimageinline => 1);
  534. }
  535. } #}}}
  536. sub htmlize ($$$$) { #{{{
  537. my $page=shift;
  538. my $destpage=shift;
  539. my $type=shift;
  540. my $content=shift;
  541. my $oneline = $content !~ /\n/;
  542. if (exists $hooks{htmlize}{$type}) {
  543. $content=$hooks{htmlize}{$type}{call}->(
  544. page => $page,
  545. content => $content,
  546. );
  547. }
  548. else {
  549. error("htmlization of $type not supported");
  550. }
  551. run_hooks(sanitize => sub {
  552. $content=shift->(
  553. page => $page,
  554. destpage => $destpage,
  555. content => $content,
  556. );
  557. });
  558. if ($oneline) {
  559. # hack to get rid of enclosing junk added by markdown
  560. # and other htmlizers
  561. $content=~s/^<p>//i;
  562. $content=~s/<\/p>$//i;
  563. chomp $content;
  564. }
  565. return $content;
  566. } #}}}
  567. sub linkify ($$$) { #{{{
  568. my $page=shift;
  569. my $destpage=shift;
  570. my $content=shift;
  571. run_hooks(linkify => sub {
  572. $content=shift->(
  573. page => $page,
  574. destpage => $destpage,
  575. content => $content,
  576. );
  577. });
  578. return $content;
  579. } #}}}
  580. our %preprocessing;
  581. our $preprocess_preview=0;
  582. sub preprocess ($$$;$$) { #{{{
  583. my $page=shift; # the page the data comes from
  584. my $destpage=shift; # the page the data will appear in (different for inline)
  585. my $content=shift;
  586. my $scan=shift;
  587. my $preview=shift;
  588. # Using local because it needs to be set within any nested calls
  589. # of this function.
  590. local $preprocess_preview=$preview if defined $preview;
  591. my $handle=sub {
  592. my $escape=shift;
  593. my $prefix=shift;
  594. my $command=shift;
  595. my $params=shift;
  596. if (length $escape) {
  597. return "[[$prefix$command $params]]";
  598. }
  599. elsif (exists $hooks{preprocess}{$command}) {
  600. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  601. # Note: preserve order of params, some plugins may
  602. # consider it significant.
  603. my @params;
  604. while ($params =~ m{
  605. (?:([-\w]+)=)? # 1: named parameter key?
  606. (?:
  607. """(.*?)""" # 2: triple-quoted value
  608. |
  609. "([^"]+)" # 3: single-quoted value
  610. |
  611. (\S+) # 4: unquoted value
  612. )
  613. (?:\s+|$) # delimiter to next param
  614. }sgx) {
  615. my $key=$1;
  616. my $val;
  617. if (defined $2) {
  618. $val=$2;
  619. $val=~s/\r\n/\n/mg;
  620. $val=~s/^\n+//g;
  621. $val=~s/\n+$//g;
  622. }
  623. elsif (defined $3) {
  624. $val=$3;
  625. }
  626. elsif (defined $4) {
  627. $val=$4;
  628. }
  629. if (defined $key) {
  630. push @params, $key, $val;
  631. }
  632. else {
  633. push @params, $val, '';
  634. }
  635. }
  636. if ($preprocessing{$page}++ > 3) {
  637. # Avoid loops of preprocessed pages preprocessing
  638. # other pages that preprocess them, etc.
  639. #translators: The first parameter is a
  640. #translators: preprocessor directive name,
  641. #translators: the second a page name, the
  642. #translators: third a number.
  643. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  644. $command, $page, $preprocessing{$page}).
  645. "]]";
  646. }
  647. my $ret;
  648. if (! $scan) {
  649. $ret=$hooks{preprocess}{$command}{call}->(
  650. @params,
  651. page => $page,
  652. destpage => $destpage,
  653. preview => $preprocess_preview,
  654. );
  655. }
  656. else {
  657. # use void context during scan pass
  658. $hooks{preprocess}{$command}{call}->(
  659. @params,
  660. page => $page,
  661. destpage => $destpage,
  662. preview => $preprocess_preview,
  663. );
  664. $ret="";
  665. }
  666. $preprocessing{$page}--;
  667. return $ret;
  668. }
  669. else {
  670. return "[[$prefix$command $params]]";
  671. }
  672. };
  673. my $regex;
  674. if ($config{prefix_directives}) {
  675. $regex = qr{
  676. (\\?) # 1: escape?
  677. \[\[(!) # directive open; 2: prefix
  678. ([-\w]+) # 3: command
  679. ( # 4: the parameters..
  680. \s+ # Must have space if parameters present
  681. (?:
  682. (?:[-\w]+=)? # named parameter key?
  683. (?:
  684. """.*?""" # triple-quoted value
  685. |
  686. "[^"]+" # single-quoted value
  687. |
  688. [^\s\]]+ # unquoted value
  689. )
  690. \s* # whitespace or end
  691. # of directive
  692. )
  693. *)? # 0 or more parameters
  694. \]\] # directive closed
  695. }sx;
  696. } else {
  697. $regex = qr{
  698. (\\?) # 1: escape?
  699. \[\[(!?) # directive open; 2: optional prefix
  700. ([-\w]+) # 3: command
  701. \s+
  702. ( # 4: the parameters..
  703. (?:
  704. (?:[-\w]+=)? # named parameter key?
  705. (?:
  706. """.*?""" # triple-quoted value
  707. |
  708. "[^"]+" # single-quoted value
  709. |
  710. [^\s\]]+ # unquoted value
  711. )
  712. \s* # whitespace or end
  713. # of directive
  714. )
  715. *) # 0 or more parameters
  716. \]\] # directive closed
  717. }sx;
  718. }
  719. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  720. return $content;
  721. } #}}}
  722. sub filter ($$$) { #{{{
  723. my $page=shift;
  724. my $destpage=shift;
  725. my $content=shift;
  726. run_hooks(filter => sub {
  727. $content=shift->(page => $page, destpage => $destpage,
  728. content => $content);
  729. });
  730. return $content;
  731. } #}}}
  732. sub indexlink () { #{{{
  733. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  734. } #}}}
  735. my $wikilock;
  736. sub lockwiki (;$) { #{{{
  737. my $wait=@_ ? shift : 1;
  738. # Take an exclusive lock on the wiki to prevent multiple concurrent
  739. # run issues. The lock will be dropped on program exit.
  740. if (! -d $config{wikistatedir}) {
  741. mkdir($config{wikistatedir});
  742. }
  743. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  744. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  745. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  746. if ($wait) {
  747. debug("wiki seems to be locked, waiting for lock");
  748. my $wait=600; # arbitrary, but don't hang forever to
  749. # prevent process pileup
  750. for (1..$wait) {
  751. return if flock($wikilock, 2 | 4);
  752. sleep 1;
  753. }
  754. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  755. }
  756. else {
  757. return 0;
  758. }
  759. }
  760. return 1;
  761. } #}}}
  762. sub unlockwiki () { #{{{
  763. return close($wikilock) if $wikilock;
  764. return;
  765. } #}}}
  766. my $commitlock;
  767. sub commit_hook_enabled () { #{{{
  768. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  769. error("cannot write to $config{wikistatedir}/commitlock: $!");
  770. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  771. close($commitlock) || error("failed closing commitlock: $!");
  772. return 0;
  773. }
  774. close($commitlock) || error("failed closing commitlock: $!");
  775. return 1;
  776. } #}}}
  777. sub disable_commit_hook () { #{{{
  778. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  779. error("cannot write to $config{wikistatedir}/commitlock: $!");
  780. if (! flock($commitlock, 2)) { # LOCK_EX
  781. error("failed to get commit lock");
  782. }
  783. return 1;
  784. } #}}}
  785. sub enable_commit_hook () { #{{{
  786. return close($commitlock) if $commitlock;
  787. return;
  788. } #}}}
  789. sub loadindex () { #{{{
  790. %oldrenderedfiles=%pagectime=();
  791. if (! $config{rebuild}) {
  792. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  793. %destsources=%renderedfiles=%pagecase=%pagestate=();
  794. }
  795. my $in;
  796. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  797. if (-e "$config{wikistatedir}/index") {
  798. system("ikiwiki-transition", "indexdb", $config{srcdir});
  799. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  800. }
  801. else {
  802. return;
  803. }
  804. }
  805. my $ret=Storable::fd_retrieve($in);
  806. if (! defined $ret) {
  807. return 0;
  808. }
  809. my %index=%$ret;
  810. foreach my $src (keys %index) {
  811. my %d=%{$index{$src}};
  812. my $page=pagename($src);
  813. $pagectime{$page}=$d{ctime};
  814. if (! $config{rebuild}) {
  815. $pagesources{$page}=$src;
  816. $pagemtime{$page}=$d{mtime};
  817. $renderedfiles{$page}=$d{dest};
  818. if (exists $d{links} && ref $d{links}) {
  819. $links{$page}=$d{links};
  820. $oldlinks{$page}=[@{$d{links}}];
  821. }
  822. if (exists $d{depends}) {
  823. $depends{$page}=$d{depends};
  824. }
  825. if (exists $d{state}) {
  826. $pagestate{$page}=$d{state};
  827. }
  828. }
  829. $oldrenderedfiles{$page}=[@{$d{dest}}];
  830. }
  831. foreach my $page (keys %pagesources) {
  832. $pagecase{lc $page}=$page;
  833. }
  834. foreach my $page (keys %renderedfiles) {
  835. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  836. }
  837. return close($in);
  838. } #}}}
  839. sub saveindex () { #{{{
  840. run_hooks(savestate => sub { shift->() });
  841. my %hookids;
  842. foreach my $type (keys %hooks) {
  843. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  844. }
  845. my @hookids=keys %hookids;
  846. if (! -d $config{wikistatedir}) {
  847. mkdir($config{wikistatedir});
  848. }
  849. my $newfile="$config{wikistatedir}/indexdb.new";
  850. my $cleanup = sub { unlink($newfile) };
  851. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  852. my %index;
  853. foreach my $page (keys %pagemtime) {
  854. next unless $pagemtime{$page};
  855. my $src=$pagesources{$page};
  856. $index{$src}={
  857. ctime => $pagectime{$page},
  858. mtime => $pagemtime{$page},
  859. dest => $renderedfiles{$page},
  860. links => $links{$page},
  861. };
  862. if (exists $depends{$page}) {
  863. $index{$src}{depends} = $depends{$page};
  864. }
  865. if (exists $pagestate{$page}) {
  866. foreach my $id (@hookids) {
  867. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  868. $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  869. }
  870. }
  871. }
  872. }
  873. my $ret=Storable::nstore_fd(\%index, $out);
  874. return if ! defined $ret || ! $ret;
  875. close $out || error("failed saving to $newfile: $!", $cleanup);
  876. rename($newfile, "$config{wikistatedir}/indexdb") ||
  877. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  878. return 1;
  879. } #}}}
  880. sub template_file ($) { #{{{
  881. my $template=shift;
  882. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  883. return "$dir/$template" if -e "$dir/$template";
  884. }
  885. return;
  886. } #}}}
  887. sub template_params (@) { #{{{
  888. my $filename=template_file(shift);
  889. if (! defined $filename) {
  890. return if wantarray;
  891. return "";
  892. }
  893. my @ret=(
  894. filter => sub {
  895. my $text_ref = shift;
  896. ${$text_ref} = decode_utf8(${$text_ref});
  897. },
  898. filename => $filename,
  899. loop_context_vars => 1,
  900. die_on_bad_params => 0,
  901. @_
  902. );
  903. return wantarray ? @ret : {@ret};
  904. } #}}}
  905. sub template ($;@) { #{{{
  906. require HTML::Template;
  907. return HTML::Template->new(template_params(@_));
  908. } #}}}
  909. sub misctemplate ($$;@) { #{{{
  910. my $title=shift;
  911. my $pagebody=shift;
  912. my $template=template("misc.tmpl");
  913. $template->param(
  914. title => $title,
  915. indexlink => indexlink(),
  916. wikiname => $config{wikiname},
  917. pagebody => $pagebody,
  918. baseurl => baseurl(),
  919. @_,
  920. );
  921. run_hooks(pagetemplate => sub {
  922. shift->(page => "", destpage => "", template => $template);
  923. });
  924. return $template->output;
  925. }#}}}
  926. sub hook (@) { # {{{
  927. my %param=@_;
  928. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  929. error 'hook requires type, call, and id parameters';
  930. }
  931. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  932. $hooks{$param{type}}{$param{id}}=\%param;
  933. return 1;
  934. } # }}}
  935. sub run_hooks ($$) { # {{{
  936. # Calls the given sub for each hook of the given type,
  937. # passing it the hook function to call.
  938. my $type=shift;
  939. my $sub=shift;
  940. if (exists $hooks{$type}) {
  941. my @deferred;
  942. foreach my $id (keys %{$hooks{$type}}) {
  943. if ($hooks{$type}{$id}{last}) {
  944. push @deferred, $id;
  945. next;
  946. }
  947. $sub->($hooks{$type}{$id}{call});
  948. }
  949. foreach my $id (@deferred) {
  950. $sub->($hooks{$type}{$id}{call});
  951. }
  952. }
  953. return 1;
  954. } #}}}
  955. sub globlist_to_pagespec ($) { #{{{
  956. my @globlist=split(' ', shift);
  957. my (@spec, @skip);
  958. foreach my $glob (@globlist) {
  959. if ($glob=~/^!(.*)/) {
  960. push @skip, $glob;
  961. }
  962. else {
  963. push @spec, $glob;
  964. }
  965. }
  966. my $spec=join(' or ', @spec);
  967. if (@skip) {
  968. my $skip=join(' and ', @skip);
  969. if (length $spec) {
  970. $spec="$skip and ($spec)";
  971. }
  972. else {
  973. $spec=$skip;
  974. }
  975. }
  976. return $spec;
  977. } #}}}
  978. sub is_globlist ($) { #{{{
  979. my $s=shift;
  980. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  981. } #}}}
  982. sub safequote ($) { #{{{
  983. my $s=shift;
  984. $s=~s/[{}]//g;
  985. return "q{$s}";
  986. } #}}}
  987. sub add_depends ($$) { #{{{
  988. my $page=shift;
  989. my $pagespec=shift;
  990. return unless pagespec_valid($pagespec);
  991. if (! exists $depends{$page}) {
  992. $depends{$page}=$pagespec;
  993. }
  994. else {
  995. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  996. }
  997. return 1;
  998. } # }}}
  999. sub file_pruned ($$) { #{{{
  1000. require File::Spec;
  1001. my $file=File::Spec->canonpath(shift);
  1002. my $base=File::Spec->canonpath(shift);
  1003. $file =~ s#^\Q$base\E/+##;
  1004. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1005. return $file =~ m/$regexp/ && $file ne $base;
  1006. } #}}}
  1007. sub gettext { #{{{
  1008. # Only use gettext in the rare cases it's needed.
  1009. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1010. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1011. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1012. if (! $gettext_obj) {
  1013. $gettext_obj=eval q{
  1014. use Locale::gettext q{textdomain};
  1015. Locale::gettext->domain('ikiwiki')
  1016. };
  1017. if ($@) {
  1018. print STDERR "$@";
  1019. $gettext_obj=undef;
  1020. return shift;
  1021. }
  1022. }
  1023. return $gettext_obj->get(shift);
  1024. }
  1025. else {
  1026. return shift;
  1027. }
  1028. } #}}}
  1029. sub pagespec_merge ($$) { #{{{
  1030. my $a=shift;
  1031. my $b=shift;
  1032. return $a if $a eq $b;
  1033. # Support for old-style GlobLists.
  1034. if (is_globlist($a)) {
  1035. $a=globlist_to_pagespec($a);
  1036. }
  1037. if (is_globlist($b)) {
  1038. $b=globlist_to_pagespec($b);
  1039. }
  1040. return "($a) or ($b)";
  1041. } #}}}
  1042. sub pagespec_translate ($) { #{{{
  1043. my $spec=shift;
  1044. # Support for old-style GlobLists.
  1045. if (is_globlist($spec)) {
  1046. $spec=globlist_to_pagespec($spec);
  1047. }
  1048. # Convert spec to perl code.
  1049. my $code="";
  1050. while ($spec=~m{
  1051. \s* # ignore whitespace
  1052. ( # 1: match a single word
  1053. \! # !
  1054. |
  1055. \( # (
  1056. |
  1057. \) # )
  1058. |
  1059. \w+\([^\)]*\) # command(params)
  1060. |
  1061. [^\s()]+ # any other text
  1062. )
  1063. \s* # ignore whitespace
  1064. }igx) {
  1065. my $word=$1;
  1066. if (lc $word eq 'and') {
  1067. $code.=' &&';
  1068. }
  1069. elsif (lc $word eq 'or') {
  1070. $code.=' ||';
  1071. }
  1072. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1073. $code.=' '.$word;
  1074. }
  1075. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1076. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1077. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1078. }
  1079. else {
  1080. $code.=' 0';
  1081. }
  1082. }
  1083. else {
  1084. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1085. }
  1086. }
  1087. if (! length $code) {
  1088. $code=0;
  1089. }
  1090. no warnings;
  1091. return eval 'sub { my $page=shift; '.$code.' }';
  1092. } #}}}
  1093. sub pagespec_match ($$;@) { #{{{
  1094. my $page=shift;
  1095. my $spec=shift;
  1096. my @params=@_;
  1097. # Backwards compatability with old calling convention.
  1098. if (@params == 1) {
  1099. unshift @params, 'location';
  1100. }
  1101. my $sub=pagespec_translate($spec);
  1102. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1103. return $sub->($page, @params);
  1104. } #}}}
  1105. sub pagespec_valid ($) { #{{{
  1106. my $spec=shift;
  1107. my $sub=pagespec_translate($spec);
  1108. return ! $@;
  1109. } #}}}
  1110. package IkiWiki::FailReason;
  1111. use overload ( #{{{
  1112. '""' => sub { ${$_[0]} },
  1113. '0+' => sub { 0 },
  1114. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1115. fallback => 1,
  1116. ); #}}}
  1117. sub new { #{{{
  1118. my $class = shift;
  1119. my $value = shift;
  1120. return bless \$value, $class;
  1121. } #}}}
  1122. package IkiWiki::SuccessReason;
  1123. use overload ( #{{{
  1124. '""' => sub { ${$_[0]} },
  1125. '0+' => sub { 1 },
  1126. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1127. fallback => 1,
  1128. ); #}}}
  1129. sub new { #{{{
  1130. my $class = shift;
  1131. my $value = shift;
  1132. return bless \$value, $class;
  1133. }; #}}}
  1134. package IkiWiki::PageSpec;
  1135. sub match_glob ($$;@) { #{{{
  1136. my $page=shift;
  1137. my $glob=shift;
  1138. my %params=@_;
  1139. my $from=exists $params{location} ? $params{location} : '';
  1140. # relative matching
  1141. if ($glob =~ m!^\./!) {
  1142. $from=~s#/?[^/]+$##;
  1143. $glob=~s#^\./##;
  1144. $glob="$from/$glob" if length $from;
  1145. }
  1146. # turn glob into safe regexp
  1147. $glob=quotemeta($glob);
  1148. $glob=~s/\\\*/.*/g;
  1149. $glob=~s/\\\?/./g;
  1150. if ($page=~/^$glob$/i) {
  1151. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1152. return IkiWiki::SuccessReason->new("$glob matches $page");
  1153. }
  1154. else {
  1155. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1156. }
  1157. }
  1158. else {
  1159. return IkiWiki::FailReason->new("$glob does not match $page");
  1160. }
  1161. } #}}}
  1162. sub match_internal ($$;@) { #{{{
  1163. return match_glob($_[0], $_[1], @_, internal => 1)
  1164. } #}}}
  1165. sub match_link ($$;@) { #{{{
  1166. my $page=shift;
  1167. my $link=lc(shift);
  1168. my %params=@_;
  1169. my $from=exists $params{location} ? $params{location} : '';
  1170. # relative matching
  1171. if ($link =~ m!^\.! && defined $from) {
  1172. $from=~s#/?[^/]+$##;
  1173. $link=~s#^\./##;
  1174. $link="$from/$link" if length $from;
  1175. }
  1176. my $links = $IkiWiki::links{$page};
  1177. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1178. my $bestlink = IkiWiki::bestlink($from, $link);
  1179. foreach my $p (@{$links}) {
  1180. if (length $bestlink) {
  1181. return IkiWiki::SuccessReason->new("$page links to $link")
  1182. if $bestlink eq IkiWiki::bestlink($page, $p);
  1183. }
  1184. else {
  1185. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1186. if match_glob($p, $link, %params);
  1187. }
  1188. }
  1189. return IkiWiki::FailReason->new("$page does not link to $link");
  1190. } #}}}
  1191. sub match_backlink ($$;@) { #{{{
  1192. return match_link($_[1], $_[0], @_);
  1193. } #}}}
  1194. sub match_created_before ($$;@) { #{{{
  1195. my $page=shift;
  1196. my $testpage=shift;
  1197. if (exists $IkiWiki::pagectime{$testpage}) {
  1198. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1199. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1200. }
  1201. else {
  1202. return IkiWiki::FailReason->new("$page not created before $testpage");
  1203. }
  1204. }
  1205. else {
  1206. return IkiWiki::FailReason->new("$testpage has no ctime");
  1207. }
  1208. } #}}}
  1209. sub match_created_after ($$;@) { #{{{
  1210. my $page=shift;
  1211. my $testpage=shift;
  1212. if (exists $IkiWiki::pagectime{$testpage}) {
  1213. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1214. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1215. }
  1216. else {
  1217. return IkiWiki::FailReason->new("$page not created after $testpage");
  1218. }
  1219. }
  1220. else {
  1221. return IkiWiki::FailReason->new("$testpage has no ctime");
  1222. }
  1223. } #}}}
  1224. sub match_creation_day ($$;@) { #{{{
  1225. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1226. return IkiWiki::SuccessReason->new('creation_day matched');
  1227. }
  1228. else {
  1229. return IkiWiki::FailReason->new('creation_day did not match');
  1230. }
  1231. } #}}}
  1232. sub match_creation_month ($$;@) { #{{{
  1233. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1234. return IkiWiki::SuccessReason->new('creation_month matched');
  1235. }
  1236. else {
  1237. return IkiWiki::FailReason->new('creation_month did not match');
  1238. }
  1239. } #}}}
  1240. sub match_creation_year ($$;@) { #{{{
  1241. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1242. return IkiWiki::SuccessReason->new('creation_year matched');
  1243. }
  1244. else {
  1245. return IkiWiki::FailReason->new('creation_year did not match');
  1246. }
  1247. } #}}}
  1248. 1