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