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