summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 2355c07807cbbd6c854002764c1b2e499208ed3e (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/(^|\/)CVS\//, 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 openiduser ($) {
  950. my $user=shift;
  951. if ($user =~ m!^https?://! &&
  952. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  953. my $display;
  954. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  955. # this works in at least 2.x
  956. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  957. }
  958. else {
  959. # this only works in 1.x
  960. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  961. $display=$oid->display;
  962. }
  963. # Convert "user.somehost.com" to "user [somehost.com]"
  964. # (also "user.somehost.co.uk")
  965. if ($display !~ /\[/) {
  966. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  967. }
  968. # Convert "http://somehost.com/user" to "user [somehost.com]".
  969. # (also "https://somehost.com/user/")
  970. if ($display !~ /\[/) {
  971. $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
  972. }
  973. $display=~s!^https?://!!; # make sure this is removed
  974. eval q{use CGI 'escapeHTML'};
  975. error($@) if $@;
  976. return escapeHTML($display);
  977. }
  978. return;
  979. }
  980. sub userlink ($) {
  981. my $user=shift;
  982. my $oiduser=eval { openiduser($user) };
  983. if (defined $oiduser) {
  984. return "<a href=\"$user\">$oiduser</a>";
  985. }
  986. else {
  987. eval q{use CGI 'escapeHTML'};
  988. error($@) if $@;
  989. return htmllink("", "", escapeHTML(
  990. length $config{userdir} ? $config{userdir}."/".$user : $user
  991. ), noimageinline => 1);
  992. }
  993. }
  994. sub htmlize ($$$$) {
  995. my $page=shift;
  996. my $destpage=shift;
  997. my $type=shift;
  998. my $content=shift;
  999. my $oneline = $content !~ /\n/;
  1000. if (exists $hooks{htmlize}{$type}) {
  1001. $content=$hooks{htmlize}{$type}{call}->(
  1002. page => $page,
  1003. content => $content,
  1004. );
  1005. }
  1006. else {
  1007. error("htmlization of $type not supported");
  1008. }
  1009. run_hooks(sanitize => sub {
  1010. $content=shift->(
  1011. page => $page,
  1012. destpage => $destpage,
  1013. content => $content,
  1014. );
  1015. });
  1016. if ($oneline) {
  1017. # hack to get rid of enclosing junk added by markdown
  1018. # and other htmlizers
  1019. $content=~s/^<p>//i;
  1020. $content=~s/<\/p>$//i;
  1021. chomp $content;
  1022. }
  1023. return $content;
  1024. }
  1025. sub linkify ($$$) {
  1026. my $page=shift;
  1027. my $destpage=shift;
  1028. my $content=shift;
  1029. run_hooks(linkify => sub {
  1030. $content=shift->(
  1031. page => $page,
  1032. destpage => $destpage,
  1033. content => $content,
  1034. );
  1035. });
  1036. return $content;
  1037. }
  1038. our %preprocessing;
  1039. our $preprocess_preview=0;
  1040. sub preprocess ($$$;$$) {
  1041. my $page=shift; # the page the data comes from
  1042. my $destpage=shift; # the page the data will appear in (different for inline)
  1043. my $content=shift;
  1044. my $scan=shift;
  1045. my $preview=shift;
  1046. # Using local because it needs to be set within any nested calls
  1047. # of this function.
  1048. local $preprocess_preview=$preview if defined $preview;
  1049. my $handle=sub {
  1050. my $escape=shift;
  1051. my $prefix=shift;
  1052. my $command=shift;
  1053. my $params=shift;
  1054. $params="" if ! defined $params;
  1055. if (length $escape) {
  1056. return "[[$prefix$command $params]]";
  1057. }
  1058. elsif (exists $hooks{preprocess}{$command}) {
  1059. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1060. # Note: preserve order of params, some plugins may
  1061. # consider it significant.
  1062. my @params;
  1063. while ($params =~ m{
  1064. (?:([-\w]+)=)? # 1: named parameter key?
  1065. (?:
  1066. """(.*?)""" # 2: triple-quoted value
  1067. |
  1068. "([^"]+)" # 3: single-quoted value
  1069. |
  1070. (\S+) # 4: unquoted value
  1071. )
  1072. (?:\s+|$) # delimiter to next param
  1073. }sgx) {
  1074. my $key=$1;
  1075. my $val;
  1076. if (defined $2) {
  1077. $val=$2;
  1078. $val=~s/\r\n/\n/mg;
  1079. $val=~s/^\n+//g;
  1080. $val=~s/\n+$//g;
  1081. }
  1082. elsif (defined $3) {
  1083. $val=$3;
  1084. }
  1085. elsif (defined $4) {
  1086. $val=$4;
  1087. }
  1088. if (defined $key) {
  1089. push @params, $key, $val;
  1090. }
  1091. else {
  1092. push @params, $val, '';
  1093. }
  1094. }
  1095. if ($preprocessing{$page}++ > 3) {
  1096. # Avoid loops of preprocessed pages preprocessing
  1097. # other pages that preprocess them, etc.
  1098. return "[[!$command <span class=\"error\">".
  1099. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1100. $page, $preprocessing{$page}).
  1101. "</span>]]";
  1102. }
  1103. my $ret;
  1104. if (! $scan) {
  1105. $ret=eval {
  1106. $hooks{preprocess}{$command}{call}->(
  1107. @params,
  1108. page => $page,
  1109. destpage => $destpage,
  1110. preview => $preprocess_preview,
  1111. );
  1112. };
  1113. if ($@) {
  1114. chomp $@;
  1115. $ret="[[!$command <span class=\"error\">".
  1116. gettext("Error").": $@"."</span>]]";
  1117. }
  1118. }
  1119. else {
  1120. # use void context during scan pass
  1121. eval {
  1122. $hooks{preprocess}{$command}{call}->(
  1123. @params,
  1124. page => $page,
  1125. destpage => $destpage,
  1126. preview => $preprocess_preview,
  1127. );
  1128. };
  1129. $ret="";
  1130. }
  1131. $preprocessing{$page}--;
  1132. return $ret;
  1133. }
  1134. else {
  1135. return "[[$prefix$command $params]]";
  1136. }
  1137. };
  1138. my $regex;
  1139. if ($config{prefix_directives}) {
  1140. $regex = qr{
  1141. (\\?) # 1: escape?
  1142. \[\[(!) # directive open; 2: prefix
  1143. ([-\w]+) # 3: command
  1144. ( # 4: the parameters..
  1145. \s+ # Must have space if parameters present
  1146. (?:
  1147. (?:[-\w]+=)? # named parameter key?
  1148. (?:
  1149. """.*?""" # triple-quoted value
  1150. |
  1151. "[^"]+" # single-quoted value
  1152. |
  1153. [^"\s\]]+ # unquoted value
  1154. )
  1155. \s* # whitespace or end
  1156. # of directive
  1157. )
  1158. *)? # 0 or more parameters
  1159. \]\] # directive closed
  1160. }sx;
  1161. }
  1162. else {
  1163. $regex = qr{
  1164. (\\?) # 1: escape?
  1165. \[\[(!?) # directive open; 2: optional prefix
  1166. ([-\w]+) # 3: command
  1167. \s+
  1168. ( # 4: the parameters..
  1169. (?:
  1170. (?:[-\w]+=)? # named parameter key?
  1171. (?:
  1172. """.*?""" # triple-quoted value
  1173. |
  1174. "[^"]+" # single-quoted value
  1175. |
  1176. [^"\s\]]+ # unquoted value
  1177. )
  1178. \s* # whitespace or end
  1179. # of directive
  1180. )
  1181. *) # 0 or more parameters
  1182. \]\] # directive closed
  1183. }sx;
  1184. }
  1185. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1186. return $content;
  1187. }
  1188. sub filter ($$$) {
  1189. my $page=shift;
  1190. my $destpage=shift;
  1191. my $content=shift;
  1192. run_hooks(filter => sub {
  1193. $content=shift->(page => $page, destpage => $destpage,
  1194. content => $content);
  1195. });
  1196. return $content;
  1197. }
  1198. sub indexlink () {
  1199. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1200. }
  1201. sub check_canedit ($$$;$) {
  1202. my $page=shift;
  1203. my $q=shift;
  1204. my $session=shift;
  1205. my $nonfatal=shift;
  1206. my $canedit;
  1207. run_hooks(canedit => sub {
  1208. return if defined $canedit;
  1209. my $ret=shift->($page, $q, $session);
  1210. if (defined $ret) {
  1211. if ($ret eq "") {
  1212. $canedit=1;
  1213. }
  1214. elsif (ref $ret eq 'CODE') {
  1215. $ret->() unless $nonfatal;
  1216. $canedit=0;
  1217. }
  1218. elsif (defined $ret) {
  1219. error($ret) unless $nonfatal;
  1220. $canedit=0;
  1221. }
  1222. }
  1223. });
  1224. return defined $canedit ? $canedit : 1;
  1225. }
  1226. sub check_content (@) {
  1227. my %params=@_;
  1228. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1229. if (exists $pagesources{$params{page}}) {
  1230. my @diff;
  1231. my %old=map { $_ => 1 }
  1232. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1233. foreach my $line (split("\n", $params{content})) {
  1234. push @diff, $line if ! exists $old{$_};
  1235. }
  1236. $params{diff}=join("\n", @diff);
  1237. }
  1238. my $ok;
  1239. run_hooks(checkcontent => sub {
  1240. return if defined $ok;
  1241. my $ret=shift->(%params);
  1242. if (defined $ret) {
  1243. if ($ret eq "") {
  1244. $ok=1;
  1245. }
  1246. elsif (ref $ret eq 'CODE') {
  1247. $ret->() unless $params{nonfatal};
  1248. $ok=0;
  1249. }
  1250. elsif (defined $ret) {
  1251. error($ret) unless $params{nonfatal};
  1252. $ok=0;
  1253. }
  1254. }
  1255. });
  1256. return defined $ok ? $ok : 1;
  1257. }
  1258. my $wikilock;
  1259. sub lockwiki () {
  1260. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1261. # run issues. The lock will be dropped on program exit.
  1262. if (! -d $config{wikistatedir}) {
  1263. mkdir($config{wikistatedir});
  1264. }
  1265. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1266. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1267. if (! flock($wikilock, 2)) { # LOCK_EX
  1268. error("failed to get lock");
  1269. }
  1270. return 1;
  1271. }
  1272. sub unlockwiki () {
  1273. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1274. return close($wikilock) if $wikilock;
  1275. return;
  1276. }
  1277. my $commitlock;
  1278. sub commit_hook_enabled () {
  1279. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1280. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1281. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1282. close($commitlock) || error("failed closing commitlock: $!");
  1283. return 0;
  1284. }
  1285. close($commitlock) || error("failed closing commitlock: $!");
  1286. return 1;
  1287. }
  1288. sub disable_commit_hook () {
  1289. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1290. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1291. if (! flock($commitlock, 2)) { # LOCK_EX
  1292. error("failed to get commit lock");
  1293. }
  1294. return 1;
  1295. }
  1296. sub enable_commit_hook () {
  1297. return close($commitlock) if $commitlock;
  1298. return;
  1299. }
  1300. sub loadindex () {
  1301. %oldrenderedfiles=%pagectime=();
  1302. if (! $config{rebuild}) {
  1303. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1304. %destsources=%renderedfiles=%pagecase=%pagestate=();
  1305. }
  1306. my $in;
  1307. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1308. if (-e "$config{wikistatedir}/index") {
  1309. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1310. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1311. }
  1312. else {
  1313. return;
  1314. }
  1315. }
  1316. my $index=Storable::fd_retrieve($in);
  1317. if (! defined $index) {
  1318. return 0;
  1319. }
  1320. my $pages;
  1321. if (exists $index->{version} && ! ref $index->{version}) {
  1322. $pages=$index->{page};
  1323. %wikistate=%{$index->{state}};
  1324. }
  1325. else {
  1326. $pages=$index;
  1327. %wikistate=();
  1328. }
  1329. foreach my $src (keys %$pages) {
  1330. my $d=$pages->{$src};
  1331. my $page=pagename($src);
  1332. $pagectime{$page}=$d->{ctime};
  1333. if (! $config{rebuild}) {
  1334. $pagesources{$page}=$src;
  1335. $pagemtime{$page}=$d->{mtime};
  1336. $renderedfiles{$page}=$d->{dest};
  1337. if (exists $d->{links} && ref $d->{links}) {
  1338. $links{$page}=$d->{links};
  1339. $oldlinks{$page}=[@{$d->{links}}];
  1340. }
  1341. if (exists $d->{depends}) {
  1342. $depends{$page}=$d->{depends};
  1343. }
  1344. if (exists $d->{state}) {
  1345. $pagestate{$page}=$d->{state};
  1346. }
  1347. }
  1348. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1349. }
  1350. foreach my $page (keys %pagesources) {
  1351. $pagecase{lc $page}=$page;
  1352. }
  1353. foreach my $page (keys %renderedfiles) {
  1354. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1355. }
  1356. return close($in);
  1357. }
  1358. sub saveindex () {
  1359. run_hooks(savestate => sub { shift->() });
  1360. my %hookids;
  1361. foreach my $type (keys %hooks) {
  1362. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1363. }
  1364. my @hookids=keys %hookids;
  1365. if (! -d $config{wikistatedir}) {
  1366. mkdir($config{wikistatedir});
  1367. }
  1368. my $newfile="$config{wikistatedir}/indexdb.new";
  1369. my $cleanup = sub { unlink($newfile) };
  1370. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1371. my %index;
  1372. foreach my $page (keys %pagemtime) {
  1373. next unless $pagemtime{$page};
  1374. my $src=$pagesources{$page};
  1375. $index{page}{$src}={
  1376. ctime => $pagectime{$page},
  1377. mtime => $pagemtime{$page},
  1378. dest => $renderedfiles{$page},
  1379. links => $links{$page},
  1380. };
  1381. if (exists $depends{$page}) {
  1382. $index{page}{$src}{depends} = $depends{$page};
  1383. }
  1384. if (exists $pagestate{$page}) {
  1385. foreach my $id (@hookids) {
  1386. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1387. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1388. }
  1389. }
  1390. }
  1391. }
  1392. $index{state}={};
  1393. foreach my $id (@hookids) {
  1394. foreach my $key (keys %{$wikistate{$id}}) {
  1395. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1396. }
  1397. }
  1398. $index{version}="3";
  1399. my $ret=Storable::nstore_fd(\%index, $out);
  1400. return if ! defined $ret || ! $ret;
  1401. close $out || error("failed saving to $newfile: $!", $cleanup);
  1402. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1403. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1404. return 1;
  1405. }
  1406. sub template_file ($) {
  1407. my $template=shift;
  1408. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1409. return "$dir/$template" if -e "$dir/$template";
  1410. }
  1411. return;
  1412. }
  1413. sub template_params (@) {
  1414. my $filename=template_file(shift);
  1415. if (! defined $filename) {
  1416. return if wantarray;
  1417. return "";
  1418. }
  1419. my @ret=(
  1420. filter => sub {
  1421. my $text_ref = shift;
  1422. ${$text_ref} = decode_utf8(${$text_ref});
  1423. },
  1424. filename => $filename,
  1425. loop_context_vars => 1,
  1426. die_on_bad_params => 0,
  1427. @_
  1428. );
  1429. return wantarray ? @ret : {@ret};
  1430. }
  1431. sub template ($;@) {
  1432. require HTML::Template;
  1433. return HTML::Template->new(template_params(@_));
  1434. }
  1435. sub misctemplate ($$;@) {
  1436. my $title=shift;
  1437. my $pagebody=shift;
  1438. my $template=template("misc.tmpl");
  1439. $template->param(
  1440. title => $title,
  1441. indexlink => indexlink(),
  1442. wikiname => $config{wikiname},
  1443. pagebody => $pagebody,
  1444. baseurl => baseurl(),
  1445. @_,
  1446. );
  1447. run_hooks(pagetemplate => sub {
  1448. shift->(page => "", destpage => "", template => $template);
  1449. });
  1450. return $template->output;
  1451. }
  1452. sub hook (@) {
  1453. my %param=@_;
  1454. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1455. error 'hook requires type, call, and id parameters';
  1456. }
  1457. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1458. $hooks{$param{type}}{$param{id}}=\%param;
  1459. return 1;
  1460. }
  1461. sub run_hooks ($$) {
  1462. # Calls the given sub for each hook of the given type,
  1463. # passing it the hook function to call.
  1464. my $type=shift;
  1465. my $sub=shift;
  1466. if (exists $hooks{$type}) {
  1467. my (@first, @middle, @last);
  1468. foreach my $id (keys %{$hooks{$type}}) {
  1469. if ($hooks{$type}{$id}{first}) {
  1470. push @first, $id;
  1471. }
  1472. elsif ($hooks{$type}{$id}{last}) {
  1473. push @last, $id;
  1474. }
  1475. else {
  1476. push @middle, $id;
  1477. }
  1478. }
  1479. foreach my $id (@first, @middle, @last) {
  1480. $sub->($hooks{$type}{$id}{call});
  1481. }
  1482. }
  1483. return 1;
  1484. }
  1485. sub rcs_update () {
  1486. $hooks{rcs}{rcs_update}{call}->(@_);
  1487. }
  1488. sub rcs_prepedit ($) {
  1489. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1490. }
  1491. sub rcs_commit ($$$;$$) {
  1492. $hooks{rcs}{rcs_commit}{call}->(@_);
  1493. }
  1494. sub rcs_commit_staged ($$$) {
  1495. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1496. }
  1497. sub rcs_add ($) {
  1498. $hooks{rcs}{rcs_add}{call}->(@_);
  1499. }
  1500. sub rcs_remove ($) {
  1501. $hooks{rcs}{rcs_remove}{call}->(@_);
  1502. }
  1503. sub rcs_rename ($$) {
  1504. $hooks{rcs}{rcs_rename}{call}->(@_);
  1505. }
  1506. sub rcs_recentchanges ($) {
  1507. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1508. }
  1509. sub rcs_diff ($) {
  1510. $hooks{rcs}{rcs_diff}{call}->(@_);
  1511. }
  1512. sub rcs_getctime ($) {
  1513. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1514. }
  1515. sub rcs_receive () {
  1516. $hooks{rcs}{rcs_receive}{call}->();
  1517. }
  1518. sub add_depends ($$) {
  1519. my $page=shift;
  1520. my $pagespec=shift;
  1521. return unless pagespec_valid($pagespec);
  1522. if (! exists $depends{$page}) {
  1523. $depends{$page}=$pagespec;
  1524. }
  1525. else {
  1526. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1527. }
  1528. return 1;
  1529. }
  1530. sub file_pruned ($$) {
  1531. require File::Spec;
  1532. my $file=File::Spec->canonpath(shift);
  1533. my $base=File::Spec->canonpath(shift);
  1534. $file =~ s#^\Q$base\E/+##;
  1535. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1536. return $file =~ m/$regexp/ && $file ne $base;
  1537. }
  1538. sub define_gettext () {
  1539. # If translation is needed, redefine the gettext function to do it.
  1540. # Otherwise, it becomes a quick no-op.
  1541. no warnings 'redefine';
  1542. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1543. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1544. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1545. *gettext=sub {
  1546. my $gettext_obj=eval q{
  1547. use Locale::gettext q{textdomain};
  1548. Locale::gettext->domain('ikiwiki')
  1549. };
  1550. if ($gettext_obj) {
  1551. $gettext_obj->get(shift);
  1552. }
  1553. else {
  1554. return shift;
  1555. }
  1556. };
  1557. }
  1558. else {
  1559. *gettext=sub { return shift };
  1560. }
  1561. }
  1562. sub gettext {
  1563. define_gettext();
  1564. gettext(@_);
  1565. }
  1566. sub yesno ($) {
  1567. my $val=shift;
  1568. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1569. }
  1570. sub inject {
  1571. # Injects a new function into the symbol table to replace an
  1572. # exported function.
  1573. my %params=@_;
  1574. # This is deep ugly perl foo, beware.
  1575. no strict;
  1576. no warnings;
  1577. if (! defined $params{parent}) {
  1578. $params{parent}='::';
  1579. $params{old}=\&{$params{name}};
  1580. $params{name}=~s/.*:://;
  1581. }
  1582. my $parent=$params{parent};
  1583. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1584. $ns = $params{parent} . $ns;
  1585. inject(%params, parent => $ns) unless $ns eq '::main::';
  1586. *{$ns . $params{name}} = $params{call}
  1587. if exists ${$ns}{$params{name}} &&
  1588. \&{${$ns}{$params{name}}} == $params{old};
  1589. }
  1590. use strict;
  1591. use warnings;
  1592. }
  1593. sub add_link ($$) {
  1594. my $page=shift;
  1595. my $link=shift;
  1596. push @{$links{$page}}, $link
  1597. unless grep { $_ eq $link } @{$links{$page}};
  1598. }
  1599. sub pagespec_merge ($$) {
  1600. my $a=shift;
  1601. my $b=shift;
  1602. return $a if $a eq $b;
  1603. return "($a) or ($b)";
  1604. }
  1605. sub pagespec_translate ($) {
  1606. my $spec=shift;
  1607. # Convert spec to perl code.
  1608. my $code="";
  1609. my @data;
  1610. while ($spec=~m{
  1611. \s* # ignore whitespace
  1612. ( # 1: match a single word
  1613. \! # !
  1614. |
  1615. \( # (
  1616. |
  1617. \) # )
  1618. |
  1619. \w+\([^\)]*\) # command(params)
  1620. |
  1621. [^\s()]+ # any other text
  1622. )
  1623. \s* # ignore whitespace
  1624. }igx) {
  1625. my $word=$1;
  1626. if (lc $word eq 'and') {
  1627. $code.=' &&';
  1628. }
  1629. elsif (lc $word eq 'or') {
  1630. $code.=' ||';
  1631. }
  1632. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1633. $code.=' '.$word;
  1634. }
  1635. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1636. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1637. push @data, $2;
  1638. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1639. }
  1640. else {
  1641. push @data, qq{unknown function in pagespec "$word"};
  1642. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1643. }
  1644. }
  1645. else {
  1646. push @data, $word;
  1647. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1648. }
  1649. }
  1650. if (! length $code) {
  1651. $code="IkiWiki::FailReason->new('empty pagespec')";
  1652. }
  1653. no warnings;
  1654. return eval 'sub { my $page=shift; '.$code.' }';
  1655. }
  1656. sub pagespec_match ($$;@) {
  1657. my $page=shift;
  1658. my $spec=shift;
  1659. my @params=@_;
  1660. # Backwards compatability with old calling convention.
  1661. if (@params == 1) {
  1662. unshift @params, 'location';
  1663. }
  1664. my $sub=pagespec_translate($spec);
  1665. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1666. if $@ || ! defined $sub;
  1667. return $sub->($page, @params);
  1668. }
  1669. sub pagespec_match_list ($$;@) {
  1670. my $pages=shift;
  1671. my $spec=shift;
  1672. my @params=@_;
  1673. my $sub=pagespec_translate($spec);
  1674. error "syntax error in pagespec \"$spec\""
  1675. if $@ || ! defined $sub;
  1676. my @ret;
  1677. my $r;
  1678. foreach my $page (@$pages) {
  1679. $r=$sub->($page, @params);
  1680. push @ret, $page if $r;
  1681. }
  1682. if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
  1683. error(sprintf(gettext("cannot match pages: %s"), $r));
  1684. }
  1685. else {
  1686. return @ret;
  1687. }
  1688. }
  1689. sub pagespec_valid ($) {
  1690. my $spec=shift;
  1691. my $sub=pagespec_translate($spec);
  1692. return ! $@;
  1693. }
  1694. sub glob2re ($) {
  1695. my $re=quotemeta(shift);
  1696. $re=~s/\\\*/.*/g;
  1697. $re=~s/\\\?/./g;
  1698. return $re;
  1699. }
  1700. package IkiWiki::FailReason;
  1701. use overload (
  1702. '""' => sub { ${$_[0]} },
  1703. '0+' => sub { 0 },
  1704. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1705. fallback => 1,
  1706. );
  1707. sub new {
  1708. my $class = shift;
  1709. my $value = shift;
  1710. return bless \$value, $class;
  1711. }
  1712. package IkiWiki::ErrorReason;
  1713. our @ISA = 'IkiWiki::FailReason';
  1714. package IkiWiki::SuccessReason;
  1715. use overload (
  1716. '""' => sub { ${$_[0]} },
  1717. '0+' => sub { 1 },
  1718. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1719. fallback => 1,
  1720. );
  1721. sub new {
  1722. my $class = shift;
  1723. my $value = shift;
  1724. return bless \$value, $class;
  1725. };
  1726. package IkiWiki::PageSpec;
  1727. sub derel ($$) {
  1728. my $path=shift;
  1729. my $from=shift;
  1730. if ($path =~ m!^\./!) {
  1731. $from=~s#/?[^/]+$## if defined $from;
  1732. $path=~s#^\./##;
  1733. $path="$from/$path" if length $from;
  1734. }
  1735. return $path;
  1736. }
  1737. sub match_glob ($$;@) {
  1738. my $page=shift;
  1739. my $glob=shift;
  1740. my %params=@_;
  1741. $glob=derel($glob, $params{location});
  1742. my $regexp=IkiWiki::glob2re($glob);
  1743. if ($page=~/^$regexp$/i) {
  1744. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1745. return IkiWiki::SuccessReason->new("$glob matches $page");
  1746. }
  1747. else {
  1748. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1749. }
  1750. }
  1751. else {
  1752. return IkiWiki::FailReason->new("$glob does not match $page");
  1753. }
  1754. }
  1755. sub match_internal ($$;@) {
  1756. return match_glob($_[0], $_[1], @_, internal => 1)
  1757. }
  1758. sub match_link ($$;@) {
  1759. my $page=shift;
  1760. my $link=lc(shift);
  1761. my %params=@_;
  1762. $link=derel($link, $params{location});
  1763. my $from=exists $params{location} ? $params{location} : '';
  1764. my $links = $IkiWiki::links{$page};
  1765. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1766. my $bestlink = IkiWiki::bestlink($from, $link);
  1767. foreach my $p (@{$links}) {
  1768. if (length $bestlink) {
  1769. return IkiWiki::SuccessReason->new("$page links to $link")
  1770. if $bestlink eq IkiWiki::bestlink($page, $p);
  1771. }
  1772. else {
  1773. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1774. if match_glob($p, $link, %params);
  1775. $p=~s/^\///;
  1776. $link=~s/^\///;
  1777. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1778. if match_glob($p, $link, %params);
  1779. }
  1780. }
  1781. return IkiWiki::FailReason->new("$page does not link to $link");
  1782. }
  1783. sub match_backlink ($$;@) {
  1784. return match_link($_[1], $_[0], @_);
  1785. }
  1786. sub match_created_before ($$;@) {
  1787. my $page=shift;
  1788. my $testpage=shift;
  1789. my %params=@_;
  1790. $testpage=derel($testpage, $params{location});
  1791. if (exists $IkiWiki::pagectime{$testpage}) {
  1792. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1793. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1794. }
  1795. else {
  1796. return IkiWiki::FailReason->new("$page not created before $testpage");
  1797. }
  1798. }
  1799. else {
  1800. return IkiWiki::FailReason->new("$testpage has no ctime");
  1801. }
  1802. }
  1803. sub match_created_after ($$;@) {
  1804. my $page=shift;
  1805. my $testpage=shift;
  1806. my %params=@_;
  1807. $testpage=derel($testpage, $params{location});
  1808. if (exists $IkiWiki::pagectime{$testpage}) {
  1809. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1810. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1811. }
  1812. else {
  1813. return IkiWiki::FailReason->new("$page not created after $testpage");
  1814. }
  1815. }
  1816. else {
  1817. return IkiWiki::FailReason->new("$testpage has no ctime");
  1818. }
  1819. }
  1820. sub match_creation_day ($$;@) {
  1821. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1822. return IkiWiki::SuccessReason->new('creation_day matched');
  1823. }
  1824. else {
  1825. return IkiWiki::FailReason->new('creation_day did not match');
  1826. }
  1827. }
  1828. sub match_creation_month ($$;@) {
  1829. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1830. return IkiWiki::SuccessReason->new('creation_month matched');
  1831. }
  1832. else {
  1833. return IkiWiki::FailReason->new('creation_month did not match');
  1834. }
  1835. }
  1836. sub match_creation_year ($$;@) {
  1837. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1838. return IkiWiki::SuccessReason->new('creation_year matched');
  1839. }
  1840. else {
  1841. return IkiWiki::FailReason->new('creation_year did not match');
  1842. }
  1843. }
  1844. sub match_user ($$;@) {
  1845. shift;
  1846. my $user=shift;
  1847. my %params=@_;
  1848. if (! exists $params{user}) {
  1849. return IkiWiki::ErrorReason->new("no user specified");
  1850. }
  1851. if (defined $params{user} && lc $params{user} eq lc $user) {
  1852. return IkiWiki::SuccessReason->new("user is $user");
  1853. }
  1854. elsif (! defined $params{user}) {
  1855. return IkiWiki::FailReason->new("not logged in");
  1856. }
  1857. else {
  1858. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1859. }
  1860. }
  1861. sub match_admin ($$;@) {
  1862. shift;
  1863. shift;
  1864. my %params=@_;
  1865. if (! exists $params{user}) {
  1866. return IkiWiki::ErrorReason->new("no user specified");
  1867. }
  1868. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1869. return IkiWiki::SuccessReason->new("user is an admin");
  1870. }
  1871. elsif (! defined $params{user}) {
  1872. return IkiWiki::FailReason->new("not logged in");
  1873. }
  1874. else {
  1875. return IkiWiki::FailReason->new("user is not an admin");
  1876. }
  1877. }
  1878. sub match_ip ($$;@) {
  1879. shift;
  1880. my $ip=shift;
  1881. my %params=@_;
  1882. if (! exists $params{ip}) {
  1883. return IkiWiki::ErrorReason->new("no IP specified");
  1884. }
  1885. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1886. return IkiWiki::SuccessReason->new("IP is $ip");
  1887. }
  1888. else {
  1889. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1890. }
  1891. }
  1892. 1