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