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