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