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