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