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