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