summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 5563a03af7d028a88c184d8f2ac227284c475f52 (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. my %pagename_cache;
  624. sub pagename ($) {
  625. my $file=shift;
  626. if (exists $pagename_cache{$file}) {
  627. return $pagename_cache{$file};
  628. }
  629. my $type=pagetype($file);
  630. my $page=$file;
  631. $page=~s/\Q.$type\E*$//
  632. if defined $type && !$hooks{htmlize}{$type}{keepextension}
  633. && !$hooks{htmlize}{$type}{noextension};
  634. if ($config{indexpages} && $page=~/(.*)\/index$/) {
  635. $page=$1;
  636. }
  637. $pagename_cache{$file} = $page;
  638. return $page;
  639. }
  640. sub newpagefile ($$) {
  641. my $page=shift;
  642. my $type=shift;
  643. if (! $config{indexpages} || $page eq 'index') {
  644. return $page.".".$type;
  645. }
  646. else {
  647. return $page."/index.".$type;
  648. }
  649. }
  650. sub targetpage ($$;$) {
  651. my $page=shift;
  652. my $ext=shift;
  653. my $filename=shift;
  654. if (defined $filename) {
  655. return $page."/".$filename.".".$ext;
  656. }
  657. elsif (! $config{usedirs} || $page eq 'index') {
  658. return $page.".".$ext;
  659. }
  660. else {
  661. return $page."/index.".$ext;
  662. }
  663. }
  664. sub htmlpage ($) {
  665. my $page=shift;
  666. return targetpage($page, $config{htmlext});
  667. }
  668. sub srcfile_stat {
  669. my $file=shift;
  670. my $nothrow=shift;
  671. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  672. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  673. return "$dir/$file", stat(_) if -e "$dir/$file";
  674. }
  675. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  676. return;
  677. }
  678. sub srcfile ($;$) {
  679. return (srcfile_stat(@_))[0];
  680. }
  681. sub add_underlay ($) {
  682. my $dir=shift;
  683. if ($dir !~ /^\//) {
  684. $dir="$config{underlaydirbase}/$dir";
  685. }
  686. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  687. unshift @{$config{underlaydirs}}, $dir;
  688. }
  689. return 1;
  690. }
  691. sub readfile ($;$$) {
  692. my $file=shift;
  693. my $binary=shift;
  694. my $wantfd=shift;
  695. if (-l $file) {
  696. error("cannot read a symlink ($file)");
  697. }
  698. local $/=undef;
  699. open (my $in, "<", $file) || error("failed to read $file: $!");
  700. binmode($in) if ($binary);
  701. return \*$in if $wantfd;
  702. my $ret=<$in>;
  703. # check for invalid utf-8, and toss it back to avoid crashes
  704. if (! utf8::valid($ret)) {
  705. $ret=encode_utf8($ret);
  706. }
  707. close $in || error("failed to read $file: $!");
  708. return $ret;
  709. }
  710. sub prep_writefile ($$) {
  711. my $file=shift;
  712. my $destdir=shift;
  713. my $test=$file;
  714. while (length $test) {
  715. if (-l "$destdir/$test") {
  716. error("cannot write to a symlink ($test)");
  717. }
  718. $test=dirname($test);
  719. }
  720. my $dir=dirname("$destdir/$file");
  721. if (! -d $dir) {
  722. my $d="";
  723. foreach my $s (split(m!/+!, $dir)) {
  724. $d.="$s/";
  725. if (! -d $d) {
  726. mkdir($d) || error("failed to create directory $d: $!");
  727. }
  728. }
  729. }
  730. return 1;
  731. }
  732. sub writefile ($$$;$$) {
  733. my $file=shift; # can include subdirs
  734. my $destdir=shift; # directory to put file in
  735. my $content=shift;
  736. my $binary=shift;
  737. my $writer=shift;
  738. prep_writefile($file, $destdir);
  739. my $newfile="$destdir/$file.ikiwiki-new";
  740. if (-l $newfile) {
  741. error("cannot write to a symlink ($newfile)");
  742. }
  743. my $cleanup = sub { unlink($newfile) };
  744. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  745. binmode($out) if ($binary);
  746. if ($writer) {
  747. $writer->(\*$out, $cleanup);
  748. }
  749. else {
  750. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  751. }
  752. close $out || error("failed saving $newfile: $!", $cleanup);
  753. rename($newfile, "$destdir/$file") ||
  754. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  755. return 1;
  756. }
  757. my %cleared;
  758. sub will_render ($$;$) {
  759. my $page=shift;
  760. my $dest=shift;
  761. my $clear=shift;
  762. # Important security check.
  763. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  764. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  765. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  766. }
  767. if (! $clear || $cleared{$page}) {
  768. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  769. }
  770. else {
  771. foreach my $old (@{$renderedfiles{$page}}) {
  772. delete $destsources{$old};
  773. }
  774. $renderedfiles{$page}=[$dest];
  775. $cleared{$page}=1;
  776. }
  777. $destsources{$dest}=$page;
  778. return 1;
  779. }
  780. sub bestlink ($$) {
  781. my $page=shift;
  782. my $link=shift;
  783. my $cwd=$page;
  784. if ($link=~s/^\/+//) {
  785. # absolute links
  786. $cwd="";
  787. }
  788. $link=~s/\/$//;
  789. do {
  790. my $l=$cwd;
  791. $l.="/" if length $l;
  792. $l.=$link;
  793. if (exists $links{$l}) {
  794. return $l;
  795. }
  796. elsif (exists $pagecase{lc $l}) {
  797. return $pagecase{lc $l};
  798. }
  799. } while $cwd=~s{/?[^/]+$}{};
  800. if (length $config{userdir}) {
  801. my $l = "$config{userdir}/".lc($link);
  802. if (exists $links{$l}) {
  803. return $l;
  804. }
  805. elsif (exists $pagecase{lc $l}) {
  806. return $pagecase{lc $l};
  807. }
  808. }
  809. #print STDERR "warning: page $page, broken link: $link\n";
  810. return "";
  811. }
  812. sub isinlinableimage ($) {
  813. my $file=shift;
  814. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  815. }
  816. sub pagetitle ($;$) {
  817. my $page=shift;
  818. my $unescaped=shift;
  819. if ($unescaped) {
  820. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  821. }
  822. else {
  823. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  824. }
  825. return $page;
  826. }
  827. sub titlepage ($) {
  828. my $title=shift;
  829. # support use w/o %config set
  830. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  831. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  832. return $title;
  833. }
  834. sub linkpage ($) {
  835. my $link=shift;
  836. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  837. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  838. return $link;
  839. }
  840. sub cgiurl (@) {
  841. my %params=@_;
  842. return $config{cgiurl}."?".
  843. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  844. }
  845. sub baseurl (;$) {
  846. my $page=shift;
  847. return "$config{url}/" if ! defined $page;
  848. $page=htmlpage($page);
  849. $page=~s/[^\/]+$//;
  850. $page=~s/[^\/]+\//..\//g;
  851. return $page;
  852. }
  853. sub abs2rel ($$) {
  854. # Work around very innefficient behavior in File::Spec if abs2rel
  855. # is passed two relative paths. It's much faster if paths are
  856. # absolute! (Debian bug #376658; fixed in debian unstable now)
  857. my $path="/".shift;
  858. my $base="/".shift;
  859. require File::Spec;
  860. my $ret=File::Spec->abs2rel($path, $base);
  861. $ret=~s/^// if defined $ret;
  862. return $ret;
  863. }
  864. sub displaytime ($;$) {
  865. # Plugins can override this function to mark up the time to
  866. # display.
  867. return '<span class="date">'.formattime(@_).'</span>';
  868. }
  869. sub formattime ($;$) {
  870. # Plugins can override this function to format the time.
  871. my $time=shift;
  872. my $format=shift;
  873. if (! defined $format) {
  874. $format=$config{timeformat};
  875. }
  876. # strftime doesn't know about encodings, so make sure
  877. # its output is properly treated as utf8
  878. return decode_utf8(POSIX::strftime($format, localtime($time)));
  879. }
  880. sub beautify_urlpath ($) {
  881. my $url=shift;
  882. # Ensure url is not an empty link, and if necessary,
  883. # add ./ to avoid colon confusion.
  884. if ($url !~ /^\// && $url !~ /^\.\.?\//) {
  885. $url="./$url";
  886. }
  887. if ($config{usedirs}) {
  888. $url =~ s!/index.$config{htmlext}$!/!;
  889. }
  890. return $url;
  891. }
  892. sub urlto ($$;$) {
  893. my $to=shift;
  894. my $from=shift;
  895. my $absolute=shift;
  896. if (! length $to) {
  897. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  898. }
  899. if (! $destsources{$to}) {
  900. $to=htmlpage($to);
  901. }
  902. if ($absolute) {
  903. return $config{url}.beautify_urlpath("/".$to);
  904. }
  905. my $link = abs2rel($to, dirname(htmlpage($from)));
  906. return beautify_urlpath($link);
  907. }
  908. sub htmllink ($$$;@) {
  909. my $lpage=shift; # the page doing the linking
  910. my $page=shift; # the page that will contain the link (different for inline)
  911. my $link=shift;
  912. my %opts=@_;
  913. $link=~s/\/$//;
  914. my $bestlink;
  915. if (! $opts{forcesubpage}) {
  916. $bestlink=bestlink($lpage, $link);
  917. }
  918. else {
  919. $bestlink="$lpage/".lc($link);
  920. }
  921. my $linktext;
  922. if (defined $opts{linktext}) {
  923. $linktext=$opts{linktext};
  924. }
  925. else {
  926. $linktext=pagetitle(basename($link));
  927. }
  928. return "<span class=\"selflink\">$linktext</span>"
  929. if length $bestlink && $page eq $bestlink &&
  930. ! defined $opts{anchor};
  931. if (! $destsources{$bestlink}) {
  932. $bestlink=htmlpage($bestlink);
  933. if (! $destsources{$bestlink}) {
  934. return $linktext unless length $config{cgiurl};
  935. return "<span class=\"createlink\"><a href=\"".
  936. cgiurl(
  937. do => "create",
  938. page => lc($link),
  939. from => $lpage
  940. ).
  941. "\" rel=\"nofollow\">?</a>$linktext</span>"
  942. }
  943. }
  944. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  945. $bestlink=beautify_urlpath($bestlink);
  946. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  947. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  948. }
  949. if (defined $opts{anchor}) {
  950. $bestlink.="#".$opts{anchor};
  951. }
  952. my @attrs;
  953. if (defined $opts{rel}) {
  954. push @attrs, ' rel="'.$opts{rel}.'"';
  955. }
  956. if (defined $opts{class}) {
  957. push @attrs, ' class="'.$opts{class}.'"';
  958. }
  959. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  960. }
  961. sub openiduser ($) {
  962. my $user=shift;
  963. if ($user =~ m!^https?://! &&
  964. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  965. my $display;
  966. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  967. # this works in at least 2.x
  968. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  969. }
  970. else {
  971. # this only works in 1.x
  972. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  973. $display=$oid->display;
  974. }
  975. # Convert "user.somehost.com" to "user [somehost.com]"
  976. # (also "user.somehost.co.uk")
  977. if ($display !~ /\[/) {
  978. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  979. }
  980. # Convert "http://somehost.com/user" to "user [somehost.com]".
  981. # (also "https://somehost.com/user/")
  982. if ($display !~ /\[/) {
  983. $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
  984. }
  985. $display=~s!^https?://!!; # make sure this is removed
  986. eval q{use CGI 'escapeHTML'};
  987. error($@) if $@;
  988. return escapeHTML($display);
  989. }
  990. return;
  991. }
  992. sub userlink ($) {
  993. my $user=shift;
  994. my $oiduser=eval { openiduser($user) };
  995. if (defined $oiduser) {
  996. return "<a href=\"$user\">$oiduser</a>";
  997. }
  998. else {
  999. eval q{use CGI 'escapeHTML'};
  1000. error($@) if $@;
  1001. return htmllink("", "", escapeHTML(
  1002. length $config{userdir} ? $config{userdir}."/".$user : $user
  1003. ), noimageinline => 1);
  1004. }
  1005. }
  1006. sub htmlize ($$$$) {
  1007. my $page=shift;
  1008. my $destpage=shift;
  1009. my $type=shift;
  1010. my $content=shift;
  1011. my $oneline = $content !~ /\n/;
  1012. if (exists $hooks{htmlize}{$type}) {
  1013. $content=$hooks{htmlize}{$type}{call}->(
  1014. page => $page,
  1015. content => $content,
  1016. );
  1017. }
  1018. else {
  1019. error("htmlization of $type not supported");
  1020. }
  1021. run_hooks(sanitize => sub {
  1022. $content=shift->(
  1023. page => $page,
  1024. destpage => $destpage,
  1025. content => $content,
  1026. );
  1027. });
  1028. if ($oneline) {
  1029. # hack to get rid of enclosing junk added by markdown
  1030. # and other htmlizers
  1031. $content=~s/^<p>//i;
  1032. $content=~s/<\/p>$//i;
  1033. chomp $content;
  1034. }
  1035. return $content;
  1036. }
  1037. sub linkify ($$$) {
  1038. my $page=shift;
  1039. my $destpage=shift;
  1040. my $content=shift;
  1041. run_hooks(linkify => sub {
  1042. $content=shift->(
  1043. page => $page,
  1044. destpage => $destpage,
  1045. content => $content,
  1046. );
  1047. });
  1048. return $content;
  1049. }
  1050. our %preprocessing;
  1051. our $preprocess_preview=0;
  1052. sub preprocess ($$$;$$) {
  1053. my $page=shift; # the page the data comes from
  1054. my $destpage=shift; # the page the data will appear in (different for inline)
  1055. my $content=shift;
  1056. my $scan=shift;
  1057. my $preview=shift;
  1058. # Using local because it needs to be set within any nested calls
  1059. # of this function.
  1060. local $preprocess_preview=$preview if defined $preview;
  1061. my $handle=sub {
  1062. my $escape=shift;
  1063. my $prefix=shift;
  1064. my $command=shift;
  1065. my $params=shift;
  1066. $params="" if ! defined $params;
  1067. if (length $escape) {
  1068. return "[[$prefix$command $params]]";
  1069. }
  1070. elsif (exists $hooks{preprocess}{$command}) {
  1071. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1072. # Note: preserve order of params, some plugins may
  1073. # consider it significant.
  1074. my @params;
  1075. while ($params =~ m{
  1076. (?:([-\w]+)=)? # 1: named parameter key?
  1077. (?:
  1078. """(.*?)""" # 2: triple-quoted value
  1079. |
  1080. "([^"]+)" # 3: single-quoted value
  1081. |
  1082. (\S+) # 4: unquoted value
  1083. )
  1084. (?:\s+|$) # delimiter to next param
  1085. }sgx) {
  1086. my $key=$1;
  1087. my $val;
  1088. if (defined $2) {
  1089. $val=$2;
  1090. $val=~s/\r\n/\n/mg;
  1091. $val=~s/^\n+//g;
  1092. $val=~s/\n+$//g;
  1093. }
  1094. elsif (defined $3) {
  1095. $val=$3;
  1096. }
  1097. elsif (defined $4) {
  1098. $val=$4;
  1099. }
  1100. if (defined $key) {
  1101. push @params, $key, $val;
  1102. }
  1103. else {
  1104. push @params, $val, '';
  1105. }
  1106. }
  1107. if ($preprocessing{$page}++ > 3) {
  1108. # Avoid loops of preprocessed pages preprocessing
  1109. # other pages that preprocess them, etc.
  1110. return "[[!$command <span class=\"error\">".
  1111. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1112. $page, $preprocessing{$page}).
  1113. "</span>]]";
  1114. }
  1115. my $ret;
  1116. if (! $scan) {
  1117. $ret=eval {
  1118. $hooks{preprocess}{$command}{call}->(
  1119. @params,
  1120. page => $page,
  1121. destpage => $destpage,
  1122. preview => $preprocess_preview,
  1123. );
  1124. };
  1125. if ($@) {
  1126. my $error=$@;
  1127. chomp $error;
  1128. $ret="[[!$command <span class=\"error\">".
  1129. gettext("Error").": $error"."</span>]]";
  1130. }
  1131. }
  1132. else {
  1133. # use void context during scan pass
  1134. eval {
  1135. $hooks{preprocess}{$command}{call}->(
  1136. @params,
  1137. page => $page,
  1138. destpage => $destpage,
  1139. preview => $preprocess_preview,
  1140. );
  1141. };
  1142. $ret="";
  1143. }
  1144. $preprocessing{$page}--;
  1145. return $ret;
  1146. }
  1147. else {
  1148. return "[[$prefix$command $params]]";
  1149. }
  1150. };
  1151. my $regex;
  1152. if ($config{prefix_directives}) {
  1153. $regex = qr{
  1154. (\\?) # 1: escape?
  1155. \[\[(!) # directive open; 2: prefix
  1156. ([-\w]+) # 3: command
  1157. ( # 4: the parameters..
  1158. \s+ # Must have space if parameters present
  1159. (?:
  1160. (?:[-\w]+=)? # named parameter key?
  1161. (?:
  1162. """.*?""" # triple-quoted value
  1163. |
  1164. "[^"]+" # single-quoted value
  1165. |
  1166. [^"\s\]]+ # unquoted value
  1167. )
  1168. \s* # whitespace or end
  1169. # of directive
  1170. )
  1171. *)? # 0 or more parameters
  1172. \]\] # directive closed
  1173. }sx;
  1174. }
  1175. else {
  1176. $regex = qr{
  1177. (\\?) # 1: escape?
  1178. \[\[(!?) # directive open; 2: optional prefix
  1179. ([-\w]+) # 3: command
  1180. \s+
  1181. ( # 4: the parameters..
  1182. (?:
  1183. (?:[-\w]+=)? # named parameter key?
  1184. (?:
  1185. """.*?""" # triple-quoted value
  1186. |
  1187. "[^"]+" # single-quoted value
  1188. |
  1189. [^"\s\]]+ # unquoted value
  1190. )
  1191. \s* # whitespace or end
  1192. # of directive
  1193. )
  1194. *) # 0 or more parameters
  1195. \]\] # directive closed
  1196. }sx;
  1197. }
  1198. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1199. return $content;
  1200. }
  1201. sub filter ($$$) {
  1202. my $page=shift;
  1203. my $destpage=shift;
  1204. my $content=shift;
  1205. run_hooks(filter => sub {
  1206. $content=shift->(page => $page, destpage => $destpage,
  1207. content => $content);
  1208. });
  1209. return $content;
  1210. }
  1211. sub indexlink () {
  1212. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1213. }
  1214. sub check_canedit ($$$;$) {
  1215. my $page=shift;
  1216. my $q=shift;
  1217. my $session=shift;
  1218. my $nonfatal=shift;
  1219. my $canedit;
  1220. run_hooks(canedit => sub {
  1221. return if defined $canedit;
  1222. my $ret=shift->($page, $q, $session);
  1223. if (defined $ret) {
  1224. if ($ret eq "") {
  1225. $canedit=1;
  1226. }
  1227. elsif (ref $ret eq 'CODE') {
  1228. $ret->() unless $nonfatal;
  1229. $canedit=0;
  1230. }
  1231. elsif (defined $ret) {
  1232. error($ret) unless $nonfatal;
  1233. $canedit=0;
  1234. }
  1235. }
  1236. });
  1237. return defined $canedit ? $canedit : 1;
  1238. }
  1239. sub check_content (@) {
  1240. my %params=@_;
  1241. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1242. if (exists $pagesources{$params{page}}) {
  1243. my @diff;
  1244. my %old=map { $_ => 1 }
  1245. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1246. foreach my $line (split("\n", $params{content})) {
  1247. push @diff, $line if ! exists $old{$_};
  1248. }
  1249. $params{diff}=join("\n", @diff);
  1250. }
  1251. my $ok;
  1252. run_hooks(checkcontent => sub {
  1253. return if defined $ok;
  1254. my $ret=shift->(%params);
  1255. if (defined $ret) {
  1256. if ($ret eq "") {
  1257. $ok=1;
  1258. }
  1259. elsif (ref $ret eq 'CODE') {
  1260. $ret->() unless $params{nonfatal};
  1261. $ok=0;
  1262. }
  1263. elsif (defined $ret) {
  1264. error($ret) unless $params{nonfatal};
  1265. $ok=0;
  1266. }
  1267. }
  1268. });
  1269. return defined $ok ? $ok : 1;
  1270. }
  1271. my $wikilock;
  1272. sub lockwiki () {
  1273. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1274. # run issues. The lock will be dropped on program exit.
  1275. if (! -d $config{wikistatedir}) {
  1276. mkdir($config{wikistatedir});
  1277. }
  1278. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1279. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1280. if (! flock($wikilock, 2)) { # LOCK_EX
  1281. error("failed to get lock");
  1282. }
  1283. return 1;
  1284. }
  1285. sub unlockwiki () {
  1286. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1287. return close($wikilock) if $wikilock;
  1288. return;
  1289. }
  1290. my $commitlock;
  1291. sub commit_hook_enabled () {
  1292. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1293. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1294. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1295. close($commitlock) || error("failed closing commitlock: $!");
  1296. return 0;
  1297. }
  1298. close($commitlock) || error("failed closing commitlock: $!");
  1299. return 1;
  1300. }
  1301. sub disable_commit_hook () {
  1302. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1303. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1304. if (! flock($commitlock, 2)) { # LOCK_EX
  1305. error("failed to get commit lock");
  1306. }
  1307. return 1;
  1308. }
  1309. sub enable_commit_hook () {
  1310. return close($commitlock) if $commitlock;
  1311. return;
  1312. }
  1313. sub loadindex () {
  1314. %oldrenderedfiles=%pagectime=();
  1315. if (! $config{rebuild}) {
  1316. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1317. %destsources=%renderedfiles=%pagecase=%pagestate=();
  1318. }
  1319. my $in;
  1320. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1321. if (-e "$config{wikistatedir}/index") {
  1322. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1323. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1324. }
  1325. else {
  1326. return;
  1327. }
  1328. }
  1329. my $index=Storable::fd_retrieve($in);
  1330. if (! defined $index) {
  1331. return 0;
  1332. }
  1333. my $pages;
  1334. if (exists $index->{version} && ! ref $index->{version}) {
  1335. $pages=$index->{page};
  1336. %wikistate=%{$index->{state}};
  1337. }
  1338. else {
  1339. $pages=$index;
  1340. %wikistate=();
  1341. }
  1342. foreach my $src (keys %$pages) {
  1343. my $d=$pages->{$src};
  1344. my $page=pagename($src);
  1345. $pagectime{$page}=$d->{ctime};
  1346. if (! $config{rebuild}) {
  1347. $pagesources{$page}=$src;
  1348. $pagemtime{$page}=$d->{mtime};
  1349. $renderedfiles{$page}=$d->{dest};
  1350. if (exists $d->{links} && ref $d->{links}) {
  1351. $links{$page}=$d->{links};
  1352. $oldlinks{$page}=[@{$d->{links}}];
  1353. }
  1354. if (exists $d->{dependslist}) {
  1355. $depends{$page}={
  1356. map { $_ => 1 } @{$d->{dependslist}}
  1357. };
  1358. }
  1359. elsif (exists $d->{depends}) {
  1360. $depends{$page}={$d->{depends} => 1};
  1361. }
  1362. if (exists $d->{state}) {
  1363. $pagestate{$page}=$d->{state};
  1364. }
  1365. }
  1366. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1367. }
  1368. foreach my $page (keys %pagesources) {
  1369. $pagecase{lc $page}=$page;
  1370. }
  1371. foreach my $page (keys %renderedfiles) {
  1372. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1373. }
  1374. return close($in);
  1375. }
  1376. sub saveindex () {
  1377. run_hooks(savestate => sub { shift->() });
  1378. my %hookids;
  1379. foreach my $type (keys %hooks) {
  1380. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1381. }
  1382. my @hookids=keys %hookids;
  1383. if (! -d $config{wikistatedir}) {
  1384. mkdir($config{wikistatedir});
  1385. }
  1386. my $newfile="$config{wikistatedir}/indexdb.new";
  1387. my $cleanup = sub { unlink($newfile) };
  1388. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1389. my %index;
  1390. foreach my $page (keys %pagemtime) {
  1391. next unless $pagemtime{$page};
  1392. my $src=$pagesources{$page};
  1393. $index{page}{$src}={
  1394. ctime => $pagectime{$page},
  1395. mtime => $pagemtime{$page},
  1396. dest => $renderedfiles{$page},
  1397. links => $links{$page},
  1398. };
  1399. if (exists $depends{$page}) {
  1400. $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
  1401. }
  1402. if (exists $pagestate{$page}) {
  1403. foreach my $id (@hookids) {
  1404. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1405. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1406. }
  1407. }
  1408. }
  1409. }
  1410. $index{state}={};
  1411. foreach my $id (@hookids) {
  1412. foreach my $key (keys %{$wikistate{$id}}) {
  1413. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1414. }
  1415. }
  1416. $index{version}="3";
  1417. my $ret=Storable::nstore_fd(\%index, $out);
  1418. return if ! defined $ret || ! $ret;
  1419. close $out || error("failed saving to $newfile: $!", $cleanup);
  1420. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1421. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1422. return 1;
  1423. }
  1424. sub template_file ($) {
  1425. my $template=shift;
  1426. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1427. return "$dir/$template" if -e "$dir/$template";
  1428. }
  1429. return;
  1430. }
  1431. sub template_params (@) {
  1432. my $filename=template_file(shift);
  1433. if (! defined $filename) {
  1434. return if wantarray;
  1435. return "";
  1436. }
  1437. my @ret=(
  1438. filter => sub {
  1439. my $text_ref = shift;
  1440. ${$text_ref} = decode_utf8(${$text_ref});
  1441. },
  1442. filename => $filename,
  1443. loop_context_vars => 1,
  1444. die_on_bad_params => 0,
  1445. @_
  1446. );
  1447. return wantarray ? @ret : {@ret};
  1448. }
  1449. sub template ($;@) {
  1450. require HTML::Template;
  1451. return HTML::Template->new(template_params(@_));
  1452. }
  1453. sub misctemplate ($$;@) {
  1454. my $title=shift;
  1455. my $pagebody=shift;
  1456. my $template=template("misc.tmpl");
  1457. $template->param(
  1458. title => $title,
  1459. indexlink => indexlink(),
  1460. wikiname => $config{wikiname},
  1461. pagebody => $pagebody,
  1462. baseurl => baseurl(),
  1463. @_,
  1464. );
  1465. run_hooks(pagetemplate => sub {
  1466. shift->(page => "", destpage => "", template => $template);
  1467. });
  1468. return $template->output;
  1469. }
  1470. sub hook (@) {
  1471. my %param=@_;
  1472. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1473. error 'hook requires type, call, and id parameters';
  1474. }
  1475. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1476. $hooks{$param{type}}{$param{id}}=\%param;
  1477. return 1;
  1478. }
  1479. sub run_hooks ($$) {
  1480. # Calls the given sub for each hook of the given type,
  1481. # passing it the hook function to call.
  1482. my $type=shift;
  1483. my $sub=shift;
  1484. if (exists $hooks{$type}) {
  1485. my (@first, @middle, @last);
  1486. foreach my $id (keys %{$hooks{$type}}) {
  1487. if ($hooks{$type}{$id}{first}) {
  1488. push @first, $id;
  1489. }
  1490. elsif ($hooks{$type}{$id}{last}) {
  1491. push @last, $id;
  1492. }
  1493. else {
  1494. push @middle, $id;
  1495. }
  1496. }
  1497. foreach my $id (@first, @middle, @last) {
  1498. $sub->($hooks{$type}{$id}{call});
  1499. }
  1500. }
  1501. return 1;
  1502. }
  1503. sub rcs_update () {
  1504. $hooks{rcs}{rcs_update}{call}->(@_);
  1505. }
  1506. sub rcs_prepedit ($) {
  1507. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1508. }
  1509. sub rcs_commit ($$$;$$) {
  1510. $hooks{rcs}{rcs_commit}{call}->(@_);
  1511. }
  1512. sub rcs_commit_staged ($$$) {
  1513. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1514. }
  1515. sub rcs_add ($) {
  1516. $hooks{rcs}{rcs_add}{call}->(@_);
  1517. }
  1518. sub rcs_remove ($) {
  1519. $hooks{rcs}{rcs_remove}{call}->(@_);
  1520. }
  1521. sub rcs_rename ($$) {
  1522. $hooks{rcs}{rcs_rename}{call}->(@_);
  1523. }
  1524. sub rcs_recentchanges ($) {
  1525. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1526. }
  1527. sub rcs_diff ($) {
  1528. $hooks{rcs}{rcs_diff}{call}->(@_);
  1529. }
  1530. sub rcs_getctime ($) {
  1531. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1532. }
  1533. sub rcs_receive () {
  1534. $hooks{rcs}{rcs_receive}{call}->();
  1535. }
  1536. sub add_depends ($$) {
  1537. my $page=shift;
  1538. my $pagespec=shift;
  1539. return unless pagespec_valid($pagespec);
  1540. $depends{$page}{$pagespec} = 1;
  1541. return 1;
  1542. }
  1543. sub file_pruned ($$) {
  1544. require File::Spec;
  1545. my $file=File::Spec->canonpath(shift);
  1546. my $base=File::Spec->canonpath(shift);
  1547. $file =~ s#^\Q$base\E/+##;
  1548. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1549. return $file =~ m/$regexp/ && $file ne $base;
  1550. }
  1551. sub define_gettext () {
  1552. # If translation is needed, redefine the gettext function to do it.
  1553. # Otherwise, it becomes a quick no-op.
  1554. no warnings 'redefine';
  1555. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1556. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1557. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1558. *gettext=sub {
  1559. my $gettext_obj=eval q{
  1560. use Locale::gettext q{textdomain};
  1561. Locale::gettext->domain('ikiwiki')
  1562. };
  1563. if ($gettext_obj) {
  1564. $gettext_obj->get(shift);
  1565. }
  1566. else {
  1567. return shift;
  1568. }
  1569. };
  1570. }
  1571. else {
  1572. *gettext=sub { return shift };
  1573. }
  1574. }
  1575. sub gettext {
  1576. define_gettext();
  1577. gettext(@_);
  1578. }
  1579. sub yesno ($) {
  1580. my $val=shift;
  1581. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1582. }
  1583. sub inject {
  1584. # Injects a new function into the symbol table to replace an
  1585. # exported function.
  1586. my %params=@_;
  1587. # This is deep ugly perl foo, beware.
  1588. no strict;
  1589. no warnings;
  1590. if (! defined $params{parent}) {
  1591. $params{parent}='::';
  1592. $params{old}=\&{$params{name}};
  1593. $params{name}=~s/.*:://;
  1594. }
  1595. my $parent=$params{parent};
  1596. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1597. $ns = $params{parent} . $ns;
  1598. inject(%params, parent => $ns) unless $ns eq '::main::';
  1599. *{$ns . $params{name}} = $params{call}
  1600. if exists ${$ns}{$params{name}} &&
  1601. \&{${$ns}{$params{name}}} == $params{old};
  1602. }
  1603. use strict;
  1604. use warnings;
  1605. }
  1606. sub add_link ($$) {
  1607. my $page=shift;
  1608. my $link=shift;
  1609. push @{$links{$page}}, $link
  1610. unless grep { $_ eq $link } @{$links{$page}};
  1611. }
  1612. sub pagespec_translate ($) {
  1613. my $spec=shift;
  1614. # Convert spec to perl code.
  1615. my $code="";
  1616. my @data;
  1617. while ($spec=~m{
  1618. \s* # ignore whitespace
  1619. ( # 1: match a single word
  1620. \! # !
  1621. |
  1622. \( # (
  1623. |
  1624. \) # )
  1625. |
  1626. \w+\([^\)]*\) # command(params)
  1627. |
  1628. [^\s()]+ # any other text
  1629. )
  1630. \s* # ignore whitespace
  1631. }igx) {
  1632. my $word=$1;
  1633. if (lc $word eq 'and') {
  1634. $code.=' &&';
  1635. }
  1636. elsif (lc $word eq 'or') {
  1637. $code.=' ||';
  1638. }
  1639. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1640. $code.=' '.$word;
  1641. }
  1642. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1643. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1644. push @data, $2;
  1645. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1646. }
  1647. else {
  1648. push @data, qq{unknown function in pagespec "$word"};
  1649. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1650. }
  1651. }
  1652. else {
  1653. push @data, $word;
  1654. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1655. }
  1656. }
  1657. if (! length $code) {
  1658. $code="IkiWiki::FailReason->new('empty pagespec')";
  1659. }
  1660. no warnings;
  1661. return eval 'sub { my $page=shift; '.$code.' }';
  1662. }
  1663. sub pagespec_match ($$;@) {
  1664. my $page=shift;
  1665. my $spec=shift;
  1666. my @params=@_;
  1667. # Backwards compatability with old calling convention.
  1668. if (@params == 1) {
  1669. unshift @params, 'location';
  1670. }
  1671. my $sub=pagespec_translate($spec);
  1672. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1673. if $@ || ! defined $sub;
  1674. return $sub->($page, @params);
  1675. }
  1676. sub pagespec_match_list ($$;@) {
  1677. my $pages=shift;
  1678. my $spec=shift;
  1679. my @params=@_;
  1680. my $sub=pagespec_translate($spec);
  1681. error "syntax error in pagespec \"$spec\""
  1682. if $@ || ! defined $sub;
  1683. my @ret;
  1684. my $r;
  1685. foreach my $page (@$pages) {
  1686. $r=$sub->($page, @params);
  1687. push @ret, $page if $r;
  1688. }
  1689. if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
  1690. error(sprintf(gettext("cannot match pages: %s"), $r));
  1691. }
  1692. else {
  1693. return @ret;
  1694. }
  1695. }
  1696. sub pagespec_valid ($) {
  1697. my $spec=shift;
  1698. my $sub=pagespec_translate($spec);
  1699. return ! $@;
  1700. }
  1701. sub glob2re ($) {
  1702. my $re=quotemeta(shift);
  1703. $re=~s/\\\*/.*/g;
  1704. $re=~s/\\\?/./g;
  1705. return $re;
  1706. }
  1707. package IkiWiki::FailReason;
  1708. use overload (
  1709. '""' => sub { ${$_[0]} },
  1710. '0+' => sub { 0 },
  1711. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1712. fallback => 1,
  1713. );
  1714. sub new {
  1715. my $class = shift;
  1716. my $value = shift;
  1717. return bless \$value, $class;
  1718. }
  1719. package IkiWiki::ErrorReason;
  1720. our @ISA = 'IkiWiki::FailReason';
  1721. package IkiWiki::SuccessReason;
  1722. use overload (
  1723. '""' => sub { ${$_[0]} },
  1724. '0+' => sub { 1 },
  1725. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1726. fallback => 1,
  1727. );
  1728. sub new {
  1729. my $class = shift;
  1730. my $value = shift;
  1731. return bless \$value, $class;
  1732. };
  1733. package IkiWiki::PageSpec;
  1734. sub derel ($$) {
  1735. my $path=shift;
  1736. my $from=shift;
  1737. if ($path =~ m!^\./!) {
  1738. $from=~s#/?[^/]+$## if defined $from;
  1739. $path=~s#^\./##;
  1740. $path="$from/$path" if length $from;
  1741. }
  1742. return $path;
  1743. }
  1744. sub match_glob ($$;@) {
  1745. my $page=shift;
  1746. my $glob=shift;
  1747. my %params=@_;
  1748. $glob=derel($glob, $params{location});
  1749. my $regexp=IkiWiki::glob2re($glob);
  1750. if ($page=~/^$regexp$/i) {
  1751. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1752. return IkiWiki::SuccessReason->new("$glob matches $page");
  1753. }
  1754. else {
  1755. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1756. }
  1757. }
  1758. else {
  1759. return IkiWiki::FailReason->new("$glob does not match $page");
  1760. }
  1761. }
  1762. sub match_internal ($$;@) {
  1763. return match_glob($_[0], $_[1], @_, internal => 1)
  1764. }
  1765. sub match_link ($$;@) {
  1766. my $page=shift;
  1767. my $link=lc(shift);
  1768. my %params=@_;
  1769. $link=derel($link, $params{location});
  1770. my $from=exists $params{location} ? $params{location} : '';
  1771. my $links = $IkiWiki::links{$page};
  1772. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1773. my $bestlink = IkiWiki::bestlink($from, $link);
  1774. foreach my $p (@{$links}) {
  1775. if (length $bestlink) {
  1776. return IkiWiki::SuccessReason->new("$page links to $link")
  1777. if $bestlink eq IkiWiki::bestlink($page, $p);
  1778. }
  1779. else {
  1780. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1781. if match_glob($p, $link, %params);
  1782. $p=~s/^\///;
  1783. $link=~s/^\///;
  1784. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1785. if match_glob($p, $link, %params);
  1786. }
  1787. }
  1788. return IkiWiki::FailReason->new("$page does not link to $link");
  1789. }
  1790. sub match_backlink ($$;@) {
  1791. return match_link($_[1], $_[0], @_);
  1792. }
  1793. sub match_created_before ($$;@) {
  1794. my $page=shift;
  1795. my $testpage=shift;
  1796. my %params=@_;
  1797. $testpage=derel($testpage, $params{location});
  1798. if (exists $IkiWiki::pagectime{$testpage}) {
  1799. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1800. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1801. }
  1802. else {
  1803. return IkiWiki::FailReason->new("$page not created before $testpage");
  1804. }
  1805. }
  1806. else {
  1807. return IkiWiki::ErrorReason->new("$testpage does not exist");
  1808. }
  1809. }
  1810. sub match_created_after ($$;@) {
  1811. my $page=shift;
  1812. my $testpage=shift;
  1813. my %params=@_;
  1814. $testpage=derel($testpage, $params{location});
  1815. if (exists $IkiWiki::pagectime{$testpage}) {
  1816. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1817. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1818. }
  1819. else {
  1820. return IkiWiki::FailReason->new("$page not created after $testpage");
  1821. }
  1822. }
  1823. else {
  1824. return IkiWiki::ErrorReason->new("$testpage does not exist");
  1825. }
  1826. }
  1827. sub match_creation_day ($$;@) {
  1828. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1829. return IkiWiki::SuccessReason->new('creation_day matched');
  1830. }
  1831. else {
  1832. return IkiWiki::FailReason->new('creation_day did not match');
  1833. }
  1834. }
  1835. sub match_creation_month ($$;@) {
  1836. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1837. return IkiWiki::SuccessReason->new('creation_month matched');
  1838. }
  1839. else {
  1840. return IkiWiki::FailReason->new('creation_month did not match');
  1841. }
  1842. }
  1843. sub match_creation_year ($$;@) {
  1844. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1845. return IkiWiki::SuccessReason->new('creation_year matched');
  1846. }
  1847. else {
  1848. return IkiWiki::FailReason->new('creation_year did not match');
  1849. }
  1850. }
  1851. sub match_user ($$;@) {
  1852. shift;
  1853. my $user=shift;
  1854. my %params=@_;
  1855. if (! exists $params{user}) {
  1856. return IkiWiki::ErrorReason->new("no user specified");
  1857. }
  1858. if (defined $params{user} && lc $params{user} eq lc $user) {
  1859. return IkiWiki::SuccessReason->new("user is $user");
  1860. }
  1861. elsif (! defined $params{user}) {
  1862. return IkiWiki::FailReason->new("not logged in");
  1863. }
  1864. else {
  1865. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1866. }
  1867. }
  1868. sub match_admin ($$;@) {
  1869. shift;
  1870. shift;
  1871. my %params=@_;
  1872. if (! exists $params{user}) {
  1873. return IkiWiki::ErrorReason->new("no user specified");
  1874. }
  1875. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1876. return IkiWiki::SuccessReason->new("user is an admin");
  1877. }
  1878. elsif (! defined $params{user}) {
  1879. return IkiWiki::FailReason->new("not logged in");
  1880. }
  1881. else {
  1882. return IkiWiki::FailReason->new("user is not an admin");
  1883. }
  1884. }
  1885. sub match_ip ($$;@) {
  1886. shift;
  1887. my $ip=shift;
  1888. my %params=@_;
  1889. if (! exists $params{ip}) {
  1890. return IkiWiki::ErrorReason->new("no IP specified");
  1891. }
  1892. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1893. return IkiWiki::SuccessReason->new("IP is $ip");
  1894. }
  1895. else {
  1896. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1897. }
  1898. }
  1899. 1