summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: c22c75df828473d01bdd599287013b5bdfe9568d (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. %autofiles};
  16. use Exporter q{import};
  17. our @EXPORT = qw(hook debug error template htmlpage deptype
  18. add_depends pagespec_match pagespec_match_list bestlink
  19. htmllink readfile writefile pagetype srcfile pagename
  20. displaytime will_render gettext ngettext urlto targetpage
  21. add_underlay pagetitle titlepage linkpage newpagefile
  22. inject add_link add_autofile
  23. %config %links %pagestate %wikistate %renderedfiles
  24. %pagesources %destsources %typedlinks);
  25. our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
  26. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  27. our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  28. # Page dependency types.
  29. our $DEPEND_CONTENT=1;
  30. our $DEPEND_PRESENCE=2;
  31. our $DEPEND_LINKS=4;
  32. # Optimisation.
  33. use Memoize;
  34. memoize("abs2rel");
  35. memoize("sortspec_translate");
  36. memoize("pagespec_translate");
  37. memoize("template_file");
  38. sub getsetup () {
  39. wikiname => {
  40. type => "string",
  41. default => "wiki",
  42. description => "name of the wiki",
  43. safe => 1,
  44. rebuild => 1,
  45. },
  46. adminemail => {
  47. type => "string",
  48. default => undef,
  49. example => 'me@example.com',
  50. description => "contact email for wiki",
  51. safe => 1,
  52. rebuild => 0,
  53. },
  54. adminuser => {
  55. type => "string",
  56. default => [],
  57. description => "users who are wiki admins",
  58. safe => 1,
  59. rebuild => 0,
  60. },
  61. banned_users => {
  62. type => "string",
  63. default => [],
  64. description => "users who are banned from the wiki",
  65. safe => 1,
  66. rebuild => 0,
  67. },
  68. srcdir => {
  69. type => "string",
  70. default => undef,
  71. example => "$ENV{HOME}/wiki",
  72. description => "where the source of the wiki is located",
  73. safe => 0, # path
  74. rebuild => 1,
  75. },
  76. destdir => {
  77. type => "string",
  78. default => undef,
  79. example => "/var/www/wiki",
  80. description => "where to build the wiki",
  81. safe => 0, # path
  82. rebuild => 1,
  83. },
  84. url => {
  85. type => "string",
  86. default => '',
  87. example => "http://example.com/wiki",
  88. description => "base url to the wiki",
  89. safe => 1,
  90. rebuild => 1,
  91. },
  92. cgiurl => {
  93. type => "string",
  94. default => '',
  95. example => "http://example.com/wiki/ikiwiki.cgi",
  96. description => "url to the ikiwiki.cgi",
  97. safe => 1,
  98. rebuild => 1,
  99. },
  100. cgi_wrapper => {
  101. type => "string",
  102. default => '',
  103. example => "/var/www/wiki/ikiwiki.cgi",
  104. description => "filename of cgi wrapper to generate",
  105. safe => 0, # file
  106. rebuild => 0,
  107. },
  108. cgi_wrappermode => {
  109. type => "string",
  110. default => '06755',
  111. description => "mode for cgi_wrapper (can safely be made suid)",
  112. safe => 0,
  113. rebuild => 0,
  114. },
  115. rcs => {
  116. type => "string",
  117. default => '',
  118. description => "rcs backend to use",
  119. safe => 0, # don't allow overriding
  120. rebuild => 0,
  121. },
  122. default_plugins => {
  123. type => "internal",
  124. default => [qw{mdwn link inline meta htmlscrubber passwordauth
  125. openid signinedit lockedit conditional
  126. recentchanges parentlinks editpage}],
  127. description => "plugins to enable by default",
  128. safe => 0,
  129. rebuild => 1,
  130. },
  131. add_plugins => {
  132. type => "string",
  133. default => [],
  134. description => "plugins to add to the default configuration",
  135. safe => 1,
  136. rebuild => 1,
  137. },
  138. disable_plugins => {
  139. type => "string",
  140. default => [],
  141. description => "plugins to disable",
  142. safe => 1,
  143. rebuild => 1,
  144. },
  145. templatedir => {
  146. type => "string",
  147. default => "$installdir/share/ikiwiki/templates",
  148. description => "location of template files",
  149. advanced => 1,
  150. safe => 0, # path
  151. rebuild => 1,
  152. },
  153. templatedirs => {
  154. type => "internal",
  155. default => [],
  156. description => "additional directories containing template files",
  157. safe => 0,
  158. rebuild => 0,
  159. },
  160. underlaydir => {
  161. type => "string",
  162. default => "$installdir/share/ikiwiki/basewiki",
  163. description => "base wiki source location",
  164. advanced => 1,
  165. safe => 0, # path
  166. rebuild => 0,
  167. },
  168. underlaydirbase => {
  169. type => "internal",
  170. default => "$installdir/share/ikiwiki",
  171. description => "parent directory containing additional underlays",
  172. safe => 0,
  173. rebuild => 0,
  174. },
  175. wrappers => {
  176. type => "internal",
  177. default => [],
  178. description => "wrappers to generate",
  179. safe => 0,
  180. rebuild => 0,
  181. },
  182. underlaydirs => {
  183. type => "internal",
  184. default => [],
  185. description => "additional underlays to use",
  186. safe => 0,
  187. rebuild => 0,
  188. },
  189. verbose => {
  190. type => "boolean",
  191. example => 1,
  192. description => "display verbose messages?",
  193. safe => 1,
  194. rebuild => 0,
  195. },
  196. syslog => {
  197. type => "boolean",
  198. example => 1,
  199. description => "log to syslog?",
  200. safe => 1,
  201. rebuild => 0,
  202. },
  203. usedirs => {
  204. type => "boolean",
  205. default => 1,
  206. description => "create output files named page/index.html?",
  207. safe => 0, # changing requires manual transition
  208. rebuild => 1,
  209. },
  210. prefix_directives => {
  211. type => "boolean",
  212. default => 1,
  213. description => "use '!'-prefixed preprocessor directives?",
  214. safe => 0, # changing requires manual transition
  215. rebuild => 1,
  216. },
  217. indexpages => {
  218. type => "boolean",
  219. default => 0,
  220. description => "use page/index.mdwn source files",
  221. safe => 1,
  222. rebuild => 1,
  223. },
  224. discussion => {
  225. type => "boolean",
  226. default => 1,
  227. description => "enable Discussion pages?",
  228. safe => 1,
  229. rebuild => 1,
  230. },
  231. discussionpage => {
  232. type => "string",
  233. default => gettext("Discussion"),
  234. description => "name of Discussion pages",
  235. safe => 1,
  236. rebuild => 1,
  237. },
  238. sslcookie => {
  239. type => "boolean",
  240. default => 0,
  241. description => "only send cookies over SSL connections?",
  242. advanced => 1,
  243. safe => 1,
  244. rebuild => 0,
  245. },
  246. default_pageext => {
  247. type => "string",
  248. default => "mdwn",
  249. description => "extension to use for new pages",
  250. safe => 0, # not sanitized
  251. rebuild => 0,
  252. },
  253. htmlext => {
  254. type => "string",
  255. default => "html",
  256. description => "extension to use for html files",
  257. safe => 0, # not sanitized
  258. rebuild => 1,
  259. },
  260. timeformat => {
  261. type => "string",
  262. default => '%c',
  263. description => "strftime format string to display date",
  264. advanced => 1,
  265. safe => 1,
  266. rebuild => 1,
  267. },
  268. locale => {
  269. type => "string",
  270. default => undef,
  271. example => "en_US.UTF-8",
  272. description => "UTF-8 locale to use",
  273. advanced => 1,
  274. safe => 0,
  275. rebuild => 1,
  276. },
  277. userdir => {
  278. type => "string",
  279. default => "",
  280. example => "users",
  281. description => "put user pages below specified page",
  282. safe => 1,
  283. rebuild => 1,
  284. },
  285. numbacklinks => {
  286. type => "integer",
  287. default => 10,
  288. description => "how many backlinks to show before hiding excess (0 to show all)",
  289. safe => 1,
  290. rebuild => 1,
  291. },
  292. hardlink => {
  293. type => "boolean",
  294. default => 0,
  295. description => "attempt to hardlink source files? (optimisation for large files)",
  296. advanced => 1,
  297. safe => 0, # paranoia
  298. rebuild => 0,
  299. },
  300. umask => {
  301. type => "integer",
  302. example => "022",
  303. description => "force ikiwiki to use a particular umask",
  304. advanced => 1,
  305. safe => 0, # paranoia
  306. rebuild => 0,
  307. },
  308. wrappergroup => {
  309. type => "string",
  310. example => "ikiwiki",
  311. description => "group for wrappers to run in",
  312. advanced => 1,
  313. safe => 0, # paranoia
  314. rebuild => 0,
  315. },
  316. libdir => {
  317. type => "string",
  318. default => "",
  319. example => "$ENV{HOME}/.ikiwiki/",
  320. description => "extra library and plugin directory",
  321. advanced => 1,
  322. safe => 0, # directory
  323. rebuild => 0,
  324. },
  325. ENV => {
  326. type => "string",
  327. default => {},
  328. description => "environment variables",
  329. safe => 0, # paranoia
  330. rebuild => 0,
  331. },
  332. include => {
  333. type => "string",
  334. default => undef,
  335. example => '^\.htaccess$',
  336. description => "regexp of normally excluded files to include",
  337. advanced => 1,
  338. safe => 0, # regexp
  339. rebuild => 1,
  340. },
  341. exclude => {
  342. type => "string",
  343. default => undef,
  344. example => '^(*\.private|Makefile)$',
  345. description => "regexp of files that should be skipped",
  346. advanced => 1,
  347. safe => 0, # regexp
  348. rebuild => 1,
  349. },
  350. wiki_file_prune_regexps => {
  351. type => "internal",
  352. default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
  353. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  354. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  355. qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
  356. qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
  357. description => "regexps of source files to ignore",
  358. safe => 0,
  359. rebuild => 1,
  360. },
  361. wiki_file_chars => {
  362. type => "string",
  363. description => "specifies the characters that are allowed in source filenames",
  364. default => "-[:alnum:]+/.:_",
  365. safe => 0,
  366. rebuild => 1,
  367. },
  368. wiki_file_regexp => {
  369. type => "internal",
  370. description => "regexp of legal source files",
  371. safe => 0,
  372. rebuild => 1,
  373. },
  374. web_commit_regexp => {
  375. type => "internal",
  376. default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
  377. description => "regexp to parse web commits from logs",
  378. safe => 0,
  379. rebuild => 0,
  380. },
  381. cgi => {
  382. type => "internal",
  383. default => 0,
  384. description => "run as a cgi",
  385. safe => 0,
  386. rebuild => 0,
  387. },
  388. cgi_disable_uploads => {
  389. type => "internal",
  390. default => 1,
  391. description => "whether CGI should accept file uploads",
  392. safe => 0,
  393. rebuild => 0,
  394. },
  395. post_commit => {
  396. type => "internal",
  397. default => 0,
  398. description => "run as a post-commit hook",
  399. safe => 0,
  400. rebuild => 0,
  401. },
  402. rebuild => {
  403. type => "internal",
  404. default => 0,
  405. description => "running in rebuild mode",
  406. safe => 0,
  407. rebuild => 0,
  408. },
  409. setup => {
  410. type => "internal",
  411. default => undef,
  412. description => "running in setup mode",
  413. safe => 0,
  414. rebuild => 0,
  415. },
  416. clean => {
  417. type => "internal",
  418. default => 0,
  419. description => "running in clean mode",
  420. safe => 0,
  421. rebuild => 0,
  422. },
  423. refresh => {
  424. type => "internal",
  425. default => 0,
  426. description => "running in refresh mode",
  427. safe => 0,
  428. rebuild => 0,
  429. },
  430. test_receive => {
  431. type => "internal",
  432. default => 0,
  433. description => "running in receive test mode",
  434. safe => 0,
  435. rebuild => 0,
  436. },
  437. gettime => {
  438. type => "internal",
  439. description => "running in gettime 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/sanitizers
  1060. $content=~s/^<p>//i;
  1061. $content=~s/<\/p>\n*$//i;
  1062. }
  1063. return $content;
  1064. }
  1065. sub linkify ($$$) {
  1066. my $page=shift;
  1067. my $destpage=shift;
  1068. my $content=shift;
  1069. run_hooks(linkify => sub {
  1070. $content=shift->(
  1071. page => $page,
  1072. destpage => $destpage,
  1073. content => $content,
  1074. );
  1075. });
  1076. return $content;
  1077. }
  1078. our %preprocessing;
  1079. our $preprocess_preview=0;
  1080. sub preprocess ($$$;$$) {
  1081. my $page=shift; # the page the data comes from
  1082. my $destpage=shift; # the page the data will appear in (different for inline)
  1083. my $content=shift;
  1084. my $scan=shift;
  1085. my $preview=shift;
  1086. # Using local because it needs to be set within any nested calls
  1087. # of this function.
  1088. local $preprocess_preview=$preview if defined $preview;
  1089. my $handle=sub {
  1090. my $escape=shift;
  1091. my $prefix=shift;
  1092. my $command=shift;
  1093. my $params=shift;
  1094. $params="" if ! defined $params;
  1095. if (length $escape) {
  1096. return "[[$prefix$command $params]]";
  1097. }
  1098. elsif (exists $hooks{preprocess}{$command}) {
  1099. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1100. # Note: preserve order of params, some plugins may
  1101. # consider it significant.
  1102. my @params;
  1103. while ($params =~ m{
  1104. (?:([-\w]+)=)? # 1: named parameter key?
  1105. (?:
  1106. """(.*?)""" # 2: triple-quoted value
  1107. |
  1108. "([^"]*?)" # 3: single-quoted value
  1109. |
  1110. (\S+) # 4: unquoted value
  1111. )
  1112. (?:\s+|$) # delimiter to next param
  1113. }sgx) {
  1114. my $key=$1;
  1115. my $val;
  1116. if (defined $2) {
  1117. $val=$2;
  1118. $val=~s/\r\n/\n/mg;
  1119. $val=~s/^\n+//g;
  1120. $val=~s/\n+$//g;
  1121. }
  1122. elsif (defined $3) {
  1123. $val=$3;
  1124. }
  1125. elsif (defined $4) {
  1126. $val=$4;
  1127. }
  1128. if (defined $key) {
  1129. push @params, $key, $val;
  1130. }
  1131. else {
  1132. push @params, $val, '';
  1133. }
  1134. }
  1135. if ($preprocessing{$page}++ > 3) {
  1136. # Avoid loops of preprocessed pages preprocessing
  1137. # other pages that preprocess them, etc.
  1138. return "[[!$command <span class=\"error\">".
  1139. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1140. $page, $preprocessing{$page}).
  1141. "</span>]]";
  1142. }
  1143. my $ret;
  1144. if (! $scan) {
  1145. $ret=eval {
  1146. $hooks{preprocess}{$command}{call}->(
  1147. @params,
  1148. page => $page,
  1149. destpage => $destpage,
  1150. preview => $preprocess_preview,
  1151. );
  1152. };
  1153. if ($@) {
  1154. my $error=$@;
  1155. chomp $error;
  1156. $ret="[[!$command <span class=\"error\">".
  1157. gettext("Error").": $error"."</span>]]";
  1158. }
  1159. }
  1160. else {
  1161. # use void context during scan pass
  1162. eval {
  1163. $hooks{preprocess}{$command}{call}->(
  1164. @params,
  1165. page => $page,
  1166. destpage => $destpage,
  1167. preview => $preprocess_preview,
  1168. );
  1169. };
  1170. $ret="";
  1171. }
  1172. $preprocessing{$page}--;
  1173. return $ret;
  1174. }
  1175. else {
  1176. return "[[$prefix$command $params]]";
  1177. }
  1178. };
  1179. my $regex;
  1180. if ($config{prefix_directives}) {
  1181. $regex = qr{
  1182. (\\?) # 1: escape?
  1183. \[\[(!) # directive open; 2: prefix
  1184. ([-\w]+) # 3: command
  1185. ( # 4: the parameters..
  1186. \s+ # Must have space if parameters present
  1187. (?:
  1188. (?:[-\w]+=)? # named parameter key?
  1189. (?:
  1190. """.*?""" # triple-quoted value
  1191. |
  1192. "[^"]*?" # single-quoted value
  1193. |
  1194. [^"\s\]]+ # unquoted value
  1195. )
  1196. \s* # whitespace or end
  1197. # of directive
  1198. )
  1199. *)? # 0 or more parameters
  1200. \]\] # directive closed
  1201. }sx;
  1202. }
  1203. else {
  1204. $regex = qr{
  1205. (\\?) # 1: escape?
  1206. \[\[(!?) # directive open; 2: optional prefix
  1207. ([-\w]+) # 3: command
  1208. \s+
  1209. ( # 4: the parameters..
  1210. (?:
  1211. (?:[-\w]+=)? # named parameter key?
  1212. (?:
  1213. """.*?""" # triple-quoted value
  1214. |
  1215. "[^"]*?" # single-quoted value
  1216. |
  1217. [^"\s\]]+ # unquoted value
  1218. )
  1219. \s* # whitespace or end
  1220. # of directive
  1221. )
  1222. *) # 0 or more parameters
  1223. \]\] # directive closed
  1224. }sx;
  1225. }
  1226. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1227. return $content;
  1228. }
  1229. sub filter ($$$) {
  1230. my $page=shift;
  1231. my $destpage=shift;
  1232. my $content=shift;
  1233. run_hooks(filter => sub {
  1234. $content=shift->(page => $page, destpage => $destpage,
  1235. content => $content);
  1236. });
  1237. return $content;
  1238. }
  1239. sub indexlink () {
  1240. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1241. }
  1242. sub check_canedit ($$$;$) {
  1243. my $page=shift;
  1244. my $q=shift;
  1245. my $session=shift;
  1246. my $nonfatal=shift;
  1247. my $canedit;
  1248. run_hooks(canedit => sub {
  1249. return if defined $canedit;
  1250. my $ret=shift->($page, $q, $session);
  1251. if (defined $ret) {
  1252. if ($ret eq "") {
  1253. $canedit=1;
  1254. }
  1255. elsif (ref $ret eq 'CODE') {
  1256. $ret->() unless $nonfatal;
  1257. $canedit=0;
  1258. }
  1259. elsif (defined $ret) {
  1260. error($ret) unless $nonfatal;
  1261. $canedit=0;
  1262. }
  1263. }
  1264. });
  1265. return defined $canedit ? $canedit : 1;
  1266. }
  1267. sub check_content (@) {
  1268. my %params=@_;
  1269. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1270. if (exists $pagesources{$params{page}}) {
  1271. my @diff;
  1272. my %old=map { $_ => 1 }
  1273. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1274. foreach my $line (split("\n", $params{content})) {
  1275. push @diff, $line if ! exists $old{$line};
  1276. }
  1277. $params{diff}=join("\n", @diff);
  1278. }
  1279. my $ok;
  1280. run_hooks(checkcontent => sub {
  1281. return if defined $ok;
  1282. my $ret=shift->(%params);
  1283. if (defined $ret) {
  1284. if ($ret eq "") {
  1285. $ok=1;
  1286. }
  1287. elsif (ref $ret eq 'CODE') {
  1288. $ret->() unless $params{nonfatal};
  1289. $ok=0;
  1290. }
  1291. elsif (defined $ret) {
  1292. error($ret) unless $params{nonfatal};
  1293. $ok=0;
  1294. }
  1295. }
  1296. });
  1297. return defined $ok ? $ok : 1;
  1298. }
  1299. my $wikilock;
  1300. sub lockwiki () {
  1301. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1302. # run issues. The lock will be dropped on program exit.
  1303. if (! -d $config{wikistatedir}) {
  1304. mkdir($config{wikistatedir});
  1305. }
  1306. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1307. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1308. if (! flock($wikilock, 2)) { # LOCK_EX
  1309. error("failed to get lock");
  1310. }
  1311. return 1;
  1312. }
  1313. sub unlockwiki () {
  1314. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1315. return close($wikilock) if $wikilock;
  1316. return;
  1317. }
  1318. my $commitlock;
  1319. sub commit_hook_enabled () {
  1320. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1321. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1322. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1323. close($commitlock) || error("failed closing commitlock: $!");
  1324. return 0;
  1325. }
  1326. close($commitlock) || error("failed closing commitlock: $!");
  1327. return 1;
  1328. }
  1329. sub disable_commit_hook () {
  1330. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1331. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1332. if (! flock($commitlock, 2)) { # LOCK_EX
  1333. error("failed to get commit lock");
  1334. }
  1335. return 1;
  1336. }
  1337. sub enable_commit_hook () {
  1338. return close($commitlock) if $commitlock;
  1339. return;
  1340. }
  1341. sub loadindex () {
  1342. %oldrenderedfiles=%pagectime=();
  1343. if (! $config{rebuild}) {
  1344. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1345. %destsources=%renderedfiles=%pagecase=%pagestate=
  1346. %depends_simple=%typedlinks=%oldtypedlinks=();
  1347. }
  1348. my $in;
  1349. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1350. if (-e "$config{wikistatedir}/index") {
  1351. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1352. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1353. }
  1354. else {
  1355. $config{gettime}=1; # first build
  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. if (exists $d->{typedlinks}) {
  1411. $typedlinks{$page}=$d->{typedlinks};
  1412. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1413. next unless %$links;
  1414. $oldtypedlinks{$page}{$type} = {%$links};
  1415. }
  1416. }
  1417. }
  1418. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1419. }
  1420. foreach my $page (keys %pagesources) {
  1421. $pagecase{lc $page}=$page;
  1422. }
  1423. foreach my $page (keys %renderedfiles) {
  1424. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1425. }
  1426. return close($in);
  1427. }
  1428. sub saveindex () {
  1429. run_hooks(savestate => sub { shift->() });
  1430. my %hookids;
  1431. foreach my $type (keys %hooks) {
  1432. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1433. }
  1434. my @hookids=keys %hookids;
  1435. if (! -d $config{wikistatedir}) {
  1436. mkdir($config{wikistatedir});
  1437. }
  1438. my $newfile="$config{wikistatedir}/indexdb.new";
  1439. my $cleanup = sub { unlink($newfile) };
  1440. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1441. my %index;
  1442. foreach my $page (keys %pagemtime) {
  1443. next unless $pagemtime{$page};
  1444. my $src=$pagesources{$page};
  1445. $index{page}{$src}={
  1446. ctime => $pagectime{$page},
  1447. mtime => $pagemtime{$page},
  1448. dest => $renderedfiles{$page},
  1449. links => $links{$page},
  1450. };
  1451. if (exists $depends{$page}) {
  1452. $index{page}{$src}{depends} = $depends{$page};
  1453. }
  1454. if (exists $depends_simple{$page}) {
  1455. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1456. }
  1457. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1458. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1459. }
  1460. if (exists $pagestate{$page}) {
  1461. foreach my $id (@hookids) {
  1462. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1463. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1464. }
  1465. }
  1466. }
  1467. }
  1468. $index{state}={};
  1469. foreach my $id (@hookids) {
  1470. foreach my $key (keys %{$wikistate{$id}}) {
  1471. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1472. }
  1473. }
  1474. $index{version}="3";
  1475. my $ret=Storable::nstore_fd(\%index, $out);
  1476. return if ! defined $ret || ! $ret;
  1477. close $out || error("failed saving to $newfile: $!", $cleanup);
  1478. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1479. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1480. return 1;
  1481. }
  1482. sub template_file ($) {
  1483. my $template=shift;
  1484. foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
  1485. "$installdir/share/ikiwiki/templates") {
  1486. return "$dir/$template" if -e "$dir/$template";
  1487. }
  1488. return;
  1489. }
  1490. sub template_params (@) {
  1491. my $filename=template_file(shift);
  1492. if (! defined $filename) {
  1493. return if wantarray;
  1494. return "";
  1495. }
  1496. my @ret=(
  1497. filter => sub {
  1498. my $text_ref = shift;
  1499. ${$text_ref} = decode_utf8(${$text_ref});
  1500. },
  1501. filename => $filename,
  1502. loop_context_vars => 1,
  1503. die_on_bad_params => 0,
  1504. @_
  1505. );
  1506. return wantarray ? @ret : {@ret};
  1507. }
  1508. sub template ($;@) {
  1509. require HTML::Template;
  1510. return HTML::Template->new(template_params(@_));
  1511. }
  1512. sub misctemplate ($$;@) {
  1513. my $title=shift;
  1514. my $pagebody=shift;
  1515. my $template=template("misc.tmpl");
  1516. $template->param(
  1517. title => $title,
  1518. indexlink => indexlink(),
  1519. wikiname => $config{wikiname},
  1520. pagebody => $pagebody,
  1521. baseurl => baseurl(),
  1522. @_,
  1523. );
  1524. run_hooks(pagetemplate => sub {
  1525. shift->(page => "", destpage => "", template => $template);
  1526. });
  1527. return $template->output;
  1528. }
  1529. sub hook (@) {
  1530. my %param=@_;
  1531. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1532. error 'hook requires type, call, and id parameters';
  1533. }
  1534. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1535. $hooks{$param{type}}{$param{id}}=\%param;
  1536. return 1;
  1537. }
  1538. sub run_hooks ($$) {
  1539. # Calls the given sub for each hook of the given type,
  1540. # passing it the hook function to call.
  1541. my $type=shift;
  1542. my $sub=shift;
  1543. if (exists $hooks{$type}) {
  1544. my (@first, @middle, @last);
  1545. foreach my $id (keys %{$hooks{$type}}) {
  1546. if ($hooks{$type}{$id}{first}) {
  1547. push @first, $id;
  1548. }
  1549. elsif ($hooks{$type}{$id}{last}) {
  1550. push @last, $id;
  1551. }
  1552. else {
  1553. push @middle, $id;
  1554. }
  1555. }
  1556. foreach my $id (@first, @middle, @last) {
  1557. $sub->($hooks{$type}{$id}{call});
  1558. }
  1559. }
  1560. return 1;
  1561. }
  1562. sub rcs_update () {
  1563. $hooks{rcs}{rcs_update}{call}->(@_);
  1564. }
  1565. sub rcs_prepedit ($) {
  1566. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1567. }
  1568. sub rcs_commit ($$$;$$) {
  1569. $hooks{rcs}{rcs_commit}{call}->(@_);
  1570. }
  1571. sub rcs_commit_staged ($$$) {
  1572. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1573. }
  1574. sub rcs_add ($) {
  1575. $hooks{rcs}{rcs_add}{call}->(@_);
  1576. }
  1577. sub rcs_remove ($) {
  1578. $hooks{rcs}{rcs_remove}{call}->(@_);
  1579. }
  1580. sub rcs_rename ($$) {
  1581. $hooks{rcs}{rcs_rename}{call}->(@_);
  1582. }
  1583. sub rcs_recentchanges ($) {
  1584. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1585. }
  1586. sub rcs_diff ($) {
  1587. $hooks{rcs}{rcs_diff}{call}->(@_);
  1588. }
  1589. sub rcs_getctime ($) {
  1590. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1591. }
  1592. sub rcs_getmtime ($) {
  1593. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1594. }
  1595. sub rcs_receive () {
  1596. $hooks{rcs}{rcs_receive}{call}->();
  1597. }
  1598. sub add_depends ($$;$) {
  1599. my $page=shift;
  1600. my $pagespec=shift;
  1601. my $deptype=shift || $DEPEND_CONTENT;
  1602. # Is the pagespec a simple page name?
  1603. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1604. $pagespec !~ /[\s*?()!]/) {
  1605. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1606. return 1;
  1607. }
  1608. # Add explicit dependencies for influences.
  1609. my $sub=pagespec_translate($pagespec);
  1610. return unless defined $sub;
  1611. foreach my $p (keys %pagesources) {
  1612. my $r=$sub->($p, location => $page);
  1613. my $i=$r->influences;
  1614. foreach my $k (keys %$i) {
  1615. $depends_simple{$page}{lc $k} |= $i->{$k};
  1616. }
  1617. last if $r->influences_static;
  1618. }
  1619. $depends{$page}{$pagespec} |= $deptype;
  1620. return 1;
  1621. }
  1622. sub deptype (@) {
  1623. my $deptype=0;
  1624. foreach my $type (@_) {
  1625. if ($type eq 'presence') {
  1626. $deptype |= $DEPEND_PRESENCE;
  1627. }
  1628. elsif ($type eq 'links') {
  1629. $deptype |= $DEPEND_LINKS;
  1630. }
  1631. elsif ($type eq 'content') {
  1632. $deptype |= $DEPEND_CONTENT;
  1633. }
  1634. }
  1635. return $deptype;
  1636. }
  1637. my $file_prune_regexp;
  1638. sub file_pruned ($;$) {
  1639. my $file=shift;
  1640. if (@_) {
  1641. require File::Spec;
  1642. $file=File::Spec->canonpath($file);
  1643. my $base=File::Spec->canonpath(shift);
  1644. return if $file eq $base;
  1645. $file =~ s#^\Q$base\E/+##;
  1646. }
  1647. if (defined $config{include} && length $config{include}) {
  1648. return 0 if $file =~ m/$config{include}/;
  1649. }
  1650. if (! defined $file_prune_regexp) {
  1651. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1652. $file_prune_regexp=qr/$file_prune_regexp/;
  1653. }
  1654. return $file =~ m/$file_prune_regexp/;
  1655. }
  1656. sub define_gettext () {
  1657. # If translation is needed, redefine the gettext function to do it.
  1658. # Otherwise, it becomes a quick no-op.
  1659. my $gettext_obj;
  1660. my $getobj;
  1661. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1662. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1663. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1664. $getobj=sub {
  1665. $gettext_obj=eval q{
  1666. use Locale::gettext q{textdomain};
  1667. Locale::gettext->domain('ikiwiki')
  1668. };
  1669. };
  1670. }
  1671. no warnings 'redefine';
  1672. *gettext=sub {
  1673. $getobj->() if $getobj;
  1674. if ($gettext_obj) {
  1675. $gettext_obj->get(shift);
  1676. }
  1677. else {
  1678. return shift;
  1679. }
  1680. };
  1681. *ngettext=sub {
  1682. $getobj->() if $getobj;
  1683. if ($gettext_obj) {
  1684. $gettext_obj->nget(@_);
  1685. }
  1686. else {
  1687. return ($_[2] == 1 ? $_[0] : $_[1])
  1688. }
  1689. };
  1690. }
  1691. sub gettext {
  1692. define_gettext();
  1693. gettext(@_);
  1694. }
  1695. sub ngettext {
  1696. define_gettext();
  1697. ngettext(@_);
  1698. }
  1699. sub yesno ($) {
  1700. my $val=shift;
  1701. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1702. }
  1703. sub inject {
  1704. # Injects a new function into the symbol table to replace an
  1705. # exported function.
  1706. my %params=@_;
  1707. # This is deep ugly perl foo, beware.
  1708. no strict;
  1709. no warnings;
  1710. if (! defined $params{parent}) {
  1711. $params{parent}='::';
  1712. $params{old}=\&{$params{name}};
  1713. $params{name}=~s/.*:://;
  1714. }
  1715. my $parent=$params{parent};
  1716. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1717. $ns = $params{parent} . $ns;
  1718. inject(%params, parent => $ns) unless $ns eq '::main::';
  1719. *{$ns . $params{name}} = $params{call}
  1720. if exists ${$ns}{$params{name}} &&
  1721. \&{${$ns}{$params{name}}} == $params{old};
  1722. }
  1723. use strict;
  1724. use warnings;
  1725. }
  1726. sub add_link ($$;$) {
  1727. my $page=shift;
  1728. my $link=shift;
  1729. my $type=shift;
  1730. push @{$links{$page}}, $link
  1731. unless grep { $_ eq $link } @{$links{$page}};
  1732. if (defined $type) {
  1733. $typedlinks{$page}{$type}{$link} = 1;
  1734. }
  1735. }
  1736. sub add_autofile ($$$) {
  1737. my $file=shift;
  1738. my $plugin=shift;
  1739. my $generator=shift;
  1740. $autofiles{$file}{plugin}=$plugin;
  1741. $autofiles{$file}{generator}=$generator;
  1742. }
  1743. sub sortspec_translate ($$) {
  1744. my $spec = shift;
  1745. my $reverse = shift;
  1746. my $code = "";
  1747. my @data;
  1748. while ($spec =~ m{
  1749. \s*
  1750. (-?) # group 1: perhaps negated
  1751. \s*
  1752. ( # group 2: a word
  1753. \w+\([^\)]*\) # command(params)
  1754. |
  1755. [^\s]+ # or anything else
  1756. )
  1757. \s*
  1758. }gx) {
  1759. my $negated = $1;
  1760. my $word = $2;
  1761. my $params = undef;
  1762. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1763. # command with parameters
  1764. $params = $2;
  1765. $word = $1;
  1766. }
  1767. elsif ($word !~ m/^\w+$/) {
  1768. error(sprintf(gettext("invalid sort type %s"), $word));
  1769. }
  1770. if (length $code) {
  1771. $code .= " || ";
  1772. }
  1773. if ($negated) {
  1774. $code .= "-";
  1775. }
  1776. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1777. if (defined $params) {
  1778. push @data, $params;
  1779. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1780. }
  1781. else {
  1782. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1783. }
  1784. }
  1785. else {
  1786. error(sprintf(gettext("unknown sort type %s"), $word));
  1787. }
  1788. }
  1789. if (! length $code) {
  1790. # undefined sorting method... sort arbitrarily
  1791. return sub { 0 };
  1792. }
  1793. if ($reverse) {
  1794. $code="-($code)";
  1795. }
  1796. no warnings;
  1797. return eval 'sub { '.$code.' }';
  1798. }
  1799. sub pagespec_translate ($) {
  1800. my $spec=shift;
  1801. # Convert spec to perl code.
  1802. my $code="";
  1803. my @data;
  1804. while ($spec=~m{
  1805. \s* # ignore whitespace
  1806. ( # 1: match a single word
  1807. \! # !
  1808. |
  1809. \( # (
  1810. |
  1811. \) # )
  1812. |
  1813. \w+\([^\)]*\) # command(params)
  1814. |
  1815. [^\s()]+ # any other text
  1816. )
  1817. \s* # ignore whitespace
  1818. }gx) {
  1819. my $word=$1;
  1820. if (lc $word eq 'and') {
  1821. $code.=' &';
  1822. }
  1823. elsif (lc $word eq 'or') {
  1824. $code.=' |';
  1825. }
  1826. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1827. $code.=' '.$word;
  1828. }
  1829. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1830. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1831. push @data, $2;
  1832. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1833. }
  1834. else {
  1835. push @data, qq{unknown function in pagespec "$word"};
  1836. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1837. }
  1838. }
  1839. else {
  1840. push @data, $word;
  1841. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1842. }
  1843. }
  1844. if (! length $code) {
  1845. $code="IkiWiki::FailReason->new('empty pagespec')";
  1846. }
  1847. no warnings;
  1848. return eval 'sub { my $page=shift; '.$code.' }';
  1849. }
  1850. sub pagespec_match ($$;@) {
  1851. my $page=shift;
  1852. my $spec=shift;
  1853. my @params=@_;
  1854. # Backwards compatability with old calling convention.
  1855. if (@params == 1) {
  1856. unshift @params, 'location';
  1857. }
  1858. my $sub=pagespec_translate($spec);
  1859. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1860. if ! defined $sub;
  1861. return $sub->($page, @params);
  1862. }
  1863. sub pagespec_match_list ($$;@) {
  1864. my $page=shift;
  1865. my $pagespec=shift;
  1866. my %params=@_;
  1867. # Backwards compatability with old calling convention.
  1868. if (ref $page) {
  1869. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1870. $params{list}=$page;
  1871. $page=$params{location}; # ugh!
  1872. }
  1873. my $sub=pagespec_translate($pagespec);
  1874. error "syntax error in pagespec \"$pagespec\""
  1875. if ! defined $sub;
  1876. my $sort=sortspec_translate($params{sort}, $params{reverse})
  1877. if defined $params{sort};
  1878. my @candidates;
  1879. if (exists $params{list}) {
  1880. @candidates=exists $params{filter}
  1881. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1882. : @{$params{list}};
  1883. }
  1884. else {
  1885. @candidates=exists $params{filter}
  1886. ? grep { ! $params{filter}->($_) } keys %pagesources
  1887. : keys %pagesources;
  1888. }
  1889. # clear params, remainder is passed to pagespec
  1890. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1891. my $num=$params{num};
  1892. delete @params{qw{num deptype reverse sort filter list}};
  1893. # when only the top matches will be returned, it's efficient to
  1894. # sort before matching to pagespec,
  1895. if (defined $num && defined $sort) {
  1896. @candidates=IkiWiki::SortSpec::sort_pages(
  1897. $sort, @candidates);
  1898. }
  1899. my @matches;
  1900. my $firstfail;
  1901. my $count=0;
  1902. my $accum=IkiWiki::SuccessReason->new();
  1903. foreach my $p (@candidates) {
  1904. my $r=$sub->($p, %params, location => $page);
  1905. error(sprintf(gettext("cannot match pages: %s"), $r))
  1906. if $r->isa("IkiWiki::ErrorReason");
  1907. $accum |= $r;
  1908. if ($r) {
  1909. push @matches, $p;
  1910. last if defined $num && ++$count == $num;
  1911. }
  1912. }
  1913. # Add simple dependencies for accumulated influences.
  1914. my $i=$accum->influences;
  1915. foreach my $k (keys %$i) {
  1916. $depends_simple{$page}{lc $k} |= $i->{$k};
  1917. }
  1918. # when all matches will be returned, it's efficient to
  1919. # sort after matching
  1920. if (! defined $num && defined $sort) {
  1921. return IkiWiki::SortSpec::sort_pages(
  1922. $sort, @matches);
  1923. }
  1924. else {
  1925. return @matches;
  1926. }
  1927. }
  1928. sub pagespec_valid ($) {
  1929. my $spec=shift;
  1930. return defined pagespec_translate($spec);
  1931. }
  1932. sub glob2re ($) {
  1933. my $re=quotemeta(shift);
  1934. $re=~s/\\\*/.*/g;
  1935. $re=~s/\\\?/./g;
  1936. return $re;
  1937. }
  1938. package IkiWiki::FailReason;
  1939. use overload (
  1940. '""' => sub { $_[0][0] },
  1941. '0+' => sub { 0 },
  1942. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1943. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  1944. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1945. fallback => 1,
  1946. );
  1947. our @ISA = 'IkiWiki::SuccessReason';
  1948. package IkiWiki::SuccessReason;
  1949. use overload (
  1950. '""' => sub { $_[0][0] },
  1951. '0+' => sub { 1 },
  1952. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1953. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  1954. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1955. fallback => 1,
  1956. );
  1957. sub new {
  1958. my $class = shift;
  1959. my $value = shift;
  1960. return bless [$value, {@_}], $class;
  1961. }
  1962. sub influences {
  1963. my $this=shift;
  1964. $this->[1]={@_} if @_;
  1965. my %i=%{$this->[1]};
  1966. delete $i{""};
  1967. return \%i;
  1968. }
  1969. sub influences_static {
  1970. return ! $_[0][1]->{""};
  1971. }
  1972. sub merge_influences {
  1973. my $this=shift;
  1974. my $other=shift;
  1975. my $anded=shift;
  1976. if (! $anded || (($this || %{$this->[1]}) &&
  1977. ($other || %{$other->[1]}))) {
  1978. foreach my $influence (keys %{$other->[1]}) {
  1979. $this->[1]{$influence} |= $other->[1]{$influence};
  1980. }
  1981. }
  1982. else {
  1983. # influence blocker
  1984. $this->[1]={};
  1985. }
  1986. }
  1987. package IkiWiki::ErrorReason;
  1988. our @ISA = 'IkiWiki::FailReason';
  1989. package IkiWiki::PageSpec;
  1990. sub derel ($$) {
  1991. my $path=shift;
  1992. my $from=shift;
  1993. if ($path =~ m!^\./!) {
  1994. $from=~s#/?[^/]+$## if defined $from;
  1995. $path=~s#^\./##;
  1996. $path="$from/$path" if length $from;
  1997. }
  1998. return $path;
  1999. }
  2000. sub match_glob ($$;@) {
  2001. my $page=shift;
  2002. my $glob=shift;
  2003. my %params=@_;
  2004. $glob=derel($glob, $params{location});
  2005. my $regexp=IkiWiki::glob2re($glob);
  2006. if ($page=~/^$regexp$/i) {
  2007. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2008. return IkiWiki::SuccessReason->new("$glob matches $page");
  2009. }
  2010. else {
  2011. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2012. }
  2013. }
  2014. else {
  2015. return IkiWiki::FailReason->new("$glob does not match $page");
  2016. }
  2017. }
  2018. sub match_internal ($$;@) {
  2019. return match_glob($_[0], $_[1], @_, internal => 1)
  2020. }
  2021. sub match_link ($$;@) {
  2022. my $page=shift;
  2023. my $link=lc(shift);
  2024. my %params=@_;
  2025. $link=derel($link, $params{location});
  2026. my $from=exists $params{location} ? $params{location} : '';
  2027. my $linktype=$params{linktype};
  2028. my $qualifier='';
  2029. if (defined $linktype) {
  2030. $qualifier=" with type $linktype";
  2031. }
  2032. my $links = $IkiWiki::links{$page};
  2033. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2034. unless $links && @{$links};
  2035. my $bestlink = IkiWiki::bestlink($from, $link);
  2036. foreach my $p (@{$links}) {
  2037. if (length $bestlink) {
  2038. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
  2039. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2040. }
  2041. }
  2042. else {
  2043. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
  2044. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2045. }
  2046. my ($p_rel)=$p=~/^\/?(.*)/;
  2047. $link=~s/^\///;
  2048. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
  2049. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2050. }
  2051. }
  2052. }
  2053. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2054. }
  2055. sub match_backlink ($$;@) {
  2056. my $ret=match_link($_[1], $_[0], @_);
  2057. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2058. return $ret;
  2059. }
  2060. sub match_created_before ($$;@) {
  2061. my $page=shift;
  2062. my $testpage=shift;
  2063. my %params=@_;
  2064. $testpage=derel($testpage, $params{location});
  2065. if (exists $IkiWiki::pagectime{$testpage}) {
  2066. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2067. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2068. }
  2069. else {
  2070. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2071. }
  2072. }
  2073. else {
  2074. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2075. }
  2076. }
  2077. sub match_created_after ($$;@) {
  2078. my $page=shift;
  2079. my $testpage=shift;
  2080. my %params=@_;
  2081. $testpage=derel($testpage, $params{location});
  2082. if (exists $IkiWiki::pagectime{$testpage}) {
  2083. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2084. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2085. }
  2086. else {
  2087. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2088. }
  2089. }
  2090. else {
  2091. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2092. }
  2093. }
  2094. sub match_creation_day ($$;@) {
  2095. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2096. return IkiWiki::SuccessReason->new('creation_day matched');
  2097. }
  2098. else {
  2099. return IkiWiki::FailReason->new('creation_day did not match');
  2100. }
  2101. }
  2102. sub match_creation_month ($$;@) {
  2103. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2104. return IkiWiki::SuccessReason->new('creation_month matched');
  2105. }
  2106. else {
  2107. return IkiWiki::FailReason->new('creation_month did not match');
  2108. }
  2109. }
  2110. sub match_creation_year ($$;@) {
  2111. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2112. return IkiWiki::SuccessReason->new('creation_year matched');
  2113. }
  2114. else {
  2115. return IkiWiki::FailReason->new('creation_year did not match');
  2116. }
  2117. }
  2118. sub match_user ($$;@) {
  2119. shift;
  2120. my $user=shift;
  2121. my %params=@_;
  2122. my $regexp=IkiWiki::glob2re($user);
  2123. if (! exists $params{user}) {
  2124. return IkiWiki::ErrorReason->new("no user specified");
  2125. }
  2126. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2127. return IkiWiki::SuccessReason->new("user is $user");
  2128. }
  2129. elsif (! defined $params{user}) {
  2130. return IkiWiki::FailReason->new("not logged in");
  2131. }
  2132. else {
  2133. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2134. }
  2135. }
  2136. sub match_admin ($$;@) {
  2137. shift;
  2138. shift;
  2139. my %params=@_;
  2140. if (! exists $params{user}) {
  2141. return IkiWiki::ErrorReason->new("no user specified");
  2142. }
  2143. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2144. return IkiWiki::SuccessReason->new("user is an admin");
  2145. }
  2146. elsif (! defined $params{user}) {
  2147. return IkiWiki::FailReason->new("not logged in");
  2148. }
  2149. else {
  2150. return IkiWiki::FailReason->new("user is not an admin");
  2151. }
  2152. }
  2153. sub match_ip ($$;@) {
  2154. shift;
  2155. my $ip=shift;
  2156. my %params=@_;
  2157. if (! exists $params{ip}) {
  2158. return IkiWiki::ErrorReason->new("no IP specified");
  2159. }
  2160. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2161. return IkiWiki::SuccessReason->new("IP is $ip");
  2162. }
  2163. else {
  2164. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2165. }
  2166. }
  2167. package IkiWiki::SortSpec;
  2168. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2169. # are easily available in this namespace, for cmp functions to use them.
  2170. sub sort_pages {
  2171. my $f=shift;
  2172. sort $f @_
  2173. }
  2174. sub cmp_title {
  2175. IkiWiki::pagetitle(IkiWiki::basename($a))
  2176. cmp
  2177. IkiWiki::pagetitle(IkiWiki::basename($b))
  2178. }
  2179. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2180. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2181. 1