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