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