summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 0c05bb0d377c8622b2e0ea3ff6a21abea14a6322 (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. url => '',
  59. cgiurl => '',
  60. historyurl => '',
  61. diffurl => '',
  62. rss => 0,
  63. atom => 0,
  64. allowrss => 0,
  65. allowatom => 0,
  66. discussion => 1,
  67. rebuild => 0,
  68. refresh => 0,
  69. getctime => 0,
  70. w3mmode => 0,
  71. wrapper => undef,
  72. wrappermode => 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 isinternal ($) { #{{{
  231. my $page=shift;
  232. return exists $pagesources{$page} &&
  233. $pagesources{$page} =~ /\._([^.]+)$/;
  234. } #}}}
  235. sub pagename ($) { #{{{
  236. my $file=shift;
  237. my $type=pagetype($file);
  238. my $page=$file;
  239. $page=~s/\Q.$type\E*$// if defined $type;
  240. return $page;
  241. } #}}}
  242. sub targetpage ($$) { #{{{
  243. my $page=shift;
  244. my $ext=shift;
  245. if (! $config{usedirs} || $page =~ /^index$/ ) {
  246. return $page.".".$ext;
  247. } else {
  248. return $page."/index.".$ext;
  249. }
  250. } #}}}
  251. sub htmlpage ($) { #{{{
  252. my $page=shift;
  253. return targetpage($page, $config{htmlext});
  254. } #}}}
  255. sub srcfile ($) { #{{{
  256. my $file=shift;
  257. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  258. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  259. return "$dir/$file" if -e "$dir/$file";
  260. }
  261. error("internal error: $file cannot be found in $config{srcdir} or underlay");
  262. return;
  263. } #}}}
  264. sub add_underlay ($) { #{{{
  265. my $dir=shift;
  266. if ($dir=~/^\//) {
  267. unshift @{$config{underlaydirs}}, $dir;
  268. }
  269. else {
  270. unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
  271. }
  272. return 1;
  273. } #}}}
  274. sub readfile ($;$$) { #{{{
  275. my $file=shift;
  276. my $binary=shift;
  277. my $wantfd=shift;
  278. if (-l $file) {
  279. error("cannot read a symlink ($file)");
  280. }
  281. local $/=undef;
  282. open (my $in, "<", $file) || error("failed to read $file: $!");
  283. binmode($in) if ($binary);
  284. return \*$in if $wantfd;
  285. my $ret=<$in>;
  286. close $in || error("failed to read $file: $!");
  287. return $ret;
  288. } #}}}
  289. sub writefile ($$$;$$) { #{{{
  290. my $file=shift; # can include subdirs
  291. my $destdir=shift; # directory to put file in
  292. my $content=shift;
  293. my $binary=shift;
  294. my $writer=shift;
  295. my $test=$file;
  296. while (length $test) {
  297. if (-l "$destdir/$test") {
  298. error("cannot write to a symlink ($test)");
  299. }
  300. $test=dirname($test);
  301. }
  302. my $newfile="$destdir/$file.ikiwiki-new";
  303. if (-l $newfile) {
  304. error("cannot write to a symlink ($newfile)");
  305. }
  306. my $dir=dirname($newfile);
  307. if (! -d $dir) {
  308. my $d="";
  309. foreach my $s (split(m!/+!, $dir)) {
  310. $d.="$s/";
  311. if (! -d $d) {
  312. mkdir($d) || error("failed to create directory $d: $!");
  313. }
  314. }
  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. return htmllink("", "", escapeHTML(
  525. length $config{userdir} ? $config{userdir}."/".$user : $user
  526. ), noimageinline => 1);
  527. }
  528. } #}}}
  529. sub htmlize ($$$) { #{{{
  530. my $page=shift;
  531. my $type=shift;
  532. my $content=shift;
  533. my $oneline = $content !~ /\n/;
  534. if (exists $hooks{htmlize}{$type}) {
  535. $content=$hooks{htmlize}{$type}{call}->(
  536. page => $page,
  537. content => $content,
  538. );
  539. }
  540. else {
  541. error("htmlization of $type not supported");
  542. }
  543. run_hooks(sanitize => sub {
  544. $content=shift->(
  545. page => $page,
  546. content => $content,
  547. );
  548. });
  549. if ($oneline) {
  550. # hack to get rid of enclosing junk added by markdown
  551. # and other htmlizers
  552. $content=~s/^<p>//i;
  553. $content=~s/<\/p>$//i;
  554. chomp $content;
  555. }
  556. return $content;
  557. } #}}}
  558. sub linkify ($$$) { #{{{
  559. my $lpage=shift; # the page containing the links
  560. my $page=shift; # the page the link will end up on (different for inline)
  561. my $content=shift;
  562. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  563. defined $2
  564. ? ( $1
  565. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  566. : htmllink($lpage, $page, linkpage($3),
  567. anchor => $4, linktext => pagetitle($2)))
  568. : ( $1
  569. ? "[[$3".($4 ? "#$4" : "")."]]"
  570. : htmllink($lpage, $page, linkpage($3),
  571. anchor => $4))
  572. }eg;
  573. return $content;
  574. } #}}}
  575. my %preprocessing;
  576. our $preprocess_preview=0;
  577. sub preprocess ($$$;$$) { #{{{
  578. my $page=shift; # the page the data comes from
  579. my $destpage=shift; # the page the data will appear in (different for inline)
  580. my $content=shift;
  581. my $scan=shift;
  582. my $preview=shift;
  583. # Using local because it needs to be set within any nested calls
  584. # of this function.
  585. local $preprocess_preview=$preview if defined $preview;
  586. my $handle=sub {
  587. my $escape=shift;
  588. my $command=shift;
  589. my $params=shift;
  590. if (length $escape) {
  591. return "[[$command $params]]";
  592. }
  593. elsif (exists $hooks{preprocess}{$command}) {
  594. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  595. # Note: preserve order of params, some plugins may
  596. # consider it significant.
  597. my @params;
  598. while ($params =~ m{
  599. (?:([-\w]+)=)? # 1: named parameter key?
  600. (?:
  601. """(.*?)""" # 2: triple-quoted value
  602. |
  603. "([^"]+)" # 3: single-quoted value
  604. |
  605. (\S+) # 4: unquoted value
  606. )
  607. (?:\s+|$) # delimiter to next param
  608. }sgx) {
  609. my $key=$1;
  610. my $val;
  611. if (defined $2) {
  612. $val=$2;
  613. $val=~s/\r\n/\n/mg;
  614. $val=~s/^\n+//g;
  615. $val=~s/\n+$//g;
  616. }
  617. elsif (defined $3) {
  618. $val=$3;
  619. }
  620. elsif (defined $4) {
  621. $val=$4;
  622. }
  623. if (defined $key) {
  624. push @params, $key, $val;
  625. }
  626. else {
  627. push @params, $val, '';
  628. }
  629. }
  630. if ($preprocessing{$page}++ > 3) {
  631. # Avoid loops of preprocessed pages preprocessing
  632. # other pages that preprocess them, etc.
  633. #translators: The first parameter is a
  634. #translators: preprocessor directive name,
  635. #translators: the second a page name, the
  636. #translators: third a number.
  637. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  638. $command, $page, $preprocessing{$page}).
  639. "]]";
  640. }
  641. my $ret;
  642. if (! $scan) {
  643. $ret=$hooks{preprocess}{$command}{call}->(
  644. @params,
  645. page => $page,
  646. destpage => $destpage,
  647. preview => $preprocess_preview,
  648. );
  649. }
  650. else {
  651. # use void context during scan pass
  652. $hooks{preprocess}{$command}{call}->(
  653. @params,
  654. page => $page,
  655. destpage => $destpage,
  656. preview => $preprocess_preview,
  657. );
  658. $ret="";
  659. }
  660. $preprocessing{$page}--;
  661. return $ret;
  662. }
  663. else {
  664. return "[[$command $params]]";
  665. }
  666. };
  667. $content =~ s{
  668. (\\?) # 1: escape?
  669. \[\[ # directive open
  670. ([-\w]+) # 2: command
  671. \s+
  672. ( # 3: the parameters..
  673. (?:
  674. (?:[-\w]+=)? # named parameter key?
  675. (?:
  676. """.*?""" # triple-quoted value
  677. |
  678. "[^"]+" # single-quoted value
  679. |
  680. [^\s\]]+ # unquoted value
  681. )
  682. \s* # whitespace or end
  683. # of directive
  684. )
  685. *) # 0 or more parameters
  686. \]\] # directive closed
  687. }{$handle->($1, $2, $3)}sexg;
  688. return $content;
  689. } #}}}
  690. sub filter ($$$) { #{{{
  691. my $page=shift;
  692. my $destpage=shift;
  693. my $content=shift;
  694. run_hooks(filter => sub {
  695. $content=shift->(page => $page, destpage => $destpage,
  696. content => $content);
  697. });
  698. return $content;
  699. } #}}}
  700. sub indexlink () { #{{{
  701. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  702. } #}}}
  703. my $wikilock;
  704. sub lockwiki (;$) { #{{{
  705. my $wait=@_ ? shift : 1;
  706. # Take an exclusive lock on the wiki to prevent multiple concurrent
  707. # run issues. The lock will be dropped on program exit.
  708. if (! -d $config{wikistatedir}) {
  709. mkdir($config{wikistatedir});
  710. }
  711. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  712. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  713. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  714. if ($wait) {
  715. debug("wiki seems to be locked, waiting for lock");
  716. my $wait=600; # arbitrary, but don't hang forever to
  717. # prevent process pileup
  718. for (1..$wait) {
  719. return if flock($wikilock, 2 | 4);
  720. sleep 1;
  721. }
  722. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  723. }
  724. else {
  725. return 0;
  726. }
  727. }
  728. return 1;
  729. } #}}}
  730. sub unlockwiki () { #{{{
  731. return close($wikilock) if $wikilock;
  732. return;
  733. } #}}}
  734. my $commitlock;
  735. sub commit_hook_enabled () { #{{{
  736. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  737. error("cannot write to $config{wikistatedir}/commitlock: $!");
  738. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  739. close($commitlock) || error("failed closing commitlock: $!");
  740. return 0;
  741. }
  742. close($commitlock) || error("failed closing commitlock: $!");
  743. return 1;
  744. } #}}}
  745. sub disable_commit_hook () { #{{{
  746. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  747. error("cannot write to $config{wikistatedir}/commitlock: $!");
  748. if (! flock($commitlock, 2)) { # LOCK_EX
  749. error("failed to get commit lock");
  750. }
  751. return 1;
  752. } #}}}
  753. sub enable_commit_hook () { #{{{
  754. return close($commitlock) if $commitlock;
  755. return;
  756. } #}}}
  757. sub loadindex () { #{{{
  758. %oldrenderedfiles=%pagectime=();
  759. if (! $config{rebuild}) {
  760. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  761. %destsources=%renderedfiles=%pagecase=%pagestate=();
  762. }
  763. open (my $in, "<", "$config{wikistatedir}/index") || return;
  764. while (<$in>) {
  765. $_=possibly_foolish_untaint($_);
  766. chomp;
  767. my %items;
  768. $items{link}=[];
  769. $items{dest}=[];
  770. foreach my $i (split(/ /, $_)) {
  771. my ($item, $val)=split(/=/, $i, 2);
  772. push @{$items{$item}}, decode_entities($val);
  773. }
  774. next unless exists $items{src}; # skip bad lines for now
  775. my $page=pagename($items{src}[0]);
  776. if (! $config{rebuild}) {
  777. $pagesources{$page}=$items{src}[0];
  778. $pagemtime{$page}=$items{mtime}[0];
  779. $oldlinks{$page}=[@{$items{link}}];
  780. $links{$page}=[@{$items{link}}];
  781. $depends{$page}=$items{depends}[0] if exists $items{depends};
  782. $destsources{$_}=$page foreach @{$items{dest}};
  783. $renderedfiles{$page}=[@{$items{dest}}];
  784. $pagecase{lc $page}=$page;
  785. foreach my $k (grep /_/, keys %items) {
  786. my ($id, $key)=split(/_/, $k, 2);
  787. $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
  788. }
  789. }
  790. $oldrenderedfiles{$page}=[@{$items{dest}}];
  791. $pagectime{$page}=$items{ctime}[0];
  792. }
  793. return close($in);
  794. } #}}}
  795. sub saveindex () { #{{{
  796. run_hooks(savestate => sub { shift->() });
  797. my %hookids;
  798. foreach my $type (keys %hooks) {
  799. $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
  800. }
  801. my @hookids=sort keys %hookids;
  802. if (! -d $config{wikistatedir}) {
  803. mkdir($config{wikistatedir});
  804. }
  805. my $newfile="$config{wikistatedir}/index.new";
  806. my $cleanup = sub { unlink($newfile) };
  807. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  808. foreach my $page (keys %pagemtime) {
  809. next unless $pagemtime{$page};
  810. my $line="mtime=$pagemtime{$page} ".
  811. "ctime=$pagectime{$page} ".
  812. "src=$pagesources{$page}";
  813. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  814. my %count;
  815. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  816. if (exists $depends{$page}) {
  817. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  818. }
  819. if (exists $pagestate{$page}) {
  820. foreach my $id (@hookids) {
  821. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  822. $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key}, " \t\n");
  823. }
  824. }
  825. }
  826. print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  827. }
  828. close $out || error("failed saving to $newfile: $!", $cleanup);
  829. rename($newfile, "$config{wikistatedir}/index") ||
  830. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  831. return 1;
  832. } #}}}
  833. sub template_file ($) { #{{{
  834. my $template=shift;
  835. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  836. return "$dir/$template" if -e "$dir/$template";
  837. }
  838. return;
  839. } #}}}
  840. sub template_params (@) { #{{{
  841. my $filename=template_file(shift);
  842. if (! defined $filename) {
  843. return if wantarray;
  844. return "";
  845. }
  846. my @ret=(
  847. filter => sub {
  848. my $text_ref = shift;
  849. ${$text_ref} = decode_utf8(${$text_ref});
  850. },
  851. filename => $filename,
  852. loop_context_vars => 1,
  853. die_on_bad_params => 0,
  854. @_
  855. );
  856. return wantarray ? @ret : {@ret};
  857. } #}}}
  858. sub template ($;@) { #{{{
  859. require HTML::Template;
  860. return HTML::Template->new(template_params(@_));
  861. } #}}}
  862. sub misctemplate ($$;@) { #{{{
  863. my $title=shift;
  864. my $pagebody=shift;
  865. my $template=template("misc.tmpl");
  866. $template->param(
  867. title => $title,
  868. indexlink => indexlink(),
  869. wikiname => $config{wikiname},
  870. pagebody => $pagebody,
  871. baseurl => baseurl(),
  872. @_,
  873. );
  874. run_hooks(pagetemplate => sub {
  875. shift->(page => "", destpage => "", template => $template);
  876. });
  877. return $template->output;
  878. }#}}}
  879. sub hook (@) { # {{{
  880. my %param=@_;
  881. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  882. error 'hook requires type, call, and id parameters';
  883. }
  884. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  885. $hooks{$param{type}}{$param{id}}=\%param;
  886. return 1;
  887. } # }}}
  888. sub run_hooks ($$) { # {{{
  889. # Calls the given sub for each hook of the given type,
  890. # passing it the hook function to call.
  891. my $type=shift;
  892. my $sub=shift;
  893. if (exists $hooks{$type}) {
  894. my @deferred;
  895. foreach my $id (keys %{$hooks{$type}}) {
  896. if ($hooks{$type}{$id}{last}) {
  897. push @deferred, $id;
  898. next;
  899. }
  900. $sub->($hooks{$type}{$id}{call});
  901. }
  902. foreach my $id (@deferred) {
  903. $sub->($hooks{$type}{$id}{call});
  904. }
  905. }
  906. return 1;
  907. } #}}}
  908. sub globlist_to_pagespec ($) { #{{{
  909. my @globlist=split(' ', shift);
  910. my (@spec, @skip);
  911. foreach my $glob (@globlist) {
  912. if ($glob=~/^!(.*)/) {
  913. push @skip, $glob;
  914. }
  915. else {
  916. push @spec, $glob;
  917. }
  918. }
  919. my $spec=join(' or ', @spec);
  920. if (@skip) {
  921. my $skip=join(' and ', @skip);
  922. if (length $spec) {
  923. $spec="$skip and ($spec)";
  924. }
  925. else {
  926. $spec=$skip;
  927. }
  928. }
  929. return $spec;
  930. } #}}}
  931. sub is_globlist ($) { #{{{
  932. my $s=shift;
  933. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  934. } #}}}
  935. sub safequote ($) { #{{{
  936. my $s=shift;
  937. $s=~s/[{}]//g;
  938. return "q{$s}";
  939. } #}}}
  940. sub add_depends ($$) { #{{{
  941. my $page=shift;
  942. my $pagespec=shift;
  943. if (! exists $depends{$page}) {
  944. $depends{$page}=$pagespec;
  945. }
  946. else {
  947. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  948. }
  949. return 1;
  950. } # }}}
  951. sub file_pruned ($$) { #{{{
  952. require File::Spec;
  953. my $file=File::Spec->canonpath(shift);
  954. my $base=File::Spec->canonpath(shift);
  955. $file =~ s#^\Q$base\E/+##;
  956. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  957. return $file =~ m/$regexp/ && $file ne $base;
  958. } #}}}
  959. sub gettext { #{{{
  960. # Only use gettext in the rare cases it's needed.
  961. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  962. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  963. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  964. if (! $gettext_obj) {
  965. $gettext_obj=eval q{
  966. use Locale::gettext q{textdomain};
  967. Locale::gettext->domain('ikiwiki')
  968. };
  969. if ($@) {
  970. print STDERR "$@";
  971. $gettext_obj=undef;
  972. return shift;
  973. }
  974. }
  975. return $gettext_obj->get(shift);
  976. }
  977. else {
  978. return shift;
  979. }
  980. } #}}}
  981. sub pagespec_merge ($$) { #{{{
  982. my $a=shift;
  983. my $b=shift;
  984. return $a if $a eq $b;
  985. # Support for old-style GlobLists.
  986. if (is_globlist($a)) {
  987. $a=globlist_to_pagespec($a);
  988. }
  989. if (is_globlist($b)) {
  990. $b=globlist_to_pagespec($b);
  991. }
  992. return "($a) or ($b)";
  993. } #}}}
  994. sub pagespec_translate ($) { #{{{
  995. # This assumes that $page is in scope in the function
  996. # that evalulates the translated pagespec code.
  997. my $spec=shift;
  998. # Support for old-style GlobLists.
  999. if (is_globlist($spec)) {
  1000. $spec=globlist_to_pagespec($spec);
  1001. }
  1002. # Convert spec to perl code.
  1003. my $code="";
  1004. while ($spec=~m{
  1005. \s* # ignore whitespace
  1006. ( # 1: match a single word
  1007. \! # !
  1008. |
  1009. \( # (
  1010. |
  1011. \) # )
  1012. |
  1013. \w+\([^\)]*\) # command(params)
  1014. |
  1015. [^\s()]+ # any other text
  1016. )
  1017. \s* # ignore whitespace
  1018. }igx) {
  1019. my $word=$1;
  1020. if (lc $word eq 'and') {
  1021. $code.=' &&';
  1022. }
  1023. elsif (lc $word eq 'or') {
  1024. $code.=' ||';
  1025. }
  1026. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1027. $code.=' '.$word;
  1028. }
  1029. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1030. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1031. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
  1032. }
  1033. else {
  1034. $code.=' 0';
  1035. }
  1036. }
  1037. else {
  1038. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
  1039. }
  1040. }
  1041. return $code;
  1042. } #}}}
  1043. sub pagespec_match ($$;@) { #{{{
  1044. my $page=shift;
  1045. my $spec=shift;
  1046. my @params=@_;
  1047. # Backwards compatability with old calling convention.
  1048. if (@params == 1) {
  1049. unshift @params, 'location';
  1050. }
  1051. my $ret=eval pagespec_translate($spec);
  1052. return IkiWiki::FailReason->new('syntax error') if $@;
  1053. return $ret;
  1054. } #}}}
  1055. package IkiWiki::FailReason;
  1056. use overload ( #{{{
  1057. '""' => sub { ${$_[0]} },
  1058. '0+' => sub { 0 },
  1059. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1060. fallback => 1,
  1061. ); #}}}
  1062. sub new { #{{{
  1063. return bless \$_[1], $_[0];
  1064. } #}}}
  1065. package IkiWiki::SuccessReason;
  1066. use overload ( #{{{
  1067. '""' => sub { ${$_[0]} },
  1068. '0+' => sub { 1 },
  1069. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1070. fallback => 1,
  1071. ); #}}}
  1072. sub new { #{{{
  1073. return bless \$_[1], $_[0];
  1074. }; #}}}
  1075. package IkiWiki::PageSpec;
  1076. sub match_glob ($$;@) { #{{{
  1077. my $page=shift;
  1078. my $glob=shift;
  1079. my %params=@_;
  1080. my $from=exists $params{location} ? $params{location} : '';
  1081. # relative matching
  1082. if ($glob =~ m!^\./!) {
  1083. $from=~s#/?[^/]+$##;
  1084. $glob=~s#^\./##;
  1085. $glob="$from/$glob" if length $from;
  1086. }
  1087. # turn glob into safe regexp
  1088. $glob=quotemeta($glob);
  1089. $glob=~s/\\\*/.*/g;
  1090. $glob=~s/\\\?/./g;
  1091. if ($page=~/^$glob$/i) {
  1092. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1093. return IkiWiki::SuccessReason->new("$glob matches $page");
  1094. }
  1095. else {
  1096. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1097. }
  1098. }
  1099. else {
  1100. return IkiWiki::FailReason->new("$glob does not match $page");
  1101. }
  1102. } #}}}
  1103. sub match_internal ($$;@) { #{{{
  1104. return match_glob($_[0], $_[1], @_, internal => 1)
  1105. } #}}}
  1106. sub match_link ($$;@) { #{{{
  1107. my $page=shift;
  1108. my $link=lc(shift);
  1109. my %params=@_;
  1110. my $from=exists $params{location} ? $params{location} : '';
  1111. # relative matching
  1112. if ($link =~ m!^\.! && defined $from) {
  1113. $from=~s#/?[^/]+$##;
  1114. $link=~s#^\./##;
  1115. $link="$from/$link" if length $from;
  1116. }
  1117. my $links = $IkiWiki::links{$page};
  1118. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1119. my $bestlink = IkiWiki::bestlink($from, $link);
  1120. foreach my $p (@{$links}) {
  1121. if (length $bestlink) {
  1122. return IkiWiki::SuccessReason->new("$page links to $link")
  1123. if $bestlink eq IkiWiki::bestlink($page, $p);
  1124. }
  1125. else {
  1126. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1127. if match_glob($p, $link, %params);
  1128. }
  1129. }
  1130. return IkiWiki::FailReason->new("$page does not link to $link");
  1131. } #}}}
  1132. sub match_backlink ($$;@) { #{{{
  1133. return match_link($_[1], $_[0], @_);
  1134. } #}}}
  1135. sub match_created_before ($$;@) { #{{{
  1136. my $page=shift;
  1137. my $testpage=shift;
  1138. if (exists $IkiWiki::pagectime{$testpage}) {
  1139. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1140. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1141. }
  1142. else {
  1143. return IkiWiki::FailReason->new("$page not created before $testpage");
  1144. }
  1145. }
  1146. else {
  1147. return IkiWiki::FailReason->new("$testpage has no ctime");
  1148. }
  1149. } #}}}
  1150. sub match_created_after ($$;@) { #{{{
  1151. my $page=shift;
  1152. my $testpage=shift;
  1153. if (exists $IkiWiki::pagectime{$testpage}) {
  1154. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1155. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1156. }
  1157. else {
  1158. return IkiWiki::FailReason->new("$page not created after $testpage");
  1159. }
  1160. }
  1161. else {
  1162. return IkiWiki::FailReason->new("$testpage has no ctime");
  1163. }
  1164. } #}}}
  1165. sub match_creation_day ($$;@) { #{{{
  1166. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1167. return IkiWiki::SuccessReason->new('creation_day matched');
  1168. }
  1169. else {
  1170. return IkiWiki::FailReason->new('creation_day did not match');
  1171. }
  1172. } #}}}
  1173. sub match_creation_month ($$;@) { #{{{
  1174. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1175. return IkiWiki::SuccessReason->new('creation_month matched');
  1176. }
  1177. else {
  1178. return IkiWiki::FailReason->new('creation_month did not match');
  1179. }
  1180. } #}}}
  1181. sub match_creation_year ($$;@) { #{{{
  1182. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1183. return IkiWiki::SuccessReason->new('creation_year matched');
  1184. }
  1185. else {
  1186. return IkiWiki::FailReason->new('creation_year did not match');
  1187. }
  1188. } #}}}
  1189. 1