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