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