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