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