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