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