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