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