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