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