summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 67149bc8bda67ba83a3225273236aceb0156607e (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_EXISTS=1;
  28. our $DEPEND_CONTENT=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 | $DEPEND_EXISTS }
  1379. @{$d->{dependslist}}
  1380. };
  1381. }
  1382. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1383. # old format
  1384. $depends{$page}={$d->{depends} => $DEPEND_CONTENT | $DEPEND_EXISTS};
  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. my $deptype=$DEPEND_CONTENT | $DEPEND_EXISTS;
  1571. if (@_) {
  1572. my %params=@_;
  1573. if (defined $params{content} && $params{content} == 0) {
  1574. $deptype=$deptype & ~$DEPEND_CONTENT;
  1575. }
  1576. }
  1577. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1578. $pagespec !~ /[\s*?()!]/) {
  1579. # a simple dependency, which can be matched by string eq
  1580. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1581. return 1;
  1582. }
  1583. return unless pagespec_valid($pagespec);
  1584. $depends{$page}{$pagespec} |= $deptype;
  1585. return 1;
  1586. }
  1587. sub file_pruned ($$) {
  1588. require File::Spec;
  1589. my $file=File::Spec->canonpath(shift);
  1590. my $base=File::Spec->canonpath(shift);
  1591. $file =~ s#^\Q$base\E/+##;
  1592. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1593. return $file =~ m/$regexp/ && $file ne $base;
  1594. }
  1595. sub define_gettext () {
  1596. # If translation is needed, redefine the gettext function to do it.
  1597. # Otherwise, it becomes a quick no-op.
  1598. no warnings 'redefine';
  1599. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1600. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1601. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1602. *gettext=sub {
  1603. my $gettext_obj=eval q{
  1604. use Locale::gettext q{textdomain};
  1605. Locale::gettext->domain('ikiwiki')
  1606. };
  1607. if ($gettext_obj) {
  1608. $gettext_obj->get(shift);
  1609. }
  1610. else {
  1611. return shift;
  1612. }
  1613. };
  1614. }
  1615. else {
  1616. *gettext=sub { return shift };
  1617. }
  1618. }
  1619. sub gettext {
  1620. define_gettext();
  1621. gettext(@_);
  1622. }
  1623. sub yesno ($) {
  1624. my $val=shift;
  1625. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1626. }
  1627. sub inject {
  1628. # Injects a new function into the symbol table to replace an
  1629. # exported function.
  1630. my %params=@_;
  1631. # This is deep ugly perl foo, beware.
  1632. no strict;
  1633. no warnings;
  1634. if (! defined $params{parent}) {
  1635. $params{parent}='::';
  1636. $params{old}=\&{$params{name}};
  1637. $params{name}=~s/.*:://;
  1638. }
  1639. my $parent=$params{parent};
  1640. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1641. $ns = $params{parent} . $ns;
  1642. inject(%params, parent => $ns) unless $ns eq '::main::';
  1643. *{$ns . $params{name}} = $params{call}
  1644. if exists ${$ns}{$params{name}} &&
  1645. \&{${$ns}{$params{name}}} == $params{old};
  1646. }
  1647. use strict;
  1648. use warnings;
  1649. }
  1650. sub add_link ($$) {
  1651. my $page=shift;
  1652. my $link=shift;
  1653. push @{$links{$page}}, $link
  1654. unless grep { $_ eq $link } @{$links{$page}};
  1655. }
  1656. sub pagespec_translate ($) {
  1657. my $spec=shift;
  1658. # Convert spec to perl code.
  1659. my $code="";
  1660. my @data;
  1661. while ($spec=~m{
  1662. \s* # ignore whitespace
  1663. ( # 1: match a single word
  1664. \! # !
  1665. |
  1666. \( # (
  1667. |
  1668. \) # )
  1669. |
  1670. \w+\([^\)]*\) # command(params)
  1671. |
  1672. [^\s()]+ # any other text
  1673. )
  1674. \s* # ignore whitespace
  1675. }igx) {
  1676. my $word=$1;
  1677. if (lc $word eq 'and') {
  1678. $code.=' &&';
  1679. }
  1680. elsif (lc $word eq 'or') {
  1681. $code.=' ||';
  1682. }
  1683. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1684. $code.=' '.$word;
  1685. }
  1686. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1687. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1688. push @data, $2;
  1689. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1690. }
  1691. else {
  1692. push @data, qq{unknown function in pagespec "$word"};
  1693. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1694. }
  1695. }
  1696. else {
  1697. push @data, $word;
  1698. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1699. }
  1700. }
  1701. if (! length $code) {
  1702. $code="IkiWiki::FailReason->new('empty pagespec')";
  1703. }
  1704. no warnings;
  1705. return eval 'sub { my $page=shift; '.$code.' }';
  1706. }
  1707. sub pagespec_match ($$;@) {
  1708. my $page=shift;
  1709. my $spec=shift;
  1710. my @params=@_;
  1711. # Backwards compatability with old calling convention.
  1712. if (@params == 1) {
  1713. unshift @params, 'location';
  1714. }
  1715. my $sub=pagespec_translate($spec);
  1716. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1717. if $@ || ! defined $sub;
  1718. return $sub->($page, @params);
  1719. }
  1720. sub pagespec_match_list ($$;@) {
  1721. my $pages=shift;
  1722. my $spec=shift;
  1723. my @params=@_;
  1724. my $sub=pagespec_translate($spec);
  1725. error "syntax error in pagespec \"$spec\""
  1726. if $@ || ! defined $sub;
  1727. my @ret;
  1728. my $r;
  1729. foreach my $page (@$pages) {
  1730. $r=$sub->($page, @params);
  1731. push @ret, $page if $r;
  1732. }
  1733. if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
  1734. error(sprintf(gettext("cannot match pages: %s"), $r));
  1735. }
  1736. else {
  1737. return @ret;
  1738. }
  1739. }
  1740. sub pagespec_valid ($) {
  1741. my $spec=shift;
  1742. my $sub=pagespec_translate($spec);
  1743. return ! $@;
  1744. }
  1745. sub glob2re ($) {
  1746. my $re=quotemeta(shift);
  1747. $re=~s/\\\*/.*/g;
  1748. $re=~s/\\\?/./g;
  1749. return $re;
  1750. }
  1751. package IkiWiki::FailReason;
  1752. use overload (
  1753. '""' => sub { ${$_[0]} },
  1754. '0+' => sub { 0 },
  1755. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1756. fallback => 1,
  1757. );
  1758. sub new {
  1759. my $class = shift;
  1760. my $value = shift;
  1761. return bless \$value, $class;
  1762. }
  1763. package IkiWiki::ErrorReason;
  1764. our @ISA = 'IkiWiki::FailReason';
  1765. package IkiWiki::SuccessReason;
  1766. use overload (
  1767. '""' => sub { ${$_[0]} },
  1768. '0+' => sub { 1 },
  1769. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1770. fallback => 1,
  1771. );
  1772. sub new {
  1773. my $class = shift;
  1774. my $value = shift;
  1775. return bless \$value, $class;
  1776. };
  1777. package IkiWiki::PageSpec;
  1778. sub derel ($$) {
  1779. my $path=shift;
  1780. my $from=shift;
  1781. if ($path =~ m!^\./!) {
  1782. $from=~s#/?[^/]+$## if defined $from;
  1783. $path=~s#^\./##;
  1784. $path="$from/$path" if length $from;
  1785. }
  1786. return $path;
  1787. }
  1788. sub match_glob ($$;@) {
  1789. my $page=shift;
  1790. my $glob=shift;
  1791. my %params=@_;
  1792. $glob=derel($glob, $params{location});
  1793. my $regexp=IkiWiki::glob2re($glob);
  1794. if ($page=~/^$regexp$/i) {
  1795. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1796. return IkiWiki::SuccessReason->new("$glob matches $page");
  1797. }
  1798. else {
  1799. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1800. }
  1801. }
  1802. else {
  1803. return IkiWiki::FailReason->new("$glob does not match $page");
  1804. }
  1805. }
  1806. sub match_internal ($$;@) {
  1807. return match_glob($_[0], $_[1], @_, internal => 1)
  1808. }
  1809. sub match_link ($$;@) {
  1810. my $page=shift;
  1811. my $link=lc(shift);
  1812. my %params=@_;
  1813. $link=derel($link, $params{location});
  1814. my $from=exists $params{location} ? $params{location} : '';
  1815. my $links = $IkiWiki::links{$page};
  1816. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1817. my $bestlink = IkiWiki::bestlink($from, $link);
  1818. foreach my $p (@{$links}) {
  1819. if (length $bestlink) {
  1820. return IkiWiki::SuccessReason->new("$page links to $link")
  1821. if $bestlink eq IkiWiki::bestlink($page, $p);
  1822. }
  1823. else {
  1824. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1825. if match_glob($p, $link, %params);
  1826. my ($p_rel)=$p=~/^\/?(.*)/;
  1827. $link=~s/^\///;
  1828. return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link")
  1829. if match_glob($p_rel, $link, %params);
  1830. }
  1831. }
  1832. return IkiWiki::FailReason->new("$page does not link to $link");
  1833. }
  1834. sub match_backlink ($$;@) {
  1835. return match_link($_[1], $_[0], @_);
  1836. }
  1837. sub match_created_before ($$;@) {
  1838. my $page=shift;
  1839. my $testpage=shift;
  1840. my %params=@_;
  1841. $testpage=derel($testpage, $params{location});
  1842. if (exists $IkiWiki::pagectime{$testpage}) {
  1843. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1844. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1845. }
  1846. else {
  1847. return IkiWiki::FailReason->new("$page not created before $testpage");
  1848. }
  1849. }
  1850. else {
  1851. return IkiWiki::ErrorReason->new("$testpage does not exist");
  1852. }
  1853. }
  1854. sub match_created_after ($$;@) {
  1855. my $page=shift;
  1856. my $testpage=shift;
  1857. my %params=@_;
  1858. $testpage=derel($testpage, $params{location});
  1859. if (exists $IkiWiki::pagectime{$testpage}) {
  1860. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1861. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1862. }
  1863. else {
  1864. return IkiWiki::FailReason->new("$page not created after $testpage");
  1865. }
  1866. }
  1867. else {
  1868. return IkiWiki::ErrorReason->new("$testpage does not exist");
  1869. }
  1870. }
  1871. sub match_creation_day ($$;@) {
  1872. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1873. return IkiWiki::SuccessReason->new('creation_day matched');
  1874. }
  1875. else {
  1876. return IkiWiki::FailReason->new('creation_day did not match');
  1877. }
  1878. }
  1879. sub match_creation_month ($$;@) {
  1880. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1881. return IkiWiki::SuccessReason->new('creation_month matched');
  1882. }
  1883. else {
  1884. return IkiWiki::FailReason->new('creation_month did not match');
  1885. }
  1886. }
  1887. sub match_creation_year ($$;@) {
  1888. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1889. return IkiWiki::SuccessReason->new('creation_year matched');
  1890. }
  1891. else {
  1892. return IkiWiki::FailReason->new('creation_year did not match');
  1893. }
  1894. }
  1895. sub match_user ($$;@) {
  1896. shift;
  1897. my $user=shift;
  1898. my %params=@_;
  1899. if (! exists $params{user}) {
  1900. return IkiWiki::ErrorReason->new("no user specified");
  1901. }
  1902. if (defined $params{user} && lc $params{user} eq lc $user) {
  1903. return IkiWiki::SuccessReason->new("user is $user");
  1904. }
  1905. elsif (! defined $params{user}) {
  1906. return IkiWiki::FailReason->new("not logged in");
  1907. }
  1908. else {
  1909. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1910. }
  1911. }
  1912. sub match_admin ($$;@) {
  1913. shift;
  1914. shift;
  1915. my %params=@_;
  1916. if (! exists $params{user}) {
  1917. return IkiWiki::ErrorReason->new("no user specified");
  1918. }
  1919. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1920. return IkiWiki::SuccessReason->new("user is an admin");
  1921. }
  1922. elsif (! defined $params{user}) {
  1923. return IkiWiki::FailReason->new("not logged in");
  1924. }
  1925. else {
  1926. return IkiWiki::FailReason->new("user is not an admin");
  1927. }
  1928. }
  1929. sub match_ip ($$;@) {
  1930. shift;
  1931. my $ip=shift;
  1932. my %params=@_;
  1933. if (! exists $params{ip}) {
  1934. return IkiWiki::ErrorReason->new("no IP specified");
  1935. }
  1936. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1937. return IkiWiki::SuccessReason->new("IP is $ip");
  1938. }
  1939. else {
  1940. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1941. }
  1942. }
  1943. 1