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