summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 00eadfd9818e6e41adc36457b6bb45361355817b (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 ngettext 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. clean => {
  406. type => "internal",
  407. default => 0,
  408. description => "running in clean mode",
  409. safe => 0,
  410. rebuild => 0,
  411. },
  412. refresh => {
  413. type => "internal",
  414. default => 0,
  415. description => "running in refresh mode",
  416. safe => 0,
  417. rebuild => 0,
  418. },
  419. test_receive => {
  420. type => "internal",
  421. default => 0,
  422. description => "running in receive test mode",
  423. safe => 0,
  424. rebuild => 0,
  425. },
  426. getctime => {
  427. type => "internal",
  428. default => 0,
  429. description => "running in getctime mode",
  430. safe => 0,
  431. rebuild => 0,
  432. },
  433. w3mmode => {
  434. type => "internal",
  435. default => 0,
  436. description => "running in w3mmode",
  437. safe => 0,
  438. rebuild => 0,
  439. },
  440. wikistatedir => {
  441. type => "internal",
  442. default => undef,
  443. description => "path to the .ikiwiki directory holding ikiwiki state",
  444. safe => 0,
  445. rebuild => 0,
  446. },
  447. setupfile => {
  448. type => "internal",
  449. default => undef,
  450. description => "path to setup file",
  451. safe => 0,
  452. rebuild => 0,
  453. },
  454. allow_symlinks_before_srcdir => {
  455. type => "boolean",
  456. default => 0,
  457. description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
  458. safe => 0,
  459. rebuild => 0,
  460. },
  461. }
  462. sub defaultconfig () {
  463. my %s=getsetup();
  464. my @ret;
  465. foreach my $key (keys %s) {
  466. push @ret, $key, $s{$key}->{default};
  467. }
  468. use Data::Dumper;
  469. return @ret;
  470. }
  471. sub checkconfig () {
  472. # locale stuff; avoid LC_ALL since it overrides everything
  473. if (defined $ENV{LC_ALL}) {
  474. $ENV{LANG} = $ENV{LC_ALL};
  475. delete $ENV{LC_ALL};
  476. }
  477. if (defined $config{locale}) {
  478. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  479. $ENV{LANG}=$config{locale};
  480. define_gettext();
  481. }
  482. }
  483. if (! defined $config{wiki_file_regexp}) {
  484. $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
  485. }
  486. if (ref $config{ENV} eq 'HASH') {
  487. foreach my $val (keys %{$config{ENV}}) {
  488. $ENV{$val}=$config{ENV}{$val};
  489. }
  490. }
  491. if ($config{w3mmode}) {
  492. eval q{use Cwd q{abs_path}};
  493. error($@) if $@;
  494. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  495. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  496. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  497. unless $config{cgiurl} =~ m!file:///!;
  498. $config{url}="file://".$config{destdir};
  499. }
  500. if ($config{cgi} && ! length $config{url}) {
  501. error(gettext("Must specify url to wiki with --url when using --cgi"));
  502. }
  503. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  504. unless exists $config{wikistatedir} && defined $config{wikistatedir};
  505. if (defined $config{umask}) {
  506. umask(possibly_foolish_untaint($config{umask}));
  507. }
  508. run_hooks(checkconfig => sub { shift->() });
  509. return 1;
  510. }
  511. sub listplugins () {
  512. my %ret;
  513. foreach my $dir (@INC, $config{libdir}) {
  514. next unless defined $dir && length $dir;
  515. foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
  516. my ($plugin)=$file=~/.*\/(.*)\.pm$/;
  517. $ret{$plugin}=1;
  518. }
  519. }
  520. foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
  521. next unless defined $dir && length $dir;
  522. foreach my $file (glob("$dir/plugins/*")) {
  523. $ret{basename($file)}=1 if -x $file;
  524. }
  525. }
  526. return keys %ret;
  527. }
  528. sub loadplugins () {
  529. if (defined $config{libdir} && length $config{libdir}) {
  530. unshift @INC, possibly_foolish_untaint($config{libdir});
  531. }
  532. foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
  533. loadplugin($plugin);
  534. }
  535. if ($config{rcs}) {
  536. if (exists $hooks{rcs}) {
  537. error(gettext("cannot use multiple rcs plugins"));
  538. }
  539. loadplugin($config{rcs});
  540. }
  541. if (! exists $hooks{rcs}) {
  542. loadplugin("norcs");
  543. }
  544. run_hooks(getopt => sub { shift->() });
  545. if (grep /^-/, @ARGV) {
  546. print STDERR "Unknown option (or missing parameter): $_\n"
  547. foreach grep /^-/, @ARGV;
  548. usage();
  549. }
  550. return 1;
  551. }
  552. sub loadplugin ($) {
  553. my $plugin=shift;
  554. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  555. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  556. "$installdir/lib/ikiwiki") {
  557. if (defined $dir && -x "$dir/plugins/$plugin") {
  558. eval { require IkiWiki::Plugin::external };
  559. if ($@) {
  560. my $reason=$@;
  561. error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
  562. }
  563. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  564. $loaded_plugins{$plugin}=1;
  565. return 1;
  566. }
  567. }
  568. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  569. eval qq{use $mod};
  570. if ($@) {
  571. error("Failed to load plugin $mod: $@");
  572. }
  573. $loaded_plugins{$plugin}=1;
  574. return 1;
  575. }
  576. sub error ($;$) {
  577. my $message=shift;
  578. my $cleaner=shift;
  579. log_message('err' => $message) if $config{syslog};
  580. if (defined $cleaner) {
  581. $cleaner->();
  582. }
  583. die $message."\n";
  584. }
  585. sub debug ($) {
  586. return unless $config{verbose};
  587. return log_message(debug => @_);
  588. }
  589. my $log_open=0;
  590. sub log_message ($$) {
  591. my $type=shift;
  592. if ($config{syslog}) {
  593. require Sys::Syslog;
  594. if (! $log_open) {
  595. Sys::Syslog::setlogsock('unix');
  596. Sys::Syslog::openlog('ikiwiki', '', 'user');
  597. $log_open=1;
  598. }
  599. return eval {
  600. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  601. };
  602. }
  603. elsif (! $config{cgi}) {
  604. return print "@_\n";
  605. }
  606. else {
  607. return print STDERR "@_\n";
  608. }
  609. }
  610. sub possibly_foolish_untaint ($) {
  611. my $tainted=shift;
  612. my ($untainted)=$tainted=~/(.*)/s;
  613. return $untainted;
  614. }
  615. sub basename ($) {
  616. my $file=shift;
  617. $file=~s!.*/+!!;
  618. return $file;
  619. }
  620. sub dirname ($) {
  621. my $file=shift;
  622. $file=~s!/*[^/]+$!!;
  623. return $file;
  624. }
  625. sub isinternal ($) {
  626. my $page=shift;
  627. return exists $pagesources{$page} &&
  628. $pagesources{$page} =~ /\._([^.]+)$/;
  629. }
  630. sub pagetype ($) {
  631. my $file=shift;
  632. if ($file =~ /\.([^.]+)$/) {
  633. return $1 if exists $hooks{htmlize}{$1};
  634. }
  635. my $base=basename($file);
  636. if (exists $hooks{htmlize}{$base} &&
  637. $hooks{htmlize}{$base}{noextension}) {
  638. return $base;
  639. }
  640. return;
  641. }
  642. my %pagename_cache;
  643. sub pagename ($) {
  644. my $file=shift;
  645. if (exists $pagename_cache{$file}) {
  646. return $pagename_cache{$file};
  647. }
  648. my $type=pagetype($file);
  649. my $page=$file;
  650. $page=~s/\Q.$type\E*$//
  651. if defined $type && !$hooks{htmlize}{$type}{keepextension}
  652. && !$hooks{htmlize}{$type}{noextension};
  653. if ($config{indexpages} && $page=~/(.*)\/index$/) {
  654. $page=$1;
  655. }
  656. $pagename_cache{$file} = $page;
  657. return $page;
  658. }
  659. sub newpagefile ($$) {
  660. my $page=shift;
  661. my $type=shift;
  662. if (! $config{indexpages} || $page eq 'index') {
  663. return $page.".".$type;
  664. }
  665. else {
  666. return $page."/index.".$type;
  667. }
  668. }
  669. sub targetpage ($$;$) {
  670. my $page=shift;
  671. my $ext=shift;
  672. my $filename=shift;
  673. if (defined $filename) {
  674. return $page."/".$filename.".".$ext;
  675. }
  676. elsif (! $config{usedirs} || $page eq 'index') {
  677. return $page.".".$ext;
  678. }
  679. else {
  680. return $page."/index.".$ext;
  681. }
  682. }
  683. sub htmlpage ($) {
  684. my $page=shift;
  685. return targetpage($page, $config{htmlext});
  686. }
  687. sub srcfile_stat {
  688. my $file=shift;
  689. my $nothrow=shift;
  690. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  691. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  692. return "$dir/$file", stat(_) if -e "$dir/$file";
  693. }
  694. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  695. return;
  696. }
  697. sub srcfile ($;$) {
  698. return (srcfile_stat(@_))[0];
  699. }
  700. sub add_underlay ($) {
  701. my $dir=shift;
  702. if ($dir !~ /^\//) {
  703. $dir="$config{underlaydirbase}/$dir";
  704. }
  705. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  706. unshift @{$config{underlaydirs}}, $dir;
  707. }
  708. return 1;
  709. }
  710. sub readfile ($;$$) {
  711. my $file=shift;
  712. my $binary=shift;
  713. my $wantfd=shift;
  714. if (-l $file) {
  715. error("cannot read a symlink ($file)");
  716. }
  717. local $/=undef;
  718. open (my $in, "<", $file) || error("failed to read $file: $!");
  719. binmode($in) if ($binary);
  720. return \*$in if $wantfd;
  721. my $ret=<$in>;
  722. # check for invalid utf-8, and toss it back to avoid crashes
  723. if (! utf8::valid($ret)) {
  724. $ret=encode_utf8($ret);
  725. }
  726. close $in || error("failed to read $file: $!");
  727. return $ret;
  728. }
  729. sub prep_writefile ($$) {
  730. my $file=shift;
  731. my $destdir=shift;
  732. my $test=$file;
  733. while (length $test) {
  734. if (-l "$destdir/$test") {
  735. error("cannot write to a symlink ($test)");
  736. }
  737. $test=dirname($test);
  738. }
  739. my $dir=dirname("$destdir/$file");
  740. if (! -d $dir) {
  741. my $d="";
  742. foreach my $s (split(m!/+!, $dir)) {
  743. $d.="$s/";
  744. if (! -d $d) {
  745. mkdir($d) || error("failed to create directory $d: $!");
  746. }
  747. }
  748. }
  749. return 1;
  750. }
  751. sub writefile ($$$;$$) {
  752. my $file=shift; # can include subdirs
  753. my $destdir=shift; # directory to put file in
  754. my $content=shift;
  755. my $binary=shift;
  756. my $writer=shift;
  757. prep_writefile($file, $destdir);
  758. my $newfile="$destdir/$file.ikiwiki-new";
  759. if (-l $newfile) {
  760. error("cannot write to a symlink ($newfile)");
  761. }
  762. my $cleanup = sub { unlink($newfile) };
  763. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  764. binmode($out) if ($binary);
  765. if ($writer) {
  766. $writer->(\*$out, $cleanup);
  767. }
  768. else {
  769. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  770. }
  771. close $out || error("failed saving $newfile: $!", $cleanup);
  772. rename($newfile, "$destdir/$file") ||
  773. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  774. return 1;
  775. }
  776. my %cleared;
  777. sub will_render ($$;$) {
  778. my $page=shift;
  779. my $dest=shift;
  780. my $clear=shift;
  781. # Important security check.
  782. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  783. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  784. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  785. }
  786. if (! $clear || $cleared{$page}) {
  787. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  788. }
  789. else {
  790. foreach my $old (@{$renderedfiles{$page}}) {
  791. delete $destsources{$old};
  792. }
  793. $renderedfiles{$page}=[$dest];
  794. $cleared{$page}=1;
  795. }
  796. $destsources{$dest}=$page;
  797. return 1;
  798. }
  799. sub bestlink ($$) {
  800. my $page=shift;
  801. my $link=shift;
  802. my $cwd=$page;
  803. if ($link=~s/^\/+//) {
  804. # absolute links
  805. $cwd="";
  806. }
  807. $link=~s/\/$//;
  808. do {
  809. my $l=$cwd;
  810. $l.="/" if length $l;
  811. $l.=$link;
  812. if (exists $pagesources{$l}) {
  813. return $l;
  814. }
  815. elsif (exists $pagecase{lc $l}) {
  816. return $pagecase{lc $l};
  817. }
  818. } while $cwd=~s{/?[^/]+$}{};
  819. if (length $config{userdir}) {
  820. my $l = "$config{userdir}/".lc($link);
  821. if (exists $pagesources{$l}) {
  822. return $l;
  823. }
  824. elsif (exists $pagecase{lc $l}) {
  825. return $pagecase{lc $l};
  826. }
  827. }
  828. #print STDERR "warning: page $page, broken link: $link\n";
  829. return "";
  830. }
  831. sub isinlinableimage ($) {
  832. my $file=shift;
  833. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  834. }
  835. sub pagetitle ($;$) {
  836. my $page=shift;
  837. my $unescaped=shift;
  838. if ($unescaped) {
  839. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  840. }
  841. else {
  842. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  843. }
  844. return $page;
  845. }
  846. sub titlepage ($) {
  847. my $title=shift;
  848. # support use w/o %config set
  849. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  850. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  851. return $title;
  852. }
  853. sub linkpage ($) {
  854. my $link=shift;
  855. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  856. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  857. return $link;
  858. }
  859. sub cgiurl (@) {
  860. my %params=@_;
  861. my $cgiurl=$config{cgiurl};
  862. if (exists $params{cgiurl}) {
  863. $cgiurl=$params{cgiurl};
  864. delete $params{cgiurl};
  865. }
  866. return $cgiurl."?".
  867. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  868. }
  869. sub baseurl (;$) {
  870. my $page=shift;
  871. return "$config{url}/" if ! defined $page;
  872. $page=htmlpage($page);
  873. $page=~s/[^\/]+$//;
  874. $page=~s/[^\/]+\//..\//g;
  875. return $page;
  876. }
  877. sub abs2rel ($$) {
  878. # Work around very innefficient behavior in File::Spec if abs2rel
  879. # is passed two relative paths. It's much faster if paths are
  880. # absolute! (Debian bug #376658; fixed in debian unstable now)
  881. my $path="/".shift;
  882. my $base="/".shift;
  883. require File::Spec;
  884. my $ret=File::Spec->abs2rel($path, $base);
  885. $ret=~s/^// if defined $ret;
  886. return $ret;
  887. }
  888. sub displaytime ($;$) {
  889. # Plugins can override this function to mark up the time to
  890. # display.
  891. return '<span class="date">'.formattime(@_).'</span>';
  892. }
  893. sub formattime ($;$) {
  894. # Plugins can override this function to format the time.
  895. my $time=shift;
  896. my $format=shift;
  897. if (! defined $format) {
  898. $format=$config{timeformat};
  899. }
  900. # strftime doesn't know about encodings, so make sure
  901. # its output is properly treated as utf8
  902. return decode_utf8(POSIX::strftime($format, localtime($time)));
  903. }
  904. sub beautify_urlpath ($) {
  905. my $url=shift;
  906. # Ensure url is not an empty link, and if necessary,
  907. # add ./ to avoid colon confusion.
  908. if ($url !~ /^\// && $url !~ /^\.\.?\//) {
  909. $url="./$url";
  910. }
  911. if ($config{usedirs}) {
  912. $url =~ s!/index.$config{htmlext}$!/!;
  913. }
  914. return $url;
  915. }
  916. sub urlto ($$;$) {
  917. my $to=shift;
  918. my $from=shift;
  919. my $absolute=shift;
  920. if (! length $to) {
  921. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  922. }
  923. if (! $destsources{$to}) {
  924. $to=htmlpage($to);
  925. }
  926. if ($absolute) {
  927. return $config{url}.beautify_urlpath("/".$to);
  928. }
  929. my $link = abs2rel($to, dirname(htmlpage($from)));
  930. return beautify_urlpath($link);
  931. }
  932. sub htmllink ($$$;@) {
  933. my $lpage=shift; # the page doing the linking
  934. my $page=shift; # the page that will contain the link (different for inline)
  935. my $link=shift;
  936. my %opts=@_;
  937. $link=~s/\/$//;
  938. my $bestlink;
  939. if (! $opts{forcesubpage}) {
  940. $bestlink=bestlink($lpage, $link);
  941. }
  942. else {
  943. $bestlink="$lpage/".lc($link);
  944. }
  945. my $linktext;
  946. if (defined $opts{linktext}) {
  947. $linktext=$opts{linktext};
  948. }
  949. else {
  950. $linktext=pagetitle(basename($link));
  951. }
  952. return "<span class=\"selflink\">$linktext</span>"
  953. if length $bestlink && $page eq $bestlink &&
  954. ! defined $opts{anchor};
  955. if (! $destsources{$bestlink}) {
  956. $bestlink=htmlpage($bestlink);
  957. if (! $destsources{$bestlink}) {
  958. return $linktext unless length $config{cgiurl};
  959. return "<span class=\"createlink\"><a href=\"".
  960. cgiurl(
  961. do => "create",
  962. page => lc($link),
  963. from => $lpage
  964. ).
  965. "\" rel=\"nofollow\">?</a>$linktext</span>"
  966. }
  967. }
  968. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  969. $bestlink=beautify_urlpath($bestlink);
  970. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  971. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  972. }
  973. if (defined $opts{anchor}) {
  974. $bestlink.="#".$opts{anchor};
  975. }
  976. my @attrs;
  977. foreach my $attr (qw{rel class title}) {
  978. if (defined $opts{$attr}) {
  979. push @attrs, " $attr=\"$opts{$attr}\"";
  980. }
  981. }
  982. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  983. }
  984. sub userpage ($) {
  985. my $user=shift;
  986. return length $config{userdir} ? "$config{userdir}/$user" : $user;
  987. }
  988. sub openiduser ($) {
  989. my $user=shift;
  990. if ($user =~ m!^https?://! &&
  991. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  992. my $display;
  993. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  994. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  995. }
  996. else {
  997. # backcompat with old version
  998. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  999. $display=$oid->display;
  1000. }
  1001. # Convert "user.somehost.com" to "user [somehost.com]"
  1002. # (also "user.somehost.co.uk")
  1003. if ($display !~ /\[/) {
  1004. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  1005. }
  1006. # Convert "http://somehost.com/user" to "user [somehost.com]".
  1007. # (also "https://somehost.com/user/")
  1008. if ($display !~ /\[/) {
  1009. $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
  1010. }
  1011. $display=~s!^https?://!!; # make sure this is removed
  1012. eval q{use CGI 'escapeHTML'};
  1013. error($@) if $@;
  1014. return escapeHTML($display);
  1015. }
  1016. return;
  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{$line};
  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. # Add explicit dependencies for influences.
  1579. my $sub=pagespec_translate($pagespec);
  1580. return if $@;
  1581. foreach my $p (keys %pagesources) {
  1582. my $r=$sub->($p, location => $page);
  1583. my $i=$r->influences;
  1584. foreach my $k (keys %$i) {
  1585. $depends_simple{$page}{lc $k} |= $i->{$k};
  1586. }
  1587. last if $r->influences_static;
  1588. }
  1589. $depends{$page}{$pagespec} |= $deptype;
  1590. return 1;
  1591. }
  1592. sub deptype (@) {
  1593. my $deptype=0;
  1594. foreach my $type (@_) {
  1595. if ($type eq 'presence') {
  1596. $deptype |= $DEPEND_PRESENCE;
  1597. }
  1598. elsif ($type eq 'links') {
  1599. $deptype |= $DEPEND_LINKS;
  1600. }
  1601. elsif ($type eq 'content') {
  1602. $deptype |= $DEPEND_CONTENT;
  1603. }
  1604. }
  1605. return $deptype;
  1606. }
  1607. sub file_pruned ($;$) {
  1608. my $file=shift;
  1609. if (@_) {
  1610. require File::Spec;
  1611. $file=File::Spec->canonpath($file);
  1612. my $base=File::Spec->canonpath(shift);
  1613. return if $file eq $base;
  1614. $file =~ s#^\Q$base\E/+##;
  1615. }
  1616. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1617. return $file =~ m/$regexp/;
  1618. }
  1619. sub define_gettext () {
  1620. # If translation is needed, redefine the gettext function to do it.
  1621. # Otherwise, it becomes a quick no-op.
  1622. my $gettext_obj;
  1623. my $getobj;
  1624. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1625. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1626. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1627. $getobj=sub {
  1628. $gettext_obj=eval q{
  1629. use Locale::gettext q{textdomain};
  1630. Locale::gettext->domain('ikiwiki')
  1631. };
  1632. };
  1633. }
  1634. no warnings 'redefine';
  1635. *gettext=sub {
  1636. $getobj->() if $getobj;
  1637. if ($gettext_obj) {
  1638. $gettext_obj->get(shift);
  1639. }
  1640. else {
  1641. return shift;
  1642. }
  1643. };
  1644. *ngettext=sub {
  1645. $getobj->() if $getobj;
  1646. if ($gettext_obj) {
  1647. $gettext_obj->nget(@_);
  1648. }
  1649. else {
  1650. return ($_[2] == 1 ? $_[0] : $_[1])
  1651. }
  1652. };
  1653. }
  1654. sub gettext {
  1655. define_gettext();
  1656. gettext(@_);
  1657. }
  1658. sub ngettext {
  1659. define_gettext();
  1660. ngettext(@_);
  1661. }
  1662. sub yesno ($) {
  1663. my $val=shift;
  1664. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1665. }
  1666. sub inject {
  1667. # Injects a new function into the symbol table to replace an
  1668. # exported function.
  1669. my %params=@_;
  1670. # This is deep ugly perl foo, beware.
  1671. no strict;
  1672. no warnings;
  1673. if (! defined $params{parent}) {
  1674. $params{parent}='::';
  1675. $params{old}=\&{$params{name}};
  1676. $params{name}=~s/.*:://;
  1677. }
  1678. my $parent=$params{parent};
  1679. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1680. $ns = $params{parent} . $ns;
  1681. inject(%params, parent => $ns) unless $ns eq '::main::';
  1682. *{$ns . $params{name}} = $params{call}
  1683. if exists ${$ns}{$params{name}} &&
  1684. \&{${$ns}{$params{name}}} == $params{old};
  1685. }
  1686. use strict;
  1687. use warnings;
  1688. }
  1689. sub add_link ($$) {
  1690. my $page=shift;
  1691. my $link=shift;
  1692. push @{$links{$page}}, $link
  1693. unless grep { $_ eq $link } @{$links{$page}};
  1694. }
  1695. sub pagespec_translate ($) {
  1696. my $spec=shift;
  1697. # Convert spec to perl code.
  1698. my $code="";
  1699. my @data;
  1700. while ($spec=~m{
  1701. \s* # ignore whitespace
  1702. ( # 1: match a single word
  1703. \! # !
  1704. |
  1705. \( # (
  1706. |
  1707. \) # )
  1708. |
  1709. \w+\([^\)]*\) # command(params)
  1710. |
  1711. [^\s()]+ # any other text
  1712. )
  1713. \s* # ignore whitespace
  1714. }gx) {
  1715. my $word=$1;
  1716. if (lc $word eq 'and') {
  1717. $code.=' &';
  1718. }
  1719. elsif (lc $word eq 'or') {
  1720. $code.=' |';
  1721. }
  1722. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1723. $code.=' '.$word;
  1724. }
  1725. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1726. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1727. push @data, $2;
  1728. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1729. }
  1730. else {
  1731. push @data, qq{unknown function in pagespec "$word"};
  1732. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1733. }
  1734. }
  1735. else {
  1736. push @data, $word;
  1737. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1738. }
  1739. }
  1740. if (! length $code) {
  1741. $code="IkiWiki::FailReason->new('empty pagespec')";
  1742. }
  1743. no warnings;
  1744. return eval 'sub { my $page=shift; '.$code.' }';
  1745. }
  1746. sub pagespec_match ($$;@) {
  1747. my $page=shift;
  1748. my $spec=shift;
  1749. my @params=@_;
  1750. # Backwards compatability with old calling convention.
  1751. if (@params == 1) {
  1752. unshift @params, 'location';
  1753. }
  1754. my $sub=pagespec_translate($spec);
  1755. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1756. if $@ || ! defined $sub;
  1757. return $sub->($page, @params);
  1758. }
  1759. sub pagespec_match_list ($$;@) {
  1760. my $page=shift;
  1761. my $pagespec=shift;
  1762. my %params=@_;
  1763. # Backwards compatability with old calling convention.
  1764. if (ref $page) {
  1765. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1766. $params{list}=$page;
  1767. $page=$params{location}; # ugh!
  1768. }
  1769. my $sub=pagespec_translate($pagespec);
  1770. error "syntax error in pagespec \"$pagespec\""
  1771. if $@ || ! defined $sub;
  1772. my @candidates;
  1773. if (exists $params{list}) {
  1774. @candidates=exists $params{filter}
  1775. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1776. : @{$params{list}};
  1777. }
  1778. else {
  1779. @candidates=exists $params{filter}
  1780. ? grep { ! $params{filter}->($_) } keys %pagesources
  1781. : keys %pagesources;
  1782. }
  1783. if (defined $params{sort}) {
  1784. my $f;
  1785. if ($params{sort} eq 'title') {
  1786. $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
  1787. }
  1788. elsif ($params{sort} eq 'title_natural') {
  1789. eval q{use Sort::Naturally};
  1790. if ($@) {
  1791. error(gettext("Sort::Naturally needed for title_natural sort"));
  1792. }
  1793. $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
  1794. }
  1795. elsif ($params{sort} eq 'mtime') {
  1796. $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
  1797. }
  1798. elsif ($params{sort} eq 'age') {
  1799. $f=sub { $pagectime{$b} <=> $pagectime{$a} };
  1800. }
  1801. else {
  1802. error sprintf(gettext("unknown sort type %s"), $params{sort});
  1803. }
  1804. @candidates = sort { &$f } @candidates;
  1805. }
  1806. @candidates=reverse(@candidates) if $params{reverse};
  1807. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1808. # clear params, remainder is passed to pagespec
  1809. my $num=$params{num};
  1810. delete @params{qw{num deptype reverse sort filter list}};
  1811. my @matches;
  1812. my $firstfail;
  1813. my $count=0;
  1814. my $accum=IkiWiki::SuccessReason->new();
  1815. foreach my $p (@candidates) {
  1816. my $r=$sub->($p, %params, location => $page);
  1817. error(sprintf(gettext("cannot match pages: %s"), $r))
  1818. if $r->isa("IkiWiki::ErrorReason");
  1819. $accum |= $r;
  1820. if ($r) {
  1821. push @matches, $p;
  1822. last if defined $num && ++$count == $num;
  1823. }
  1824. }
  1825. # Add simple dependencies for accumulated influences.
  1826. my $i=$accum->influences;
  1827. foreach my $k (keys %$i) {
  1828. $depends_simple{$page}{lc $k} |= $i->{$k};
  1829. }
  1830. return @matches;
  1831. }
  1832. sub pagespec_valid ($) {
  1833. my $spec=shift;
  1834. my $sub=pagespec_translate($spec);
  1835. return ! $@;
  1836. }
  1837. sub glob2re ($) {
  1838. my $re=quotemeta(shift);
  1839. $re=~s/\\\*/.*/g;
  1840. $re=~s/\\\?/./g;
  1841. return $re;
  1842. }
  1843. package IkiWiki::FailReason;
  1844. use overload (
  1845. '""' => sub { $_[0][0] },
  1846. '0+' => sub { 0 },
  1847. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1848. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  1849. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1850. fallback => 1,
  1851. );
  1852. our @ISA = 'IkiWiki::SuccessReason';
  1853. package IkiWiki::SuccessReason;
  1854. use overload (
  1855. '""' => sub { $_[0][0] },
  1856. '0+' => sub { 1 },
  1857. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1858. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  1859. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1860. fallback => 1,
  1861. );
  1862. sub new {
  1863. my $class = shift;
  1864. my $value = shift;
  1865. return bless [$value, {@_}], $class;
  1866. }
  1867. sub influences {
  1868. my $this=shift;
  1869. $this->[1]={@_} if @_;
  1870. my %i=%{$this->[1]};
  1871. delete $i{""};
  1872. return \%i;
  1873. }
  1874. sub influences_static {
  1875. return ! $_[0][1]->{""};
  1876. }
  1877. sub merge_influences {
  1878. my $this=shift;
  1879. my $other=shift;
  1880. my $anded=shift;
  1881. if (! $anded || (($this || %{$this->[1]}) &&
  1882. ($other || %{$other->[1]}))) {
  1883. foreach my $influence (keys %{$other->[1]}) {
  1884. $this->[1]{$influence} |= $other->[1]{$influence};
  1885. }
  1886. }
  1887. else {
  1888. # influence blocker
  1889. $this->[1]={};
  1890. }
  1891. }
  1892. package IkiWiki::ErrorReason;
  1893. our @ISA = 'IkiWiki::FailReason';
  1894. package IkiWiki::PageSpec;
  1895. sub derel ($$) {
  1896. my $path=shift;
  1897. my $from=shift;
  1898. if ($path =~ m!^\./!) {
  1899. $from=~s#/?[^/]+$## if defined $from;
  1900. $path=~s#^\./##;
  1901. $path="$from/$path" if length $from;
  1902. }
  1903. return $path;
  1904. }
  1905. sub match_glob ($$;@) {
  1906. my $page=shift;
  1907. my $glob=shift;
  1908. my %params=@_;
  1909. $glob=derel($glob, $params{location});
  1910. my $regexp=IkiWiki::glob2re($glob);
  1911. if ($page=~/^$regexp$/i) {
  1912. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1913. return IkiWiki::SuccessReason->new("$glob matches $page");
  1914. }
  1915. else {
  1916. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1917. }
  1918. }
  1919. else {
  1920. return IkiWiki::FailReason->new("$glob does not match $page");
  1921. }
  1922. }
  1923. sub match_internal ($$;@) {
  1924. return match_glob($_[0], $_[1], @_, internal => 1)
  1925. }
  1926. sub match_link ($$;@) {
  1927. my $page=shift;
  1928. my $link=lc(shift);
  1929. my %params=@_;
  1930. $link=derel($link, $params{location});
  1931. my $from=exists $params{location} ? $params{location} : '';
  1932. my $links = $IkiWiki::links{$page};
  1933. return IkiWiki::FailReason->new("$page has no links", "" => 1)
  1934. unless $links && @{$links};
  1935. my $bestlink = IkiWiki::bestlink($from, $link);
  1936. foreach my $p (@{$links}) {
  1937. if (length $bestlink) {
  1938. return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1939. if $bestlink eq IkiWiki::bestlink($page, $p);
  1940. }
  1941. else {
  1942. return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1943. if match_glob($p, $link, %params);
  1944. my ($p_rel)=$p=~/^\/?(.*)/;
  1945. $link=~s/^\///;
  1946. return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1947. if match_glob($p_rel, $link, %params);
  1948. }
  1949. }
  1950. return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
  1951. }
  1952. sub match_backlink ($$;@) {
  1953. my $ret=match_link($_[1], $_[0], @_);
  1954. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  1955. return $ret;
  1956. }
  1957. sub match_created_before ($$;@) {
  1958. my $page=shift;
  1959. my $testpage=shift;
  1960. my %params=@_;
  1961. $testpage=derel($testpage, $params{location});
  1962. if (exists $IkiWiki::pagectime{$testpage}) {
  1963. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1964. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1965. }
  1966. else {
  1967. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1968. }
  1969. }
  1970. else {
  1971. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1972. }
  1973. }
  1974. sub match_created_after ($$;@) {
  1975. my $page=shift;
  1976. my $testpage=shift;
  1977. my %params=@_;
  1978. $testpage=derel($testpage, $params{location});
  1979. if (exists $IkiWiki::pagectime{$testpage}) {
  1980. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1981. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1982. }
  1983. else {
  1984. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1985. }
  1986. }
  1987. else {
  1988. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1989. }
  1990. }
  1991. sub match_creation_day ($$;@) {
  1992. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1993. return IkiWiki::SuccessReason->new('creation_day matched');
  1994. }
  1995. else {
  1996. return IkiWiki::FailReason->new('creation_day did not match');
  1997. }
  1998. }
  1999. sub match_creation_month ($$;@) {
  2000. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2001. return IkiWiki::SuccessReason->new('creation_month matched');
  2002. }
  2003. else {
  2004. return IkiWiki::FailReason->new('creation_month did not match');
  2005. }
  2006. }
  2007. sub match_creation_year ($$;@) {
  2008. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2009. return IkiWiki::SuccessReason->new('creation_year matched');
  2010. }
  2011. else {
  2012. return IkiWiki::FailReason->new('creation_year did not match');
  2013. }
  2014. }
  2015. sub match_user ($$;@) {
  2016. shift;
  2017. my $user=shift;
  2018. my %params=@_;
  2019. my $regexp=IkiWiki::glob2re($user);
  2020. if (! exists $params{user}) {
  2021. return IkiWiki::ErrorReason->new("no user specified");
  2022. }
  2023. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2024. return IkiWiki::SuccessReason->new("user is $user");
  2025. }
  2026. elsif (! defined $params{user}) {
  2027. return IkiWiki::FailReason->new("not logged in");
  2028. }
  2029. else {
  2030. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2031. }
  2032. }
  2033. sub match_admin ($$;@) {
  2034. shift;
  2035. shift;
  2036. my %params=@_;
  2037. if (! exists $params{user}) {
  2038. return IkiWiki::ErrorReason->new("no user specified");
  2039. }
  2040. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2041. return IkiWiki::SuccessReason->new("user is an admin");
  2042. }
  2043. elsif (! defined $params{user}) {
  2044. return IkiWiki::FailReason->new("not logged in");
  2045. }
  2046. else {
  2047. return IkiWiki::FailReason->new("user is not an admin");
  2048. }
  2049. }
  2050. sub match_ip ($$;@) {
  2051. shift;
  2052. my $ip=shift;
  2053. my %params=@_;
  2054. if (! exists $params{ip}) {
  2055. return IkiWiki::ErrorReason->new("no IP specified");
  2056. }
  2057. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2058. return IkiWiki::SuccessReason->new("IP is $ip");
  2059. }
  2060. else {
  2061. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2062. }
  2063. }
  2064. 1