summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 3430c57420df18fc02ea6bca88229534d5b59d15 (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. return $config{cgiurl}."?".
  855. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  856. }
  857. sub baseurl (;$) {
  858. my $page=shift;
  859. return "$config{url}/" if ! defined $page;
  860. $page=htmlpage($page);
  861. $page=~s/[^\/]+$//;
  862. $page=~s/[^\/]+\//..\//g;
  863. return $page;
  864. }
  865. sub abs2rel ($$) {
  866. # Work around very innefficient behavior in File::Spec if abs2rel
  867. # is passed two relative paths. It's much faster if paths are
  868. # absolute! (Debian bug #376658; fixed in debian unstable now)
  869. my $path="/".shift;
  870. my $base="/".shift;
  871. require File::Spec;
  872. my $ret=File::Spec->abs2rel($path, $base);
  873. $ret=~s/^// if defined $ret;
  874. return $ret;
  875. }
  876. sub displaytime ($;$) {
  877. # Plugins can override this function to mark up the time to
  878. # display.
  879. return '<span class="date">'.formattime(@_).'</span>';
  880. }
  881. sub formattime ($;$) {
  882. # Plugins can override this function to format the time.
  883. my $time=shift;
  884. my $format=shift;
  885. if (! defined $format) {
  886. $format=$config{timeformat};
  887. }
  888. # strftime doesn't know about encodings, so make sure
  889. # its output is properly treated as utf8
  890. return decode_utf8(POSIX::strftime($format, localtime($time)));
  891. }
  892. sub beautify_urlpath ($) {
  893. my $url=shift;
  894. # Ensure url is not an empty link, and if necessary,
  895. # add ./ to avoid colon confusion.
  896. if ($url !~ /^\// && $url !~ /^\.\.?\//) {
  897. $url="./$url";
  898. }
  899. if ($config{usedirs}) {
  900. $url =~ s!/index.$config{htmlext}$!/!;
  901. }
  902. return $url;
  903. }
  904. sub urlto ($$;$) {
  905. my $to=shift;
  906. my $from=shift;
  907. my $absolute=shift;
  908. if (! length $to) {
  909. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  910. }
  911. if (! $destsources{$to}) {
  912. $to=htmlpage($to);
  913. }
  914. if ($absolute) {
  915. return $config{url}.beautify_urlpath("/".$to);
  916. }
  917. my $link = abs2rel($to, dirname(htmlpage($from)));
  918. return beautify_urlpath($link);
  919. }
  920. sub htmllink ($$$;@) {
  921. my $lpage=shift; # the page doing the linking
  922. my $page=shift; # the page that will contain the link (different for inline)
  923. my $link=shift;
  924. my %opts=@_;
  925. $link=~s/\/$//;
  926. my $bestlink;
  927. if (! $opts{forcesubpage}) {
  928. $bestlink=bestlink($lpage, $link);
  929. }
  930. else {
  931. $bestlink="$lpage/".lc($link);
  932. }
  933. my $linktext;
  934. if (defined $opts{linktext}) {
  935. $linktext=$opts{linktext};
  936. }
  937. else {
  938. $linktext=pagetitle(basename($link));
  939. }
  940. return "<span class=\"selflink\">$linktext</span>"
  941. if length $bestlink && $page eq $bestlink &&
  942. ! defined $opts{anchor};
  943. if (! $destsources{$bestlink}) {
  944. $bestlink=htmlpage($bestlink);
  945. if (! $destsources{$bestlink}) {
  946. return $linktext unless length $config{cgiurl};
  947. return "<span class=\"createlink\"><a href=\"".
  948. cgiurl(
  949. do => "create",
  950. page => lc($link),
  951. from => $lpage
  952. ).
  953. "\" rel=\"nofollow\">?</a>$linktext</span>"
  954. }
  955. }
  956. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  957. $bestlink=beautify_urlpath($bestlink);
  958. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  959. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  960. }
  961. if (defined $opts{anchor}) {
  962. $bestlink.="#".$opts{anchor};
  963. }
  964. my @attrs;
  965. foreach my $attr (qw{rel class title}) {
  966. if (defined $opts{$attr}) {
  967. push @attrs, " $attr=\"$opts{$attr}\"";
  968. }
  969. }
  970. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  971. }
  972. sub openiduser ($) {
  973. my $user=shift;
  974. if ($user =~ m!^https?://! &&
  975. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  976. my $display;
  977. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  978. # this works in at least 2.x
  979. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  980. }
  981. else {
  982. # this only works in 1.x
  983. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  984. $display=$oid->display;
  985. }
  986. # Convert "user.somehost.com" to "user [somehost.com]"
  987. # (also "user.somehost.co.uk")
  988. if ($display !~ /\[/) {
  989. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  990. }
  991. # Convert "http://somehost.com/user" to "user [somehost.com]".
  992. # (also "https://somehost.com/user/")
  993. if ($display !~ /\[/) {
  994. $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
  995. }
  996. $display=~s!^https?://!!; # make sure this is removed
  997. eval q{use CGI 'escapeHTML'};
  998. error($@) if $@;
  999. return escapeHTML($display);
  1000. }
  1001. return;
  1002. }
  1003. sub userlink ($) {
  1004. my $user=shift;
  1005. my $oiduser=eval { openiduser($user) };
  1006. if (defined $oiduser) {
  1007. return "<a href=\"$user\">$oiduser</a>";
  1008. }
  1009. else {
  1010. eval q{use CGI 'escapeHTML'};
  1011. error($@) if $@;
  1012. return htmllink("", "", escapeHTML(
  1013. length $config{userdir} ? $config{userdir}."/".$user : $user
  1014. ), noimageinline => 1);
  1015. }
  1016. }
  1017. sub htmlize ($$$$) {
  1018. my $page=shift;
  1019. my $destpage=shift;
  1020. my $type=shift;
  1021. my $content=shift;
  1022. my $oneline = $content !~ /\n/;
  1023. if (exists $hooks{htmlize}{$type}) {
  1024. $content=$hooks{htmlize}{$type}{call}->(
  1025. page => $page,
  1026. content => $content,
  1027. );
  1028. }
  1029. else {
  1030. error("htmlization of $type not supported");
  1031. }
  1032. run_hooks(sanitize => sub {
  1033. $content=shift->(
  1034. page => $page,
  1035. destpage => $destpage,
  1036. content => $content,
  1037. );
  1038. });
  1039. if ($oneline) {
  1040. # hack to get rid of enclosing junk added by markdown
  1041. # and other htmlizers
  1042. $content=~s/^<p>//i;
  1043. $content=~s/<\/p>$//i;
  1044. chomp $content;
  1045. }
  1046. return $content;
  1047. }
  1048. sub linkify ($$$) {
  1049. my $page=shift;
  1050. my $destpage=shift;
  1051. my $content=shift;
  1052. run_hooks(linkify => sub {
  1053. $content=shift->(
  1054. page => $page,
  1055. destpage => $destpage,
  1056. content => $content,
  1057. );
  1058. });
  1059. return $content;
  1060. }
  1061. our %preprocessing;
  1062. our $preprocess_preview=0;
  1063. sub preprocess ($$$;$$) {
  1064. my $page=shift; # the page the data comes from
  1065. my $destpage=shift; # the page the data will appear in (different for inline)
  1066. my $content=shift;
  1067. my $scan=shift;
  1068. my $preview=shift;
  1069. # Using local because it needs to be set within any nested calls
  1070. # of this function.
  1071. local $preprocess_preview=$preview if defined $preview;
  1072. my $handle=sub {
  1073. my $escape=shift;
  1074. my $prefix=shift;
  1075. my $command=shift;
  1076. my $params=shift;
  1077. $params="" if ! defined $params;
  1078. if (length $escape) {
  1079. return "[[$prefix$command $params]]";
  1080. }
  1081. elsif (exists $hooks{preprocess}{$command}) {
  1082. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1083. # Note: preserve order of params, some plugins may
  1084. # consider it significant.
  1085. my @params;
  1086. while ($params =~ m{
  1087. (?:([-\w]+)=)? # 1: named parameter key?
  1088. (?:
  1089. """(.*?)""" # 2: triple-quoted value
  1090. |
  1091. "([^"]+)" # 3: single-quoted value
  1092. |
  1093. (\S+) # 4: unquoted value
  1094. )
  1095. (?:\s+|$) # delimiter to next param
  1096. }sgx) {
  1097. my $key=$1;
  1098. my $val;
  1099. if (defined $2) {
  1100. $val=$2;
  1101. $val=~s/\r\n/\n/mg;
  1102. $val=~s/^\n+//g;
  1103. $val=~s/\n+$//g;
  1104. }
  1105. elsif (defined $3) {
  1106. $val=$3;
  1107. }
  1108. elsif (defined $4) {
  1109. $val=$4;
  1110. }
  1111. if (defined $key) {
  1112. push @params, $key, $val;
  1113. }
  1114. else {
  1115. push @params, $val, '';
  1116. }
  1117. }
  1118. if ($preprocessing{$page}++ > 3) {
  1119. # Avoid loops of preprocessed pages preprocessing
  1120. # other pages that preprocess them, etc.
  1121. return "[[!$command <span class=\"error\">".
  1122. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1123. $page, $preprocessing{$page}).
  1124. "</span>]]";
  1125. }
  1126. my $ret;
  1127. if (! $scan) {
  1128. $ret=eval {
  1129. $hooks{preprocess}{$command}{call}->(
  1130. @params,
  1131. page => $page,
  1132. destpage => $destpage,
  1133. preview => $preprocess_preview,
  1134. );
  1135. };
  1136. if ($@) {
  1137. my $error=$@;
  1138. chomp $error;
  1139. $ret="[[!$command <span class=\"error\">".
  1140. gettext("Error").": $error"."</span>]]";
  1141. }
  1142. }
  1143. else {
  1144. # use void context during scan pass
  1145. eval {
  1146. $hooks{preprocess}{$command}{call}->(
  1147. @params,
  1148. page => $page,
  1149. destpage => $destpage,
  1150. preview => $preprocess_preview,
  1151. );
  1152. };
  1153. $ret="";
  1154. }
  1155. $preprocessing{$page}--;
  1156. return $ret;
  1157. }
  1158. else {
  1159. return "[[$prefix$command $params]]";
  1160. }
  1161. };
  1162. my $regex;
  1163. if ($config{prefix_directives}) {
  1164. $regex = qr{
  1165. (\\?) # 1: escape?
  1166. \[\[(!) # directive open; 2: prefix
  1167. ([-\w]+) # 3: command
  1168. ( # 4: the parameters..
  1169. \s+ # Must have space if parameters present
  1170. (?:
  1171. (?:[-\w]+=)? # named parameter key?
  1172. (?:
  1173. """.*?""" # triple-quoted value
  1174. |
  1175. "[^"]+" # single-quoted value
  1176. |
  1177. [^"\s\]]+ # unquoted value
  1178. )
  1179. \s* # whitespace or end
  1180. # of directive
  1181. )
  1182. *)? # 0 or more parameters
  1183. \]\] # directive closed
  1184. }sx;
  1185. }
  1186. else {
  1187. $regex = qr{
  1188. (\\?) # 1: escape?
  1189. \[\[(!?) # directive open; 2: optional prefix
  1190. ([-\w]+) # 3: command
  1191. \s+
  1192. ( # 4: the parameters..
  1193. (?:
  1194. (?:[-\w]+=)? # named parameter key?
  1195. (?:
  1196. """.*?""" # triple-quoted value
  1197. |
  1198. "[^"]+" # single-quoted value
  1199. |
  1200. [^"\s\]]+ # unquoted value
  1201. )
  1202. \s* # whitespace or end
  1203. # of directive
  1204. )
  1205. *) # 0 or more parameters
  1206. \]\] # directive closed
  1207. }sx;
  1208. }
  1209. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1210. return $content;
  1211. }
  1212. sub filter ($$$) {
  1213. my $page=shift;
  1214. my $destpage=shift;
  1215. my $content=shift;
  1216. run_hooks(filter => sub {
  1217. $content=shift->(page => $page, destpage => $destpage,
  1218. content => $content);
  1219. });
  1220. return $content;
  1221. }
  1222. sub indexlink () {
  1223. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1224. }
  1225. sub check_canedit ($$$;$) {
  1226. my $page=shift;
  1227. my $q=shift;
  1228. my $session=shift;
  1229. my $nonfatal=shift;
  1230. my $canedit;
  1231. run_hooks(canedit => sub {
  1232. return if defined $canedit;
  1233. my $ret=shift->($page, $q, $session);
  1234. if (defined $ret) {
  1235. if ($ret eq "") {
  1236. $canedit=1;
  1237. }
  1238. elsif (ref $ret eq 'CODE') {
  1239. $ret->() unless $nonfatal;
  1240. $canedit=0;
  1241. }
  1242. elsif (defined $ret) {
  1243. error($ret) unless $nonfatal;
  1244. $canedit=0;
  1245. }
  1246. }
  1247. });
  1248. return defined $canedit ? $canedit : 1;
  1249. }
  1250. sub check_content (@) {
  1251. my %params=@_;
  1252. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1253. if (exists $pagesources{$params{page}}) {
  1254. my @diff;
  1255. my %old=map { $_ => 1 }
  1256. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1257. foreach my $line (split("\n", $params{content})) {
  1258. push @diff, $line if ! exists $old{$_};
  1259. }
  1260. $params{diff}=join("\n", @diff);
  1261. }
  1262. my $ok;
  1263. run_hooks(checkcontent => sub {
  1264. return if defined $ok;
  1265. my $ret=shift->(%params);
  1266. if (defined $ret) {
  1267. if ($ret eq "") {
  1268. $ok=1;
  1269. }
  1270. elsif (ref $ret eq 'CODE') {
  1271. $ret->() unless $params{nonfatal};
  1272. $ok=0;
  1273. }
  1274. elsif (defined $ret) {
  1275. error($ret) unless $params{nonfatal};
  1276. $ok=0;
  1277. }
  1278. }
  1279. });
  1280. return defined $ok ? $ok : 1;
  1281. }
  1282. my $wikilock;
  1283. sub lockwiki () {
  1284. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1285. # run issues. The lock will be dropped on program exit.
  1286. if (! -d $config{wikistatedir}) {
  1287. mkdir($config{wikistatedir});
  1288. }
  1289. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1290. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1291. if (! flock($wikilock, 2)) { # LOCK_EX
  1292. error("failed to get lock");
  1293. }
  1294. return 1;
  1295. }
  1296. sub unlockwiki () {
  1297. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1298. return close($wikilock) if $wikilock;
  1299. return;
  1300. }
  1301. my $commitlock;
  1302. sub commit_hook_enabled () {
  1303. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1304. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1305. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1306. close($commitlock) || error("failed closing commitlock: $!");
  1307. return 0;
  1308. }
  1309. close($commitlock) || error("failed closing commitlock: $!");
  1310. return 1;
  1311. }
  1312. sub disable_commit_hook () {
  1313. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1314. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1315. if (! flock($commitlock, 2)) { # LOCK_EX
  1316. error("failed to get commit lock");
  1317. }
  1318. return 1;
  1319. }
  1320. sub enable_commit_hook () {
  1321. return close($commitlock) if $commitlock;
  1322. return;
  1323. }
  1324. sub loadindex () {
  1325. %oldrenderedfiles=%pagectime=();
  1326. if (! $config{rebuild}) {
  1327. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1328. %destsources=%renderedfiles=%pagecase=%pagestate=
  1329. %depends_simple=();
  1330. }
  1331. my $in;
  1332. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1333. if (-e "$config{wikistatedir}/index") {
  1334. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1335. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1336. }
  1337. else {
  1338. return;
  1339. }
  1340. }
  1341. my $index=Storable::fd_retrieve($in);
  1342. if (! defined $index) {
  1343. return 0;
  1344. }
  1345. my $pages;
  1346. if (exists $index->{version} && ! ref $index->{version}) {
  1347. $pages=$index->{page};
  1348. %wikistate=%{$index->{state}};
  1349. }
  1350. else {
  1351. $pages=$index;
  1352. %wikistate=();
  1353. }
  1354. foreach my $src (keys %$pages) {
  1355. my $d=$pages->{$src};
  1356. my $page=pagename($src);
  1357. $pagectime{$page}=$d->{ctime};
  1358. if (! $config{rebuild}) {
  1359. $pagesources{$page}=$src;
  1360. $pagemtime{$page}=$d->{mtime};
  1361. $renderedfiles{$page}=$d->{dest};
  1362. if (exists $d->{links} && ref $d->{links}) {
  1363. $links{$page}=$d->{links};
  1364. $oldlinks{$page}=[@{$d->{links}}];
  1365. }
  1366. if (ref $d->{depends_simple} eq 'ARRAY') {
  1367. # old format
  1368. $depends_simple{$page}={
  1369. map { $_ => 1 } @{$d->{depends_simple}}
  1370. };
  1371. }
  1372. elsif (exists $d->{depends_simple}) {
  1373. $depends_simple{$page}=$d->{depends_simple};
  1374. }
  1375. if (exists $d->{dependslist}) {
  1376. # old format
  1377. $depends{$page}={
  1378. map { $_ => $DEPEND_CONTENT }
  1379. @{$d->{dependslist}}
  1380. };
  1381. }
  1382. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1383. # old format
  1384. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1385. }
  1386. elsif (exists $d->{depends}) {
  1387. $depends{$page}=$d->{depends};
  1388. }
  1389. if (exists $d->{state}) {
  1390. $pagestate{$page}=$d->{state};
  1391. }
  1392. }
  1393. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1394. }
  1395. foreach my $page (keys %pagesources) {
  1396. $pagecase{lc $page}=$page;
  1397. }
  1398. foreach my $page (keys %renderedfiles) {
  1399. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1400. }
  1401. return close($in);
  1402. }
  1403. sub saveindex () {
  1404. run_hooks(savestate => sub { shift->() });
  1405. my %hookids;
  1406. foreach my $type (keys %hooks) {
  1407. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1408. }
  1409. my @hookids=keys %hookids;
  1410. if (! -d $config{wikistatedir}) {
  1411. mkdir($config{wikistatedir});
  1412. }
  1413. my $newfile="$config{wikistatedir}/indexdb.new";
  1414. my $cleanup = sub { unlink($newfile) };
  1415. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1416. my %index;
  1417. foreach my $page (keys %pagemtime) {
  1418. next unless $pagemtime{$page};
  1419. my $src=$pagesources{$page};
  1420. $index{page}{$src}={
  1421. ctime => $pagectime{$page},
  1422. mtime => $pagemtime{$page},
  1423. dest => $renderedfiles{$page},
  1424. links => $links{$page},
  1425. };
  1426. if (exists $depends{$page}) {
  1427. $index{page}{$src}{depends} = $depends{$page};
  1428. }
  1429. if (exists $depends_simple{$page}) {
  1430. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1431. }
  1432. if (exists $pagestate{$page}) {
  1433. foreach my $id (@hookids) {
  1434. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1435. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1436. }
  1437. }
  1438. }
  1439. }
  1440. $index{state}={};
  1441. foreach my $id (@hookids) {
  1442. foreach my $key (keys %{$wikistate{$id}}) {
  1443. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1444. }
  1445. }
  1446. $index{version}="3";
  1447. my $ret=Storable::nstore_fd(\%index, $out);
  1448. return if ! defined $ret || ! $ret;
  1449. close $out || error("failed saving to $newfile: $!", $cleanup);
  1450. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1451. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1452. return 1;
  1453. }
  1454. sub template_file ($) {
  1455. my $template=shift;
  1456. foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
  1457. "$installdir/share/ikiwiki/templates") {
  1458. return "$dir/$template" if -e "$dir/$template";
  1459. }
  1460. return;
  1461. }
  1462. sub template_params (@) {
  1463. my $filename=template_file(shift);
  1464. if (! defined $filename) {
  1465. return if wantarray;
  1466. return "";
  1467. }
  1468. my @ret=(
  1469. filter => sub {
  1470. my $text_ref = shift;
  1471. ${$text_ref} = decode_utf8(${$text_ref});
  1472. },
  1473. filename => $filename,
  1474. loop_context_vars => 1,
  1475. die_on_bad_params => 0,
  1476. @_
  1477. );
  1478. return wantarray ? @ret : {@ret};
  1479. }
  1480. sub template ($;@) {
  1481. require HTML::Template;
  1482. return HTML::Template->new(template_params(@_));
  1483. }
  1484. sub misctemplate ($$;@) {
  1485. my $title=shift;
  1486. my $pagebody=shift;
  1487. my $template=template("misc.tmpl");
  1488. $template->param(
  1489. title => $title,
  1490. indexlink => indexlink(),
  1491. wikiname => $config{wikiname},
  1492. pagebody => $pagebody,
  1493. baseurl => baseurl(),
  1494. @_,
  1495. );
  1496. run_hooks(pagetemplate => sub {
  1497. shift->(page => "", destpage => "", template => $template);
  1498. });
  1499. return $template->output;
  1500. }
  1501. sub hook (@) {
  1502. my %param=@_;
  1503. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1504. error 'hook requires type, call, and id parameters';
  1505. }
  1506. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1507. $hooks{$param{type}}{$param{id}}=\%param;
  1508. return 1;
  1509. }
  1510. sub run_hooks ($$) {
  1511. # Calls the given sub for each hook of the given type,
  1512. # passing it the hook function to call.
  1513. my $type=shift;
  1514. my $sub=shift;
  1515. if (exists $hooks{$type}) {
  1516. my (@first, @middle, @last);
  1517. foreach my $id (keys %{$hooks{$type}}) {
  1518. if ($hooks{$type}{$id}{first}) {
  1519. push @first, $id;
  1520. }
  1521. elsif ($hooks{$type}{$id}{last}) {
  1522. push @last, $id;
  1523. }
  1524. else {
  1525. push @middle, $id;
  1526. }
  1527. }
  1528. foreach my $id (@first, @middle, @last) {
  1529. $sub->($hooks{$type}{$id}{call});
  1530. }
  1531. }
  1532. return 1;
  1533. }
  1534. sub rcs_update () {
  1535. $hooks{rcs}{rcs_update}{call}->(@_);
  1536. }
  1537. sub rcs_prepedit ($) {
  1538. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1539. }
  1540. sub rcs_commit ($$$;$$) {
  1541. $hooks{rcs}{rcs_commit}{call}->(@_);
  1542. }
  1543. sub rcs_commit_staged ($$$) {
  1544. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1545. }
  1546. sub rcs_add ($) {
  1547. $hooks{rcs}{rcs_add}{call}->(@_);
  1548. }
  1549. sub rcs_remove ($) {
  1550. $hooks{rcs}{rcs_remove}{call}->(@_);
  1551. }
  1552. sub rcs_rename ($$) {
  1553. $hooks{rcs}{rcs_rename}{call}->(@_);
  1554. }
  1555. sub rcs_recentchanges ($) {
  1556. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1557. }
  1558. sub rcs_diff ($) {
  1559. $hooks{rcs}{rcs_diff}{call}->(@_);
  1560. }
  1561. sub rcs_getctime ($) {
  1562. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1563. }
  1564. sub rcs_receive () {
  1565. $hooks{rcs}{rcs_receive}{call}->();
  1566. }
  1567. sub add_depends ($$;$) {
  1568. my $page=shift;
  1569. my $pagespec=shift;
  1570. my $deptype=shift || $DEPEND_CONTENT;
  1571. # Is the pagespec a simple page name?
  1572. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1573. $pagespec !~ /[\s*?()!]/) {
  1574. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1575. return 1;
  1576. }
  1577. # Add explicit dependencies for influences.
  1578. my $sub=pagespec_translate($pagespec);
  1579. return if $@;
  1580. foreach my $p (keys %pagesources) {
  1581. my $r=$sub->($p, location => $page);
  1582. my $i=$r->influences;
  1583. foreach my $k (keys %$i) {
  1584. $depends_simple{$page}{lc $k} |= $i->{$k};
  1585. }
  1586. last if $r->influences_static;
  1587. }
  1588. $depends{$page}{$pagespec} |= $deptype;
  1589. return 1;
  1590. }
  1591. sub deptype (@) {
  1592. my $deptype=0;
  1593. foreach my $type (@_) {
  1594. if ($type eq 'presence') {
  1595. $deptype |= $DEPEND_PRESENCE;
  1596. }
  1597. elsif ($type eq 'links') {
  1598. $deptype |= $DEPEND_LINKS;
  1599. }
  1600. elsif ($type eq 'content') {
  1601. $deptype |= $DEPEND_CONTENT;
  1602. }
  1603. }
  1604. return $deptype;
  1605. }
  1606. sub file_pruned ($;$) {
  1607. my $file=shift;
  1608. if (@_) {
  1609. require File::Spec;
  1610. $file=File::Spec->canonpath($file);
  1611. my $base=File::Spec->canonpath(shift);
  1612. return if $file eq $base;
  1613. $file =~ s#^\Q$base\E/+##;
  1614. }
  1615. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1616. return $file =~ m/$regexp/;
  1617. }
  1618. sub define_gettext () {
  1619. # If translation is needed, redefine the gettext function to do it.
  1620. # Otherwise, it becomes a quick no-op.
  1621. no warnings 'redefine';
  1622. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1623. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1624. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1625. *gettext=sub {
  1626. my $gettext_obj=eval q{
  1627. use Locale::gettext q{textdomain};
  1628. Locale::gettext->domain('ikiwiki')
  1629. };
  1630. if ($gettext_obj) {
  1631. $gettext_obj->get(shift);
  1632. }
  1633. else {
  1634. return shift;
  1635. }
  1636. };
  1637. }
  1638. else {
  1639. *gettext=sub { return shift };
  1640. }
  1641. }
  1642. sub gettext {
  1643. define_gettext();
  1644. gettext(@_);
  1645. }
  1646. sub yesno ($) {
  1647. my $val=shift;
  1648. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1649. }
  1650. sub inject {
  1651. # Injects a new function into the symbol table to replace an
  1652. # exported function.
  1653. my %params=@_;
  1654. # This is deep ugly perl foo, beware.
  1655. no strict;
  1656. no warnings;
  1657. if (! defined $params{parent}) {
  1658. $params{parent}='::';
  1659. $params{old}=\&{$params{name}};
  1660. $params{name}=~s/.*:://;
  1661. }
  1662. my $parent=$params{parent};
  1663. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1664. $ns = $params{parent} . $ns;
  1665. inject(%params, parent => $ns) unless $ns eq '::main::';
  1666. *{$ns . $params{name}} = $params{call}
  1667. if exists ${$ns}{$params{name}} &&
  1668. \&{${$ns}{$params{name}}} == $params{old};
  1669. }
  1670. use strict;
  1671. use warnings;
  1672. }
  1673. sub add_link ($$) {
  1674. my $page=shift;
  1675. my $link=shift;
  1676. push @{$links{$page}}, $link
  1677. unless grep { $_ eq $link } @{$links{$page}};
  1678. }
  1679. sub pagespec_translate ($) {
  1680. my $spec=shift;
  1681. # Convert spec to perl code.
  1682. my $code="";
  1683. my @data;
  1684. while ($spec=~m{
  1685. \s* # ignore whitespace
  1686. ( # 1: match a single word
  1687. \! # !
  1688. |
  1689. \( # (
  1690. |
  1691. \) # )
  1692. |
  1693. \w+\([^\)]*\) # command(params)
  1694. |
  1695. [^\s()]+ # any other text
  1696. )
  1697. \s* # ignore whitespace
  1698. }gx) {
  1699. my $word=$1;
  1700. if (lc $word eq 'and') {
  1701. $code.=' &';
  1702. }
  1703. elsif (lc $word eq 'or') {
  1704. $code.=' |';
  1705. }
  1706. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1707. $code.=' '.$word;
  1708. }
  1709. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1710. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1711. push @data, $2;
  1712. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1713. }
  1714. else {
  1715. push @data, qq{unknown function in pagespec "$word"};
  1716. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1717. }
  1718. }
  1719. else {
  1720. push @data, $word;
  1721. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1722. }
  1723. }
  1724. if (! length $code) {
  1725. $code="IkiWiki::FailReason->new('empty pagespec')";
  1726. }
  1727. no warnings;
  1728. return eval 'sub { my $page=shift; '.$code.' }';
  1729. }
  1730. sub pagespec_match ($$;@) {
  1731. my $page=shift;
  1732. my $spec=shift;
  1733. my @params=@_;
  1734. # Backwards compatability with old calling convention.
  1735. if (@params == 1) {
  1736. unshift @params, 'location';
  1737. }
  1738. my $sub=pagespec_translate($spec);
  1739. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1740. if $@ || ! defined $sub;
  1741. return $sub->($page, @params);
  1742. }
  1743. sub pagespec_match_list ($$;@) {
  1744. my $page=shift;
  1745. my $pagespec=shift;
  1746. my %params=@_;
  1747. # Backwards compatability with old calling convention.
  1748. if (ref $page) {
  1749. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1750. $params{list}=$page;
  1751. $page=$params{location}; # ugh!
  1752. }
  1753. my $sub=pagespec_translate($pagespec);
  1754. error "syntax error in pagespec \"$pagespec\""
  1755. if $@ || ! defined $sub;
  1756. my @candidates;
  1757. if (exists $params{list}) {
  1758. @candidates=exists $params{filter}
  1759. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1760. : @{$params{list}};
  1761. }
  1762. else {
  1763. @candidates=exists $params{filter}
  1764. ? grep { ! $params{filter}->($_) } keys %pagesources
  1765. : keys %pagesources;
  1766. }
  1767. if (defined $params{sort}) {
  1768. my $f;
  1769. if ($params{sort} eq 'title') {
  1770. $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
  1771. }
  1772. elsif ($params{sort} eq 'title_natural') {
  1773. eval q{use Sort::Naturally};
  1774. if ($@) {
  1775. error(gettext("Sort::Naturally needed for title_natural sort"));
  1776. }
  1777. $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
  1778. }
  1779. elsif ($params{sort} eq 'mtime') {
  1780. $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
  1781. }
  1782. elsif ($params{sort} eq 'age') {
  1783. $f=sub { $pagectime{$b} <=> $pagectime{$a} };
  1784. }
  1785. else {
  1786. error sprintf(gettext("unknown sort type %s"), $params{sort});
  1787. }
  1788. @candidates = sort { &$f } @candidates;
  1789. }
  1790. @candidates=reverse(@candidates) if $params{reverse};
  1791. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1792. # clear params, remainder is passed to pagespec
  1793. my $num=$params{num};
  1794. delete @params{qw{num deptype reverse sort filter list}};
  1795. my @matches;
  1796. my $firstfail;
  1797. my $count=0;
  1798. my $accum=IkiWiki::SuccessReason->new();
  1799. foreach my $p (@candidates) {
  1800. my $r=$sub->($p, %params, location => $page);
  1801. error(sprintf(gettext("cannot match pages: %s"), $r))
  1802. if $r->isa("IkiWiki::ErrorReason");
  1803. $accum |= $r;
  1804. if ($r) {
  1805. push @matches, $p;
  1806. last if defined $num && ++$count == $num;
  1807. }
  1808. }
  1809. # Add simple dependencies for accumulated influences.
  1810. my $i=$accum->influences;
  1811. foreach my $k (keys %$i) {
  1812. $depends_simple{$page}{lc $k} |= $i->{$k};
  1813. }
  1814. return @matches;
  1815. }
  1816. sub pagespec_valid ($) {
  1817. my $spec=shift;
  1818. my $sub=pagespec_translate($spec);
  1819. return ! $@;
  1820. }
  1821. sub glob2re ($) {
  1822. my $re=quotemeta(shift);
  1823. $re=~s/\\\*/.*/g;
  1824. $re=~s/\\\?/./g;
  1825. return $re;
  1826. }
  1827. package IkiWiki::FailReason;
  1828. use overload (
  1829. '""' => sub { $_[0][0] },
  1830. '0+' => sub { 0 },
  1831. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1832. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  1833. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1834. fallback => 1,
  1835. );
  1836. our @ISA = 'IkiWiki::SuccessReason';
  1837. package IkiWiki::SuccessReason;
  1838. use overload (
  1839. '""' => sub { $_[0][0] },
  1840. '0+' => sub { 1 },
  1841. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1842. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  1843. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1844. fallback => 1,
  1845. );
  1846. sub new {
  1847. my $class = shift;
  1848. my $value = shift;
  1849. return bless [$value, {@_}], $class;
  1850. }
  1851. sub influences {
  1852. my $this=shift;
  1853. $this->[1]={@_} if @_;
  1854. my %i=%{$this->[1]};
  1855. delete $i{""};
  1856. return \%i;
  1857. }
  1858. sub influences_static {
  1859. return ! $_[0][1]->{""};
  1860. }
  1861. sub merge_influences {
  1862. my $this=shift;
  1863. my $other=shift;
  1864. my $anded=shift;
  1865. if (! $anded || (($this || %{$this->[1]}) &&
  1866. ($other || %{$other->[1]}))) {
  1867. foreach my $influence (keys %{$other->[1]}) {
  1868. $this->[1]{$influence} |= $other->[1]{$influence};
  1869. }
  1870. }
  1871. else {
  1872. # influence blocker
  1873. $this->[1]={};
  1874. }
  1875. }
  1876. package IkiWiki::ErrorReason;
  1877. our @ISA = 'IkiWiki::FailReason';
  1878. package IkiWiki::PageSpec;
  1879. sub derel ($$) {
  1880. my $path=shift;
  1881. my $from=shift;
  1882. if ($path =~ m!^\./!) {
  1883. $from=~s#/?[^/]+$## if defined $from;
  1884. $path=~s#^\./##;
  1885. $path="$from/$path" if length $from;
  1886. }
  1887. return $path;
  1888. }
  1889. sub match_glob ($$;@) {
  1890. my $page=shift;
  1891. my $glob=shift;
  1892. my %params=@_;
  1893. $glob=derel($glob, $params{location});
  1894. my $regexp=IkiWiki::glob2re($glob);
  1895. if ($page=~/^$regexp$/i) {
  1896. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1897. return IkiWiki::SuccessReason->new("$glob matches $page");
  1898. }
  1899. else {
  1900. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1901. }
  1902. }
  1903. else {
  1904. return IkiWiki::FailReason->new("$glob does not match $page");
  1905. }
  1906. }
  1907. sub match_internal ($$;@) {
  1908. return match_glob($_[0], $_[1], @_, internal => 1)
  1909. }
  1910. sub match_link ($$;@) {
  1911. my $page=shift;
  1912. my $link=lc(shift);
  1913. my %params=@_;
  1914. $link=derel($link, $params{location});
  1915. my $from=exists $params{location} ? $params{location} : '';
  1916. my $links = $IkiWiki::links{$page};
  1917. return IkiWiki::FailReason->new("$page has no links", "" => 1)
  1918. unless $links && @{$links};
  1919. my $bestlink = IkiWiki::bestlink($from, $link);
  1920. foreach my $p (@{$links}) {
  1921. if (length $bestlink) {
  1922. return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1923. if $bestlink eq IkiWiki::bestlink($page, $p);
  1924. }
  1925. else {
  1926. return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1927. if match_glob($p, $link, %params);
  1928. my ($p_rel)=$p=~/^\/?(.*)/;
  1929. $link=~s/^\///;
  1930. return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1931. if match_glob($p_rel, $link, %params);
  1932. }
  1933. }
  1934. return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
  1935. }
  1936. sub match_backlink ($$;@) {
  1937. my $ret=match_link($_[1], $_[0], @_);
  1938. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  1939. return $ret;
  1940. }
  1941. sub match_created_before ($$;@) {
  1942. my $page=shift;
  1943. my $testpage=shift;
  1944. my %params=@_;
  1945. $testpage=derel($testpage, $params{location});
  1946. if (exists $IkiWiki::pagectime{$testpage}) {
  1947. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1948. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1949. }
  1950. else {
  1951. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1952. }
  1953. }
  1954. else {
  1955. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1956. }
  1957. }
  1958. sub match_created_after ($$;@) {
  1959. my $page=shift;
  1960. my $testpage=shift;
  1961. my %params=@_;
  1962. $testpage=derel($testpage, $params{location});
  1963. if (exists $IkiWiki::pagectime{$testpage}) {
  1964. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1965. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1966. }
  1967. else {
  1968. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1969. }
  1970. }
  1971. else {
  1972. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1973. }
  1974. }
  1975. sub match_creation_day ($$;@) {
  1976. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1977. return IkiWiki::SuccessReason->new('creation_day matched');
  1978. }
  1979. else {
  1980. return IkiWiki::FailReason->new('creation_day did not match');
  1981. }
  1982. }
  1983. sub match_creation_month ($$;@) {
  1984. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1985. return IkiWiki::SuccessReason->new('creation_month matched');
  1986. }
  1987. else {
  1988. return IkiWiki::FailReason->new('creation_month did not match');
  1989. }
  1990. }
  1991. sub match_creation_year ($$;@) {
  1992. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1993. return IkiWiki::SuccessReason->new('creation_year matched');
  1994. }
  1995. else {
  1996. return IkiWiki::FailReason->new('creation_year did not match');
  1997. }
  1998. }
  1999. sub match_user ($$;@) {
  2000. shift;
  2001. my $user=shift;
  2002. my %params=@_;
  2003. if (! exists $params{user}) {
  2004. return IkiWiki::ErrorReason->new("no user specified");
  2005. }
  2006. if (defined $params{user} && lc $params{user} eq lc $user) {
  2007. return IkiWiki::SuccessReason->new("user is $user");
  2008. }
  2009. elsif (! defined $params{user}) {
  2010. return IkiWiki::FailReason->new("not logged in");
  2011. }
  2012. else {
  2013. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2014. }
  2015. }
  2016. sub match_admin ($$;@) {
  2017. shift;
  2018. shift;
  2019. my %params=@_;
  2020. if (! exists $params{user}) {
  2021. return IkiWiki::ErrorReason->new("no user specified");
  2022. }
  2023. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2024. return IkiWiki::SuccessReason->new("user is an admin");
  2025. }
  2026. elsif (! defined $params{user}) {
  2027. return IkiWiki::FailReason->new("not logged in");
  2028. }
  2029. else {
  2030. return IkiWiki::FailReason->new("user is not an admin");
  2031. }
  2032. }
  2033. sub match_ip ($$;@) {
  2034. shift;
  2035. my $ip=shift;
  2036. my %params=@_;
  2037. if (! exists $params{ip}) {
  2038. return IkiWiki::ErrorReason->new("no IP specified");
  2039. }
  2040. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2041. return IkiWiki::SuccessReason->new("IP is $ip");
  2042. }
  2043. else {
  2044. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2045. }
  2046. }
  2047. 1