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