summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 0cbc847887b1b6d8493268e41721a7f8d8784a32 (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/sanitizers
  1059. $content=~s/^<p>//i;
  1060. $content=~s/<\/p>\n*$//i;
  1061. }
  1062. return $content;
  1063. }
  1064. sub linkify ($$$) {
  1065. my $page=shift;
  1066. my $destpage=shift;
  1067. my $content=shift;
  1068. run_hooks(linkify => sub {
  1069. $content=shift->(
  1070. page => $page,
  1071. destpage => $destpage,
  1072. content => $content,
  1073. );
  1074. });
  1075. return $content;
  1076. }
  1077. our %preprocessing;
  1078. our $preprocess_preview=0;
  1079. sub preprocess ($$$;$$) {
  1080. my $page=shift; # the page the data comes from
  1081. my $destpage=shift; # the page the data will appear in (different for inline)
  1082. my $content=shift;
  1083. my $scan=shift;
  1084. my $preview=shift;
  1085. # Using local because it needs to be set within any nested calls
  1086. # of this function.
  1087. local $preprocess_preview=$preview if defined $preview;
  1088. my $handle=sub {
  1089. my $escape=shift;
  1090. my $prefix=shift;
  1091. my $command=shift;
  1092. my $params=shift;
  1093. $params="" if ! defined $params;
  1094. if (length $escape) {
  1095. return "[[$prefix$command $params]]";
  1096. }
  1097. elsif (exists $hooks{preprocess}{$command}) {
  1098. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1099. # Note: preserve order of params, some plugins may
  1100. # consider it significant.
  1101. my @params;
  1102. while ($params =~ m{
  1103. (?:([-\w]+)=)? # 1: named parameter key?
  1104. (?:
  1105. """(.*?)""" # 2: triple-quoted value
  1106. |
  1107. "([^"]*?)" # 3: single-quoted value
  1108. |
  1109. (\S+) # 4: unquoted value
  1110. )
  1111. (?:\s+|$) # delimiter to next param
  1112. }sgx) {
  1113. my $key=$1;
  1114. my $val;
  1115. if (defined $2) {
  1116. $val=$2;
  1117. $val=~s/\r\n/\n/mg;
  1118. $val=~s/^\n+//g;
  1119. $val=~s/\n+$//g;
  1120. }
  1121. elsif (defined $3) {
  1122. $val=$3;
  1123. }
  1124. elsif (defined $4) {
  1125. $val=$4;
  1126. }
  1127. if (defined $key) {
  1128. push @params, $key, $val;
  1129. }
  1130. else {
  1131. push @params, $val, '';
  1132. }
  1133. }
  1134. if ($preprocessing{$page}++ > 3) {
  1135. # Avoid loops of preprocessed pages preprocessing
  1136. # other pages that preprocess them, etc.
  1137. return "[[!$command <span class=\"error\">".
  1138. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1139. $page, $preprocessing{$page}).
  1140. "</span>]]";
  1141. }
  1142. my $ret;
  1143. if (! $scan) {
  1144. $ret=eval {
  1145. $hooks{preprocess}{$command}{call}->(
  1146. @params,
  1147. page => $page,
  1148. destpage => $destpage,
  1149. preview => $preprocess_preview,
  1150. );
  1151. };
  1152. if ($@) {
  1153. my $error=$@;
  1154. chomp $error;
  1155. $ret="[[!$command <span class=\"error\">".
  1156. gettext("Error").": $error"."</span>]]";
  1157. }
  1158. }
  1159. else {
  1160. # use void context during scan pass
  1161. eval {
  1162. $hooks{preprocess}{$command}{call}->(
  1163. @params,
  1164. page => $page,
  1165. destpage => $destpage,
  1166. preview => $preprocess_preview,
  1167. );
  1168. };
  1169. $ret="";
  1170. }
  1171. $preprocessing{$page}--;
  1172. return $ret;
  1173. }
  1174. else {
  1175. return "[[$prefix$command $params]]";
  1176. }
  1177. };
  1178. my $regex;
  1179. if ($config{prefix_directives}) {
  1180. $regex = qr{
  1181. (\\?) # 1: escape?
  1182. \[\[(!) # directive open; 2: prefix
  1183. ([-\w]+) # 3: command
  1184. ( # 4: the parameters..
  1185. \s+ # Must have space if parameters present
  1186. (?:
  1187. (?:[-\w]+=)? # named parameter key?
  1188. (?:
  1189. """.*?""" # triple-quoted value
  1190. |
  1191. "[^"]*?" # single-quoted value
  1192. |
  1193. [^"\s\]]+ # unquoted value
  1194. )
  1195. \s* # whitespace or end
  1196. # of directive
  1197. )
  1198. *)? # 0 or more parameters
  1199. \]\] # directive closed
  1200. }sx;
  1201. }
  1202. else {
  1203. $regex = qr{
  1204. (\\?) # 1: escape?
  1205. \[\[(!?) # directive open; 2: optional prefix
  1206. ([-\w]+) # 3: command
  1207. \s+
  1208. ( # 4: the parameters..
  1209. (?:
  1210. (?:[-\w]+=)? # named parameter key?
  1211. (?:
  1212. """.*?""" # triple-quoted value
  1213. |
  1214. "[^"]*?" # single-quoted value
  1215. |
  1216. [^"\s\]]+ # unquoted value
  1217. )
  1218. \s* # whitespace or end
  1219. # of directive
  1220. )
  1221. *) # 0 or more parameters
  1222. \]\] # directive closed
  1223. }sx;
  1224. }
  1225. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1226. return $content;
  1227. }
  1228. sub filter ($$$) {
  1229. my $page=shift;
  1230. my $destpage=shift;
  1231. my $content=shift;
  1232. run_hooks(filter => sub {
  1233. $content=shift->(page => $page, destpage => $destpage,
  1234. content => $content);
  1235. });
  1236. return $content;
  1237. }
  1238. sub indexlink () {
  1239. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1240. }
  1241. sub check_canedit ($$$;$) {
  1242. my $page=shift;
  1243. my $q=shift;
  1244. my $session=shift;
  1245. my $nonfatal=shift;
  1246. my $canedit;
  1247. run_hooks(canedit => sub {
  1248. return if defined $canedit;
  1249. my $ret=shift->($page, $q, $session);
  1250. if (defined $ret) {
  1251. if ($ret eq "") {
  1252. $canedit=1;
  1253. }
  1254. elsif (ref $ret eq 'CODE') {
  1255. $ret->() unless $nonfatal;
  1256. $canedit=0;
  1257. }
  1258. elsif (defined $ret) {
  1259. error($ret) unless $nonfatal;
  1260. $canedit=0;
  1261. }
  1262. }
  1263. });
  1264. return defined $canedit ? $canedit : 1;
  1265. }
  1266. sub check_content (@) {
  1267. my %params=@_;
  1268. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1269. if (exists $pagesources{$params{page}}) {
  1270. my @diff;
  1271. my %old=map { $_ => 1 }
  1272. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1273. foreach my $line (split("\n", $params{content})) {
  1274. push @diff, $line if ! exists $old{$line};
  1275. }
  1276. $params{diff}=join("\n", @diff);
  1277. }
  1278. my $ok;
  1279. run_hooks(checkcontent => sub {
  1280. return if defined $ok;
  1281. my $ret=shift->(%params);
  1282. if (defined $ret) {
  1283. if ($ret eq "") {
  1284. $ok=1;
  1285. }
  1286. elsif (ref $ret eq 'CODE') {
  1287. $ret->() unless $params{nonfatal};
  1288. $ok=0;
  1289. }
  1290. elsif (defined $ret) {
  1291. error($ret) unless $params{nonfatal};
  1292. $ok=0;
  1293. }
  1294. }
  1295. });
  1296. return defined $ok ? $ok : 1;
  1297. }
  1298. my $wikilock;
  1299. sub lockwiki () {
  1300. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1301. # run issues. The lock will be dropped on program exit.
  1302. if (! -d $config{wikistatedir}) {
  1303. mkdir($config{wikistatedir});
  1304. }
  1305. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1306. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1307. if (! flock($wikilock, 2)) { # LOCK_EX
  1308. error("failed to get lock");
  1309. }
  1310. return 1;
  1311. }
  1312. sub unlockwiki () {
  1313. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1314. return close($wikilock) if $wikilock;
  1315. return;
  1316. }
  1317. my $commitlock;
  1318. sub commit_hook_enabled () {
  1319. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1320. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1321. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1322. close($commitlock) || error("failed closing commitlock: $!");
  1323. return 0;
  1324. }
  1325. close($commitlock) || error("failed closing commitlock: $!");
  1326. return 1;
  1327. }
  1328. sub disable_commit_hook () {
  1329. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1330. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1331. if (! flock($commitlock, 2)) { # LOCK_EX
  1332. error("failed to get commit lock");
  1333. }
  1334. return 1;
  1335. }
  1336. sub enable_commit_hook () {
  1337. return close($commitlock) if $commitlock;
  1338. return;
  1339. }
  1340. sub loadindex () {
  1341. %oldrenderedfiles=%pagectime=();
  1342. if (! $config{rebuild}) {
  1343. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1344. %destsources=%renderedfiles=%pagecase=%pagestate=
  1345. %depends_simple=();
  1346. }
  1347. my $in;
  1348. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1349. if (-e "$config{wikistatedir}/index") {
  1350. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1351. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1352. }
  1353. else {
  1354. return;
  1355. }
  1356. }
  1357. my $index=Storable::fd_retrieve($in);
  1358. if (! defined $index) {
  1359. return 0;
  1360. }
  1361. my $pages;
  1362. if (exists $index->{version} && ! ref $index->{version}) {
  1363. $pages=$index->{page};
  1364. %wikistate=%{$index->{state}};
  1365. }
  1366. else {
  1367. $pages=$index;
  1368. %wikistate=();
  1369. }
  1370. foreach my $src (keys %$pages) {
  1371. my $d=$pages->{$src};
  1372. my $page=pagename($src);
  1373. $pagectime{$page}=$d->{ctime};
  1374. if (! $config{rebuild}) {
  1375. $pagesources{$page}=$src;
  1376. $pagemtime{$page}=$d->{mtime};
  1377. $renderedfiles{$page}=$d->{dest};
  1378. if (exists $d->{links} && ref $d->{links}) {
  1379. $links{$page}=$d->{links};
  1380. $oldlinks{$page}=[@{$d->{links}}];
  1381. }
  1382. if (ref $d->{depends_simple} eq 'ARRAY') {
  1383. # old format
  1384. $depends_simple{$page}={
  1385. map { $_ => 1 } @{$d->{depends_simple}}
  1386. };
  1387. }
  1388. elsif (exists $d->{depends_simple}) {
  1389. $depends_simple{$page}=$d->{depends_simple};
  1390. }
  1391. if (exists $d->{dependslist}) {
  1392. # old format
  1393. $depends{$page}={
  1394. map { $_ => $DEPEND_CONTENT }
  1395. @{$d->{dependslist}}
  1396. };
  1397. }
  1398. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1399. # old format
  1400. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1401. }
  1402. elsif (exists $d->{depends}) {
  1403. $depends{$page}=$d->{depends};
  1404. }
  1405. if (exists $d->{state}) {
  1406. $pagestate{$page}=$d->{state};
  1407. }
  1408. }
  1409. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1410. }
  1411. foreach my $page (keys %pagesources) {
  1412. $pagecase{lc $page}=$page;
  1413. }
  1414. foreach my $page (keys %renderedfiles) {
  1415. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1416. }
  1417. return close($in);
  1418. }
  1419. sub saveindex () {
  1420. run_hooks(savestate => sub { shift->() });
  1421. my %hookids;
  1422. foreach my $type (keys %hooks) {
  1423. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1424. }
  1425. my @hookids=keys %hookids;
  1426. if (! -d $config{wikistatedir}) {
  1427. mkdir($config{wikistatedir});
  1428. }
  1429. my $newfile="$config{wikistatedir}/indexdb.new";
  1430. my $cleanup = sub { unlink($newfile) };
  1431. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1432. my %index;
  1433. foreach my $page (keys %pagemtime) {
  1434. next unless $pagemtime{$page};
  1435. my $src=$pagesources{$page};
  1436. $index{page}{$src}={
  1437. ctime => $pagectime{$page},
  1438. mtime => $pagemtime{$page},
  1439. dest => $renderedfiles{$page},
  1440. links => $links{$page},
  1441. };
  1442. if (exists $depends{$page}) {
  1443. $index{page}{$src}{depends} = $depends{$page};
  1444. }
  1445. if (exists $depends_simple{$page}) {
  1446. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1447. }
  1448. if (exists $pagestate{$page}) {
  1449. foreach my $id (@hookids) {
  1450. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1451. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1452. }
  1453. }
  1454. }
  1455. }
  1456. $index{state}={};
  1457. foreach my $id (@hookids) {
  1458. foreach my $key (keys %{$wikistate{$id}}) {
  1459. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1460. }
  1461. }
  1462. $index{version}="3";
  1463. my $ret=Storable::nstore_fd(\%index, $out);
  1464. return if ! defined $ret || ! $ret;
  1465. close $out || error("failed saving to $newfile: $!", $cleanup);
  1466. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1467. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1468. return 1;
  1469. }
  1470. sub template_file ($) {
  1471. my $template=shift;
  1472. foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
  1473. "$installdir/share/ikiwiki/templates") {
  1474. return "$dir/$template" if -e "$dir/$template";
  1475. }
  1476. return;
  1477. }
  1478. sub template_params (@) {
  1479. my $filename=template_file(shift);
  1480. if (! defined $filename) {
  1481. return if wantarray;
  1482. return "";
  1483. }
  1484. my @ret=(
  1485. filter => sub {
  1486. my $text_ref = shift;
  1487. ${$text_ref} = decode_utf8(${$text_ref});
  1488. },
  1489. filename => $filename,
  1490. loop_context_vars => 1,
  1491. die_on_bad_params => 0,
  1492. @_
  1493. );
  1494. return wantarray ? @ret : {@ret};
  1495. }
  1496. sub template ($;@) {
  1497. require HTML::Template;
  1498. return HTML::Template->new(template_params(@_));
  1499. }
  1500. sub misctemplate ($$;@) {
  1501. my $title=shift;
  1502. my $pagebody=shift;
  1503. my $template=template("misc.tmpl");
  1504. $template->param(
  1505. title => $title,
  1506. indexlink => indexlink(),
  1507. wikiname => $config{wikiname},
  1508. pagebody => $pagebody,
  1509. baseurl => baseurl(),
  1510. @_,
  1511. );
  1512. run_hooks(pagetemplate => sub {
  1513. shift->(page => "", destpage => "", template => $template);
  1514. });
  1515. return $template->output;
  1516. }
  1517. sub hook (@) {
  1518. my %param=@_;
  1519. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1520. error 'hook requires type, call, and id parameters';
  1521. }
  1522. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1523. $hooks{$param{type}}{$param{id}}=\%param;
  1524. return 1;
  1525. }
  1526. sub run_hooks ($$) {
  1527. # Calls the given sub for each hook of the given type,
  1528. # passing it the hook function to call.
  1529. my $type=shift;
  1530. my $sub=shift;
  1531. if (exists $hooks{$type}) {
  1532. my (@first, @middle, @last);
  1533. foreach my $id (keys %{$hooks{$type}}) {
  1534. if ($hooks{$type}{$id}{first}) {
  1535. push @first, $id;
  1536. }
  1537. elsif ($hooks{$type}{$id}{last}) {
  1538. push @last, $id;
  1539. }
  1540. else {
  1541. push @middle, $id;
  1542. }
  1543. }
  1544. foreach my $id (@first, @middle, @last) {
  1545. $sub->($hooks{$type}{$id}{call});
  1546. }
  1547. }
  1548. return 1;
  1549. }
  1550. sub rcs_update () {
  1551. $hooks{rcs}{rcs_update}{call}->(@_);
  1552. }
  1553. sub rcs_prepedit ($) {
  1554. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1555. }
  1556. sub rcs_commit ($$$;$$) {
  1557. $hooks{rcs}{rcs_commit}{call}->(@_);
  1558. }
  1559. sub rcs_commit_staged ($$$) {
  1560. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1561. }
  1562. sub rcs_add ($) {
  1563. $hooks{rcs}{rcs_add}{call}->(@_);
  1564. }
  1565. sub rcs_remove ($) {
  1566. $hooks{rcs}{rcs_remove}{call}->(@_);
  1567. }
  1568. sub rcs_rename ($$) {
  1569. $hooks{rcs}{rcs_rename}{call}->(@_);
  1570. }
  1571. sub rcs_recentchanges ($) {
  1572. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1573. }
  1574. sub rcs_diff ($) {
  1575. $hooks{rcs}{rcs_diff}{call}->(@_);
  1576. }
  1577. sub rcs_getctime ($) {
  1578. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1579. }
  1580. sub rcs_receive () {
  1581. $hooks{rcs}{rcs_receive}{call}->();
  1582. }
  1583. sub add_depends ($$;$) {
  1584. my $page=shift;
  1585. my $pagespec=shift;
  1586. my $deptype=shift || $DEPEND_CONTENT;
  1587. # Is the pagespec a simple page name?
  1588. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1589. $pagespec !~ /[\s*?()!]/) {
  1590. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1591. return 1;
  1592. }
  1593. # Add explicit dependencies for influences.
  1594. my $sub=pagespec_translate($pagespec);
  1595. return unless defined $sub;
  1596. foreach my $p (keys %pagesources) {
  1597. my $r=$sub->($p, location => $page);
  1598. my $i=$r->influences;
  1599. foreach my $k (keys %$i) {
  1600. $depends_simple{$page}{lc $k} |= $i->{$k};
  1601. }
  1602. last if $r->influences_static;
  1603. }
  1604. $depends{$page}{$pagespec} |= $deptype;
  1605. return 1;
  1606. }
  1607. sub deptype (@) {
  1608. my $deptype=0;
  1609. foreach my $type (@_) {
  1610. if ($type eq 'presence') {
  1611. $deptype |= $DEPEND_PRESENCE;
  1612. }
  1613. elsif ($type eq 'links') {
  1614. $deptype |= $DEPEND_LINKS;
  1615. }
  1616. elsif ($type eq 'content') {
  1617. $deptype |= $DEPEND_CONTENT;
  1618. }
  1619. }
  1620. return $deptype;
  1621. }
  1622. my $file_prune_regexp;
  1623. sub file_pruned ($;$) {
  1624. my $file=shift;
  1625. if (@_) {
  1626. require File::Spec;
  1627. $file=File::Spec->canonpath($file);
  1628. my $base=File::Spec->canonpath(shift);
  1629. return if $file eq $base;
  1630. $file =~ s#^\Q$base\E/+##;
  1631. }
  1632. if (defined $config{include} && length $config{include}) {
  1633. return 0 if $file =~ m/$config{include}/;
  1634. }
  1635. if (! defined $file_prune_regexp) {
  1636. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1637. $file_prune_regexp=qr/$file_prune_regexp/;
  1638. }
  1639. return $file =~ m/$file_prune_regexp/;
  1640. }
  1641. sub define_gettext () {
  1642. # If translation is needed, redefine the gettext function to do it.
  1643. # Otherwise, it becomes a quick no-op.
  1644. my $gettext_obj;
  1645. my $getobj;
  1646. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1647. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1648. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1649. $getobj=sub {
  1650. $gettext_obj=eval q{
  1651. use Locale::gettext q{textdomain};
  1652. Locale::gettext->domain('ikiwiki')
  1653. };
  1654. };
  1655. }
  1656. no warnings 'redefine';
  1657. *gettext=sub {
  1658. $getobj->() if $getobj;
  1659. if ($gettext_obj) {
  1660. $gettext_obj->get(shift);
  1661. }
  1662. else {
  1663. return shift;
  1664. }
  1665. };
  1666. *ngettext=sub {
  1667. $getobj->() if $getobj;
  1668. if ($gettext_obj) {
  1669. $gettext_obj->nget(@_);
  1670. }
  1671. else {
  1672. return ($_[2] == 1 ? $_[0] : $_[1])
  1673. }
  1674. };
  1675. }
  1676. sub gettext {
  1677. define_gettext();
  1678. gettext(@_);
  1679. }
  1680. sub ngettext {
  1681. define_gettext();
  1682. ngettext(@_);
  1683. }
  1684. sub yesno ($) {
  1685. my $val=shift;
  1686. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1687. }
  1688. sub inject {
  1689. # Injects a new function into the symbol table to replace an
  1690. # exported function.
  1691. my %params=@_;
  1692. # This is deep ugly perl foo, beware.
  1693. no strict;
  1694. no warnings;
  1695. if (! defined $params{parent}) {
  1696. $params{parent}='::';
  1697. $params{old}=\&{$params{name}};
  1698. $params{name}=~s/.*:://;
  1699. }
  1700. my $parent=$params{parent};
  1701. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1702. $ns = $params{parent} . $ns;
  1703. inject(%params, parent => $ns) unless $ns eq '::main::';
  1704. *{$ns . $params{name}} = $params{call}
  1705. if exists ${$ns}{$params{name}} &&
  1706. \&{${$ns}{$params{name}}} == $params{old};
  1707. }
  1708. use strict;
  1709. use warnings;
  1710. }
  1711. sub add_link ($$) {
  1712. my $page=shift;
  1713. my $link=shift;
  1714. push @{$links{$page}}, $link
  1715. unless grep { $_ eq $link } @{$links{$page}};
  1716. }
  1717. sub pagespec_translate ($) {
  1718. my $spec=shift;
  1719. # Convert spec to perl code.
  1720. my $code="";
  1721. my @data;
  1722. while ($spec=~m{
  1723. \s* # ignore whitespace
  1724. ( # 1: match a single word
  1725. \! # !
  1726. |
  1727. \( # (
  1728. |
  1729. \) # )
  1730. |
  1731. \w+\([^\)]*\) # command(params)
  1732. |
  1733. [^\s()]+ # any other text
  1734. )
  1735. \s* # ignore whitespace
  1736. }gx) {
  1737. my $word=$1;
  1738. if (lc $word eq 'and') {
  1739. $code.=' &';
  1740. }
  1741. elsif (lc $word eq 'or') {
  1742. $code.=' |';
  1743. }
  1744. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1745. $code.=' '.$word;
  1746. }
  1747. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1748. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1749. push @data, $2;
  1750. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1751. }
  1752. else {
  1753. push @data, qq{unknown function in pagespec "$word"};
  1754. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1755. }
  1756. }
  1757. else {
  1758. push @data, $word;
  1759. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1760. }
  1761. }
  1762. if (! length $code) {
  1763. $code="IkiWiki::FailReason->new('empty pagespec')";
  1764. }
  1765. no warnings;
  1766. return eval 'sub { my $page=shift; '.$code.' }';
  1767. }
  1768. sub pagespec_match ($$;@) {
  1769. my $page=shift;
  1770. my $spec=shift;
  1771. my @params=@_;
  1772. # Backwards compatability with old calling convention.
  1773. if (@params == 1) {
  1774. unshift @params, 'location';
  1775. }
  1776. my $sub=pagespec_translate($spec);
  1777. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1778. if ! defined $sub;
  1779. return $sub->($page, @params);
  1780. }
  1781. sub pagespec_match_list ($$;@) {
  1782. my $page=shift;
  1783. my $pagespec=shift;
  1784. my %params=@_;
  1785. # Backwards compatability with old calling convention.
  1786. if (ref $page) {
  1787. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1788. $params{list}=$page;
  1789. $page=$params{location}; # ugh!
  1790. }
  1791. my $sub=pagespec_translate($pagespec);
  1792. error "syntax error in pagespec \"$pagespec\""
  1793. if ! defined $sub;
  1794. my @candidates;
  1795. if (exists $params{list}) {
  1796. @candidates=exists $params{filter}
  1797. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1798. : @{$params{list}};
  1799. }
  1800. else {
  1801. @candidates=exists $params{filter}
  1802. ? grep { ! $params{filter}->($_) } keys %pagesources
  1803. : keys %pagesources;
  1804. }
  1805. if (defined $params{sort}) {
  1806. my $f;
  1807. if ($params{sort} eq 'title') {
  1808. $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
  1809. }
  1810. elsif ($params{sort} eq 'title_natural') {
  1811. eval q{use Sort::Naturally};
  1812. if ($@) {
  1813. error(gettext("Sort::Naturally needed for title_natural sort"));
  1814. }
  1815. $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
  1816. }
  1817. elsif ($params{sort} eq 'mtime') {
  1818. $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
  1819. }
  1820. elsif ($params{sort} eq 'age') {
  1821. $f=sub { $pagectime{$b} <=> $pagectime{$a} };
  1822. }
  1823. else {
  1824. error sprintf(gettext("unknown sort type %s"), $params{sort});
  1825. }
  1826. @candidates = sort { &$f } @candidates;
  1827. }
  1828. @candidates=reverse(@candidates) if $params{reverse};
  1829. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1830. # clear params, remainder is passed to pagespec
  1831. my $num=$params{num};
  1832. delete @params{qw{num deptype reverse sort filter list}};
  1833. my @matches;
  1834. my $firstfail;
  1835. my $count=0;
  1836. my $accum=IkiWiki::SuccessReason->new();
  1837. foreach my $p (@candidates) {
  1838. my $r=$sub->($p, %params, location => $page);
  1839. error(sprintf(gettext("cannot match pages: %s"), $r))
  1840. if $r->isa("IkiWiki::ErrorReason");
  1841. $accum |= $r;
  1842. if ($r) {
  1843. push @matches, $p;
  1844. last if defined $num && ++$count == $num;
  1845. }
  1846. }
  1847. # Add simple dependencies for accumulated influences.
  1848. my $i=$accum->influences;
  1849. foreach my $k (keys %$i) {
  1850. $depends_simple{$page}{lc $k} |= $i->{$k};
  1851. }
  1852. return @matches;
  1853. }
  1854. sub pagespec_valid ($) {
  1855. my $spec=shift;
  1856. return defined pagespec_translate($spec);
  1857. }
  1858. sub glob2re ($) {
  1859. my $re=quotemeta(shift);
  1860. $re=~s/\\\*/.*/g;
  1861. $re=~s/\\\?/./g;
  1862. return $re;
  1863. }
  1864. package IkiWiki::FailReason;
  1865. use overload (
  1866. '""' => sub { $_[0][0] },
  1867. '0+' => sub { 0 },
  1868. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1869. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  1870. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1871. fallback => 1,
  1872. );
  1873. our @ISA = 'IkiWiki::SuccessReason';
  1874. package IkiWiki::SuccessReason;
  1875. use overload (
  1876. '""' => sub { $_[0][0] },
  1877. '0+' => sub { 1 },
  1878. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1879. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  1880. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1881. fallback => 1,
  1882. );
  1883. sub new {
  1884. my $class = shift;
  1885. my $value = shift;
  1886. return bless [$value, {@_}], $class;
  1887. }
  1888. sub influences {
  1889. my $this=shift;
  1890. $this->[1]={@_} if @_;
  1891. my %i=%{$this->[1]};
  1892. delete $i{""};
  1893. return \%i;
  1894. }
  1895. sub influences_static {
  1896. return ! $_[0][1]->{""};
  1897. }
  1898. sub merge_influences {
  1899. my $this=shift;
  1900. my $other=shift;
  1901. my $anded=shift;
  1902. if (! $anded || (($this || %{$this->[1]}) &&
  1903. ($other || %{$other->[1]}))) {
  1904. foreach my $influence (keys %{$other->[1]}) {
  1905. $this->[1]{$influence} |= $other->[1]{$influence};
  1906. }
  1907. }
  1908. else {
  1909. # influence blocker
  1910. $this->[1]={};
  1911. }
  1912. }
  1913. package IkiWiki::ErrorReason;
  1914. our @ISA = 'IkiWiki::FailReason';
  1915. package IkiWiki::PageSpec;
  1916. sub derel ($$) {
  1917. my $path=shift;
  1918. my $from=shift;
  1919. if ($path =~ m!^\./!) {
  1920. $from=~s#/?[^/]+$## if defined $from;
  1921. $path=~s#^\./##;
  1922. $path="$from/$path" if length $from;
  1923. }
  1924. return $path;
  1925. }
  1926. sub match_glob ($$;@) {
  1927. my $page=shift;
  1928. my $glob=shift;
  1929. my %params=@_;
  1930. $glob=derel($glob, $params{location});
  1931. my $regexp=IkiWiki::glob2re($glob);
  1932. if ($page=~/^$regexp$/i) {
  1933. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1934. return IkiWiki::SuccessReason->new("$glob matches $page");
  1935. }
  1936. else {
  1937. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1938. }
  1939. }
  1940. else {
  1941. return IkiWiki::FailReason->new("$glob does not match $page");
  1942. }
  1943. }
  1944. sub match_internal ($$;@) {
  1945. return match_glob($_[0], $_[1], @_, internal => 1)
  1946. }
  1947. sub match_link ($$;@) {
  1948. my $page=shift;
  1949. my $link=lc(shift);
  1950. my %params=@_;
  1951. $link=derel($link, $params{location});
  1952. my $from=exists $params{location} ? $params{location} : '';
  1953. my $links = $IkiWiki::links{$page};
  1954. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1955. unless $links && @{$links};
  1956. my $bestlink = IkiWiki::bestlink($from, $link);
  1957. foreach my $p (@{$links}) {
  1958. if (length $bestlink) {
  1959. return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1960. if $bestlink eq IkiWiki::bestlink($page, $p);
  1961. }
  1962. else {
  1963. return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1964. if match_glob($p, $link, %params);
  1965. my ($p_rel)=$p=~/^\/?(.*)/;
  1966. $link=~s/^\///;
  1967. return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  1968. if match_glob($p_rel, $link, %params);
  1969. }
  1970. }
  1971. return IkiWiki::FailReason->new("$page does not link to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  1972. }
  1973. sub match_backlink ($$;@) {
  1974. my $ret=match_link($_[1], $_[0], @_);
  1975. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  1976. return $ret;
  1977. }
  1978. sub match_created_before ($$;@) {
  1979. my $page=shift;
  1980. my $testpage=shift;
  1981. my %params=@_;
  1982. $testpage=derel($testpage, $params{location});
  1983. if (exists $IkiWiki::pagectime{$testpage}) {
  1984. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1985. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1986. }
  1987. else {
  1988. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1989. }
  1990. }
  1991. else {
  1992. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  1993. }
  1994. }
  1995. sub match_created_after ($$;@) {
  1996. my $page=shift;
  1997. my $testpage=shift;
  1998. my %params=@_;
  1999. $testpage=derel($testpage, $params{location});
  2000. if (exists $IkiWiki::pagectime{$testpage}) {
  2001. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2002. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2003. }
  2004. else {
  2005. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2006. }
  2007. }
  2008. else {
  2009. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2010. }
  2011. }
  2012. sub match_creation_day ($$;@) {
  2013. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2014. return IkiWiki::SuccessReason->new('creation_day matched');
  2015. }
  2016. else {
  2017. return IkiWiki::FailReason->new('creation_day did not match');
  2018. }
  2019. }
  2020. sub match_creation_month ($$;@) {
  2021. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2022. return IkiWiki::SuccessReason->new('creation_month matched');
  2023. }
  2024. else {
  2025. return IkiWiki::FailReason->new('creation_month did not match');
  2026. }
  2027. }
  2028. sub match_creation_year ($$;@) {
  2029. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2030. return IkiWiki::SuccessReason->new('creation_year matched');
  2031. }
  2032. else {
  2033. return IkiWiki::FailReason->new('creation_year did not match');
  2034. }
  2035. }
  2036. sub match_user ($$;@) {
  2037. shift;
  2038. my $user=shift;
  2039. my %params=@_;
  2040. my $regexp=IkiWiki::glob2re($user);
  2041. if (! exists $params{user}) {
  2042. return IkiWiki::ErrorReason->new("no user specified");
  2043. }
  2044. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2045. return IkiWiki::SuccessReason->new("user is $user");
  2046. }
  2047. elsif (! defined $params{user}) {
  2048. return IkiWiki::FailReason->new("not logged in");
  2049. }
  2050. else {
  2051. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2052. }
  2053. }
  2054. sub match_admin ($$;@) {
  2055. shift;
  2056. shift;
  2057. my %params=@_;
  2058. if (! exists $params{user}) {
  2059. return IkiWiki::ErrorReason->new("no user specified");
  2060. }
  2061. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2062. return IkiWiki::SuccessReason->new("user is an admin");
  2063. }
  2064. elsif (! defined $params{user}) {
  2065. return IkiWiki::FailReason->new("not logged in");
  2066. }
  2067. else {
  2068. return IkiWiki::FailReason->new("user is not an admin");
  2069. }
  2070. }
  2071. sub match_ip ($$;@) {
  2072. shift;
  2073. my $ip=shift;
  2074. my %params=@_;
  2075. if (! exists $params{ip}) {
  2076. return IkiWiki::ErrorReason->new("no IP specified");
  2077. }
  2078. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2079. return IkiWiki::SuccessReason->new("IP is $ip");
  2080. }
  2081. else {
  2082. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2083. }
  2084. }
  2085. 1