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