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