summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 49c76c4d4cb08901b6d102bd6e466ebb9f2f8a8c (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 $links{$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 $links{$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. if (defined $opts{rel}) {
  966. push @attrs, ' rel="'.$opts{rel}.'"';
  967. }
  968. if (defined $opts{class}) {
  969. push @attrs, ' class="'.$opts{class}.'"';
  970. }
  971. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  972. }
  973. sub openiduser ($) {
  974. my $user=shift;
  975. if ($user =~ m!^https?://! &&
  976. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  977. my $display;
  978. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  979. # this works in at least 2.x
  980. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  981. }
  982. else {
  983. # this only works in 1.x
  984. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  985. $display=$oid->display;
  986. }
  987. # Convert "user.somehost.com" to "user [somehost.com]"
  988. # (also "user.somehost.co.uk")
  989. if ($display !~ /\[/) {
  990. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  991. }
  992. # Convert "http://somehost.com/user" to "user [somehost.com]".
  993. # (also "https://somehost.com/user/")
  994. if ($display !~ /\[/) {
  995. $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
  996. }
  997. $display=~s!^https?://!!; # make sure this is removed
  998. eval q{use CGI 'escapeHTML'};
  999. error($@) if $@;
  1000. return escapeHTML($display);
  1001. }
  1002. return;
  1003. }
  1004. sub userlink ($) {
  1005. my $user=shift;
  1006. my $oiduser=eval { openiduser($user) };
  1007. if (defined $oiduser) {
  1008. return "<a href=\"$user\">$oiduser</a>";
  1009. }
  1010. else {
  1011. eval q{use CGI 'escapeHTML'};
  1012. error($@) if $@;
  1013. return htmllink("", "", escapeHTML(
  1014. length $config{userdir} ? $config{userdir}."/".$user : $user
  1015. ), noimageinline => 1);
  1016. }
  1017. }
  1018. sub htmlize ($$$$) {
  1019. my $page=shift;
  1020. my $destpage=shift;
  1021. my $type=shift;
  1022. my $content=shift;
  1023. my $oneline = $content !~ /\n/;
  1024. if (exists $hooks{htmlize}{$type}) {
  1025. $content=$hooks{htmlize}{$type}{call}->(
  1026. page => $page,
  1027. content => $content,
  1028. );
  1029. }
  1030. else {
  1031. error("htmlization of $type not supported");
  1032. }
  1033. run_hooks(sanitize => sub {
  1034. $content=shift->(
  1035. page => $page,
  1036. destpage => $destpage,
  1037. content => $content,
  1038. );
  1039. });
  1040. if ($oneline) {
  1041. # hack to get rid of enclosing junk added by markdown
  1042. # and other htmlizers
  1043. $content=~s/^<p>//i;
  1044. $content=~s/<\/p>$//i;
  1045. chomp $content;
  1046. }
  1047. return $content;
  1048. }
  1049. sub linkify ($$$) {
  1050. my $page=shift;
  1051. my $destpage=shift;
  1052. my $content=shift;
  1053. run_hooks(linkify => sub {
  1054. $content=shift->(
  1055. page => $page,
  1056. destpage => $destpage,
  1057. content => $content,
  1058. );
  1059. });
  1060. return $content;
  1061. }
  1062. our %preprocessing;
  1063. our $preprocess_preview=0;
  1064. sub preprocess ($$$;$$) {
  1065. my $page=shift; # the page the data comes from
  1066. my $destpage=shift; # the page the data will appear in (different for inline)
  1067. my $content=shift;
  1068. my $scan=shift;
  1069. my $preview=shift;
  1070. # Using local because it needs to be set within any nested calls
  1071. # of this function.
  1072. local $preprocess_preview=$preview if defined $preview;
  1073. my $handle=sub {
  1074. my $escape=shift;
  1075. my $prefix=shift;
  1076. my $command=shift;
  1077. my $params=shift;
  1078. $params="" if ! defined $params;
  1079. if (length $escape) {
  1080. return "[[$prefix$command $params]]";
  1081. }
  1082. elsif (exists $hooks{preprocess}{$command}) {
  1083. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1084. # Note: preserve order of params, some plugins may
  1085. # consider it significant.
  1086. my @params;
  1087. while ($params =~ m{
  1088. (?:([-\w]+)=)? # 1: named parameter key?
  1089. (?:
  1090. """(.*?)""" # 2: triple-quoted value
  1091. |
  1092. "([^"]+)" # 3: single-quoted value
  1093. |
  1094. (\S+) # 4: unquoted value
  1095. )
  1096. (?:\s+|$) # delimiter to next param
  1097. }sgx) {
  1098. my $key=$1;
  1099. my $val;
  1100. if (defined $2) {
  1101. $val=$2;
  1102. $val=~s/\r\n/\n/mg;
  1103. $val=~s/^\n+//g;
  1104. $val=~s/\n+$//g;
  1105. }
  1106. elsif (defined $3) {
  1107. $val=$3;
  1108. }
  1109. elsif (defined $4) {
  1110. $val=$4;
  1111. }
  1112. if (defined $key) {
  1113. push @params, $key, $val;
  1114. }
  1115. else {
  1116. push @params, $val, '';
  1117. }
  1118. }
  1119. if ($preprocessing{$page}++ > 3) {
  1120. # Avoid loops of preprocessed pages preprocessing
  1121. # other pages that preprocess them, etc.
  1122. return "[[!$command <span class=\"error\">".
  1123. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1124. $page, $preprocessing{$page}).
  1125. "</span>]]";
  1126. }
  1127. my $ret;
  1128. if (! $scan) {
  1129. $ret=eval {
  1130. $hooks{preprocess}{$command}{call}->(
  1131. @params,
  1132. page => $page,
  1133. destpage => $destpage,
  1134. preview => $preprocess_preview,
  1135. );
  1136. };
  1137. if ($@) {
  1138. my $error=$@;
  1139. chomp $error;
  1140. $ret="[[!$command <span class=\"error\">".
  1141. gettext("Error").": $error"."</span>]]";
  1142. }
  1143. }
  1144. else {
  1145. # use void context during scan pass
  1146. eval {
  1147. $hooks{preprocess}{$command}{call}->(
  1148. @params,
  1149. page => $page,
  1150. destpage => $destpage,
  1151. preview => $preprocess_preview,
  1152. );
  1153. };
  1154. $ret="";
  1155. }
  1156. $preprocessing{$page}--;
  1157. return $ret;
  1158. }
  1159. else {
  1160. return "[[$prefix$command $params]]";
  1161. }
  1162. };
  1163. my $regex;
  1164. if ($config{prefix_directives}) {
  1165. $regex = qr{
  1166. (\\?) # 1: escape?
  1167. \[\[(!) # directive open; 2: prefix
  1168. ([-\w]+) # 3: command
  1169. ( # 4: the parameters..
  1170. \s+ # Must have space if parameters present
  1171. (?:
  1172. (?:[-\w]+=)? # named parameter key?
  1173. (?:
  1174. """.*?""" # triple-quoted value
  1175. |
  1176. "[^"]+" # single-quoted value
  1177. |
  1178. [^"\s\]]+ # unquoted value
  1179. )
  1180. \s* # whitespace or end
  1181. # of directive
  1182. )
  1183. *)? # 0 or more parameters
  1184. \]\] # directive closed
  1185. }sx;
  1186. }
  1187. else {
  1188. $regex = qr{
  1189. (\\?) # 1: escape?
  1190. \[\[(!?) # directive open; 2: optional prefix
  1191. ([-\w]+) # 3: command
  1192. \s+
  1193. ( # 4: the parameters..
  1194. (?:
  1195. (?:[-\w]+=)? # named parameter key?
  1196. (?:
  1197. """.*?""" # triple-quoted value
  1198. |
  1199. "[^"]+" # single-quoted value
  1200. |
  1201. [^"\s\]]+ # unquoted value
  1202. )
  1203. \s* # whitespace or end
  1204. # of directive
  1205. )
  1206. *) # 0 or more parameters
  1207. \]\] # directive closed
  1208. }sx;
  1209. }
  1210. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1211. return $content;
  1212. }
  1213. sub filter ($$$) {
  1214. my $page=shift;
  1215. my $destpage=shift;
  1216. my $content=shift;
  1217. run_hooks(filter => sub {
  1218. $content=shift->(page => $page, destpage => $destpage,
  1219. content => $content);
  1220. });
  1221. return $content;
  1222. }
  1223. sub indexlink () {
  1224. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1225. }
  1226. sub check_canedit ($$$;$) {
  1227. my $page=shift;
  1228. my $q=shift;
  1229. my $session=shift;
  1230. my $nonfatal=shift;
  1231. my $canedit;
  1232. run_hooks(canedit => sub {
  1233. return if defined $canedit;
  1234. my $ret=shift->($page, $q, $session);
  1235. if (defined $ret) {
  1236. if ($ret eq "") {
  1237. $canedit=1;
  1238. }
  1239. elsif (ref $ret eq 'CODE') {
  1240. $ret->() unless $nonfatal;
  1241. $canedit=0;
  1242. }
  1243. elsif (defined $ret) {
  1244. error($ret) unless $nonfatal;
  1245. $canedit=0;
  1246. }
  1247. }
  1248. });
  1249. return defined $canedit ? $canedit : 1;
  1250. }
  1251. sub check_content (@) {
  1252. my %params=@_;
  1253. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1254. if (exists $pagesources{$params{page}}) {
  1255. my @diff;
  1256. my %old=map { $_ => 1 }
  1257. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1258. foreach my $line (split("\n", $params{content})) {
  1259. push @diff, $line if ! exists $old{$_};
  1260. }
  1261. $params{diff}=join("\n", @diff);
  1262. }
  1263. my $ok;
  1264. run_hooks(checkcontent => sub {
  1265. return if defined $ok;
  1266. my $ret=shift->(%params);
  1267. if (defined $ret) {
  1268. if ($ret eq "") {
  1269. $ok=1;
  1270. }
  1271. elsif (ref $ret eq 'CODE') {
  1272. $ret->() unless $params{nonfatal};
  1273. $ok=0;
  1274. }
  1275. elsif (defined $ret) {
  1276. error($ret) unless $params{nonfatal};
  1277. $ok=0;
  1278. }
  1279. }
  1280. });
  1281. return defined $ok ? $ok : 1;
  1282. }
  1283. my $wikilock;
  1284. sub lockwiki () {
  1285. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1286. # run issues. The lock will be dropped on program exit.
  1287. if (! -d $config{wikistatedir}) {
  1288. mkdir($config{wikistatedir});
  1289. }
  1290. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1291. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1292. if (! flock($wikilock, 2)) { # LOCK_EX
  1293. error("failed to get lock");
  1294. }
  1295. return 1;
  1296. }
  1297. sub unlockwiki () {
  1298. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1299. return close($wikilock) if $wikilock;
  1300. return;
  1301. }
  1302. my $commitlock;
  1303. sub commit_hook_enabled () {
  1304. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1305. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1306. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1307. close($commitlock) || error("failed closing commitlock: $!");
  1308. return 0;
  1309. }
  1310. close($commitlock) || error("failed closing commitlock: $!");
  1311. return 1;
  1312. }
  1313. sub disable_commit_hook () {
  1314. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1315. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1316. if (! flock($commitlock, 2)) { # LOCK_EX
  1317. error("failed to get commit lock");
  1318. }
  1319. return 1;
  1320. }
  1321. sub enable_commit_hook () {
  1322. return close($commitlock) if $commitlock;
  1323. return;
  1324. }
  1325. sub loadindex () {
  1326. %oldrenderedfiles=%pagectime=();
  1327. if (! $config{rebuild}) {
  1328. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1329. %destsources=%renderedfiles=%pagecase=%pagestate=
  1330. %depends_simple=();
  1331. }
  1332. my $in;
  1333. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1334. if (-e "$config{wikistatedir}/index") {
  1335. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1336. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1337. }
  1338. else {
  1339. return;
  1340. }
  1341. }
  1342. my $index=Storable::fd_retrieve($in);
  1343. if (! defined $index) {
  1344. return 0;
  1345. }
  1346. my $pages;
  1347. if (exists $index->{version} && ! ref $index->{version}) {
  1348. $pages=$index->{page};
  1349. %wikistate=%{$index->{state}};
  1350. }
  1351. else {
  1352. $pages=$index;
  1353. %wikistate=();
  1354. }
  1355. foreach my $src (keys %$pages) {
  1356. my $d=$pages->{$src};
  1357. my $page=pagename($src);
  1358. $pagectime{$page}=$d->{ctime};
  1359. if (! $config{rebuild}) {
  1360. $pagesources{$page}=$src;
  1361. $pagemtime{$page}=$d->{mtime};
  1362. $renderedfiles{$page}=$d->{dest};
  1363. if (exists $d->{links} && ref $d->{links}) {
  1364. $links{$page}=$d->{links};
  1365. $oldlinks{$page}=[@{$d->{links}}];
  1366. }
  1367. if (ref $d->{depends_simple} eq 'ARRAY') {
  1368. # old format
  1369. $depends_simple{$page}={
  1370. map { $_ => 1 } @{$d->{depends_simple}}
  1371. };
  1372. }
  1373. elsif (exists $d->{depends_simple}) {
  1374. $depends_simple{$page}=$d->{depends_simple};
  1375. }
  1376. if (exists $d->{dependslist}) {
  1377. # old format
  1378. $depends{$page}={
  1379. map { $_ => $DEPEND_CONTENT }
  1380. @{$d->{dependslist}}
  1381. };
  1382. }
  1383. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1384. # old format
  1385. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1386. }
  1387. elsif (exists $d->{depends}) {
  1388. $depends{$page}=$d->{depends};
  1389. }
  1390. if (exists $d->{state}) {
  1391. $pagestate{$page}=$d->{state};
  1392. }
  1393. }
  1394. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1395. }
  1396. foreach my $page (keys %pagesources) {
  1397. $pagecase{lc $page}=$page;
  1398. }
  1399. foreach my $page (keys %renderedfiles) {
  1400. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1401. }
  1402. return close($in);
  1403. }
  1404. sub saveindex () {
  1405. run_hooks(savestate => sub { shift->() });
  1406. my %hookids;
  1407. foreach my $type (keys %hooks) {
  1408. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1409. }
  1410. my @hookids=keys %hookids;
  1411. if (! -d $config{wikistatedir}) {
  1412. mkdir($config{wikistatedir});
  1413. }
  1414. my $newfile="$config{wikistatedir}/indexdb.new";
  1415. my $cleanup = sub { unlink($newfile) };
  1416. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1417. my %index;
  1418. foreach my $page (keys %pagemtime) {
  1419. next unless $pagemtime{$page};
  1420. my $src=$pagesources{$page};
  1421. $index{page}{$src}={
  1422. ctime => $pagectime{$page},
  1423. mtime => $pagemtime{$page},
  1424. dest => $renderedfiles{$page},
  1425. links => $links{$page},
  1426. };
  1427. if (exists $depends{$page}) {
  1428. $index{page}{$src}{depends} = $depends{$page};
  1429. }
  1430. if (exists $depends_simple{$page}) {
  1431. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1432. }
  1433. if (exists $pagestate{$page}) {
  1434. foreach my $id (@hookids) {
  1435. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1436. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1437. }
  1438. }
  1439. }
  1440. }
  1441. $index{state}={};
  1442. foreach my $id (@hookids) {
  1443. foreach my $key (keys %{$wikistate{$id}}) {
  1444. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1445. }
  1446. }
  1447. $index{version}="3";
  1448. my $ret=Storable::nstore_fd(\%index, $out);
  1449. return if ! defined $ret || ! $ret;
  1450. close $out || error("failed saving to $newfile: $!", $cleanup);
  1451. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1452. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1453. return 1;
  1454. }
  1455. sub template_file ($) {
  1456. my $template=shift;
  1457. foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
  1458. "$installdir/share/ikiwiki/templates") {
  1459. return "$dir/$template" if -e "$dir/$template";
  1460. }
  1461. return;
  1462. }
  1463. sub template_params (@) {
  1464. my $filename=template_file(shift);
  1465. if (! defined $filename) {
  1466. return if wantarray;
  1467. return "";
  1468. }
  1469. my @ret=(
  1470. filter => sub {
  1471. my $text_ref = shift;
  1472. ${$text_ref} = decode_utf8(${$text_ref});
  1473. },
  1474. filename => $filename,
  1475. loop_context_vars => 1,
  1476. die_on_bad_params => 0,
  1477. @_
  1478. );
  1479. return wantarray ? @ret : {@ret};
  1480. }
  1481. sub template ($;@) {
  1482. require HTML::Template;
  1483. return HTML::Template->new(template_params(@_));
  1484. }
  1485. sub misctemplate ($$;@) {
  1486. my $title=shift;
  1487. my $pagebody=shift;
  1488. my $template=template("misc.tmpl");
  1489. $template->param(
  1490. title => $title,
  1491. indexlink => indexlink(),
  1492. wikiname => $config{wikiname},
  1493. pagebody => $pagebody,
  1494. baseurl => baseurl(),
  1495. @_,
  1496. );
  1497. run_hooks(pagetemplate => sub {
  1498. shift->(page => "", destpage => "", template => $template);
  1499. });
  1500. return $template->output;
  1501. }
  1502. sub hook (@) {
  1503. my %param=@_;
  1504. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1505. error 'hook requires type, call, and id parameters';
  1506. }
  1507. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1508. $hooks{$param{type}}{$param{id}}=\%param;
  1509. return 1;
  1510. }
  1511. sub run_hooks ($$) {
  1512. # Calls the given sub for each hook of the given type,
  1513. # passing it the hook function to call.
  1514. my $type=shift;
  1515. my $sub=shift;
  1516. if (exists $hooks{$type}) {
  1517. my (@first, @middle, @last);
  1518. foreach my $id (keys %{$hooks{$type}}) {
  1519. if ($hooks{$type}{$id}{first}) {
  1520. push @first, $id;
  1521. }
  1522. elsif ($hooks{$type}{$id}{last}) {
  1523. push @last, $id;
  1524. }
  1525. else {
  1526. push @middle, $id;
  1527. }
  1528. }
  1529. foreach my $id (@first, @middle, @last) {
  1530. $sub->($hooks{$type}{$id}{call});
  1531. }
  1532. }
  1533. return 1;
  1534. }
  1535. sub rcs_update () {
  1536. $hooks{rcs}{rcs_update}{call}->(@_);
  1537. }
  1538. sub rcs_prepedit ($) {
  1539. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1540. }
  1541. sub rcs_commit ($$$;$$) {
  1542. $hooks{rcs}{rcs_commit}{call}->(@_);
  1543. }
  1544. sub rcs_commit_staged ($$$) {
  1545. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1546. }
  1547. sub rcs_add ($) {
  1548. $hooks{rcs}{rcs_add}{call}->(@_);
  1549. }
  1550. sub rcs_remove ($) {
  1551. $hooks{rcs}{rcs_remove}{call}->(@_);
  1552. }
  1553. sub rcs_rename ($$) {
  1554. $hooks{rcs}{rcs_rename}{call}->(@_);
  1555. }
  1556. sub rcs_recentchanges ($) {
  1557. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1558. }
  1559. sub rcs_diff ($) {
  1560. $hooks{rcs}{rcs_diff}{call}->(@_);
  1561. }
  1562. sub rcs_getctime ($) {
  1563. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1564. }
  1565. sub rcs_receive () {
  1566. $hooks{rcs}{rcs_receive}{call}->();
  1567. }
  1568. sub add_depends ($$;$) {
  1569. my $page=shift;
  1570. my $pagespec=shift;
  1571. my $deptype=shift || $DEPEND_CONTENT;
  1572. # Is the pagespec a simple page name?
  1573. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1574. $pagespec !~ /[\s*?()!]/) {
  1575. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1576. return 1;
  1577. }
  1578. # Analyse the pagespec, and match it against all pages
  1579. # to get a list of influences, and add explicit dependencies
  1580. # for those.
  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 $i (keys %i) {
  1587. # $depends_simple{$page}{lc $i} |= $i{$i};
  1588. # }
  1589. #}
  1590. print STDERR "warning: use of add_depends by ".caller()."; influences not tracked\n";
  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{filter}) {
  1761. @candidates=grep { ! $params{filter}->($_) } keys %pagesources;
  1762. }
  1763. else {
  1764. @candidates=keys %pagesources;
  1765. }
  1766. if (defined $params{sort}) {
  1767. my $f;
  1768. if ($params{sort} eq 'title') {
  1769. $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
  1770. }
  1771. elsif ($params{sort} eq 'title_natural') {
  1772. eval q{use Sort::Naturally};
  1773. if ($@) {
  1774. error(gettext("Sort::Naturally needed for title_natural sort"));
  1775. }
  1776. $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
  1777. }
  1778. elsif ($params{sort} eq 'mtime') {
  1779. $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
  1780. }
  1781. elsif ($params{sort} eq 'age') {
  1782. $f=sub { $pagectime{$b} <=> $pagectime{$a} };
  1783. }
  1784. else {
  1785. error sprintf(gettext("unknown sort type %s"), $params{sort});
  1786. }
  1787. @candidates = sort { &$f } @candidates;
  1788. }
  1789. @candidates=reverse(@candidates) if $params{reverse};
  1790. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1791. # clear params, remainder is passed to pagespec
  1792. my $num=$params{num};
  1793. delete @params{qw{num deptype reverse sort filter}};
  1794. my @matches;
  1795. my $firstfail;
  1796. my $count=0;
  1797. foreach my $p (@candidates) {
  1798. my $r=$sub->($p, %params, location => $page);
  1799. if ($r) {
  1800. push @matches, [$p, $r];
  1801. last if defined $num && ++$count == $num;
  1802. }
  1803. elsif (! defined $firstfail) {
  1804. $firstfail=$r;
  1805. }
  1806. }
  1807. my @ret;
  1808. if (@matches) {
  1809. # Add all influences from successful matches.
  1810. foreach my $m (@matches) {
  1811. push @ret, $m->[0];
  1812. my %i=$m->[1]->influences;
  1813. foreach my $i (keys %i) {
  1814. $depends_simple{$page}{lc $i} |= $i{$i};
  1815. }
  1816. }
  1817. }
  1818. elsif (defined $firstfail) {
  1819. # Add influences from one failure. (Which one should not
  1820. # matter; all should have the same influences.)
  1821. my %i=$firstfail->influences;
  1822. foreach my $i (keys %i) {
  1823. $depends_simple{$page}{lc $i} |= $i{$i};
  1824. }
  1825. error(sprintf(gettext("cannot match pages: %s"), $firstfail))
  1826. if $firstfail->isa("IkiWiki::ErrorReason");
  1827. }
  1828. return @ret;
  1829. }
  1830. sub pagespec_valid ($) {
  1831. my $spec=shift;
  1832. my $sub=pagespec_translate($spec);
  1833. return ! $@;
  1834. }
  1835. sub glob2re ($) {
  1836. my $re=quotemeta(shift);
  1837. $re=~s/\\\*/.*/g;
  1838. $re=~s/\\\?/./g;
  1839. return $re;
  1840. }
  1841. package IkiWiki::FailReason;
  1842. use overload (
  1843. '""' => sub { $_[0][0] },
  1844. '0+' => sub { 0 },
  1845. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1846. '&' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1847. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1848. fallback => 1,
  1849. );
  1850. our @ISA = 'IkiWiki::SuccessReason';
  1851. package IkiWiki::SuccessReason;
  1852. use overload (
  1853. '""' => sub { $_[0][0] },
  1854. '0+' => sub { 1 },
  1855. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1856. '&' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1857. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1858. fallback => 1,
  1859. );
  1860. sub new {
  1861. my $class = shift;
  1862. my $value = shift;
  1863. return bless [$value, {@_}], $class;
  1864. }
  1865. sub influences {
  1866. my $this=shift;
  1867. if (! @_) {
  1868. return %{$this->[1]};
  1869. }
  1870. else {
  1871. $this->[1]={@_};
  1872. }
  1873. }
  1874. sub merge_influences {
  1875. my $this=shift;
  1876. my $other=shift;
  1877. foreach my $influence (keys %{$other->[1]}) {
  1878. $this->[1]{$influence} |= $other->[1]{$influence};
  1879. }
  1880. }
  1881. package IkiWiki::ErrorReason;
  1882. our @ISA = 'IkiWiki::FailReason';
  1883. package IkiWiki::PageSpec;
  1884. sub derel ($$) {
  1885. my $path=shift;
  1886. my $from=shift;
  1887. if ($path =~ m!^\./!) {
  1888. $from=~s#/?[^/]+$## if defined $from;
  1889. $path=~s#^\./##;
  1890. $path="$from/$path" if length $from;
  1891. }
  1892. return $path;
  1893. }
  1894. sub match_glob ($$;@) {
  1895. my $page=shift;
  1896. my $glob=shift;
  1897. my %params=@_;
  1898. $glob=derel($glob, $params{location});
  1899. my $regexp=IkiWiki::glob2re($glob);
  1900. if ($page=~/^$regexp$/i) {
  1901. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1902. return IkiWiki::SuccessReason->new("$glob matches $page");
  1903. }
  1904. else {
  1905. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1906. }
  1907. }
  1908. else {
  1909. return IkiWiki::FailReason->new("$glob does not match $page");
  1910. }
  1911. }
  1912. sub match_internal ($$;@) {
  1913. return match_glob($_[0], $_[1], @_, internal => 1)
  1914. }
  1915. sub match_link ($$;@) {
  1916. my $page=shift;
  1917. my $link=lc(shift);
  1918. my %params=@_;
  1919. $link=derel($link, $params{location});
  1920. my $from=exists $params{location} ? $params{location} : '';
  1921. my $links = $IkiWiki::links{$page};
  1922. return IkiWiki::FailReason->new("$page has no links")
  1923. unless $links && @{$links};
  1924. my $bestlink = IkiWiki::bestlink($from, $link);
  1925. foreach my $p (@{$links}) {
  1926. if (length $bestlink) {
  1927. return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS)
  1928. if $bestlink eq IkiWiki::bestlink($page, $p);
  1929. }
  1930. else {
  1931. return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS)
  1932. if match_glob($p, $link, %params);
  1933. my ($p_rel)=$p=~/^\/?(.*)/;
  1934. $link=~s/^\///;
  1935. return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS)
  1936. if match_glob($p_rel, $link, %params);
  1937. }
  1938. }
  1939. return IkiWiki::FailReason->new("$page does not link to $link");
  1940. }
  1941. sub match_backlink ($$;@) {
  1942. my $ret=match_link($_[1], $_[0], @_);
  1943. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  1944. return $ret;
  1945. }
  1946. sub match_created_before ($$;@) {
  1947. my $page=shift;
  1948. my $testpage=shift;
  1949. my %params=@_;
  1950. $testpage=derel($testpage, $params{location});
  1951. if (exists $IkiWiki::pagectime{$testpage}) {
  1952. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1953. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1954. }
  1955. else {
  1956. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1957. }
  1958. }
  1959. else {
  1960. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1961. }
  1962. }
  1963. sub match_created_after ($$;@) {
  1964. my $page=shift;
  1965. my $testpage=shift;
  1966. my %params=@_;
  1967. $testpage=derel($testpage, $params{location});
  1968. if (exists $IkiWiki::pagectime{$testpage}) {
  1969. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1970. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1971. }
  1972. else {
  1973. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1974. }
  1975. }
  1976. else {
  1977. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1978. }
  1979. }
  1980. sub match_creation_day ($$;@) {
  1981. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1982. return IkiWiki::SuccessReason->new('creation_day matched');
  1983. }
  1984. else {
  1985. return IkiWiki::FailReason->new('creation_day did not match');
  1986. }
  1987. }
  1988. sub match_creation_month ($$;@) {
  1989. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1990. return IkiWiki::SuccessReason->new('creation_month matched');
  1991. }
  1992. else {
  1993. return IkiWiki::FailReason->new('creation_month did not match');
  1994. }
  1995. }
  1996. sub match_creation_year ($$;@) {
  1997. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1998. return IkiWiki::SuccessReason->new('creation_year matched');
  1999. }
  2000. else {
  2001. return IkiWiki::FailReason->new('creation_year did not match');
  2002. }
  2003. }
  2004. sub match_user ($$;@) {
  2005. shift;
  2006. my $user=shift;
  2007. my %params=@_;
  2008. if (! exists $params{user}) {
  2009. return IkiWiki::ErrorReason->new("no user specified");
  2010. }
  2011. if (defined $params{user} && lc $params{user} eq lc $user) {
  2012. return IkiWiki::SuccessReason->new("user is $user");
  2013. }
  2014. elsif (! defined $params{user}) {
  2015. return IkiWiki::FailReason->new("not logged in");
  2016. }
  2017. else {
  2018. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2019. }
  2020. }
  2021. sub match_admin ($$;@) {
  2022. shift;
  2023. shift;
  2024. my %params=@_;
  2025. if (! exists $params{user}) {
  2026. return IkiWiki::ErrorReason->new("no user specified");
  2027. }
  2028. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2029. return IkiWiki::SuccessReason->new("user is an admin");
  2030. }
  2031. elsif (! defined $params{user}) {
  2032. return IkiWiki::FailReason->new("not logged in");
  2033. }
  2034. else {
  2035. return IkiWiki::FailReason->new("user is not an admin");
  2036. }
  2037. }
  2038. sub match_ip ($$;@) {
  2039. shift;
  2040. my $ip=shift;
  2041. my %params=@_;
  2042. if (! exists $params{ip}) {
  2043. return IkiWiki::ErrorReason->new("no IP specified");
  2044. }
  2045. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2046. return IkiWiki::SuccessReason->new("IP is $ip");
  2047. }
  2048. else {
  2049. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2050. }
  2051. }
  2052. 1