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