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