summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: b37b1f34485b6301dfd7847d75ebb625e8c6295d (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 %typedlinks %oldtypedlinks};
  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 %typedlinks);
  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. gettime => {
  437. type => "internal",
  438. description => "running in gettime 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=%typedlinks=%oldtypedlinks=();
  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. $config{gettime}=1; # first build
  1355. return;
  1356. }
  1357. }
  1358. my $index=Storable::fd_retrieve($in);
  1359. if (! defined $index) {
  1360. return 0;
  1361. }
  1362. my $pages;
  1363. if (exists $index->{version} && ! ref $index->{version}) {
  1364. $pages=$index->{page};
  1365. %wikistate=%{$index->{state}};
  1366. }
  1367. else {
  1368. $pages=$index;
  1369. %wikistate=();
  1370. }
  1371. foreach my $src (keys %$pages) {
  1372. my $d=$pages->{$src};
  1373. my $page=pagename($src);
  1374. $pagectime{$page}=$d->{ctime};
  1375. if (! $config{rebuild}) {
  1376. $pagesources{$page}=$src;
  1377. $pagemtime{$page}=$d->{mtime};
  1378. $renderedfiles{$page}=$d->{dest};
  1379. if (exists $d->{links} && ref $d->{links}) {
  1380. $links{$page}=$d->{links};
  1381. $oldlinks{$page}=[@{$d->{links}}];
  1382. }
  1383. if (ref $d->{depends_simple} eq 'ARRAY') {
  1384. # old format
  1385. $depends_simple{$page}={
  1386. map { $_ => 1 } @{$d->{depends_simple}}
  1387. };
  1388. }
  1389. elsif (exists $d->{depends_simple}) {
  1390. $depends_simple{$page}=$d->{depends_simple};
  1391. }
  1392. if (exists $d->{dependslist}) {
  1393. # old format
  1394. $depends{$page}={
  1395. map { $_ => $DEPEND_CONTENT }
  1396. @{$d->{dependslist}}
  1397. };
  1398. }
  1399. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1400. # old format
  1401. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1402. }
  1403. elsif (exists $d->{depends}) {
  1404. $depends{$page}=$d->{depends};
  1405. }
  1406. if (exists $d->{state}) {
  1407. $pagestate{$page}=$d->{state};
  1408. }
  1409. if (exists $d->{typedlinks}) {
  1410. $typedlinks{$page}=$d->{typedlinks};
  1411. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1412. next unless %$links;
  1413. $oldtypedlinks{$page}{$type} = {%$links};
  1414. }
  1415. }
  1416. }
  1417. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1418. }
  1419. foreach my $page (keys %pagesources) {
  1420. $pagecase{lc $page}=$page;
  1421. }
  1422. foreach my $page (keys %renderedfiles) {
  1423. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1424. }
  1425. return close($in);
  1426. }
  1427. sub saveindex () {
  1428. run_hooks(savestate => sub { shift->() });
  1429. my %hookids;
  1430. foreach my $type (keys %hooks) {
  1431. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1432. }
  1433. my @hookids=keys %hookids;
  1434. if (! -d $config{wikistatedir}) {
  1435. mkdir($config{wikistatedir});
  1436. }
  1437. my $newfile="$config{wikistatedir}/indexdb.new";
  1438. my $cleanup = sub { unlink($newfile) };
  1439. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1440. my %index;
  1441. foreach my $page (keys %pagemtime) {
  1442. next unless $pagemtime{$page};
  1443. my $src=$pagesources{$page};
  1444. $index{page}{$src}={
  1445. ctime => $pagectime{$page},
  1446. mtime => $pagemtime{$page},
  1447. dest => $renderedfiles{$page},
  1448. links => $links{$page},
  1449. };
  1450. if (exists $depends{$page}) {
  1451. $index{page}{$src}{depends} = $depends{$page};
  1452. }
  1453. if (exists $depends_simple{$page}) {
  1454. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1455. }
  1456. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1457. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1458. }
  1459. if (exists $pagestate{$page}) {
  1460. foreach my $id (@hookids) {
  1461. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1462. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1463. }
  1464. }
  1465. }
  1466. }
  1467. $index{state}={};
  1468. foreach my $id (@hookids) {
  1469. foreach my $key (keys %{$wikistate{$id}}) {
  1470. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1471. }
  1472. }
  1473. $index{version}="3";
  1474. my $ret=Storable::nstore_fd(\%index, $out);
  1475. return if ! defined $ret || ! $ret;
  1476. close $out || error("failed saving to $newfile: $!", $cleanup);
  1477. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1478. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1479. return 1;
  1480. }
  1481. sub template_file ($) {
  1482. my $template=shift;
  1483. foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
  1484. "$installdir/share/ikiwiki/templates") {
  1485. return "$dir/$template" if -e "$dir/$template";
  1486. }
  1487. return;
  1488. }
  1489. sub template_params (@) {
  1490. my $filename=template_file(shift);
  1491. if (! defined $filename) {
  1492. return if wantarray;
  1493. return "";
  1494. }
  1495. my @ret=(
  1496. filter => sub {
  1497. my $text_ref = shift;
  1498. ${$text_ref} = decode_utf8(${$text_ref});
  1499. },
  1500. filename => $filename,
  1501. loop_context_vars => 1,
  1502. die_on_bad_params => 0,
  1503. @_
  1504. );
  1505. return wantarray ? @ret : {@ret};
  1506. }
  1507. sub template ($;@) {
  1508. require HTML::Template;
  1509. return HTML::Template->new(template_params(@_));
  1510. }
  1511. sub misctemplate ($$;@) {
  1512. my $title=shift;
  1513. my $pagebody=shift;
  1514. my $template=template("misc.tmpl");
  1515. $template->param(
  1516. title => $title,
  1517. indexlink => indexlink(),
  1518. wikiname => $config{wikiname},
  1519. pagebody => $pagebody,
  1520. baseurl => baseurl(),
  1521. @_,
  1522. );
  1523. run_hooks(pagetemplate => sub {
  1524. shift->(page => "", destpage => "", template => $template);
  1525. });
  1526. return $template->output;
  1527. }
  1528. sub hook (@) {
  1529. my %param=@_;
  1530. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1531. error 'hook requires type, call, and id parameters';
  1532. }
  1533. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1534. $hooks{$param{type}}{$param{id}}=\%param;
  1535. return 1;
  1536. }
  1537. sub run_hooks ($$) {
  1538. # Calls the given sub for each hook of the given type,
  1539. # passing it the hook function to call.
  1540. my $type=shift;
  1541. my $sub=shift;
  1542. if (exists $hooks{$type}) {
  1543. my (@first, @middle, @last);
  1544. foreach my $id (keys %{$hooks{$type}}) {
  1545. if ($hooks{$type}{$id}{first}) {
  1546. push @first, $id;
  1547. }
  1548. elsif ($hooks{$type}{$id}{last}) {
  1549. push @last, $id;
  1550. }
  1551. else {
  1552. push @middle, $id;
  1553. }
  1554. }
  1555. foreach my $id (@first, @middle, @last) {
  1556. $sub->($hooks{$type}{$id}{call});
  1557. }
  1558. }
  1559. return 1;
  1560. }
  1561. sub rcs_update () {
  1562. $hooks{rcs}{rcs_update}{call}->(@_);
  1563. }
  1564. sub rcs_prepedit ($) {
  1565. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1566. }
  1567. sub rcs_commit ($$$;$$) {
  1568. $hooks{rcs}{rcs_commit}{call}->(@_);
  1569. }
  1570. sub rcs_commit_staged ($$$) {
  1571. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1572. }
  1573. sub rcs_add ($) {
  1574. $hooks{rcs}{rcs_add}{call}->(@_);
  1575. }
  1576. sub rcs_remove ($) {
  1577. $hooks{rcs}{rcs_remove}{call}->(@_);
  1578. }
  1579. sub rcs_rename ($$) {
  1580. $hooks{rcs}{rcs_rename}{call}->(@_);
  1581. }
  1582. sub rcs_recentchanges ($) {
  1583. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1584. }
  1585. sub rcs_diff ($) {
  1586. $hooks{rcs}{rcs_diff}{call}->(@_);
  1587. }
  1588. sub rcs_getctime ($) {
  1589. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1590. }
  1591. sub rcs_getmtime ($) {
  1592. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1593. }
  1594. sub rcs_receive () {
  1595. $hooks{rcs}{rcs_receive}{call}->();
  1596. }
  1597. sub add_depends ($$;$) {
  1598. my $page=shift;
  1599. my $pagespec=shift;
  1600. my $deptype=shift || $DEPEND_CONTENT;
  1601. # Is the pagespec a simple page name?
  1602. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1603. $pagespec !~ /[\s*?()!]/) {
  1604. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1605. return 1;
  1606. }
  1607. # Add explicit dependencies for influences.
  1608. my $sub=pagespec_translate($pagespec);
  1609. return unless defined $sub;
  1610. foreach my $p (keys %pagesources) {
  1611. my $r=$sub->($p, location => $page);
  1612. my $i=$r->influences;
  1613. foreach my $k (keys %$i) {
  1614. $depends_simple{$page}{lc $k} |= $i->{$k};
  1615. }
  1616. last if $r->influences_static;
  1617. }
  1618. $depends{$page}{$pagespec} |= $deptype;
  1619. return 1;
  1620. }
  1621. sub deptype (@) {
  1622. my $deptype=0;
  1623. foreach my $type (@_) {
  1624. if ($type eq 'presence') {
  1625. $deptype |= $DEPEND_PRESENCE;
  1626. }
  1627. elsif ($type eq 'links') {
  1628. $deptype |= $DEPEND_LINKS;
  1629. }
  1630. elsif ($type eq 'content') {
  1631. $deptype |= $DEPEND_CONTENT;
  1632. }
  1633. }
  1634. return $deptype;
  1635. }
  1636. my $file_prune_regexp;
  1637. sub file_pruned ($;$) {
  1638. my $file=shift;
  1639. if (@_) {
  1640. require File::Spec;
  1641. $file=File::Spec->canonpath($file);
  1642. my $base=File::Spec->canonpath(shift);
  1643. return if $file eq $base;
  1644. $file =~ s#^\Q$base\E/+##;
  1645. }
  1646. if (defined $config{include} && length $config{include}) {
  1647. return 0 if $file =~ m/$config{include}/;
  1648. }
  1649. if (! defined $file_prune_regexp) {
  1650. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1651. $file_prune_regexp=qr/$file_prune_regexp/;
  1652. }
  1653. return $file =~ m/$file_prune_regexp/;
  1654. }
  1655. sub define_gettext () {
  1656. # If translation is needed, redefine the gettext function to do it.
  1657. # Otherwise, it becomes a quick no-op.
  1658. my $gettext_obj;
  1659. my $getobj;
  1660. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1661. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1662. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1663. $getobj=sub {
  1664. $gettext_obj=eval q{
  1665. use Locale::gettext q{textdomain};
  1666. Locale::gettext->domain('ikiwiki')
  1667. };
  1668. };
  1669. }
  1670. no warnings 'redefine';
  1671. *gettext=sub {
  1672. $getobj->() if $getobj;
  1673. if ($gettext_obj) {
  1674. $gettext_obj->get(shift);
  1675. }
  1676. else {
  1677. return shift;
  1678. }
  1679. };
  1680. *ngettext=sub {
  1681. $getobj->() if $getobj;
  1682. if ($gettext_obj) {
  1683. $gettext_obj->nget(@_);
  1684. }
  1685. else {
  1686. return ($_[2] == 1 ? $_[0] : $_[1])
  1687. }
  1688. };
  1689. }
  1690. sub gettext {
  1691. define_gettext();
  1692. gettext(@_);
  1693. }
  1694. sub ngettext {
  1695. define_gettext();
  1696. ngettext(@_);
  1697. }
  1698. sub yesno ($) {
  1699. my $val=shift;
  1700. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1701. }
  1702. sub inject {
  1703. # Injects a new function into the symbol table to replace an
  1704. # exported function.
  1705. my %params=@_;
  1706. # This is deep ugly perl foo, beware.
  1707. no strict;
  1708. no warnings;
  1709. if (! defined $params{parent}) {
  1710. $params{parent}='::';
  1711. $params{old}=\&{$params{name}};
  1712. $params{name}=~s/.*:://;
  1713. }
  1714. my $parent=$params{parent};
  1715. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1716. $ns = $params{parent} . $ns;
  1717. inject(%params, parent => $ns) unless $ns eq '::main::';
  1718. *{$ns . $params{name}} = $params{call}
  1719. if exists ${$ns}{$params{name}} &&
  1720. \&{${$ns}{$params{name}}} == $params{old};
  1721. }
  1722. use strict;
  1723. use warnings;
  1724. }
  1725. sub add_link ($$;$) {
  1726. my $page=shift;
  1727. my $link=shift;
  1728. my $type=shift;
  1729. push @{$links{$page}}, $link
  1730. unless grep { $_ eq $link } @{$links{$page}};
  1731. if (defined $type) {
  1732. $typedlinks{$page}{$type}{$link} = 1;
  1733. }
  1734. }
  1735. sub sortspec_translate ($$) {
  1736. my $spec = shift;
  1737. my $reverse = shift;
  1738. my $code = "";
  1739. my @data;
  1740. while ($spec =~ m{
  1741. \s*
  1742. (-?) # group 1: perhaps negated
  1743. \s*
  1744. ( # group 2: a word
  1745. \w+\([^\)]*\) # command(params)
  1746. |
  1747. [^\s]+ # or anything else
  1748. )
  1749. \s*
  1750. }gx) {
  1751. my $negated = $1;
  1752. my $word = $2;
  1753. my $params = undef;
  1754. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1755. # command with parameters
  1756. $params = $2;
  1757. $word = $1;
  1758. }
  1759. elsif ($word !~ m/^\w+$/) {
  1760. error(sprintf(gettext("invalid sort type %s"), $word));
  1761. }
  1762. if (length $code) {
  1763. $code .= " || ";
  1764. }
  1765. if ($negated) {
  1766. $code .= "-";
  1767. }
  1768. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1769. if (defined $params) {
  1770. push @data, $params;
  1771. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1772. }
  1773. else {
  1774. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1775. }
  1776. }
  1777. else {
  1778. error(sprintf(gettext("unknown sort type %s"), $word));
  1779. }
  1780. }
  1781. if (! length $code) {
  1782. # undefined sorting method... sort arbitrarily
  1783. return sub { 0 };
  1784. }
  1785. if ($reverse) {
  1786. $code="-($code)";
  1787. }
  1788. no warnings;
  1789. return eval 'sub { '.$code.' }';
  1790. }
  1791. sub pagespec_translate ($) {
  1792. my $spec=shift;
  1793. # Convert spec to perl code.
  1794. my $code="";
  1795. my @data;
  1796. while ($spec=~m{
  1797. \s* # ignore whitespace
  1798. ( # 1: match a single word
  1799. \! # !
  1800. |
  1801. \( # (
  1802. |
  1803. \) # )
  1804. |
  1805. \w+\([^\)]*\) # command(params)
  1806. |
  1807. [^\s()]+ # any other text
  1808. )
  1809. \s* # ignore whitespace
  1810. }gx) {
  1811. my $word=$1;
  1812. if (lc $word eq 'and') {
  1813. $code.=' &';
  1814. }
  1815. elsif (lc $word eq 'or') {
  1816. $code.=' |';
  1817. }
  1818. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1819. $code.=' '.$word;
  1820. }
  1821. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1822. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1823. push @data, $2;
  1824. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1825. }
  1826. else {
  1827. push @data, qq{unknown function in pagespec "$word"};
  1828. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1829. }
  1830. }
  1831. else {
  1832. push @data, $word;
  1833. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1834. }
  1835. }
  1836. if (! length $code) {
  1837. $code="IkiWiki::FailReason->new('empty pagespec')";
  1838. }
  1839. no warnings;
  1840. return eval 'sub { my $page=shift; '.$code.' }';
  1841. }
  1842. sub pagespec_match ($$;@) {
  1843. my $page=shift;
  1844. my $spec=shift;
  1845. my @params=@_;
  1846. # Backwards compatability with old calling convention.
  1847. if (@params == 1) {
  1848. unshift @params, 'location';
  1849. }
  1850. my $sub=pagespec_translate($spec);
  1851. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1852. if ! defined $sub;
  1853. return $sub->($page, @params);
  1854. }
  1855. sub pagespec_match_list ($$;@) {
  1856. my $page=shift;
  1857. my $pagespec=shift;
  1858. my %params=@_;
  1859. # Backwards compatability with old calling convention.
  1860. if (ref $page) {
  1861. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1862. $params{list}=$page;
  1863. $page=$params{location}; # ugh!
  1864. }
  1865. my $sub=pagespec_translate($pagespec);
  1866. error "syntax error in pagespec \"$pagespec\""
  1867. if ! defined $sub;
  1868. my $sort=sortspec_translate($params{sort}, $params{reverse})
  1869. if defined $params{sort};
  1870. my @candidates;
  1871. if (exists $params{list}) {
  1872. @candidates=exists $params{filter}
  1873. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1874. : @{$params{list}};
  1875. }
  1876. else {
  1877. @candidates=exists $params{filter}
  1878. ? grep { ! $params{filter}->($_) } keys %pagesources
  1879. : keys %pagesources;
  1880. }
  1881. # clear params, remainder is passed to pagespec
  1882. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1883. my $num=$params{num};
  1884. delete @params{qw{num deptype reverse sort filter list}};
  1885. # when only the top matches will be returned, it's efficient to
  1886. # sort before matching to pagespec,
  1887. if (defined $num && defined $sort) {
  1888. @candidates=IkiWiki::SortSpec::sort_pages(
  1889. $sort, @candidates);
  1890. }
  1891. my @matches;
  1892. my $firstfail;
  1893. my $count=0;
  1894. my $accum=IkiWiki::SuccessReason->new();
  1895. foreach my $p (@candidates) {
  1896. my $r=$sub->($p, %params, location => $page);
  1897. error(sprintf(gettext("cannot match pages: %s"), $r))
  1898. if $r->isa("IkiWiki::ErrorReason");
  1899. $accum |= $r;
  1900. if ($r) {
  1901. push @matches, $p;
  1902. last if defined $num && ++$count == $num;
  1903. }
  1904. }
  1905. # Add simple dependencies for accumulated influences.
  1906. my $i=$accum->influences;
  1907. foreach my $k (keys %$i) {
  1908. $depends_simple{$page}{lc $k} |= $i->{$k};
  1909. }
  1910. # when all matches will be returned, it's efficient to
  1911. # sort after matching
  1912. if (! defined $num && defined $sort) {
  1913. return IkiWiki::SortSpec::sort_pages(
  1914. $sort, @matches);
  1915. }
  1916. else {
  1917. return @matches;
  1918. }
  1919. }
  1920. sub pagespec_valid ($) {
  1921. my $spec=shift;
  1922. return defined pagespec_translate($spec);
  1923. }
  1924. sub glob2re ($) {
  1925. my $re=quotemeta(shift);
  1926. $re=~s/\\\*/.*/g;
  1927. $re=~s/\\\?/./g;
  1928. return $re;
  1929. }
  1930. package IkiWiki::FailReason;
  1931. use overload (
  1932. '""' => sub { $_[0][0] },
  1933. '0+' => sub { 0 },
  1934. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1935. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  1936. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1937. fallback => 1,
  1938. );
  1939. our @ISA = 'IkiWiki::SuccessReason';
  1940. package IkiWiki::SuccessReason;
  1941. use overload (
  1942. '""' => sub { $_[0][0] },
  1943. '0+' => sub { 1 },
  1944. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1945. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  1946. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1947. fallback => 1,
  1948. );
  1949. sub new {
  1950. my $class = shift;
  1951. my $value = shift;
  1952. return bless [$value, {@_}], $class;
  1953. }
  1954. sub influences {
  1955. my $this=shift;
  1956. $this->[1]={@_} if @_;
  1957. my %i=%{$this->[1]};
  1958. delete $i{""};
  1959. return \%i;
  1960. }
  1961. sub influences_static {
  1962. return ! $_[0][1]->{""};
  1963. }
  1964. sub merge_influences {
  1965. my $this=shift;
  1966. my $other=shift;
  1967. my $anded=shift;
  1968. if (! $anded || (($this || %{$this->[1]}) &&
  1969. ($other || %{$other->[1]}))) {
  1970. foreach my $influence (keys %{$other->[1]}) {
  1971. $this->[1]{$influence} |= $other->[1]{$influence};
  1972. }
  1973. }
  1974. else {
  1975. # influence blocker
  1976. $this->[1]={};
  1977. }
  1978. }
  1979. package IkiWiki::ErrorReason;
  1980. our @ISA = 'IkiWiki::FailReason';
  1981. package IkiWiki::PageSpec;
  1982. sub derel ($$) {
  1983. my $path=shift;
  1984. my $from=shift;
  1985. if ($path =~ m!^\./!) {
  1986. $from=~s#/?[^/]+$## if defined $from;
  1987. $path=~s#^\./##;
  1988. $path="$from/$path" if length $from;
  1989. }
  1990. return $path;
  1991. }
  1992. sub match_glob ($$;@) {
  1993. my $page=shift;
  1994. my $glob=shift;
  1995. my %params=@_;
  1996. $glob=derel($glob, $params{location});
  1997. my $regexp=IkiWiki::glob2re($glob);
  1998. if ($page=~/^$regexp$/i) {
  1999. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2000. return IkiWiki::SuccessReason->new("$glob matches $page");
  2001. }
  2002. else {
  2003. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2004. }
  2005. }
  2006. else {
  2007. return IkiWiki::FailReason->new("$glob does not match $page");
  2008. }
  2009. }
  2010. sub match_internal ($$;@) {
  2011. return match_glob($_[0], $_[1], @_, internal => 1)
  2012. }
  2013. sub match_link ($$;@) {
  2014. my $page=shift;
  2015. my $link=lc(shift);
  2016. my %params=@_;
  2017. $link=derel($link, $params{location});
  2018. my $from=exists $params{location} ? $params{location} : '';
  2019. my $linktype=$params{linktype};
  2020. my $qualifier='';
  2021. if (defined $linktype) {
  2022. $qualifier=" with type $linktype";
  2023. }
  2024. my $links = $IkiWiki::links{$page};
  2025. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2026. unless $links && @{$links};
  2027. my $bestlink = IkiWiki::bestlink($from, $link);
  2028. foreach my $p (@{$links}) {
  2029. if (length $bestlink) {
  2030. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
  2031. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2032. }
  2033. }
  2034. else {
  2035. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
  2036. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2037. }
  2038. my ($p_rel)=$p=~/^\/?(.*)/;
  2039. $link=~s/^\///;
  2040. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
  2041. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2042. }
  2043. }
  2044. }
  2045. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2046. }
  2047. sub match_backlink ($$;@) {
  2048. my $ret=match_link($_[1], $_[0], @_);
  2049. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2050. return $ret;
  2051. }
  2052. sub match_created_before ($$;@) {
  2053. my $page=shift;
  2054. my $testpage=shift;
  2055. my %params=@_;
  2056. $testpage=derel($testpage, $params{location});
  2057. if (exists $IkiWiki::pagectime{$testpage}) {
  2058. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2059. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2060. }
  2061. else {
  2062. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2063. }
  2064. }
  2065. else {
  2066. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2067. }
  2068. }
  2069. sub match_created_after ($$;@) {
  2070. my $page=shift;
  2071. my $testpage=shift;
  2072. my %params=@_;
  2073. $testpage=derel($testpage, $params{location});
  2074. if (exists $IkiWiki::pagectime{$testpage}) {
  2075. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2076. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2077. }
  2078. else {
  2079. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2080. }
  2081. }
  2082. else {
  2083. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2084. }
  2085. }
  2086. sub match_creation_day ($$;@) {
  2087. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2088. return IkiWiki::SuccessReason->new('creation_day matched');
  2089. }
  2090. else {
  2091. return IkiWiki::FailReason->new('creation_day did not match');
  2092. }
  2093. }
  2094. sub match_creation_month ($$;@) {
  2095. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2096. return IkiWiki::SuccessReason->new('creation_month matched');
  2097. }
  2098. else {
  2099. return IkiWiki::FailReason->new('creation_month did not match');
  2100. }
  2101. }
  2102. sub match_creation_year ($$;@) {
  2103. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2104. return IkiWiki::SuccessReason->new('creation_year matched');
  2105. }
  2106. else {
  2107. return IkiWiki::FailReason->new('creation_year did not match');
  2108. }
  2109. }
  2110. sub match_user ($$;@) {
  2111. shift;
  2112. my $user=shift;
  2113. my %params=@_;
  2114. my $regexp=IkiWiki::glob2re($user);
  2115. if (! exists $params{user}) {
  2116. return IkiWiki::ErrorReason->new("no user specified");
  2117. }
  2118. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2119. return IkiWiki::SuccessReason->new("user is $user");
  2120. }
  2121. elsif (! defined $params{user}) {
  2122. return IkiWiki::FailReason->new("not logged in");
  2123. }
  2124. else {
  2125. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2126. }
  2127. }
  2128. sub match_admin ($$;@) {
  2129. shift;
  2130. shift;
  2131. my %params=@_;
  2132. if (! exists $params{user}) {
  2133. return IkiWiki::ErrorReason->new("no user specified");
  2134. }
  2135. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2136. return IkiWiki::SuccessReason->new("user is an admin");
  2137. }
  2138. elsif (! defined $params{user}) {
  2139. return IkiWiki::FailReason->new("not logged in");
  2140. }
  2141. else {
  2142. return IkiWiki::FailReason->new("user is not an admin");
  2143. }
  2144. }
  2145. sub match_ip ($$;@) {
  2146. shift;
  2147. my $ip=shift;
  2148. my %params=@_;
  2149. if (! exists $params{ip}) {
  2150. return IkiWiki::ErrorReason->new("no IP specified");
  2151. }
  2152. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2153. return IkiWiki::SuccessReason->new("IP is $ip");
  2154. }
  2155. else {
  2156. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2157. }
  2158. }
  2159. package IkiWiki::SortSpec;
  2160. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2161. # are easily available in this namespace, for cmp functions to use them.
  2162. sub sort_pages {
  2163. my $f=shift;
  2164. sort $f @_
  2165. }
  2166. sub cmp_title {
  2167. IkiWiki::pagetitle(IkiWiki::basename($a))
  2168. cmp
  2169. IkiWiki::pagetitle(IkiWiki::basename($b))
  2170. }
  2171. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2172. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2173. 1