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