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