summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 90fedca4f5dfb5614c229be58f453ea83307ea28 (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 %wikistate %renderedfiles %oldrenderedfiles
  13. %pagesources %destsources %depends %hooks %forcerebuild
  14. $gettext_obj %loaded_plugins};
  15. use Exporter q{import};
  16. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  17. bestlink htmllink readfile writefile pagetype srcfile pagename
  18. displaytime will_render gettext urlto targetpage
  19. add_underlay pagetitle titlepage linkpage newpagefile
  20. inject
  21. %config %links %pagestate %wikistate %renderedfiles
  22. %pagesources %destsources);
  23. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  24. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  25. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  26. # Optimisation.
  27. use Memoize;
  28. memoize("abs2rel");
  29. memoize("pagespec_translate");
  30. memoize("file_pruned");
  31. sub getsetup () { #{{{
  32. wikiname => {
  33. type => "string",
  34. default => "wiki",
  35. description => "name of the wiki",
  36. safe => 1,
  37. rebuild => 1,
  38. },
  39. adminemail => {
  40. type => "string",
  41. default => undef,
  42. example => 'me@example.com',
  43. description => "contact email for wiki",
  44. safe => 1,
  45. rebuild => 0,
  46. },
  47. adminuser => {
  48. type => "string",
  49. default => [],
  50. description => "users who are wiki admins",
  51. safe => 1,
  52. rebuild => 0,
  53. },
  54. banned_users => {
  55. type => "string",
  56. default => [],
  57. description => "users who are banned from the wiki",
  58. safe => 1,
  59. rebuild => 0,
  60. },
  61. srcdir => {
  62. type => "string",
  63. default => undef,
  64. example => "$ENV{HOME}/wiki",
  65. description => "where the source of the wiki is located",
  66. safe => 0, # path
  67. rebuild => 1,
  68. },
  69. destdir => {
  70. type => "string",
  71. default => undef,
  72. example => "/var/www/wiki",
  73. description => "where to build the wiki",
  74. safe => 0, # path
  75. rebuild => 1,
  76. },
  77. url => {
  78. type => "string",
  79. default => '',
  80. example => "http://example.com/wiki",
  81. description => "base url to the wiki",
  82. safe => 1,
  83. rebuild => 1,
  84. },
  85. cgiurl => {
  86. type => "string",
  87. default => '',
  88. example => "http://example.com/wiki/ikiwiki.cgi",
  89. description => "url to the ikiwiki.cgi",
  90. safe => 1,
  91. rebuild => 1,
  92. },
  93. cgi_wrapper => {
  94. type => "string",
  95. default => '',
  96. example => "/var/www/wiki/ikiwiki.cgi",
  97. description => "cgi wrapper to generate",
  98. safe => 0, # file
  99. rebuild => 0,
  100. },
  101. cgi_wrappermode => {
  102. type => "string",
  103. default => '06755',
  104. description => "mode for cgi_wrapper (can safely be made suid)",
  105. safe => 0,
  106. rebuild => 0,
  107. },
  108. rcs => {
  109. type => "string",
  110. default => '',
  111. description => "rcs backend to use",
  112. safe => 0, # don't allow overriding
  113. rebuild => 0,
  114. },
  115. default_plugins => {
  116. type => "internal",
  117. default => [qw{mdwn link inline htmlscrubber passwordauth
  118. openid signinedit lockedit conditional
  119. recentchanges parentlinks editpage}],
  120. description => "plugins to enable by default",
  121. safe => 0,
  122. rebuild => 1,
  123. },
  124. add_plugins => {
  125. type => "string",
  126. default => [],
  127. description => "plugins to add to the default configuration",
  128. safe => 1,
  129. rebuild => 1,
  130. },
  131. disable_plugins => {
  132. type => "string",
  133. default => [],
  134. description => "plugins to disable",
  135. safe => 1,
  136. rebuild => 1,
  137. },
  138. templatedir => {
  139. type => "string",
  140. default => "$installdir/share/ikiwiki/templates",
  141. description => "location of template files",
  142. advanced => 1,
  143. safe => 0, # path
  144. rebuild => 1,
  145. },
  146. underlaydir => {
  147. type => "string",
  148. default => "$installdir/share/ikiwiki/basewiki",
  149. description => "base wiki source location",
  150. advanced => 1,
  151. safe => 0, # path
  152. rebuild => 0,
  153. },
  154. wrappers => {
  155. type => "internal",
  156. default => [],
  157. description => "wrappers to generate",
  158. safe => 0,
  159. rebuild => 0,
  160. },
  161. underlaydirs => {
  162. type => "internal",
  163. default => [],
  164. description => "additional underlays to use",
  165. safe => 0,
  166. rebuild => 0,
  167. },
  168. verbose => {
  169. type => "boolean",
  170. example => 1,
  171. description => "display verbose messages when building?",
  172. safe => 1,
  173. rebuild => 0,
  174. },
  175. syslog => {
  176. type => "boolean",
  177. example => 1,
  178. description => "log to syslog?",
  179. safe => 1,
  180. rebuild => 0,
  181. },
  182. usedirs => {
  183. type => "boolean",
  184. default => 1,
  185. description => "create output files named page/index.html?",
  186. safe => 0, # changing requires manual transition
  187. rebuild => 1,
  188. },
  189. prefix_directives => {
  190. type => "boolean",
  191. default => 0,
  192. description => "use '!'-prefixed preprocessor directives?",
  193. safe => 0, # changing requires manual transition
  194. rebuild => 1,
  195. },
  196. indexpages => {
  197. type => "boolean",
  198. default => 0,
  199. description => "use page/index.mdwn source files",
  200. safe => 1,
  201. rebuild => 1,
  202. },
  203. discussion => {
  204. type => "boolean",
  205. default => 1,
  206. description => "enable Discussion pages?",
  207. safe => 1,
  208. rebuild => 1,
  209. },
  210. sslcookie => {
  211. type => "boolean",
  212. default => 0,
  213. description => "only send cookies over SSL connections?",
  214. advanced => 1,
  215. safe => 1,
  216. rebuild => 0,
  217. },
  218. default_pageext => {
  219. type => "string",
  220. default => "mdwn",
  221. description => "extension to use for new pages",
  222. safe => 0, # not sanitized
  223. rebuild => 0,
  224. },
  225. htmlext => {
  226. type => "string",
  227. default => "html",
  228. description => "extension to use for html files",
  229. safe => 0, # not sanitized
  230. rebuild => 1,
  231. },
  232. timeformat => {
  233. type => "string",
  234. default => '%c',
  235. description => "strftime format string to display date",
  236. advanced => 1,
  237. safe => 1,
  238. rebuild => 1,
  239. },
  240. locale => {
  241. type => "string",
  242. default => undef,
  243. example => "en_US.UTF-8",
  244. description => "UTF-8 locale to use",
  245. advanced => 1,
  246. safe => 0,
  247. rebuild => 1,
  248. },
  249. userdir => {
  250. type => "string",
  251. default => "",
  252. example => "users",
  253. description => "put user pages below specified page",
  254. safe => 1,
  255. rebuild => 1,
  256. },
  257. numbacklinks => {
  258. type => "integer",
  259. default => 10,
  260. description => "how many backlinks to show before hiding excess (0 to show all)",
  261. safe => 1,
  262. rebuild => 1,
  263. },
  264. hardlink => {
  265. type => "boolean",
  266. default => 0,
  267. description => "attempt to hardlink source files? (optimisation for large files)",
  268. advanced => 1,
  269. safe => 0, # paranoia
  270. rebuild => 0,
  271. },
  272. umask => {
  273. type => "integer",
  274. description => "",
  275. example => "022",
  276. description => "force ikiwiki to use a particular umask",
  277. advanced => 1,
  278. safe => 0, # paranoia
  279. rebuild => 0,
  280. },
  281. libdir => {
  282. type => "string",
  283. default => "",
  284. example => "$ENV{HOME}/.ikiwiki/",
  285. description => "extra library and plugin directory",
  286. advanced => 1,
  287. safe => 0, # directory
  288. rebuild => 0,
  289. },
  290. ENV => {
  291. type => "string",
  292. default => {},
  293. description => "environment variables",
  294. safe => 0, # paranoia
  295. rebuild => 0,
  296. },
  297. exclude => {
  298. type => "string",
  299. default => undef,
  300. example => '\.wav$',
  301. description => "regexp of source files to ignore",
  302. advanced => 1,
  303. safe => 0, # regexp
  304. rebuild => 1,
  305. },
  306. wiki_file_prune_regexps => {
  307. type => "internal",
  308. default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
  309. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  310. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  311. qr/(^|\/)_MTN\//,
  312. qr/\.dpkg-tmp$/],
  313. description => "regexps of source files to ignore",
  314. safe => 0,
  315. rebuild => 1,
  316. },
  317. wiki_file_chars => {
  318. type => "string",
  319. description => "specifies the characters that are allowed in source filenames",
  320. default => "-[:alnum:]+/.:_",
  321. safe => 0,
  322. rebuild => 1,
  323. },
  324. wiki_file_regexp => {
  325. type => "internal",
  326. description => "regexp of legal source files",
  327. safe => 0,
  328. rebuild => 1,
  329. },
  330. web_commit_regexp => {
  331. type => "internal",
  332. default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  333. description => "regexp to parse web commits from logs",
  334. safe => 0,
  335. rebuild => 0,
  336. },
  337. cgi => {
  338. type => "internal",
  339. default => 0,
  340. description => "run as a cgi",
  341. safe => 0,
  342. rebuild => 0,
  343. },
  344. cgi_disable_uploads => {
  345. type => "internal",
  346. default => 1,
  347. description => "whether CGI should accept file uploads",
  348. safe => 0,
  349. rebuild => 0,
  350. },
  351. post_commit => {
  352. type => "internal",
  353. default => 0,
  354. description => "run as a post-commit hook",
  355. safe => 0,
  356. rebuild => 0,
  357. },
  358. rebuild => {
  359. type => "internal",
  360. default => 0,
  361. description => "running in rebuild mode",
  362. safe => 0,
  363. rebuild => 0,
  364. },
  365. setup => {
  366. type => "internal",
  367. default => undef,
  368. description => "running in setup mode",
  369. safe => 0,
  370. rebuild => 0,
  371. },
  372. refresh => {
  373. type => "internal",
  374. default => 0,
  375. description => "running in refresh mode",
  376. safe => 0,
  377. rebuild => 0,
  378. },
  379. test_receive => {
  380. type => "internal",
  381. default => 0,
  382. description => "running in receive test mode",
  383. safe => 0,
  384. rebuild => 0,
  385. },
  386. getctime => {
  387. type => "internal",
  388. default => 0,
  389. description => "running in getctime mode",
  390. safe => 0,
  391. rebuild => 0,
  392. },
  393. w3mmode => {
  394. type => "internal",
  395. default => 0,
  396. description => "running in w3mmode",
  397. safe => 0,
  398. rebuild => 0,
  399. },
  400. setupfile => {
  401. type => "internal",
  402. default => undef,
  403. description => "path to setup file",
  404. safe => 0,
  405. rebuild => 0,
  406. },
  407. allow_symlinks_before_srcdir => {
  408. type => "boolean",
  409. default => 0,
  410. description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
  411. safe => 0,
  412. rebuild => 0,
  413. },
  414. } #}}}
  415. sub defaultconfig () { #{{{
  416. my %s=getsetup();
  417. my @ret;
  418. foreach my $key (keys %s) {
  419. push @ret, $key, $s{$key}->{default};
  420. }
  421. use Data::Dumper;
  422. return @ret;
  423. } #}}}
  424. sub checkconfig () { #{{{
  425. # locale stuff; avoid LC_ALL since it overrides everything
  426. if (defined $ENV{LC_ALL}) {
  427. $ENV{LANG} = $ENV{LC_ALL};
  428. delete $ENV{LC_ALL};
  429. }
  430. if (defined $config{locale}) {
  431. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  432. $ENV{LANG}=$config{locale};
  433. $gettext_obj=undef;
  434. }
  435. }
  436. if (! defined $config{wiki_file_regexp}) {
  437. $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
  438. }
  439. if (ref $config{ENV} eq 'HASH') {
  440. foreach my $val (keys %{$config{ENV}}) {
  441. $ENV{$val}=$config{ENV}{$val};
  442. }
  443. }
  444. if ($config{w3mmode}) {
  445. eval q{use Cwd q{abs_path}};
  446. error($@) if $@;
  447. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  448. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  449. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  450. unless $config{cgiurl} =~ m!file:///!;
  451. $config{url}="file://".$config{destdir};
  452. }
  453. if ($config{cgi} && ! length $config{url}) {
  454. error(gettext("Must specify url to wiki with --url when using --cgi"));
  455. }
  456. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  457. unless exists $config{wikistatedir};
  458. if (defined $config{umask}) {
  459. umask(possibly_foolish_untaint($config{umask}));
  460. }
  461. run_hooks(checkconfig => sub { shift->() });
  462. return 1;
  463. } #}}}
  464. sub listplugins () { #{{{
  465. my %ret;
  466. foreach my $dir (@INC, $config{libdir}) {
  467. next unless defined $dir && length $dir;
  468. foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
  469. my ($plugin)=$file=~/.*\/(.*)\.pm$/;
  470. $ret{$plugin}=1;
  471. }
  472. }
  473. foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
  474. next unless defined $dir && length $dir;
  475. foreach my $file (glob("$dir/plugins/*")) {
  476. $ret{basename($file)}=1 if -x $file;
  477. }
  478. }
  479. return keys %ret;
  480. } #}}}
  481. sub loadplugins () { #{{{
  482. if (defined $config{libdir} && length $config{libdir}) {
  483. unshift @INC, possibly_foolish_untaint($config{libdir});
  484. }
  485. foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
  486. loadplugin($plugin);
  487. }
  488. if ($config{rcs}) {
  489. if (exists $IkiWiki::hooks{rcs}) {
  490. error(gettext("cannot use multiple rcs plugins"));
  491. }
  492. loadplugin($config{rcs});
  493. }
  494. if (! exists $IkiWiki::hooks{rcs}) {
  495. loadplugin("norcs");
  496. }
  497. run_hooks(getopt => sub { shift->() });
  498. if (grep /^-/, @ARGV) {
  499. print STDERR "Unknown option: $_\n"
  500. foreach grep /^-/, @ARGV;
  501. usage();
  502. }
  503. return 1;
  504. } #}}}
  505. sub loadplugin ($) { #{{{
  506. my $plugin=shift;
  507. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  508. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  509. "$installdir/lib/ikiwiki") {
  510. if (defined $dir && -x "$dir/plugins/$plugin") {
  511. eval { require IkiWiki::Plugin::external };
  512. if ($@) {
  513. my $reason=$@;
  514. error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
  515. }
  516. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  517. $loaded_plugins{$plugin}=1;
  518. return 1;
  519. }
  520. }
  521. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  522. eval qq{use $mod};
  523. if ($@) {
  524. error("Failed to load plugin $mod: $@");
  525. }
  526. $loaded_plugins{$plugin}=1;
  527. return 1;
  528. } #}}}
  529. sub error ($;$) { #{{{
  530. my $message=shift;
  531. my $cleaner=shift;
  532. log_message('err' => $message) if $config{syslog};
  533. if (defined $cleaner) {
  534. $cleaner->();
  535. }
  536. die $message."\n";
  537. } #}}}
  538. sub debug ($) { #{{{
  539. return unless $config{verbose};
  540. return log_message(debug => @_);
  541. } #}}}
  542. my $log_open=0;
  543. sub log_message ($$) { #{{{
  544. my $type=shift;
  545. if ($config{syslog}) {
  546. require Sys::Syslog;
  547. if (! $log_open) {
  548. Sys::Syslog::setlogsock('unix');
  549. Sys::Syslog::openlog('ikiwiki', '', 'user');
  550. $log_open=1;
  551. }
  552. return eval {
  553. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  554. };
  555. }
  556. elsif (! $config{cgi}) {
  557. return print "@_\n";
  558. }
  559. else {
  560. return print STDERR "@_\n";
  561. }
  562. } #}}}
  563. sub possibly_foolish_untaint ($) { #{{{
  564. my $tainted=shift;
  565. my ($untainted)=$tainted=~/(.*)/s;
  566. return $untainted;
  567. } #}}}
  568. sub basename ($) { #{{{
  569. my $file=shift;
  570. $file=~s!.*/+!!;
  571. return $file;
  572. } #}}}
  573. sub dirname ($) { #{{{
  574. my $file=shift;
  575. $file=~s!/*[^/]+$!!;
  576. return $file;
  577. } #}}}
  578. sub pagetype ($) { #{{{
  579. my $page=shift;
  580. if ($page =~ /\.([^.]+)$/) {
  581. return $1 if exists $hooks{htmlize}{$1};
  582. }
  583. return;
  584. } #}}}
  585. sub isinternal ($) { #{{{
  586. my $page=shift;
  587. return exists $pagesources{$page} &&
  588. $pagesources{$page} =~ /\._([^.]+)$/;
  589. } #}}}
  590. sub pagename ($) { #{{{
  591. my $file=shift;
  592. my $type=pagetype($file);
  593. my $page=$file;
  594. $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
  595. if ($config{indexpages} && $page=~/(.*)\/index$/) {
  596. $page=$1;
  597. }
  598. return $page;
  599. } #}}}
  600. sub newpagefile ($$) { #{{{
  601. my $page=shift;
  602. my $type=shift;
  603. if (! $config{indexpages} || $page eq 'index') {
  604. return $page.".".$type;
  605. }
  606. else {
  607. return $page."/index.".$type;
  608. }
  609. } #}}}
  610. sub targetpage ($$) { #{{{
  611. my $page=shift;
  612. my $ext=shift;
  613. my $targetpage='';
  614. run_hooks(targetpage => sub {
  615. $targetpage=shift->(
  616. page => $page,
  617. ext => $ext,
  618. );
  619. });
  620. if (defined $targetpage && (length($targetpage) > 0)) {
  621. return $targetpage;
  622. }
  623. elsif (! $config{usedirs} || $page eq 'index') {
  624. return $page.".".$ext;
  625. }
  626. else {
  627. return $page."/index.".$ext;
  628. }
  629. } #}}}
  630. sub htmlpage ($) { #{{{
  631. my $page=shift;
  632. return targetpage($page, $config{htmlext});
  633. } #}}}
  634. sub srcfile_stat { #{{{
  635. my $file=shift;
  636. my $nothrow=shift;
  637. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  638. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  639. return "$dir/$file", stat(_) if -e "$dir/$file";
  640. }
  641. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  642. return;
  643. } #}}}
  644. sub srcfile ($;$) { #{{{
  645. return (srcfile_stat(@_))[0];
  646. } #}}}
  647. sub add_underlay ($) { #{{{
  648. my $dir=shift;
  649. if ($dir !~ /^\//) {
  650. $dir="$config{underlaydir}/../$dir";
  651. }
  652. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  653. unshift @{$config{underlaydirs}}, $dir;
  654. }
  655. return 1;
  656. } #}}}
  657. sub readfile ($;$$) { #{{{
  658. my $file=shift;
  659. my $binary=shift;
  660. my $wantfd=shift;
  661. if (-l $file) {
  662. error("cannot read a symlink ($file)");
  663. }
  664. local $/=undef;
  665. open (my $in, "<", $file) || error("failed to read $file: $!");
  666. binmode($in) if ($binary);
  667. return \*$in if $wantfd;
  668. my $ret=<$in>;
  669. close $in || error("failed to read $file: $!");
  670. return $ret;
  671. } #}}}
  672. sub prep_writefile ($$) { #{{{
  673. my $file=shift;
  674. my $destdir=shift;
  675. my $test=$file;
  676. while (length $test) {
  677. if (-l "$destdir/$test") {
  678. error("cannot write to a symlink ($test)");
  679. }
  680. $test=dirname($test);
  681. }
  682. my $dir=dirname("$destdir/$file");
  683. if (! -d $dir) {
  684. my $d="";
  685. foreach my $s (split(m!/+!, $dir)) {
  686. $d.="$s/";
  687. if (! -d $d) {
  688. mkdir($d) || error("failed to create directory $d: $!");
  689. }
  690. }
  691. }
  692. return 1;
  693. } #}}}
  694. sub writefile ($$$;$$) { #{{{
  695. my $file=shift; # can include subdirs
  696. my $destdir=shift; # directory to put file in
  697. my $content=shift;
  698. my $binary=shift;
  699. my $writer=shift;
  700. prep_writefile($file, $destdir);
  701. my $newfile="$destdir/$file.ikiwiki-new";
  702. if (-l $newfile) {
  703. error("cannot write to a symlink ($newfile)");
  704. }
  705. my $cleanup = sub { unlink($newfile) };
  706. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  707. binmode($out) if ($binary);
  708. if ($writer) {
  709. $writer->(\*$out, $cleanup);
  710. }
  711. else {
  712. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  713. }
  714. close $out || error("failed saving $newfile: $!", $cleanup);
  715. rename($newfile, "$destdir/$file") ||
  716. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  717. return 1;
  718. } #}}}
  719. my %cleared;
  720. sub will_render ($$;$) { #{{{
  721. my $page=shift;
  722. my $dest=shift;
  723. my $clear=shift;
  724. # Important security check.
  725. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  726. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  727. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  728. }
  729. if (! $clear || $cleared{$page}) {
  730. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  731. }
  732. else {
  733. foreach my $old (@{$renderedfiles{$page}}) {
  734. delete $destsources{$old};
  735. }
  736. $renderedfiles{$page}=[$dest];
  737. $cleared{$page}=1;
  738. }
  739. $destsources{$dest}=$page;
  740. return 1;
  741. } #}}}
  742. sub bestlink ($$) { #{{{
  743. my $page=shift;
  744. my $link=shift;
  745. my $res=undef;
  746. my $cwd=$page;
  747. if ($link=~s/^\/+//) {
  748. # absolute links
  749. $cwd="";
  750. }
  751. $link=~s/\/$//;
  752. do {
  753. my $l=$cwd;
  754. $l.="/" if length $l;
  755. $l.=$link;
  756. if (exists $links{$l}) {
  757. $res=$l;
  758. }
  759. elsif (exists $pagecase{lc $l}) {
  760. $res=$pagecase{lc $l};
  761. }
  762. } while ($cwd=~s{/?[^/]+$}{} && ! defined $res);
  763. if (! defined $res && length $config{userdir}) {
  764. my $l = "$config{userdir}/".lc($link);
  765. if (exists $links{$l}) {
  766. $res=$l;
  767. }
  768. elsif (exists $pagecase{lc $l}) {
  769. $res=$pagecase{lc $l};
  770. }
  771. }
  772. if (defined $res) {
  773. run_hooks(tweakbestlink => sub {
  774. $res=shift->(
  775. page => $page,
  776. link => $res);
  777. });
  778. return $res;
  779. }
  780. else {
  781. #print STDERR "warning: page $page, broken link: $link\n";
  782. return "";
  783. }
  784. } #}}}
  785. sub isinlinableimage ($) { #{{{
  786. my $file=shift;
  787. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  788. } #}}}
  789. sub pagetitle ($;$) { #{{{
  790. my $page=shift;
  791. my $unescaped=shift;
  792. if ($unescaped) {
  793. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  794. }
  795. else {
  796. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  797. }
  798. return $page;
  799. } #}}}
  800. sub titlepage ($) { #{{{
  801. my $title=shift;
  802. # support use w/o %config set
  803. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  804. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  805. return $title;
  806. } #}}}
  807. sub linkpage ($) { #{{{
  808. my $link=shift;
  809. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  810. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  811. return $link;
  812. } #}}}
  813. sub cgiurl (@) { #{{{
  814. my %params=@_;
  815. return $config{cgiurl}."?".
  816. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  817. } #}}}
  818. sub baseurl (;$) { #{{{
  819. my $page=shift;
  820. return "$config{url}/" if ! defined $page;
  821. $page=htmlpage($page);
  822. $page=~s/[^\/]+$//;
  823. $page=~s/[^\/]+\//..\//g;
  824. return $page;
  825. } #}}}
  826. sub abs2rel ($$) { #{{{
  827. # Work around very innefficient behavior in File::Spec if abs2rel
  828. # is passed two relative paths. It's much faster if paths are
  829. # absolute! (Debian bug #376658; fixed in debian unstable now)
  830. my $path="/".shift;
  831. my $base="/".shift;
  832. require File::Spec;
  833. my $ret=File::Spec->abs2rel($path, $base);
  834. $ret=~s/^// if defined $ret;
  835. return $ret;
  836. } #}}}
  837. sub displaytime ($;$) { #{{{
  838. # Plugins can override this function to mark up the time to
  839. # display.
  840. return '<span class="date">'.formattime(@_).'</span>';
  841. } #}}}
  842. sub formattime ($;$) { #{{{
  843. # Plugins can override this function to format the time.
  844. my $time=shift;
  845. my $format=shift;
  846. if (! defined $format) {
  847. $format=$config{timeformat};
  848. }
  849. # strftime doesn't know about encodings, so make sure
  850. # its output is properly treated as utf8
  851. return decode_utf8(POSIX::strftime($format, localtime($time)));
  852. } #}}}
  853. sub beautify_urlpath ($) { #{{{
  854. my $url=shift;
  855. if ($config{usedirs}) {
  856. $url =~ s!/index.$config{htmlext}$!/!;
  857. }
  858. run_hooks(tweakurlpath => sub {
  859. $url=shift->(url => $url);
  860. });
  861. # Ensure url is not an empty link, and
  862. # if it's relative, make that explicit to avoid colon confusion.
  863. if ($url !~ /^\//) {
  864. $url="./$url";
  865. }
  866. return $url;
  867. } #}}}
  868. sub urlto ($$;$) { #{{{
  869. my $to=shift;
  870. my $from=shift;
  871. my $absolute=shift;
  872. if (! length $to) {
  873. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  874. }
  875. if (! $destsources{$to}) {
  876. $to=htmlpage($to);
  877. }
  878. if ($absolute) {
  879. return $config{url}.beautify_urlpath("/".$to);
  880. }
  881. my $link = abs2rel($to, dirname(htmlpage($from)));
  882. return beautify_urlpath($link);
  883. } #}}}
  884. sub htmllink ($$$;@) { #{{{
  885. my $lpage=shift; # the page doing the linking
  886. my $page=shift; # the page that will contain the link (different for inline)
  887. my $link=shift;
  888. my %opts=@_;
  889. $link=~s/\/$//;
  890. my $bestlink;
  891. if (! $opts{forcesubpage}) {
  892. $bestlink=bestlink($lpage, $link);
  893. }
  894. else {
  895. $bestlink="$lpage/".lc($link);
  896. }
  897. my $linktext;
  898. if (defined $opts{linktext}) {
  899. $linktext=$opts{linktext};
  900. }
  901. else {
  902. $linktext=pagetitle(basename($link));
  903. }
  904. return "<span class=\"selflink\">$linktext</span>"
  905. if length $bestlink && $page eq $bestlink &&
  906. ! defined $opts{anchor};
  907. if (! $destsources{$bestlink}) {
  908. $bestlink=htmlpage($bestlink);
  909. if (! $destsources{$bestlink}) {
  910. return $linktext unless length $config{cgiurl};
  911. return "<span class=\"createlink\"><a href=\"".
  912. cgiurl(
  913. do => "create",
  914. page => lc($link),
  915. from => $lpage
  916. ).
  917. "\" rel=\"nofollow\">?</a>$linktext</span>"
  918. }
  919. }
  920. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  921. $bestlink=beautify_urlpath($bestlink);
  922. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  923. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  924. }
  925. if (defined $opts{anchor}) {
  926. $bestlink.="#".$opts{anchor};
  927. }
  928. my @attrs;
  929. if (defined $opts{rel}) {
  930. push @attrs, ' rel="'.$opts{rel}.'"';
  931. }
  932. if (defined $opts{class}) {
  933. push @attrs, ' class="'.$opts{class}.'"';
  934. }
  935. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  936. } #}}}
  937. sub userlink ($) { #{{{
  938. my $user=shift;
  939. my $oiduser=eval { openiduser($user) };
  940. if (defined $oiduser) {
  941. return "<a href=\"$user\">$oiduser</a>";
  942. }
  943. else {
  944. eval q{use CGI 'escapeHTML'};
  945. error($@) if $@;
  946. return htmllink("", "", escapeHTML(
  947. length $config{userdir} ? $config{userdir}."/".$user : $user
  948. ), noimageinline => 1);
  949. }
  950. } #}}}
  951. sub htmlize ($$$$) { #{{{
  952. my $page=shift;
  953. my $destpage=shift;
  954. my $type=shift;
  955. my $content=shift;
  956. my $oneline = $content !~ /\n/;
  957. if (exists $hooks{htmlize}{$type}) {
  958. $content=$hooks{htmlize}{$type}{call}->(
  959. page => $page,
  960. content => $content,
  961. );
  962. }
  963. else {
  964. error("htmlization of $type not supported");
  965. }
  966. run_hooks(sanitize => sub {
  967. $content=shift->(
  968. page => $page,
  969. destpage => $destpage,
  970. content => $content,
  971. );
  972. });
  973. if ($oneline) {
  974. # hack to get rid of enclosing junk added by markdown
  975. # and other htmlizers
  976. $content=~s/^<p>//i;
  977. $content=~s/<\/p>$//i;
  978. chomp $content;
  979. }
  980. return $content;
  981. } #}}}
  982. sub linkify ($$$) { #{{{
  983. my $page=shift;
  984. my $destpage=shift;
  985. my $content=shift;
  986. run_hooks(linkify => sub {
  987. $content=shift->(
  988. page => $page,
  989. destpage => $destpage,
  990. content => $content,
  991. );
  992. });
  993. return $content;
  994. } #}}}
  995. our %preprocessing;
  996. our $preprocess_preview=0;
  997. sub preprocess ($$$;$$) { #{{{
  998. my $page=shift; # the page the data comes from
  999. my $destpage=shift; # the page the data will appear in (different for inline)
  1000. my $content=shift;
  1001. my $scan=shift;
  1002. my $preview=shift;
  1003. # Using local because it needs to be set within any nested calls
  1004. # of this function.
  1005. local $preprocess_preview=$preview if defined $preview;
  1006. my $handle=sub {
  1007. my $escape=shift;
  1008. my $prefix=shift;
  1009. my $command=shift;
  1010. my $params=shift;
  1011. $params="" if ! defined $params;
  1012. if (length $escape) {
  1013. return "[[$prefix$command $params]]";
  1014. }
  1015. elsif (exists $hooks{preprocess}{$command}) {
  1016. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1017. # Note: preserve order of params, some plugins may
  1018. # consider it significant.
  1019. my @params;
  1020. while ($params =~ m{
  1021. (?:([-\w]+)=)? # 1: named parameter key?
  1022. (?:
  1023. """(.*?)""" # 2: triple-quoted value
  1024. |
  1025. "([^"]+)" # 3: single-quoted value
  1026. |
  1027. (\S+) # 4: unquoted value
  1028. )
  1029. (?:\s+|$) # delimiter to next param
  1030. }sgx) {
  1031. my $key=$1;
  1032. my $val;
  1033. if (defined $2) {
  1034. $val=$2;
  1035. $val=~s/\r\n/\n/mg;
  1036. $val=~s/^\n+//g;
  1037. $val=~s/\n+$//g;
  1038. }
  1039. elsif (defined $3) {
  1040. $val=$3;
  1041. }
  1042. elsif (defined $4) {
  1043. $val=$4;
  1044. }
  1045. if (defined $key) {
  1046. push @params, $key, $val;
  1047. }
  1048. else {
  1049. push @params, $val, '';
  1050. }
  1051. }
  1052. if ($preprocessing{$page}++ > 3) {
  1053. # Avoid loops of preprocessed pages preprocessing
  1054. # other pages that preprocess them, etc.
  1055. return "[[!$command <span class=\"error\">".
  1056. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1057. $page, $preprocessing{$page}).
  1058. "</span>]]";
  1059. }
  1060. my $ret;
  1061. if (! $scan) {
  1062. $ret=eval {
  1063. $hooks{preprocess}{$command}{call}->(
  1064. @params,
  1065. page => $page,
  1066. destpage => $destpage,
  1067. preview => $preprocess_preview,
  1068. );
  1069. };
  1070. if ($@) {
  1071. chomp $@;
  1072. $ret="[[!$command <span class=\"error\">".
  1073. gettext("Error").": $@"."</span>]]";
  1074. }
  1075. }
  1076. else {
  1077. # use void context during scan pass
  1078. eval {
  1079. $hooks{preprocess}{$command}{call}->(
  1080. @params,
  1081. page => $page,
  1082. destpage => $destpage,
  1083. preview => $preprocess_preview,
  1084. );
  1085. };
  1086. $ret="";
  1087. }
  1088. $preprocessing{$page}--;
  1089. return $ret;
  1090. }
  1091. else {
  1092. return "[[$prefix$command $params]]";
  1093. }
  1094. };
  1095. my $regex;
  1096. if ($config{prefix_directives}) {
  1097. $regex = qr{
  1098. (\\?) # 1: escape?
  1099. \[\[(!) # directive open; 2: prefix
  1100. ([-\w]+) # 3: command
  1101. ( # 4: the parameters..
  1102. \s+ # Must have space if parameters present
  1103. (?:
  1104. (?:[-\w]+=)? # named parameter key?
  1105. (?:
  1106. """.*?""" # triple-quoted value
  1107. |
  1108. "[^"]+" # single-quoted value
  1109. |
  1110. [^\s\]]+ # unquoted value
  1111. )
  1112. \s* # whitespace or end
  1113. # of directive
  1114. )
  1115. *)? # 0 or more parameters
  1116. \]\] # directive closed
  1117. }sx;
  1118. }
  1119. else {
  1120. $regex = qr{
  1121. (\\?) # 1: escape?
  1122. \[\[(!?) # directive open; 2: optional prefix
  1123. ([-\w]+) # 3: command
  1124. \s+
  1125. ( # 4: the parameters..
  1126. (?:
  1127. (?:[-\w]+=)? # named parameter key?
  1128. (?:
  1129. """.*?""" # triple-quoted value
  1130. |
  1131. "[^"]+" # single-quoted value
  1132. |
  1133. [^\s\]]+ # unquoted value
  1134. )
  1135. \s* # whitespace or end
  1136. # of directive
  1137. )
  1138. *) # 0 or more parameters
  1139. \]\] # directive closed
  1140. }sx;
  1141. }
  1142. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1143. return $content;
  1144. } #}}}
  1145. sub filter ($$$) { #{{{
  1146. my $page=shift;
  1147. my $destpage=shift;
  1148. my $content=shift;
  1149. run_hooks(filter => sub {
  1150. $content=shift->(page => $page, destpage => $destpage,
  1151. content => $content);
  1152. });
  1153. return $content;
  1154. } #}}}
  1155. sub indexlink () { #{{{
  1156. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1157. } #}}}
  1158. my $wikilock;
  1159. sub lockwiki (;$) { #{{{
  1160. my $wait=@_ ? shift : 1;
  1161. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1162. # run issues. The lock will be dropped on program exit.
  1163. if (! -d $config{wikistatedir}) {
  1164. mkdir($config{wikistatedir});
  1165. }
  1166. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1167. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1168. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  1169. if ($wait) {
  1170. debug("wiki seems to be locked, waiting for lock");
  1171. my $wait=600; # arbitrary, but don't hang forever to
  1172. # prevent process pileup
  1173. for (1..$wait) {
  1174. return if flock($wikilock, 2 | 4);
  1175. sleep 1;
  1176. }
  1177. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  1178. }
  1179. else {
  1180. return 0;
  1181. }
  1182. }
  1183. return 1;
  1184. } #}}}
  1185. sub unlockwiki () { #{{{
  1186. return close($wikilock) if $wikilock;
  1187. return;
  1188. } #}}}
  1189. my $commitlock;
  1190. sub commit_hook_enabled () { #{{{
  1191. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1192. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1193. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1194. close($commitlock) || error("failed closing commitlock: $!");
  1195. return 0;
  1196. }
  1197. close($commitlock) || error("failed closing commitlock: $!");
  1198. return 1;
  1199. } #}}}
  1200. sub disable_commit_hook () { #{{{
  1201. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1202. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1203. if (! flock($commitlock, 2)) { # LOCK_EX
  1204. error("failed to get commit lock");
  1205. }
  1206. return 1;
  1207. } #}}}
  1208. sub enable_commit_hook () { #{{{
  1209. return close($commitlock) if $commitlock;
  1210. return;
  1211. } #}}}
  1212. sub loadindex () { #{{{
  1213. %oldrenderedfiles=%pagectime=();
  1214. if (! $config{rebuild}) {
  1215. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1216. %destsources=%renderedfiles=%pagecase=%pagestate=();
  1217. }
  1218. my $in;
  1219. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1220. if (-e "$config{wikistatedir}/index") {
  1221. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1222. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1223. }
  1224. else {
  1225. return;
  1226. }
  1227. }
  1228. my $index=Storable::fd_retrieve($in);
  1229. if (! defined $index) {
  1230. return 0;
  1231. }
  1232. my $pages;
  1233. if (exists $index->{version} && ! ref $index->{version}) {
  1234. $pages=$index->{page};
  1235. %wikistate=%{$index->{state}};
  1236. }
  1237. else {
  1238. $pages=$index;
  1239. %wikistate=();
  1240. }
  1241. foreach my $src (keys %$pages) {
  1242. my $d=$pages->{$src};
  1243. my $page=pagename($src);
  1244. $pagectime{$page}=$d->{ctime};
  1245. if (! $config{rebuild}) {
  1246. $pagesources{$page}=$src;
  1247. $pagemtime{$page}=$d->{mtime};
  1248. $renderedfiles{$page}=$d->{dest};
  1249. if (exists $d->{links} && ref $d->{links}) {
  1250. $links{$page}=$d->{links};
  1251. $oldlinks{$page}=[@{$d->{links}}];
  1252. }
  1253. if (exists $d->{depends}) {
  1254. $depends{$page}=$d->{depends};
  1255. }
  1256. if (exists $d->{state}) {
  1257. $pagestate{$page}=$d->{state};
  1258. }
  1259. }
  1260. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1261. }
  1262. foreach my $page (keys %pagesources) {
  1263. $pagecase{lc $page}=$page;
  1264. }
  1265. foreach my $page (keys %renderedfiles) {
  1266. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1267. }
  1268. return close($in);
  1269. } #}}}
  1270. sub saveindex () { #{{{
  1271. run_hooks(savestate => sub { shift->() });
  1272. my %hookids;
  1273. foreach my $type (keys %hooks) {
  1274. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1275. }
  1276. my @hookids=keys %hookids;
  1277. if (! -d $config{wikistatedir}) {
  1278. mkdir($config{wikistatedir});
  1279. }
  1280. my $newfile="$config{wikistatedir}/indexdb.new";
  1281. my $cleanup = sub { unlink($newfile) };
  1282. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1283. my %index;
  1284. foreach my $page (keys %pagemtime) {
  1285. next unless $pagemtime{$page};
  1286. my $src=$pagesources{$page};
  1287. $index{page}{$src}={
  1288. ctime => $pagectime{$page},
  1289. mtime => $pagemtime{$page},
  1290. dest => $renderedfiles{$page},
  1291. links => $links{$page},
  1292. };
  1293. if (exists $depends{$page}) {
  1294. $index{page}{$src}{depends} = $depends{$page};
  1295. }
  1296. if (exists $pagestate{$page}) {
  1297. foreach my $id (@hookids) {
  1298. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1299. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1300. }
  1301. }
  1302. }
  1303. }
  1304. $index{state}={};
  1305. foreach my $id (@hookids) {
  1306. foreach my $key (keys %{$wikistate{$id}}) {
  1307. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1308. }
  1309. }
  1310. $index{version}="3";
  1311. my $ret=Storable::nstore_fd(\%index, $out);
  1312. return if ! defined $ret || ! $ret;
  1313. close $out || error("failed saving to $newfile: $!", $cleanup);
  1314. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1315. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1316. return 1;
  1317. } #}}}
  1318. sub template_file ($) { #{{{
  1319. my $template=shift;
  1320. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1321. return "$dir/$template" if -e "$dir/$template";
  1322. }
  1323. return;
  1324. } #}}}
  1325. sub template_params (@) { #{{{
  1326. my $filename=template_file(shift);
  1327. if (! defined $filename) {
  1328. return if wantarray;
  1329. return "";
  1330. }
  1331. my @ret=(
  1332. filter => sub {
  1333. my $text_ref = shift;
  1334. ${$text_ref} = decode_utf8(${$text_ref});
  1335. },
  1336. filename => $filename,
  1337. loop_context_vars => 1,
  1338. die_on_bad_params => 0,
  1339. @_
  1340. );
  1341. return wantarray ? @ret : {@ret};
  1342. } #}}}
  1343. sub template ($;@) { #{{{
  1344. require HTML::Template;
  1345. return HTML::Template->new(template_params(@_));
  1346. } #}}}
  1347. sub misctemplate ($$;@) { #{{{
  1348. my $title=shift;
  1349. my $pagebody=shift;
  1350. my $template=template("misc.tmpl");
  1351. $template->param(
  1352. title => $title,
  1353. indexlink => indexlink(),
  1354. wikiname => $config{wikiname},
  1355. pagebody => $pagebody,
  1356. baseurl => baseurl(),
  1357. @_,
  1358. );
  1359. run_hooks(pagetemplate => sub {
  1360. shift->(page => "", destpage => "", template => $template);
  1361. });
  1362. return $template->output;
  1363. }#}}}
  1364. sub hook (@) { # {{{
  1365. my %param=@_;
  1366. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1367. error 'hook requires type, call, and id parameters';
  1368. }
  1369. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1370. $hooks{$param{type}}{$param{id}}=\%param;
  1371. return 1;
  1372. } # }}}
  1373. sub run_hooks ($$) { # {{{
  1374. # Calls the given sub for each hook of the given type,
  1375. # passing it the hook function to call.
  1376. my $type=shift;
  1377. my $sub=shift;
  1378. if (exists $hooks{$type}) {
  1379. my @deferred;
  1380. foreach my $id (keys %{$hooks{$type}}) {
  1381. if ($hooks{$type}{$id}{last}) {
  1382. push @deferred, $id;
  1383. next;
  1384. }
  1385. $sub->($hooks{$type}{$id}{call});
  1386. }
  1387. foreach my $id (@deferred) {
  1388. $sub->($hooks{$type}{$id}{call});
  1389. }
  1390. }
  1391. return 1;
  1392. } #}}}
  1393. sub rcs_update () { #{{{
  1394. $hooks{rcs}{rcs_update}{call}->(@_);
  1395. } #}}}
  1396. sub rcs_prepedit ($) { #{{{
  1397. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1398. } #}}}
  1399. sub rcs_commit ($$$;$$) { #{{{
  1400. $hooks{rcs}{rcs_commit}{call}->(@_);
  1401. } #}}}
  1402. sub rcs_commit_staged ($$$) { #{{{
  1403. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1404. } #}}}
  1405. sub rcs_add ($) { #{{{
  1406. $hooks{rcs}{rcs_add}{call}->(@_);
  1407. } #}}}
  1408. sub rcs_remove ($) { #{{{
  1409. $hooks{rcs}{rcs_remove}{call}->(@_);
  1410. } #}}}
  1411. sub rcs_rename ($$) { #{{{
  1412. $hooks{rcs}{rcs_rename}{call}->(@_);
  1413. } #}}}
  1414. sub rcs_recentchanges ($) { #{{{
  1415. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1416. } #}}}
  1417. sub rcs_diff ($) { #{{{
  1418. $hooks{rcs}{rcs_diff}{call}->(@_);
  1419. } #}}}
  1420. sub rcs_getctime ($) { #{{{
  1421. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1422. } #}}}
  1423. sub rcs_receive () { #{{{
  1424. $hooks{rcs}{rcs_receive}{call}->();
  1425. } #}}}
  1426. sub globlist_to_pagespec ($) { #{{{
  1427. my @globlist=split(' ', shift);
  1428. my (@spec, @skip);
  1429. foreach my $glob (@globlist) {
  1430. if ($glob=~/^!(.*)/) {
  1431. push @skip, $glob;
  1432. }
  1433. else {
  1434. push @spec, $glob;
  1435. }
  1436. }
  1437. my $spec=join(' or ', @spec);
  1438. if (@skip) {
  1439. my $skip=join(' and ', @skip);
  1440. if (length $spec) {
  1441. $spec="$skip and ($spec)";
  1442. }
  1443. else {
  1444. $spec=$skip;
  1445. }
  1446. }
  1447. return $spec;
  1448. } #}}}
  1449. sub is_globlist ($) { #{{{
  1450. my $s=shift;
  1451. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  1452. } #}}}
  1453. sub safequote ($) { #{{{
  1454. my $s=shift;
  1455. $s=~s/[{}]//g;
  1456. return "q{$s}";
  1457. } #}}}
  1458. sub add_depends ($$) { #{{{
  1459. my $page=shift;
  1460. my $pagespec=shift;
  1461. return unless pagespec_valid($pagespec);
  1462. if (! exists $depends{$page}) {
  1463. $depends{$page}=$pagespec;
  1464. }
  1465. else {
  1466. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1467. }
  1468. return 1;
  1469. } # }}}
  1470. sub file_pruned ($$) { #{{{
  1471. require File::Spec;
  1472. my $file=File::Spec->canonpath(shift);
  1473. my $base=File::Spec->canonpath(shift);
  1474. $file =~ s#^\Q$base\E/+##;
  1475. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1476. return $file =~ m/$regexp/ && $file ne $base;
  1477. } #}}}
  1478. sub gettext { #{{{
  1479. # Only use gettext in the rare cases it's needed.
  1480. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1481. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1482. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1483. if (! $gettext_obj) {
  1484. $gettext_obj=eval q{
  1485. use Locale::gettext q{textdomain};
  1486. Locale::gettext->domain('ikiwiki')
  1487. };
  1488. if ($@) {
  1489. print STDERR "$@";
  1490. $gettext_obj=undef;
  1491. return shift;
  1492. }
  1493. }
  1494. return $gettext_obj->get(shift);
  1495. }
  1496. else {
  1497. return shift;
  1498. }
  1499. } #}}}
  1500. sub yesno ($) { #{{{
  1501. my $val=shift;
  1502. return (defined $val && lc($val) eq gettext("yes"));
  1503. } #}}}
  1504. sub inject { #{{{
  1505. # Injects a new function into the symbol table to replace an
  1506. # exported function.
  1507. my %params=@_;
  1508. # This is deep ugly perl foo, beware.
  1509. no strict;
  1510. no warnings;
  1511. if (! defined $params{parent}) {
  1512. $params{parent}='::';
  1513. $params{old}=\&{$params{name}};
  1514. $params{name}=~s/.*:://;
  1515. }
  1516. my $parent=$params{parent};
  1517. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1518. $ns = $params{parent} . $ns;
  1519. inject(%params, parent => $ns) unless $ns eq '::main::';
  1520. *{$ns . $params{name}} = $params{call}
  1521. if exists ${$ns}{$params{name}} &&
  1522. \&{${$ns}{$params{name}}} == $params{old};
  1523. }
  1524. use strict;
  1525. use warnings;
  1526. } #}}}
  1527. sub pagespec_merge ($$) { #{{{
  1528. my $a=shift;
  1529. my $b=shift;
  1530. return $a if $a eq $b;
  1531. # Support for old-style GlobLists.
  1532. if (is_globlist($a)) {
  1533. $a=globlist_to_pagespec($a);
  1534. }
  1535. if (is_globlist($b)) {
  1536. $b=globlist_to_pagespec($b);
  1537. }
  1538. return "($a) or ($b)";
  1539. } #}}}
  1540. sub pagespec_translate ($) { #{{{
  1541. my $spec=shift;
  1542. # Support for old-style GlobLists.
  1543. if (is_globlist($spec)) {
  1544. $spec=globlist_to_pagespec($spec);
  1545. }
  1546. # Convert spec to perl code.
  1547. my $code="";
  1548. while ($spec=~m{
  1549. \s* # ignore whitespace
  1550. ( # 1: match a single word
  1551. \! # !
  1552. |
  1553. \( # (
  1554. |
  1555. \) # )
  1556. |
  1557. \w+\([^\)]*\) # command(params)
  1558. |
  1559. [^\s()]+ # any other text
  1560. )
  1561. \s* # ignore whitespace
  1562. }igx) {
  1563. my $word=$1;
  1564. if (lc $word eq 'and') {
  1565. $code.=' &&';
  1566. }
  1567. elsif (lc $word eq 'or') {
  1568. $code.=' ||';
  1569. }
  1570. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1571. $code.=' '.$word;
  1572. }
  1573. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1574. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1575. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1576. }
  1577. else {
  1578. $code.=' 0';
  1579. }
  1580. }
  1581. else {
  1582. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1583. }
  1584. }
  1585. if (! length $code) {
  1586. $code=0;
  1587. }
  1588. no warnings;
  1589. return eval 'sub { my $page=shift; '.$code.' }';
  1590. } #}}}
  1591. sub pagespec_match ($$;@) { #{{{
  1592. my $page=shift;
  1593. my $spec=shift;
  1594. my @params=@_;
  1595. # Backwards compatability with old calling convention.
  1596. if (@params == 1) {
  1597. unshift @params, 'location';
  1598. }
  1599. my $sub=pagespec_translate($spec);
  1600. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1601. return $sub->($page, @params);
  1602. } #}}}
  1603. sub pagespec_valid ($) { #{{{
  1604. my $spec=shift;
  1605. my $sub=pagespec_translate($spec);
  1606. return ! $@;
  1607. } #}}}
  1608. sub glob2re ($) { #{{{
  1609. my $re=quotemeta(shift);
  1610. $re=~s/\\\*/.*/g;
  1611. $re=~s/\\\?/./g;
  1612. return $re;
  1613. } #}}}
  1614. package IkiWiki::FailReason;
  1615. use overload ( #{{{
  1616. '""' => sub { ${$_[0]} },
  1617. '0+' => sub { 0 },
  1618. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1619. fallback => 1,
  1620. ); #}}}
  1621. sub new { #{{{
  1622. my $class = shift;
  1623. my $value = shift;
  1624. return bless \$value, $class;
  1625. } #}}}
  1626. package IkiWiki::SuccessReason;
  1627. use overload ( #{{{
  1628. '""' => sub { ${$_[0]} },
  1629. '0+' => sub { 1 },
  1630. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1631. fallback => 1,
  1632. ); #}}}
  1633. sub new { #{{{
  1634. my $class = shift;
  1635. my $value = shift;
  1636. return bless \$value, $class;
  1637. }; #}}}
  1638. package IkiWiki::PageSpec;
  1639. sub match_glob ($$;@) { #{{{
  1640. my $page=shift;
  1641. my $glob=shift;
  1642. my %params=@_;
  1643. my $from=exists $params{location} ? $params{location} : '';
  1644. # relative matching
  1645. if ($glob =~ m!^\./!) {
  1646. $from=~s#/?[^/]+$##;
  1647. $glob=~s#^\./##;
  1648. $glob="$from/$glob" if length $from;
  1649. }
  1650. my $regexp=IkiWiki::glob2re($glob);
  1651. if ($page=~/^$regexp$/i) {
  1652. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1653. return IkiWiki::SuccessReason->new("$glob matches $page");
  1654. }
  1655. else {
  1656. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1657. }
  1658. }
  1659. else {
  1660. return IkiWiki::FailReason->new("$glob does not match $page");
  1661. }
  1662. } #}}}
  1663. sub match_internal ($$;@) { #{{{
  1664. return match_glob($_[0], $_[1], @_, internal => 1)
  1665. } #}}}
  1666. sub match_link ($$;@) { #{{{
  1667. my $page=shift;
  1668. my $link=lc(shift);
  1669. my %params=@_;
  1670. my $from=exists $params{location} ? $params{location} : '';
  1671. # relative matching
  1672. if ($link =~ m!^\.! && defined $from) {
  1673. $from=~s#/?[^/]+$##;
  1674. $link=~s#^\./##;
  1675. $link="$from/$link" if length $from;
  1676. }
  1677. my $links = $IkiWiki::links{$page};
  1678. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1679. my $bestlink = IkiWiki::bestlink($from, $link);
  1680. foreach my $p (@{$links}) {
  1681. if (length $bestlink) {
  1682. return IkiWiki::SuccessReason->new("$page links to $link")
  1683. if $bestlink eq IkiWiki::bestlink($page, $p);
  1684. }
  1685. else {
  1686. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1687. if match_glob($p, $link, %params);
  1688. }
  1689. }
  1690. return IkiWiki::FailReason->new("$page does not link to $link");
  1691. } #}}}
  1692. sub match_backlink ($$;@) { #{{{
  1693. return match_link($_[1], $_[0], @_);
  1694. } #}}}
  1695. sub match_created_before ($$;@) { #{{{
  1696. my $page=shift;
  1697. my $testpage=shift;
  1698. if (exists $IkiWiki::pagectime{$testpage}) {
  1699. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1700. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1701. }
  1702. else {
  1703. return IkiWiki::FailReason->new("$page not created before $testpage");
  1704. }
  1705. }
  1706. else {
  1707. return IkiWiki::FailReason->new("$testpage has no ctime");
  1708. }
  1709. } #}}}
  1710. sub match_created_after ($$;@) { #{{{
  1711. my $page=shift;
  1712. my $testpage=shift;
  1713. if (exists $IkiWiki::pagectime{$testpage}) {
  1714. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1715. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1716. }
  1717. else {
  1718. return IkiWiki::FailReason->new("$page not created after $testpage");
  1719. }
  1720. }
  1721. else {
  1722. return IkiWiki::FailReason->new("$testpage has no ctime");
  1723. }
  1724. } #}}}
  1725. sub match_creation_day ($$;@) { #{{{
  1726. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1727. return IkiWiki::SuccessReason->new('creation_day matched');
  1728. }
  1729. else {
  1730. return IkiWiki::FailReason->new('creation_day did not match');
  1731. }
  1732. } #}}}
  1733. sub match_creation_month ($$;@) { #{{{
  1734. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1735. return IkiWiki::SuccessReason->new('creation_month matched');
  1736. }
  1737. else {
  1738. return IkiWiki::FailReason->new('creation_month did not match');
  1739. }
  1740. } #}}}
  1741. sub match_creation_year ($$;@) { #{{{
  1742. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1743. return IkiWiki::SuccessReason->new('creation_year matched');
  1744. }
  1745. else {
  1746. return IkiWiki::FailReason->new('creation_year did not match');
  1747. }
  1748. } #}}}
  1749. sub match_user ($$;@) { #{{{
  1750. shift;
  1751. my $user=shift;
  1752. my %params=@_;
  1753. if (! exists $params{user}) {
  1754. return IkiWiki::FailReason->new("no user specified");
  1755. }
  1756. if (defined $params{user} && lc $params{user} eq lc $user) {
  1757. return IkiWiki::SuccessReason->new("user is $user");
  1758. }
  1759. elsif (! defined $params{user}) {
  1760. return IkiWiki::FailReason->new("not logged in");
  1761. }
  1762. else {
  1763. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1764. }
  1765. } #}}}
  1766. sub match_admin ($$;@) { #{{{
  1767. shift;
  1768. shift;
  1769. my %params=@_;
  1770. if (! exists $params{user}) {
  1771. return IkiWiki::FailReason->new("no user specified");
  1772. }
  1773. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1774. return IkiWiki::SuccessReason->new("user is an admin");
  1775. }
  1776. elsif (! defined $params{user}) {
  1777. return IkiWiki::FailReason->new("not logged in");
  1778. }
  1779. else {
  1780. return IkiWiki::FailReason->new("user is not an admin");
  1781. }
  1782. } #}}}
  1783. sub match_ip ($$;@) { #{{{
  1784. shift;
  1785. my $ip=shift;
  1786. my %params=@_;
  1787. if (! exists $params{ip}) {
  1788. return IkiWiki::FailReason->new("no IP specified");
  1789. }
  1790. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1791. return IkiWiki::SuccessReason->new("IP is $ip");
  1792. }
  1793. else {
  1794. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1795. }
  1796. } #}}}
  1797. 1