summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 207ca87fb4d96dbecacddc897015647559d91a62 (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. if (! $config{usedirs} || $page eq 'index') {
  606. return $page.".".$ext;
  607. }
  608. else {
  609. return $page."/index.".$ext;
  610. }
  611. } #}}}
  612. sub htmlpage ($) { #{{{
  613. my $page=shift;
  614. return targetpage($page, $config{htmlext});
  615. } #}}}
  616. sub srcfile_stat { #{{{
  617. my $file=shift;
  618. my $nothrow=shift;
  619. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  620. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  621. return "$dir/$file", stat(_) if -e "$dir/$file";
  622. }
  623. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  624. return;
  625. } #}}}
  626. sub srcfile ($;$) { #{{{
  627. return (srcfile_stat(@_))[0];
  628. } #}}}
  629. sub add_underlay ($) { #{{{
  630. my $dir=shift;
  631. if ($dir !~ /^\//) {
  632. $dir="$config{underlaydir}/../$dir";
  633. }
  634. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  635. unshift @{$config{underlaydirs}}, $dir;
  636. }
  637. return 1;
  638. } #}}}
  639. sub readfile ($;$$) { #{{{
  640. my $file=shift;
  641. my $binary=shift;
  642. my $wantfd=shift;
  643. if (-l $file) {
  644. error("cannot read a symlink ($file)");
  645. }
  646. local $/=undef;
  647. open (my $in, "<", $file) || error("failed to read $file: $!");
  648. binmode($in) if ($binary);
  649. return \*$in if $wantfd;
  650. my $ret=<$in>;
  651. close $in || error("failed to read $file: $!");
  652. return $ret;
  653. } #}}}
  654. sub prep_writefile ($$) { #{{{
  655. my $file=shift;
  656. my $destdir=shift;
  657. my $test=$file;
  658. while (length $test) {
  659. if (-l "$destdir/$test") {
  660. error("cannot write to a symlink ($test)");
  661. }
  662. $test=dirname($test);
  663. }
  664. my $dir=dirname("$destdir/$file");
  665. if (! -d $dir) {
  666. my $d="";
  667. foreach my $s (split(m!/+!, $dir)) {
  668. $d.="$s/";
  669. if (! -d $d) {
  670. mkdir($d) || error("failed to create directory $d: $!");
  671. }
  672. }
  673. }
  674. return 1;
  675. } #}}}
  676. sub writefile ($$$;$$) { #{{{
  677. my $file=shift; # can include subdirs
  678. my $destdir=shift; # directory to put file in
  679. my $content=shift;
  680. my $binary=shift;
  681. my $writer=shift;
  682. prep_writefile($file, $destdir);
  683. my $newfile="$destdir/$file.ikiwiki-new";
  684. if (-l $newfile) {
  685. error("cannot write to a symlink ($newfile)");
  686. }
  687. my $cleanup = sub { unlink($newfile) };
  688. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  689. binmode($out) if ($binary);
  690. if ($writer) {
  691. $writer->(\*$out, $cleanup);
  692. }
  693. else {
  694. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  695. }
  696. close $out || error("failed saving $newfile: $!", $cleanup);
  697. rename($newfile, "$destdir/$file") ||
  698. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  699. return 1;
  700. } #}}}
  701. my %cleared;
  702. sub will_render ($$;$) { #{{{
  703. my $page=shift;
  704. my $dest=shift;
  705. my $clear=shift;
  706. # Important security check.
  707. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  708. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  709. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  710. }
  711. if (! $clear || $cleared{$page}) {
  712. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  713. }
  714. else {
  715. foreach my $old (@{$renderedfiles{$page}}) {
  716. delete $destsources{$old};
  717. }
  718. $renderedfiles{$page}=[$dest];
  719. $cleared{$page}=1;
  720. }
  721. $destsources{$dest}=$page;
  722. return 1;
  723. } #}}}
  724. sub bestlink ($$) { #{{{
  725. my $page=shift;
  726. my $link=shift;
  727. my $cwd=$page;
  728. if ($link=~s/^\/+//) {
  729. # absolute links
  730. $cwd="";
  731. }
  732. $link=~s/\/$//;
  733. do {
  734. my $l=$cwd;
  735. $l.="/" if length $l;
  736. $l.=$link;
  737. if (exists $links{$l}) {
  738. return $l;
  739. }
  740. elsif (exists $pagecase{lc $l}) {
  741. return $pagecase{lc $l};
  742. }
  743. } while $cwd=~s{/?[^/]+$}{};
  744. if (length $config{userdir}) {
  745. my $l = "$config{userdir}/".lc($link);
  746. if (exists $links{$l}) {
  747. return $l;
  748. }
  749. elsif (exists $pagecase{lc $l}) {
  750. return $pagecase{lc $l};
  751. }
  752. }
  753. #print STDERR "warning: page $page, broken link: $link\n";
  754. return "";
  755. } #}}}
  756. sub isinlinableimage ($) { #{{{
  757. my $file=shift;
  758. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  759. } #}}}
  760. sub pagetitle ($;$) { #{{{
  761. my $page=shift;
  762. my $unescaped=shift;
  763. if ($unescaped) {
  764. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  765. }
  766. else {
  767. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  768. }
  769. return $page;
  770. } #}}}
  771. sub titlepage ($) { #{{{
  772. my $title=shift;
  773. # support use w/o %config set
  774. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  775. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  776. return $title;
  777. } #}}}
  778. sub linkpage ($) { #{{{
  779. my $link=shift;
  780. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  781. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  782. return $link;
  783. } #}}}
  784. sub cgiurl (@) { #{{{
  785. my %params=@_;
  786. return $config{cgiurl}."?".
  787. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  788. } #}}}
  789. sub baseurl (;$) { #{{{
  790. my $page=shift;
  791. return "$config{url}/" if ! defined $page;
  792. $page=htmlpage($page);
  793. $page=~s/[^\/]+$//;
  794. $page=~s/[^\/]+\//..\//g;
  795. return $page;
  796. } #}}}
  797. sub abs2rel ($$) { #{{{
  798. # Work around very innefficient behavior in File::Spec if abs2rel
  799. # is passed two relative paths. It's much faster if paths are
  800. # absolute! (Debian bug #376658; fixed in debian unstable now)
  801. my $path="/".shift;
  802. my $base="/".shift;
  803. require File::Spec;
  804. my $ret=File::Spec->abs2rel($path, $base);
  805. $ret=~s/^// if defined $ret;
  806. return $ret;
  807. } #}}}
  808. sub displaytime ($;$) { #{{{
  809. my $time=shift;
  810. my $format=shift;
  811. if (exists $hooks{displaytime}) {
  812. my $ret;
  813. run_hooks(displaytime => sub {
  814. $ret=shift->($time, $format)
  815. });
  816. return $ret;
  817. }
  818. else {
  819. return formattime($time, $format);
  820. }
  821. } #}}}
  822. sub formattime ($;$) { #{{{
  823. # Plugins can override this function to mark up the time for
  824. # display.
  825. my $time=shift;
  826. my $format=shift;
  827. if (! defined $format) {
  828. $format=$config{timeformat};
  829. }
  830. # strftime doesn't know about encodings, so make sure
  831. # its output is properly treated as utf8
  832. return decode_utf8(POSIX::strftime($format, localtime($time)));
  833. } #}}}
  834. sub beautify_urlpath ($) { #{{{
  835. my $url=shift;
  836. if ($config{usedirs}) {
  837. $url =~ s!/index.$config{htmlext}$!/!;
  838. }
  839. # Ensure url is not an empty link, and
  840. # if it's relative, make that explicit to avoid colon confusion.
  841. if ($url !~ /^\//) {
  842. $url="./$url";
  843. }
  844. return $url;
  845. } #}}}
  846. sub urlto ($$;$) { #{{{
  847. my $to=shift;
  848. my $from=shift;
  849. my $absolute=shift;
  850. if (! length $to) {
  851. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  852. }
  853. if (! $destsources{$to}) {
  854. $to=htmlpage($to);
  855. }
  856. if ($absolute) {
  857. return $config{url}.beautify_urlpath("/".$to);
  858. }
  859. my $link = abs2rel($to, dirname(htmlpage($from)));
  860. return beautify_urlpath($link);
  861. } #}}}
  862. sub htmllink ($$$;@) { #{{{
  863. my $lpage=shift; # the page doing the linking
  864. my $page=shift; # the page that will contain the link (different for inline)
  865. my $link=shift;
  866. my %opts=@_;
  867. $link=~s/\/$//;
  868. my $bestlink;
  869. if (! $opts{forcesubpage}) {
  870. $bestlink=bestlink($lpage, $link);
  871. }
  872. else {
  873. $bestlink="$lpage/".lc($link);
  874. }
  875. my $linktext;
  876. if (defined $opts{linktext}) {
  877. $linktext=$opts{linktext};
  878. }
  879. else {
  880. $linktext=pagetitle(basename($link));
  881. }
  882. return "<span class=\"selflink\">$linktext</span>"
  883. if length $bestlink && $page eq $bestlink &&
  884. ! defined $opts{anchor};
  885. if (! $destsources{$bestlink}) {
  886. $bestlink=htmlpage($bestlink);
  887. if (! $destsources{$bestlink}) {
  888. return $linktext unless length $config{cgiurl};
  889. return "<span class=\"createlink\"><a href=\"".
  890. cgiurl(
  891. do => "create",
  892. page => lc($link),
  893. from => $lpage
  894. ).
  895. "\" rel=\"nofollow\">?</a>$linktext</span>"
  896. }
  897. }
  898. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  899. $bestlink=beautify_urlpath($bestlink);
  900. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  901. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  902. }
  903. if (defined $opts{anchor}) {
  904. $bestlink.="#".$opts{anchor};
  905. }
  906. my @attrs;
  907. if (defined $opts{rel}) {
  908. push @attrs, ' rel="'.$opts{rel}.'"';
  909. }
  910. if (defined $opts{class}) {
  911. push @attrs, ' class="'.$opts{class}.'"';
  912. }
  913. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  914. } #}}}
  915. sub userlink ($) { #{{{
  916. my $user=shift;
  917. my $oiduser=eval { openiduser($user) };
  918. if (defined $oiduser) {
  919. return "<a href=\"$user\">$oiduser</a>";
  920. }
  921. else {
  922. eval q{use CGI 'escapeHTML'};
  923. error($@) if $@;
  924. return htmllink("", "", escapeHTML(
  925. length $config{userdir} ? $config{userdir}."/".$user : $user
  926. ), noimageinline => 1);
  927. }
  928. } #}}}
  929. sub htmlize ($$$$) { #{{{
  930. my $page=shift;
  931. my $destpage=shift;
  932. my $type=shift;
  933. my $content=shift;
  934. my $oneline = $content !~ /\n/;
  935. if (exists $hooks{htmlize}{$type}) {
  936. $content=$hooks{htmlize}{$type}{call}->(
  937. page => $page,
  938. content => $content,
  939. );
  940. }
  941. else {
  942. error("htmlization of $type not supported");
  943. }
  944. run_hooks(sanitize => sub {
  945. $content=shift->(
  946. page => $page,
  947. destpage => $destpage,
  948. content => $content,
  949. );
  950. });
  951. if ($oneline) {
  952. # hack to get rid of enclosing junk added by markdown
  953. # and other htmlizers
  954. $content=~s/^<p>//i;
  955. $content=~s/<\/p>$//i;
  956. chomp $content;
  957. }
  958. return $content;
  959. } #}}}
  960. sub linkify ($$$) { #{{{
  961. my $page=shift;
  962. my $destpage=shift;
  963. my $content=shift;
  964. run_hooks(linkify => sub {
  965. $content=shift->(
  966. page => $page,
  967. destpage => $destpage,
  968. content => $content,
  969. );
  970. });
  971. return $content;
  972. } #}}}
  973. our %preprocessing;
  974. our $preprocess_preview=0;
  975. sub preprocess ($$$;$$) { #{{{
  976. my $page=shift; # the page the data comes from
  977. my $destpage=shift; # the page the data will appear in (different for inline)
  978. my $content=shift;
  979. my $scan=shift;
  980. my $preview=shift;
  981. # Using local because it needs to be set within any nested calls
  982. # of this function.
  983. local $preprocess_preview=$preview if defined $preview;
  984. my $handle=sub {
  985. my $escape=shift;
  986. my $prefix=shift;
  987. my $command=shift;
  988. my $params=shift;
  989. $params="" if ! defined $params;
  990. if (length $escape) {
  991. return "[[$prefix$command $params]]";
  992. }
  993. elsif (exists $hooks{preprocess}{$command}) {
  994. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  995. # Note: preserve order of params, some plugins may
  996. # consider it significant.
  997. my @params;
  998. while ($params =~ m{
  999. (?:([-\w]+)=)? # 1: named parameter key?
  1000. (?:
  1001. """(.*?)""" # 2: triple-quoted value
  1002. |
  1003. "([^"]+)" # 3: single-quoted value
  1004. |
  1005. (\S+) # 4: unquoted value
  1006. )
  1007. (?:\s+|$) # delimiter to next param
  1008. }sgx) {
  1009. my $key=$1;
  1010. my $val;
  1011. if (defined $2) {
  1012. $val=$2;
  1013. $val=~s/\r\n/\n/mg;
  1014. $val=~s/^\n+//g;
  1015. $val=~s/\n+$//g;
  1016. }
  1017. elsif (defined $3) {
  1018. $val=$3;
  1019. }
  1020. elsif (defined $4) {
  1021. $val=$4;
  1022. }
  1023. if (defined $key) {
  1024. push @params, $key, $val;
  1025. }
  1026. else {
  1027. push @params, $val, '';
  1028. }
  1029. }
  1030. if ($preprocessing{$page}++ > 3) {
  1031. # Avoid loops of preprocessed pages preprocessing
  1032. # other pages that preprocess them, etc.
  1033. return "[[!$command <span class=\"error\">".
  1034. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1035. $page, $preprocessing{$page}).
  1036. "</span>]]";
  1037. }
  1038. my $ret;
  1039. if (! $scan) {
  1040. $ret=eval {
  1041. $hooks{preprocess}{$command}{call}->(
  1042. @params,
  1043. page => $page,
  1044. destpage => $destpage,
  1045. preview => $preprocess_preview,
  1046. );
  1047. };
  1048. if ($@) {
  1049. chomp $@;
  1050. $ret="[[!$command <span class=\"error\">".
  1051. gettext("Error").": $@"."</span>]]";
  1052. }
  1053. }
  1054. else {
  1055. # use void context during scan pass
  1056. eval {
  1057. $hooks{preprocess}{$command}{call}->(
  1058. @params,
  1059. page => $page,
  1060. destpage => $destpage,
  1061. preview => $preprocess_preview,
  1062. );
  1063. };
  1064. $ret="";
  1065. }
  1066. $preprocessing{$page}--;
  1067. return $ret;
  1068. }
  1069. else {
  1070. return "[[$prefix$command $params]]";
  1071. }
  1072. };
  1073. my $regex;
  1074. if ($config{prefix_directives}) {
  1075. $regex = qr{
  1076. (\\?) # 1: escape?
  1077. \[\[(!) # directive open; 2: prefix
  1078. ([-\w]+) # 3: command
  1079. ( # 4: the parameters..
  1080. \s+ # Must have space if parameters present
  1081. (?:
  1082. (?:[-\w]+=)? # named parameter key?
  1083. (?:
  1084. """.*?""" # triple-quoted value
  1085. |
  1086. "[^"]+" # single-quoted value
  1087. |
  1088. [^\s\]]+ # unquoted value
  1089. )
  1090. \s* # whitespace or end
  1091. # of directive
  1092. )
  1093. *)? # 0 or more parameters
  1094. \]\] # directive closed
  1095. }sx;
  1096. }
  1097. else {
  1098. $regex = qr{
  1099. (\\?) # 1: escape?
  1100. \[\[(!?) # directive open; 2: optional prefix
  1101. ([-\w]+) # 3: command
  1102. \s+
  1103. ( # 4: the parameters..
  1104. (?:
  1105. (?:[-\w]+=)? # named parameter key?
  1106. (?:
  1107. """.*?""" # triple-quoted value
  1108. |
  1109. "[^"]+" # single-quoted value
  1110. |
  1111. [^\s\]]+ # unquoted value
  1112. )
  1113. \s* # whitespace or end
  1114. # of directive
  1115. )
  1116. *) # 0 or more parameters
  1117. \]\] # directive closed
  1118. }sx;
  1119. }
  1120. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1121. return $content;
  1122. } #}}}
  1123. sub filter ($$$) { #{{{
  1124. my $page=shift;
  1125. my $destpage=shift;
  1126. my $content=shift;
  1127. run_hooks(filter => sub {
  1128. $content=shift->(page => $page, destpage => $destpage,
  1129. content => $content);
  1130. });
  1131. return $content;
  1132. } #}}}
  1133. sub indexlink () { #{{{
  1134. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1135. } #}}}
  1136. my $wikilock;
  1137. sub lockwiki (;$) { #{{{
  1138. my $wait=@_ ? shift : 1;
  1139. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1140. # run issues. The lock will be dropped on program exit.
  1141. if (! -d $config{wikistatedir}) {
  1142. mkdir($config{wikistatedir});
  1143. }
  1144. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1145. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1146. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  1147. if ($wait) {
  1148. debug("wiki seems to be locked, waiting for lock");
  1149. my $wait=600; # arbitrary, but don't hang forever to
  1150. # prevent process pileup
  1151. for (1..$wait) {
  1152. return if flock($wikilock, 2 | 4);
  1153. sleep 1;
  1154. }
  1155. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  1156. }
  1157. else {
  1158. return 0;
  1159. }
  1160. }
  1161. return 1;
  1162. } #}}}
  1163. sub unlockwiki () { #{{{
  1164. return close($wikilock) if $wikilock;
  1165. return;
  1166. } #}}}
  1167. my $commitlock;
  1168. sub commit_hook_enabled () { #{{{
  1169. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1170. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1171. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1172. close($commitlock) || error("failed closing commitlock: $!");
  1173. return 0;
  1174. }
  1175. close($commitlock) || error("failed closing commitlock: $!");
  1176. return 1;
  1177. } #}}}
  1178. sub disable_commit_hook () { #{{{
  1179. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1180. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1181. if (! flock($commitlock, 2)) { # LOCK_EX
  1182. error("failed to get commit lock");
  1183. }
  1184. return 1;
  1185. } #}}}
  1186. sub enable_commit_hook () { #{{{
  1187. return close($commitlock) if $commitlock;
  1188. return;
  1189. } #}}}
  1190. sub loadindex () { #{{{
  1191. %oldrenderedfiles=%pagectime=();
  1192. if (! $config{rebuild}) {
  1193. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1194. %destsources=%renderedfiles=%pagecase=%pagestate=();
  1195. }
  1196. my $in;
  1197. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1198. if (-e "$config{wikistatedir}/index") {
  1199. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1200. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1201. }
  1202. else {
  1203. return;
  1204. }
  1205. }
  1206. my $index=Storable::fd_retrieve($in);
  1207. if (! defined $index) {
  1208. return 0;
  1209. }
  1210. my $pages;
  1211. if (exists $index->{version} && ! ref $index->{version}) {
  1212. $pages=$index->{page};
  1213. %wikistate=%{$index->{state}};
  1214. }
  1215. else {
  1216. $pages=$index;
  1217. %wikistate=();
  1218. }
  1219. foreach my $src (keys %$pages) {
  1220. my $d=$pages->{$src};
  1221. my $page=pagename($src);
  1222. $pagectime{$page}=$d->{ctime};
  1223. if (! $config{rebuild}) {
  1224. $pagesources{$page}=$src;
  1225. $pagemtime{$page}=$d->{mtime};
  1226. $renderedfiles{$page}=$d->{dest};
  1227. if (exists $d->{links} && ref $d->{links}) {
  1228. $links{$page}=$d->{links};
  1229. $oldlinks{$page}=[@{$d->{links}}];
  1230. }
  1231. if (exists $d->{depends}) {
  1232. $depends{$page}=$d->{depends};
  1233. }
  1234. if (exists $d->{state}) {
  1235. $pagestate{$page}=$d->{state};
  1236. }
  1237. }
  1238. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1239. }
  1240. foreach my $page (keys %pagesources) {
  1241. $pagecase{lc $page}=$page;
  1242. }
  1243. foreach my $page (keys %renderedfiles) {
  1244. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1245. }
  1246. return close($in);
  1247. } #}}}
  1248. sub saveindex () { #{{{
  1249. run_hooks(savestate => sub { shift->() });
  1250. my %hookids;
  1251. foreach my $type (keys %hooks) {
  1252. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1253. }
  1254. my @hookids=keys %hookids;
  1255. if (! -d $config{wikistatedir}) {
  1256. mkdir($config{wikistatedir});
  1257. }
  1258. my $newfile="$config{wikistatedir}/indexdb.new";
  1259. my $cleanup = sub { unlink($newfile) };
  1260. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1261. my %index;
  1262. foreach my $page (keys %pagemtime) {
  1263. next unless $pagemtime{$page};
  1264. my $src=$pagesources{$page};
  1265. $index{page}{$src}={
  1266. ctime => $pagectime{$page},
  1267. mtime => $pagemtime{$page},
  1268. dest => $renderedfiles{$page},
  1269. links => $links{$page},
  1270. };
  1271. if (exists $depends{$page}) {
  1272. $index{page}{$src}{depends} = $depends{$page};
  1273. }
  1274. if (exists $pagestate{$page}) {
  1275. foreach my $id (@hookids) {
  1276. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1277. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1278. }
  1279. }
  1280. }
  1281. }
  1282. $index{state}={};
  1283. foreach my $id (@hookids) {
  1284. foreach my $key (keys %{$wikistate{$id}}) {
  1285. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1286. }
  1287. }
  1288. $index{version}="3";
  1289. my $ret=Storable::nstore_fd(\%index, $out);
  1290. return if ! defined $ret || ! $ret;
  1291. close $out || error("failed saving to $newfile: $!", $cleanup);
  1292. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1293. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1294. return 1;
  1295. } #}}}
  1296. sub template_file ($) { #{{{
  1297. my $template=shift;
  1298. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1299. return "$dir/$template" if -e "$dir/$template";
  1300. }
  1301. return;
  1302. } #}}}
  1303. sub template_params (@) { #{{{
  1304. my $filename=template_file(shift);
  1305. if (! defined $filename) {
  1306. return if wantarray;
  1307. return "";
  1308. }
  1309. my @ret=(
  1310. filter => sub {
  1311. my $text_ref = shift;
  1312. ${$text_ref} = decode_utf8(${$text_ref});
  1313. },
  1314. filename => $filename,
  1315. loop_context_vars => 1,
  1316. die_on_bad_params => 0,
  1317. @_
  1318. );
  1319. return wantarray ? @ret : {@ret};
  1320. } #}}}
  1321. sub template ($;@) { #{{{
  1322. require HTML::Template;
  1323. return HTML::Template->new(template_params(@_));
  1324. } #}}}
  1325. sub misctemplate ($$;@) { #{{{
  1326. my $title=shift;
  1327. my $pagebody=shift;
  1328. my $template=template("misc.tmpl");
  1329. $template->param(
  1330. title => $title,
  1331. indexlink => indexlink(),
  1332. wikiname => $config{wikiname},
  1333. pagebody => $pagebody,
  1334. baseurl => baseurl(),
  1335. @_,
  1336. );
  1337. run_hooks(pagetemplate => sub {
  1338. shift->(page => "", destpage => "", template => $template);
  1339. });
  1340. return $template->output;
  1341. }#}}}
  1342. sub hook (@) { # {{{
  1343. my %param=@_;
  1344. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1345. error 'hook requires type, call, and id parameters';
  1346. }
  1347. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1348. $hooks{$param{type}}{$param{id}}=\%param;
  1349. return 1;
  1350. } # }}}
  1351. sub run_hooks ($$) { # {{{
  1352. # Calls the given sub for each hook of the given type,
  1353. # passing it the hook function to call.
  1354. my $type=shift;
  1355. my $sub=shift;
  1356. if (exists $hooks{$type}) {
  1357. my @deferred;
  1358. foreach my $id (keys %{$hooks{$type}}) {
  1359. if ($hooks{$type}{$id}{last}) {
  1360. push @deferred, $id;
  1361. next;
  1362. }
  1363. $sub->($hooks{$type}{$id}{call});
  1364. }
  1365. foreach my $id (@deferred) {
  1366. $sub->($hooks{$type}{$id}{call});
  1367. }
  1368. }
  1369. return 1;
  1370. } #}}}
  1371. sub rcs_update () { #{{{
  1372. $hooks{rcs}{rcs_update}{call}->(@_);
  1373. } #}}}
  1374. sub rcs_prepedit ($) { #{{{
  1375. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1376. } #}}}
  1377. sub rcs_commit ($$$;$$) { #{{{
  1378. $hooks{rcs}{rcs_commit}{call}->(@_);
  1379. } #}}}
  1380. sub rcs_commit_staged ($$$) { #{{{
  1381. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1382. } #}}}
  1383. sub rcs_add ($) { #{{{
  1384. $hooks{rcs}{rcs_add}{call}->(@_);
  1385. } #}}}
  1386. sub rcs_remove ($) { #{{{
  1387. $hooks{rcs}{rcs_remove}{call}->(@_);
  1388. } #}}}
  1389. sub rcs_rename ($$) { #{{{
  1390. $hooks{rcs}{rcs_rename}{call}->(@_);
  1391. } #}}}
  1392. sub rcs_recentchanges ($) { #{{{
  1393. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1394. } #}}}
  1395. sub rcs_diff ($) { #{{{
  1396. $hooks{rcs}{rcs_diff}{call}->(@_);
  1397. } #}}}
  1398. sub rcs_getctime ($) { #{{{
  1399. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1400. } #}}}
  1401. sub globlist_to_pagespec ($) { #{{{
  1402. my @globlist=split(' ', shift);
  1403. my (@spec, @skip);
  1404. foreach my $glob (@globlist) {
  1405. if ($glob=~/^!(.*)/) {
  1406. push @skip, $glob;
  1407. }
  1408. else {
  1409. push @spec, $glob;
  1410. }
  1411. }
  1412. my $spec=join(' or ', @spec);
  1413. if (@skip) {
  1414. my $skip=join(' and ', @skip);
  1415. if (length $spec) {
  1416. $spec="$skip and ($spec)";
  1417. }
  1418. else {
  1419. $spec=$skip;
  1420. }
  1421. }
  1422. return $spec;
  1423. } #}}}
  1424. sub is_globlist ($) { #{{{
  1425. my $s=shift;
  1426. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  1427. } #}}}
  1428. sub safequote ($) { #{{{
  1429. my $s=shift;
  1430. $s=~s/[{}]//g;
  1431. return "q{$s}";
  1432. } #}}}
  1433. sub add_depends ($$) { #{{{
  1434. my $page=shift;
  1435. my $pagespec=shift;
  1436. return unless pagespec_valid($pagespec);
  1437. if (! exists $depends{$page}) {
  1438. $depends{$page}=$pagespec;
  1439. }
  1440. else {
  1441. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1442. }
  1443. return 1;
  1444. } # }}}
  1445. sub file_pruned ($$) { #{{{
  1446. require File::Spec;
  1447. my $file=File::Spec->canonpath(shift);
  1448. my $base=File::Spec->canonpath(shift);
  1449. $file =~ s#^\Q$base\E/+##;
  1450. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1451. return $file =~ m/$regexp/ && $file ne $base;
  1452. } #}}}
  1453. sub gettext { #{{{
  1454. # Only use gettext in the rare cases it's needed.
  1455. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1456. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1457. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1458. if (! $gettext_obj) {
  1459. $gettext_obj=eval q{
  1460. use Locale::gettext q{textdomain};
  1461. Locale::gettext->domain('ikiwiki')
  1462. };
  1463. if ($@) {
  1464. print STDERR "$@";
  1465. $gettext_obj=undef;
  1466. return shift;
  1467. }
  1468. }
  1469. return $gettext_obj->get(shift);
  1470. }
  1471. else {
  1472. return shift;
  1473. }
  1474. } #}}}
  1475. sub yesno ($) { #{{{
  1476. my $val=shift;
  1477. return (defined $val && lc($val) eq gettext("yes"));
  1478. } #}}}
  1479. sub pagespec_merge ($$) { #{{{
  1480. my $a=shift;
  1481. my $b=shift;
  1482. return $a if $a eq $b;
  1483. # Support for old-style GlobLists.
  1484. if (is_globlist($a)) {
  1485. $a=globlist_to_pagespec($a);
  1486. }
  1487. if (is_globlist($b)) {
  1488. $b=globlist_to_pagespec($b);
  1489. }
  1490. return "($a) or ($b)";
  1491. } #}}}
  1492. sub pagespec_translate ($) { #{{{
  1493. my $spec=shift;
  1494. # Support for old-style GlobLists.
  1495. if (is_globlist($spec)) {
  1496. $spec=globlist_to_pagespec($spec);
  1497. }
  1498. # Convert spec to perl code.
  1499. my $code="";
  1500. while ($spec=~m{
  1501. \s* # ignore whitespace
  1502. ( # 1: match a single word
  1503. \! # !
  1504. |
  1505. \( # (
  1506. |
  1507. \) # )
  1508. |
  1509. \w+\([^\)]*\) # command(params)
  1510. |
  1511. [^\s()]+ # any other text
  1512. )
  1513. \s* # ignore whitespace
  1514. }igx) {
  1515. my $word=$1;
  1516. if (lc $word eq 'and') {
  1517. $code.=' &&';
  1518. }
  1519. elsif (lc $word eq 'or') {
  1520. $code.=' ||';
  1521. }
  1522. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1523. $code.=' '.$word;
  1524. }
  1525. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1526. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1527. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1528. }
  1529. else {
  1530. $code.=' 0';
  1531. }
  1532. }
  1533. else {
  1534. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1535. }
  1536. }
  1537. if (! length $code) {
  1538. $code=0;
  1539. }
  1540. no warnings;
  1541. return eval 'sub { my $page=shift; '.$code.' }';
  1542. } #}}}
  1543. sub pagespec_match ($$;@) { #{{{
  1544. my $page=shift;
  1545. my $spec=shift;
  1546. my @params=@_;
  1547. # Backwards compatability with old calling convention.
  1548. if (@params == 1) {
  1549. unshift @params, 'location';
  1550. }
  1551. my $sub=pagespec_translate($spec);
  1552. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1553. return $sub->($page, @params);
  1554. } #}}}
  1555. sub pagespec_valid ($) { #{{{
  1556. my $spec=shift;
  1557. my $sub=pagespec_translate($spec);
  1558. return ! $@;
  1559. } #}}}
  1560. sub glob2re ($) { #{{{
  1561. my $re=quotemeta(shift);
  1562. $re=~s/\\\*/.*/g;
  1563. $re=~s/\\\?/./g;
  1564. return $re;
  1565. } #}}}
  1566. package IkiWiki::FailReason;
  1567. use overload ( #{{{
  1568. '""' => sub { ${$_[0]} },
  1569. '0+' => sub { 0 },
  1570. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1571. fallback => 1,
  1572. ); #}}}
  1573. sub new { #{{{
  1574. my $class = shift;
  1575. my $value = shift;
  1576. return bless \$value, $class;
  1577. } #}}}
  1578. package IkiWiki::SuccessReason;
  1579. use overload ( #{{{
  1580. '""' => sub { ${$_[0]} },
  1581. '0+' => sub { 1 },
  1582. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1583. fallback => 1,
  1584. ); #}}}
  1585. sub new { #{{{
  1586. my $class = shift;
  1587. my $value = shift;
  1588. return bless \$value, $class;
  1589. }; #}}}
  1590. package IkiWiki::PageSpec;
  1591. sub match_glob ($$;@) { #{{{
  1592. my $page=shift;
  1593. my $glob=shift;
  1594. my %params=@_;
  1595. my $from=exists $params{location} ? $params{location} : '';
  1596. # relative matching
  1597. if ($glob =~ m!^\./!) {
  1598. $from=~s#/?[^/]+$##;
  1599. $glob=~s#^\./##;
  1600. $glob="$from/$glob" if length $from;
  1601. }
  1602. my $regexp=IkiWiki::glob2re($glob);
  1603. if ($page=~/^$regexp$/i) {
  1604. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1605. return IkiWiki::SuccessReason->new("$glob matches $page");
  1606. }
  1607. else {
  1608. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1609. }
  1610. }
  1611. else {
  1612. return IkiWiki::FailReason->new("$glob does not match $page");
  1613. }
  1614. } #}}}
  1615. sub match_internal ($$;@) { #{{{
  1616. return match_glob($_[0], $_[1], @_, internal => 1)
  1617. } #}}}
  1618. sub match_link ($$;@) { #{{{
  1619. my $page=shift;
  1620. my $link=lc(shift);
  1621. my %params=@_;
  1622. my $from=exists $params{location} ? $params{location} : '';
  1623. # relative matching
  1624. if ($link =~ m!^\.! && defined $from) {
  1625. $from=~s#/?[^/]+$##;
  1626. $link=~s#^\./##;
  1627. $link="$from/$link" if length $from;
  1628. }
  1629. my $links = $IkiWiki::links{$page};
  1630. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1631. my $bestlink = IkiWiki::bestlink($from, $link);
  1632. foreach my $p (@{$links}) {
  1633. if (length $bestlink) {
  1634. return IkiWiki::SuccessReason->new("$page links to $link")
  1635. if $bestlink eq IkiWiki::bestlink($page, $p);
  1636. }
  1637. else {
  1638. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1639. if match_glob($p, $link, %params);
  1640. }
  1641. }
  1642. return IkiWiki::FailReason->new("$page does not link to $link");
  1643. } #}}}
  1644. sub match_backlink ($$;@) { #{{{
  1645. return match_link($_[1], $_[0], @_);
  1646. } #}}}
  1647. sub match_created_before ($$;@) { #{{{
  1648. my $page=shift;
  1649. my $testpage=shift;
  1650. if (exists $IkiWiki::pagectime{$testpage}) {
  1651. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1652. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1653. }
  1654. else {
  1655. return IkiWiki::FailReason->new("$page not created before $testpage");
  1656. }
  1657. }
  1658. else {
  1659. return IkiWiki::FailReason->new("$testpage has no ctime");
  1660. }
  1661. } #}}}
  1662. sub match_created_after ($$;@) { #{{{
  1663. my $page=shift;
  1664. my $testpage=shift;
  1665. if (exists $IkiWiki::pagectime{$testpage}) {
  1666. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1667. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1668. }
  1669. else {
  1670. return IkiWiki::FailReason->new("$page not created after $testpage");
  1671. }
  1672. }
  1673. else {
  1674. return IkiWiki::FailReason->new("$testpage has no ctime");
  1675. }
  1676. } #}}}
  1677. sub match_creation_day ($$;@) { #{{{
  1678. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1679. return IkiWiki::SuccessReason->new('creation_day matched');
  1680. }
  1681. else {
  1682. return IkiWiki::FailReason->new('creation_day did not match');
  1683. }
  1684. } #}}}
  1685. sub match_creation_month ($$;@) { #{{{
  1686. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1687. return IkiWiki::SuccessReason->new('creation_month matched');
  1688. }
  1689. else {
  1690. return IkiWiki::FailReason->new('creation_month did not match');
  1691. }
  1692. } #}}}
  1693. sub match_creation_year ($$;@) { #{{{
  1694. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1695. return IkiWiki::SuccessReason->new('creation_year matched');
  1696. }
  1697. else {
  1698. return IkiWiki::FailReason->new('creation_year did not match');
  1699. }
  1700. } #}}}
  1701. sub match_user ($$;@) { #{{{
  1702. shift;
  1703. my $user=shift;
  1704. my %params=@_;
  1705. if (! exists $params{user}) {
  1706. return IkiWiki::FailReason->new("no user specified");
  1707. }
  1708. if (defined $params{user} && lc $params{user} eq lc $user) {
  1709. return IkiWiki::SuccessReason->new("user is $user");
  1710. }
  1711. elsif (! defined $params{user}) {
  1712. return IkiWiki::FailReason->new("not logged in");
  1713. }
  1714. else {
  1715. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1716. }
  1717. } #}}}
  1718. sub match_admin ($$;@) { #{{{
  1719. shift;
  1720. shift;
  1721. my %params=@_;
  1722. if (! exists $params{user}) {
  1723. return IkiWiki::FailReason->new("no user specified");
  1724. }
  1725. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1726. return IkiWiki::SuccessReason->new("user is an admin");
  1727. }
  1728. elsif (! defined $params{user}) {
  1729. return IkiWiki::FailReason->new("not logged in");
  1730. }
  1731. else {
  1732. return IkiWiki::FailReason->new("user is not an admin");
  1733. }
  1734. } #}}}
  1735. sub match_ip ($$;@) { #{{{
  1736. shift;
  1737. my $ip=shift;
  1738. my %params=@_;
  1739. if (! exists $params{ip}) {
  1740. return IkiWiki::FailReason->new("no IP specified");
  1741. }
  1742. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1743. return IkiWiki::SuccessReason->new("IP is $ip");
  1744. }
  1745. else {
  1746. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1747. }
  1748. } #}}}
  1749. 1