summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 97946bfcf888a185a193cf5d4ef2f2c353cdb058 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use URI::Escape q{uri_escape_utf8};
  7. use POSIX ();
  8. use Storable;
  9. use open qw{:utf8 :std};
  10. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  11. %pagestate %wikistate %renderedfiles %oldrenderedfiles
  12. %pagesources %delpagesources %destsources %depends %depends_simple
  13. @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
  14. %oldtypedlinks %autofiles};
  15. use Exporter q{import};
  16. our @EXPORT = qw(hook debug error htmlpage template template_depends
  17. deptype add_depends pagespec_match pagespec_match_list bestlink
  18. htmllink readfile writefile pagetype srcfile pagename
  19. displaytime will_render gettext ngettext urlto targetpage
  20. add_underlay pagetitle titlepage linkpage newpagefile
  21. inject add_link add_autofile
  22. %config %links %pagestate %wikistate %renderedfiles
  23. %pagesources %destsources %typedlinks);
  24. our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
  25. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  26. our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  27. # Page dependency types.
  28. our $DEPEND_CONTENT=1;
  29. our $DEPEND_PRESENCE=2;
  30. our $DEPEND_LINKS=4;
  31. # Optimisation.
  32. use Memoize;
  33. memoize("abs2rel");
  34. memoize("sortspec_translate");
  35. memoize("pagespec_translate");
  36. memoize("template_file");
  37. sub getsetup () {
  38. wikiname => {
  39. type => "string",
  40. default => "wiki",
  41. description => "name of the wiki",
  42. safe => 1,
  43. rebuild => 1,
  44. },
  45. adminemail => {
  46. type => "string",
  47. default => undef,
  48. example => 'me@example.com',
  49. description => "contact email for wiki",
  50. safe => 1,
  51. rebuild => 0,
  52. },
  53. adminuser => {
  54. type => "string",
  55. default => [],
  56. description => "users who are wiki admins",
  57. safe => 1,
  58. rebuild => 0,
  59. },
  60. banned_users => {
  61. type => "string",
  62. default => [],
  63. description => "users who are banned from the wiki",
  64. safe => 1,
  65. rebuild => 0,
  66. },
  67. srcdir => {
  68. type => "string",
  69. default => undef,
  70. example => "$ENV{HOME}/wiki",
  71. description => "where the source of the wiki is located",
  72. safe => 0, # path
  73. rebuild => 1,
  74. },
  75. destdir => {
  76. type => "string",
  77. default => undef,
  78. example => "/var/www/wiki",
  79. description => "where to build the wiki",
  80. safe => 0, # path
  81. rebuild => 1,
  82. },
  83. url => {
  84. type => "string",
  85. default => '',
  86. example => "http://example.com/wiki",
  87. description => "base url to the wiki",
  88. safe => 1,
  89. rebuild => 1,
  90. },
  91. cgiurl => {
  92. type => "string",
  93. default => '',
  94. example => "http://example.com/wiki/ikiwiki.cgi",
  95. description => "url to the ikiwiki.cgi",
  96. safe => 1,
  97. rebuild => 1,
  98. },
  99. cgi_wrapper => {
  100. type => "string",
  101. default => '',
  102. example => "/var/www/wiki/ikiwiki.cgi",
  103. description => "filename of cgi wrapper to generate",
  104. safe => 0, # file
  105. rebuild => 0,
  106. },
  107. cgi_wrappermode => {
  108. type => "string",
  109. default => '06755',
  110. description => "mode for cgi_wrapper (can safely be made suid)",
  111. safe => 0,
  112. rebuild => 0,
  113. },
  114. rcs => {
  115. type => "string",
  116. default => '',
  117. description => "rcs backend to use",
  118. safe => 0, # don't allow overriding
  119. rebuild => 0,
  120. },
  121. default_plugins => {
  122. type => "internal",
  123. default => [qw{mdwn link inline meta htmlscrubber passwordauth
  124. openid signinedit lockedit conditional
  125. recentchanges parentlinks editpage}],
  126. description => "plugins to enable by default",
  127. safe => 0,
  128. rebuild => 1,
  129. },
  130. add_plugins => {
  131. type => "string",
  132. default => [],
  133. description => "plugins to add to the default configuration",
  134. safe => 1,
  135. rebuild => 1,
  136. },
  137. disable_plugins => {
  138. type => "string",
  139. default => [],
  140. description => "plugins to disable",
  141. safe => 1,
  142. rebuild => 1,
  143. },
  144. templatedir => {
  145. type => "string",
  146. default => "$installdir/share/ikiwiki/templates",
  147. description => "additional directory to search for template files",
  148. advanced => 1,
  149. safe => 0, # path
  150. rebuild => 1,
  151. },
  152. underlaydir => {
  153. type => "string",
  154. default => "$installdir/share/ikiwiki/basewiki",
  155. description => "base wiki source location",
  156. advanced => 1,
  157. safe => 0, # path
  158. rebuild => 0,
  159. },
  160. underlaydirbase => {
  161. type => "internal",
  162. default => "$installdir/share/ikiwiki",
  163. description => "parent directory containing additional underlays",
  164. safe => 0,
  165. rebuild => 0,
  166. },
  167. wrappers => {
  168. type => "internal",
  169. default => [],
  170. description => "wrappers to generate",
  171. safe => 0,
  172. rebuild => 0,
  173. },
  174. underlaydirs => {
  175. type => "internal",
  176. default => [],
  177. description => "additional underlays to use",
  178. safe => 0,
  179. rebuild => 0,
  180. },
  181. verbose => {
  182. type => "boolean",
  183. example => 1,
  184. description => "display verbose messages?",
  185. safe => 1,
  186. rebuild => 0,
  187. },
  188. syslog => {
  189. type => "boolean",
  190. example => 1,
  191. description => "log to syslog?",
  192. safe => 1,
  193. rebuild => 0,
  194. },
  195. usedirs => {
  196. type => "boolean",
  197. default => 1,
  198. description => "create output files named page/index.html?",
  199. safe => 0, # changing requires manual transition
  200. rebuild => 1,
  201. },
  202. prefix_directives => {
  203. type => "boolean",
  204. default => 1,
  205. description => "use '!'-prefixed preprocessor directives?",
  206. safe => 0, # changing requires manual transition
  207. rebuild => 1,
  208. },
  209. indexpages => {
  210. type => "boolean",
  211. default => 0,
  212. description => "use page/index.mdwn source files",
  213. safe => 1,
  214. rebuild => 1,
  215. },
  216. discussion => {
  217. type => "boolean",
  218. default => 1,
  219. description => "enable Discussion pages?",
  220. safe => 1,
  221. rebuild => 1,
  222. },
  223. discussionpage => {
  224. type => "string",
  225. default => gettext("Discussion"),
  226. description => "name of Discussion pages",
  227. safe => 1,
  228. rebuild => 1,
  229. },
  230. html5 => {
  231. type => "boolean",
  232. default => 0,
  233. description => "generate HTML5? (experimental)",
  234. advanced => 1,
  235. safe => 1,
  236. rebuild => 1,
  237. },
  238. sslcookie => {
  239. type => "boolean",
  240. default => 0,
  241. description => "only send cookies over SSL connections?",
  242. advanced => 1,
  243. safe => 1,
  244. rebuild => 0,
  245. },
  246. default_pageext => {
  247. type => "string",
  248. default => "mdwn",
  249. description => "extension to use for new pages",
  250. safe => 0, # not sanitized
  251. rebuild => 0,
  252. },
  253. htmlext => {
  254. type => "string",
  255. default => "html",
  256. description => "extension to use for html files",
  257. safe => 0, # not sanitized
  258. rebuild => 1,
  259. },
  260. timeformat => {
  261. type => "string",
  262. default => '%c',
  263. description => "strftime format string to display date",
  264. advanced => 1,
  265. safe => 1,
  266. rebuild => 1,
  267. },
  268. locale => {
  269. type => "string",
  270. default => undef,
  271. example => "en_US.UTF-8",
  272. description => "UTF-8 locale to use",
  273. advanced => 1,
  274. safe => 0,
  275. rebuild => 1,
  276. },
  277. userdir => {
  278. type => "string",
  279. default => "",
  280. example => "users",
  281. description => "put user pages below specified page",
  282. safe => 1,
  283. rebuild => 1,
  284. },
  285. numbacklinks => {
  286. type => "integer",
  287. default => 10,
  288. description => "how many backlinks to show before hiding excess (0 to show all)",
  289. safe => 1,
  290. rebuild => 1,
  291. },
  292. hardlink => {
  293. type => "boolean",
  294. default => 0,
  295. description => "attempt to hardlink source files? (optimisation for large files)",
  296. advanced => 1,
  297. safe => 0, # paranoia
  298. rebuild => 0,
  299. },
  300. umask => {
  301. type => "integer",
  302. example => "022",
  303. description => "force ikiwiki to use a particular umask",
  304. advanced => 1,
  305. safe => 0, # paranoia
  306. rebuild => 0,
  307. },
  308. wrappergroup => {
  309. type => "string",
  310. example => "ikiwiki",
  311. description => "group for wrappers to run in",
  312. advanced => 1,
  313. safe => 0, # paranoia
  314. rebuild => 0,
  315. },
  316. libdir => {
  317. type => "string",
  318. default => "",
  319. example => "$ENV{HOME}/.ikiwiki/",
  320. description => "extra library and plugin directory",
  321. advanced => 1,
  322. safe => 0, # directory
  323. rebuild => 0,
  324. },
  325. ENV => {
  326. type => "string",
  327. default => {},
  328. description => "environment variables",
  329. safe => 0, # paranoia
  330. rebuild => 0,
  331. },
  332. include => {
  333. type => "string",
  334. default => undef,
  335. example => '^\.htaccess$',
  336. description => "regexp of normally excluded files to include",
  337. advanced => 1,
  338. safe => 0, # regexp
  339. rebuild => 1,
  340. },
  341. exclude => {
  342. type => "string",
  343. default => undef,
  344. example => '^(*\.private|Makefile)$',
  345. description => "regexp of files that should be skipped",
  346. advanced => 1,
  347. safe => 0, # regexp
  348. rebuild => 1,
  349. },
  350. wiki_file_prune_regexps => {
  351. type => "internal",
  352. default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
  353. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  354. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  355. qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
  356. qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
  357. description => "regexps of source files to ignore",
  358. safe => 0,
  359. rebuild => 1,
  360. },
  361. wiki_file_chars => {
  362. type => "string",
  363. description => "specifies the characters that are allowed in source filenames",
  364. default => "-[:alnum:]+/.:_",
  365. safe => 0,
  366. rebuild => 1,
  367. },
  368. wiki_file_regexp => {
  369. type => "internal",
  370. description => "regexp of legal source files",
  371. safe => 0,
  372. rebuild => 1,
  373. },
  374. web_commit_regexp => {
  375. type => "internal",
  376. default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
  377. description => "regexp to parse web commits from logs",
  378. safe => 0,
  379. rebuild => 0,
  380. },
  381. cgi => {
  382. type => "internal",
  383. default => 0,
  384. description => "run as a cgi",
  385. safe => 0,
  386. rebuild => 0,
  387. },
  388. cgi_disable_uploads => {
  389. type => "internal",
  390. default => 1,
  391. description => "whether CGI should accept file uploads",
  392. safe => 0,
  393. rebuild => 0,
  394. },
  395. post_commit => {
  396. type => "internal",
  397. default => 0,
  398. description => "run as a post-commit hook",
  399. safe => 0,
  400. rebuild => 0,
  401. },
  402. rebuild => {
  403. type => "internal",
  404. default => 0,
  405. description => "running in rebuild mode",
  406. safe => 0,
  407. rebuild => 0,
  408. },
  409. setup => {
  410. type => "internal",
  411. default => undef,
  412. description => "running in setup mode",
  413. safe => 0,
  414. rebuild => 0,
  415. },
  416. clean => {
  417. type => "internal",
  418. default => 0,
  419. description => "running in clean mode",
  420. safe => 0,
  421. rebuild => 0,
  422. },
  423. refresh => {
  424. type => "internal",
  425. default => 0,
  426. description => "running in refresh mode",
  427. safe => 0,
  428. rebuild => 0,
  429. },
  430. test_receive => {
  431. type => "internal",
  432. default => 0,
  433. description => "running in receive test mode",
  434. safe => 0,
  435. rebuild => 0,
  436. },
  437. wrapper_background_command => {
  438. type => "internal",
  439. default => '',
  440. description => "background shell command to run",
  441. safe => 0,
  442. rebuild => 0,
  443. },
  444. gettime => {
  445. type => "internal",
  446. description => "running in gettime mode",
  447. safe => 0,
  448. rebuild => 0,
  449. },
  450. w3mmode => {
  451. type => "internal",
  452. default => 0,
  453. description => "running in w3mmode",
  454. safe => 0,
  455. rebuild => 0,
  456. },
  457. wikistatedir => {
  458. type => "internal",
  459. default => undef,
  460. description => "path to the .ikiwiki directory holding ikiwiki state",
  461. safe => 0,
  462. rebuild => 0,
  463. },
  464. setupfile => {
  465. type => "internal",
  466. default => undef,
  467. description => "path to setup file",
  468. safe => 0,
  469. rebuild => 0,
  470. },
  471. setuptype => {
  472. type => "internal",
  473. default => "Standard",
  474. description => "perl class to use to dump setup file",
  475. safe => 0,
  476. rebuild => 0,
  477. },
  478. allow_symlinks_before_srcdir => {
  479. type => "boolean",
  480. default => 0,
  481. description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
  482. safe => 0,
  483. rebuild => 0,
  484. },
  485. }
  486. sub defaultconfig () {
  487. my %s=getsetup();
  488. my @ret;
  489. foreach my $key (keys %s) {
  490. push @ret, $key, $s{$key}->{default};
  491. }
  492. use Data::Dumper;
  493. return @ret;
  494. }
  495. # URL to top of wiki as a path starting with /, valid from any wiki page or
  496. # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
  497. my $local_url;
  498. # URL to CGI script, similar to $local_url
  499. my $local_cgiurl;
  500. sub checkconfig () {
  501. # locale stuff; avoid LC_ALL since it overrides everything
  502. if (defined $ENV{LC_ALL}) {
  503. $ENV{LANG} = $ENV{LC_ALL};
  504. delete $ENV{LC_ALL};
  505. }
  506. if (defined $config{locale}) {
  507. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  508. $ENV{LANG}=$config{locale};
  509. define_gettext();
  510. }
  511. }
  512. if (! defined $config{wiki_file_regexp}) {
  513. $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
  514. }
  515. if (ref $config{ENV} eq 'HASH') {
  516. foreach my $val (keys %{$config{ENV}}) {
  517. $ENV{$val}=$config{ENV}{$val};
  518. }
  519. }
  520. if ($config{w3mmode}) {
  521. eval q{use Cwd q{abs_path}};
  522. error($@) if $@;
  523. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  524. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  525. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  526. unless $config{cgiurl} =~ m!file:///!;
  527. $config{url}="file://".$config{destdir};
  528. }
  529. if ($config{cgi} && ! length $config{url}) {
  530. error(gettext("Must specify url to wiki with --url when using --cgi"));
  531. }
  532. if (length $config{url}) {
  533. eval q{use URI};
  534. my $baseurl = URI->new($config{url});
  535. $local_url = $baseurl->path . "/";
  536. $local_cgiurl = undef;
  537. if (length $config{cgiurl}) {
  538. my $cgiurl = URI->new($config{cgiurl});
  539. $local_cgiurl = $cgiurl->path;
  540. if ($cgiurl->scheme ne $baseurl->scheme or
  541. $cgiurl->authority ne $baseurl->authority) {
  542. # too far apart, fall back to absolute URLs
  543. $local_url = "$config{url}/";
  544. $local_cgiurl = $config{cgiurl};
  545. }
  546. }
  547. $local_url =~ s{//$}{/};
  548. }
  549. else {
  550. $local_cgiurl = $config{cgiurl};
  551. }
  552. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  553. unless exists $config{wikistatedir} && defined $config{wikistatedir};
  554. if (defined $config{umask}) {
  555. umask(possibly_foolish_untaint($config{umask}));
  556. }
  557. run_hooks(checkconfig => sub { shift->() });
  558. return 1;
  559. }
  560. sub listplugins () {
  561. my %ret;
  562. foreach my $dir (@INC, $config{libdir}) {
  563. next unless defined $dir && length $dir;
  564. foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
  565. my ($plugin)=$file=~/.*\/(.*)\.pm$/;
  566. $ret{$plugin}=1;
  567. }
  568. }
  569. foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
  570. next unless defined $dir && length $dir;
  571. foreach my $file (glob("$dir/plugins/*")) {
  572. $ret{basename($file)}=1 if -x $file;
  573. }
  574. }
  575. return keys %ret;
  576. }
  577. sub loadplugins () {
  578. if (defined $config{libdir} && length $config{libdir}) {
  579. unshift @INC, possibly_foolish_untaint($config{libdir});
  580. }
  581. foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
  582. loadplugin($plugin);
  583. }
  584. if ($config{rcs}) {
  585. if (exists $hooks{rcs}) {
  586. error(gettext("cannot use multiple rcs plugins"));
  587. }
  588. loadplugin($config{rcs});
  589. }
  590. if (! exists $hooks{rcs}) {
  591. loadplugin("norcs");
  592. }
  593. run_hooks(getopt => sub { shift->() });
  594. if (grep /^-/, @ARGV) {
  595. print STDERR "Unknown option (or missing parameter): $_\n"
  596. foreach grep /^-/, @ARGV;
  597. usage();
  598. }
  599. return 1;
  600. }
  601. sub loadplugin ($;$) {
  602. my $plugin=shift;
  603. my $force=shift;
  604. return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
  605. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  606. "$installdir/lib/ikiwiki") {
  607. if (defined $dir && -x "$dir/plugins/$plugin") {
  608. eval { require IkiWiki::Plugin::external };
  609. if ($@) {
  610. my $reason=$@;
  611. error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
  612. }
  613. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  614. $loaded_plugins{$plugin}=1;
  615. return 1;
  616. }
  617. }
  618. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  619. eval qq{use $mod};
  620. if ($@) {
  621. error("Failed to load plugin $mod: $@");
  622. }
  623. $loaded_plugins{$plugin}=1;
  624. return 1;
  625. }
  626. sub error ($;$) {
  627. my $message=shift;
  628. my $cleaner=shift;
  629. log_message('err' => $message) if $config{syslog};
  630. if (defined $cleaner) {
  631. $cleaner->();
  632. }
  633. die $message."\n";
  634. }
  635. sub debug ($) {
  636. return unless $config{verbose};
  637. return log_message(debug => @_);
  638. }
  639. my $log_open=0;
  640. sub log_message ($$) {
  641. my $type=shift;
  642. if ($config{syslog}) {
  643. require Sys::Syslog;
  644. if (! $log_open) {
  645. Sys::Syslog::setlogsock('unix');
  646. Sys::Syslog::openlog('ikiwiki', '', 'user');
  647. $log_open=1;
  648. }
  649. return eval {
  650. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  651. };
  652. }
  653. elsif (! $config{cgi}) {
  654. return print "@_\n";
  655. }
  656. else {
  657. return print STDERR "@_\n";
  658. }
  659. }
  660. sub possibly_foolish_untaint ($) {
  661. my $tainted=shift;
  662. my ($untainted)=$tainted=~/(.*)/s;
  663. return $untainted;
  664. }
  665. sub basename ($) {
  666. my $file=shift;
  667. $file=~s!.*/+!!;
  668. return $file;
  669. }
  670. sub dirname ($) {
  671. my $file=shift;
  672. $file=~s!/*[^/]+$!!;
  673. return $file;
  674. }
  675. sub isinternal ($) {
  676. my $page=shift;
  677. return exists $pagesources{$page} &&
  678. $pagesources{$page} =~ /\._([^.]+)$/;
  679. }
  680. sub pagetype ($) {
  681. my $file=shift;
  682. if ($file =~ /\.([^.]+)$/) {
  683. return $1 if exists $hooks{htmlize}{$1};
  684. }
  685. my $base=basename($file);
  686. if (exists $hooks{htmlize}{$base} &&
  687. $hooks{htmlize}{$base}{noextension}) {
  688. return $base;
  689. }
  690. return;
  691. }
  692. my %pagename_cache;
  693. sub pagename ($) {
  694. my $file=shift;
  695. if (exists $pagename_cache{$file}) {
  696. return $pagename_cache{$file};
  697. }
  698. my $type=pagetype($file);
  699. my $page=$file;
  700. $page=~s/\Q.$type\E*$//
  701. if defined $type && !$hooks{htmlize}{$type}{keepextension}
  702. && !$hooks{htmlize}{$type}{noextension};
  703. if ($config{indexpages} && $page=~/(.*)\/index$/) {
  704. $page=$1;
  705. }
  706. $pagename_cache{$file} = $page;
  707. return $page;
  708. }
  709. sub newpagefile ($$) {
  710. my $page=shift;
  711. my $type=shift;
  712. if (! $config{indexpages} || $page eq 'index') {
  713. return $page.".".$type;
  714. }
  715. else {
  716. return $page."/index.".$type;
  717. }
  718. }
  719. sub targetpage ($$;$) {
  720. my $page=shift;
  721. my $ext=shift;
  722. my $filename=shift;
  723. if (defined $filename) {
  724. return $page."/".$filename.".".$ext;
  725. }
  726. elsif (! $config{usedirs} || $page eq 'index') {
  727. return $page.".".$ext;
  728. }
  729. else {
  730. return $page."/index.".$ext;
  731. }
  732. }
  733. sub htmlpage ($) {
  734. my $page=shift;
  735. return targetpage($page, $config{htmlext});
  736. }
  737. sub srcfile_stat {
  738. my $file=shift;
  739. my $nothrow=shift;
  740. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  741. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  742. return "$dir/$file", stat(_) if -e "$dir/$file";
  743. }
  744. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  745. return;
  746. }
  747. sub srcfile ($;$) {
  748. return (srcfile_stat(@_))[0];
  749. }
  750. sub add_underlay ($) {
  751. my $dir=shift;
  752. if ($dir !~ /^\//) {
  753. $dir="$config{underlaydirbase}/$dir";
  754. }
  755. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  756. unshift @{$config{underlaydirs}}, $dir;
  757. }
  758. return 1;
  759. }
  760. sub readfile ($;$$) {
  761. my $file=shift;
  762. my $binary=shift;
  763. my $wantfd=shift;
  764. if (-l $file) {
  765. error("cannot read a symlink ($file)");
  766. }
  767. local $/=undef;
  768. open (my $in, "<", $file) || error("failed to read $file: $!");
  769. binmode($in) if ($binary);
  770. return \*$in if $wantfd;
  771. my $ret=<$in>;
  772. # check for invalid utf-8, and toss it back to avoid crashes
  773. if (! utf8::valid($ret)) {
  774. $ret=encode_utf8($ret);
  775. }
  776. close $in || error("failed to read $file: $!");
  777. return $ret;
  778. }
  779. sub prep_writefile ($$) {
  780. my $file=shift;
  781. my $destdir=shift;
  782. my $test=$file;
  783. while (length $test) {
  784. if (-l "$destdir/$test") {
  785. error("cannot write to a symlink ($test)");
  786. }
  787. if (-f _ && $test ne $file) {
  788. # Remove conflicting file.
  789. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  790. foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  791. if ($f eq $test) {
  792. unlink("$destdir/$test");
  793. last;
  794. }
  795. }
  796. }
  797. }
  798. $test=dirname($test);
  799. }
  800. my $dir=dirname("$destdir/$file");
  801. if (! -d $dir) {
  802. my $d="";
  803. foreach my $s (split(m!/+!, $dir)) {
  804. $d.="$s/";
  805. if (! -d $d) {
  806. mkdir($d) || error("failed to create directory $d: $!");
  807. }
  808. }
  809. }
  810. return 1;
  811. }
  812. sub writefile ($$$;$$) {
  813. my $file=shift; # can include subdirs
  814. my $destdir=shift; # directory to put file in
  815. my $content=shift;
  816. my $binary=shift;
  817. my $writer=shift;
  818. prep_writefile($file, $destdir);
  819. my $newfile="$destdir/$file.ikiwiki-new";
  820. if (-l $newfile) {
  821. error("cannot write to a symlink ($newfile)");
  822. }
  823. my $cleanup = sub { unlink($newfile) };
  824. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  825. binmode($out) if ($binary);
  826. if ($writer) {
  827. $writer->(\*$out, $cleanup);
  828. }
  829. else {
  830. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  831. }
  832. close $out || error("failed saving $newfile: $!", $cleanup);
  833. rename($newfile, "$destdir/$file") ||
  834. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  835. return 1;
  836. }
  837. my %cleared;
  838. sub will_render ($$;$) {
  839. my $page=shift;
  840. my $dest=shift;
  841. my $clear=shift;
  842. # Important security check for independently created files.
  843. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  844. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  845. my $from_other_page=0;
  846. # Expensive, but rarely runs.
  847. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  848. if (grep {
  849. $_ eq $dest ||
  850. dirname($_) eq $dest
  851. } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  852. $from_other_page=1;
  853. last;
  854. }
  855. }
  856. error("$config{destdir}/$dest independently created, not overwriting with version from $page")
  857. unless $from_other_page;
  858. }
  859. # If $dest exists as a directory, remove conflicting files in it
  860. # rendered from other pages.
  861. if (-d _) {
  862. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  863. foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  864. if (dirname($f) eq $dest) {
  865. unlink("$config{destdir}/$f");
  866. rmdir(dirname("$config{destdir}/$f"));
  867. }
  868. }
  869. }
  870. }
  871. if (! $clear || $cleared{$page}) {
  872. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  873. }
  874. else {
  875. foreach my $old (@{$renderedfiles{$page}}) {
  876. delete $destsources{$old};
  877. }
  878. $renderedfiles{$page}=[$dest];
  879. $cleared{$page}=1;
  880. }
  881. $destsources{$dest}=$page;
  882. return 1;
  883. }
  884. sub bestlink ($$) {
  885. my $page=shift;
  886. my $link=shift;
  887. my $cwd=$page;
  888. if ($link=~s/^\/+//) {
  889. # absolute links
  890. $cwd="";
  891. }
  892. $link=~s/\/$//;
  893. do {
  894. my $l=$cwd;
  895. $l.="/" if length $l;
  896. $l.=$link;
  897. if (exists $pagesources{$l}) {
  898. return $l;
  899. }
  900. elsif (exists $pagecase{lc $l}) {
  901. return $pagecase{lc $l};
  902. }
  903. } while $cwd=~s{/?[^/]+$}{};
  904. if (length $config{userdir}) {
  905. my $l = "$config{userdir}/".lc($link);
  906. if (exists $pagesources{$l}) {
  907. return $l;
  908. }
  909. elsif (exists $pagecase{lc $l}) {
  910. return $pagecase{lc $l};
  911. }
  912. }
  913. #print STDERR "warning: page $page, broken link: $link\n";
  914. return "";
  915. }
  916. sub isinlinableimage ($) {
  917. my $file=shift;
  918. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  919. }
  920. sub pagetitle ($;$) {
  921. my $page=shift;
  922. my $unescaped=shift;
  923. if ($unescaped) {
  924. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  925. }
  926. else {
  927. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  928. }
  929. return $page;
  930. }
  931. sub titlepage ($) {
  932. my $title=shift;
  933. # support use w/o %config set
  934. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  935. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  936. return $title;
  937. }
  938. sub linkpage ($) {
  939. my $link=shift;
  940. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  941. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  942. return $link;
  943. }
  944. sub cgiurl (@) {
  945. my %params=@_;
  946. my $cgiurl=$local_cgiurl;
  947. if (exists $params{cgiurl}) {
  948. $cgiurl=$params{cgiurl};
  949. delete $params{cgiurl};
  950. }
  951. unless (%params) {
  952. return $cgiurl;
  953. }
  954. return $cgiurl."?".
  955. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  956. }
  957. sub baseurl (;$) {
  958. my $page=shift;
  959. return $local_url if ! defined $page;
  960. $page=htmlpage($page);
  961. $page=~s/[^\/]+$//;
  962. $page=~s/[^\/]+\//..\//g;
  963. return $page;
  964. }
  965. sub abs2rel ($$) {
  966. # Work around very innefficient behavior in File::Spec if abs2rel
  967. # is passed two relative paths. It's much faster if paths are
  968. # absolute! (Debian bug #376658; fixed in debian unstable now)
  969. my $path="/".shift;
  970. my $base="/".shift;
  971. require File::Spec;
  972. my $ret=File::Spec->abs2rel($path, $base);
  973. $ret=~s/^// if defined $ret;
  974. return $ret;
  975. }
  976. sub displaytime ($;$$) {
  977. # Plugins can override this function to mark up the time to
  978. # display.
  979. my $time=formattime($_[0], $_[1]);
  980. if ($config{html5}) {
  981. return '<time datetime="'.date_3339($_[0]).'"'.
  982. ($_[2] ? ' pubdate="pubdate"' : '').
  983. '>'.$time.'</time>';
  984. }
  985. else {
  986. return '<span class="date">'.$time.'</span>';
  987. }
  988. }
  989. sub formattime ($;$) {
  990. # Plugins can override this function to format the time.
  991. my $time=shift;
  992. my $format=shift;
  993. if (! defined $format) {
  994. $format=$config{timeformat};
  995. }
  996. # strftime doesn't know about encodings, so make sure
  997. # its output is properly treated as utf8
  998. return decode_utf8(POSIX::strftime($format, localtime($time)));
  999. }
  1000. sub date_3339 ($) {
  1001. my $time=shift;
  1002. my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
  1003. POSIX::setlocale(&POSIX::LC_TIME, "C");
  1004. my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
  1005. POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
  1006. return $ret;
  1007. }
  1008. sub beautify_urlpath ($) {
  1009. my $url=shift;
  1010. # Ensure url is not an empty link, and if necessary,
  1011. # add ./ to avoid colon confusion.
  1012. if ($url !~ /^\// && $url !~ /^\.\.?\//) {
  1013. $url="./$url";
  1014. }
  1015. if ($config{usedirs}) {
  1016. $url =~ s!/index.$config{htmlext}$!/!;
  1017. }
  1018. return $url;
  1019. }
  1020. sub urlto ($;$$) {
  1021. my $to=shift;
  1022. my $from=shift;
  1023. my $absolute=shift;
  1024. if (! length $to) {
  1025. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  1026. }
  1027. if (! $destsources{$to}) {
  1028. $to=htmlpage($to);
  1029. }
  1030. if ($absolute) {
  1031. return $config{url}.beautify_urlpath("/".$to);
  1032. }
  1033. if (! defined $from) {
  1034. my $u = $local_url;
  1035. $u =~ s{/$}{};
  1036. return $u.beautify_urlpath("/".$to);
  1037. }
  1038. my $link = abs2rel($to, dirname(htmlpage($from)));
  1039. return beautify_urlpath($link);
  1040. }
  1041. sub isselflink ($$) {
  1042. # Plugins can override this function to support special types
  1043. # of selflinks.
  1044. my $page=shift;
  1045. my $link=shift;
  1046. return $page eq $link;
  1047. }
  1048. sub htmllink ($$$;@) {
  1049. my $lpage=shift; # the page doing the linking
  1050. my $page=shift; # the page that will contain the link (different for inline)
  1051. my $link=shift;
  1052. my %opts=@_;
  1053. $link=~s/\/$//;
  1054. my $bestlink;
  1055. if (! $opts{forcesubpage}) {
  1056. $bestlink=bestlink($lpage, $link);
  1057. }
  1058. else {
  1059. $bestlink="$lpage/".lc($link);
  1060. }
  1061. my $linktext;
  1062. if (defined $opts{linktext}) {
  1063. $linktext=$opts{linktext};
  1064. }
  1065. else {
  1066. $linktext=pagetitle(basename($link));
  1067. }
  1068. return "<span class=\"selflink\">$linktext</span>"
  1069. if length $bestlink && isselflink($page, $bestlink) &&
  1070. ! defined $opts{anchor};
  1071. if (! $destsources{$bestlink}) {
  1072. $bestlink=htmlpage($bestlink);
  1073. if (! $destsources{$bestlink}) {
  1074. my $cgilink = "";
  1075. if (length $config{cgiurl}) {
  1076. $cgilink = "<a href=\"".
  1077. cgiurl(
  1078. do => "create",
  1079. page => lc($link),
  1080. from => $lpage
  1081. )."\" rel=\"nofollow\">?</a>";
  1082. }
  1083. return "<span class=\"createlink\">$cgilink$linktext</span>"
  1084. }
  1085. }
  1086. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  1087. $bestlink=beautify_urlpath($bestlink);
  1088. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  1089. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  1090. }
  1091. if (defined $opts{anchor}) {
  1092. $bestlink.="#".$opts{anchor};
  1093. }
  1094. my @attrs;
  1095. foreach my $attr (qw{rel class title}) {
  1096. if (defined $opts{$attr}) {
  1097. push @attrs, " $attr=\"$opts{$attr}\"";
  1098. }
  1099. }
  1100. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  1101. }
  1102. sub userpage ($) {
  1103. my $user=shift;
  1104. return length $config{userdir} ? "$config{userdir}/$user" : $user;
  1105. }
  1106. sub openiduser ($) {
  1107. my $user=shift;
  1108. if (defined $user && $user =~ m!^https?://! &&
  1109. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  1110. my $display;
  1111. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  1112. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  1113. }
  1114. else {
  1115. # backcompat with old version
  1116. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  1117. $display=$oid->display;
  1118. }
  1119. # Convert "user.somehost.com" to "user [somehost.com]"
  1120. # (also "user.somehost.co.uk")
  1121. if ($display !~ /\[/) {
  1122. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  1123. }
  1124. # Convert "http://somehost.com/user" to "user [somehost.com]".
  1125. # (also "https://somehost.com/user/")
  1126. if ($display !~ /\[/) {
  1127. $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
  1128. }
  1129. $display=~s!^https?://!!; # make sure this is removed
  1130. eval q{use CGI 'escapeHTML'};
  1131. error($@) if $@;
  1132. return escapeHTML($display);
  1133. }
  1134. return;
  1135. }
  1136. sub htmlize ($$$$) {
  1137. my $page=shift;
  1138. my $destpage=shift;
  1139. my $type=shift;
  1140. my $content=shift;
  1141. my $oneline = $content !~ /\n/;
  1142. if (exists $hooks{htmlize}{$type}) {
  1143. $content=$hooks{htmlize}{$type}{call}->(
  1144. page => $page,
  1145. content => $content,
  1146. );
  1147. }
  1148. else {
  1149. error("htmlization of $type not supported");
  1150. }
  1151. run_hooks(sanitize => sub {
  1152. $content=shift->(
  1153. page => $page,
  1154. destpage => $destpage,
  1155. content => $content,
  1156. );
  1157. });
  1158. if ($oneline) {
  1159. # hack to get rid of enclosing junk added by markdown
  1160. # and other htmlizers/sanitizers
  1161. $content=~s/^<p>//i;
  1162. $content=~s/<\/p>\n*$//i;
  1163. }
  1164. return $content;
  1165. }
  1166. sub linkify ($$$) {
  1167. my $page=shift;
  1168. my $destpage=shift;
  1169. my $content=shift;
  1170. run_hooks(linkify => sub {
  1171. $content=shift->(
  1172. page => $page,
  1173. destpage => $destpage,
  1174. content => $content,
  1175. );
  1176. });
  1177. return $content;
  1178. }
  1179. our %preprocessing;
  1180. our $preprocess_preview=0;
  1181. sub preprocess ($$$;$$) {
  1182. my $page=shift; # the page the data comes from
  1183. my $destpage=shift; # the page the data will appear in (different for inline)
  1184. my $content=shift;
  1185. my $scan=shift;
  1186. my $preview=shift;
  1187. # Using local because it needs to be set within any nested calls
  1188. # of this function.
  1189. local $preprocess_preview=$preview if defined $preview;
  1190. my $handle=sub {
  1191. my $escape=shift;
  1192. my $prefix=shift;
  1193. my $command=shift;
  1194. my $params=shift;
  1195. $params="" if ! defined $params;
  1196. if (length $escape) {
  1197. return "[[$prefix$command $params]]";
  1198. }
  1199. elsif (exists $hooks{preprocess}{$command}) {
  1200. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1201. # Note: preserve order of params, some plugins may
  1202. # consider it significant.
  1203. my @params;
  1204. while ($params =~ m{
  1205. (?:([-\w]+)=)? # 1: named parameter key?
  1206. (?:
  1207. """(.*?)""" # 2: triple-quoted value
  1208. |
  1209. "([^"]*?)" # 3: single-quoted value
  1210. |
  1211. (\S+) # 4: unquoted value
  1212. )
  1213. (?:\s+|$) # delimiter to next param
  1214. }sgx) {
  1215. my $key=$1;
  1216. my $val;
  1217. if (defined $2) {
  1218. $val=$2;
  1219. $val=~s/\r\n/\n/mg;
  1220. $val=~s/^\n+//g;
  1221. $val=~s/\n+$//g;
  1222. }
  1223. elsif (defined $3) {
  1224. $val=$3;
  1225. }
  1226. elsif (defined $4) {
  1227. $val=$4;
  1228. }
  1229. if (defined $key) {
  1230. push @params, $key, $val;
  1231. }
  1232. else {
  1233. push @params, $val, '';
  1234. }
  1235. }
  1236. if ($preprocessing{$page}++ > 3) {
  1237. # Avoid loops of preprocessed pages preprocessing
  1238. # other pages that preprocess them, etc.
  1239. return "[[!$command <span class=\"error\">".
  1240. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1241. $page, $preprocessing{$page}).
  1242. "</span>]]";
  1243. }
  1244. my $ret;
  1245. if (! $scan) {
  1246. $ret=eval {
  1247. $hooks{preprocess}{$command}{call}->(
  1248. @params,
  1249. page => $page,
  1250. destpage => $destpage,
  1251. preview => $preprocess_preview,
  1252. );
  1253. };
  1254. if ($@) {
  1255. my $error=$@;
  1256. chomp $error;
  1257. $ret="[[!$command <span class=\"error\">".
  1258. gettext("Error").": $error"."</span>]]";
  1259. }
  1260. }
  1261. else {
  1262. # use void context during scan pass
  1263. eval {
  1264. $hooks{preprocess}{$command}{call}->(
  1265. @params,
  1266. page => $page,
  1267. destpage => $destpage,
  1268. preview => $preprocess_preview,
  1269. );
  1270. };
  1271. $ret="";
  1272. }
  1273. $preprocessing{$page}--;
  1274. return $ret;
  1275. }
  1276. else {
  1277. return "[[$prefix$command $params]]";
  1278. }
  1279. };
  1280. my $regex;
  1281. if ($config{prefix_directives}) {
  1282. $regex = qr{
  1283. (\\?) # 1: escape?
  1284. \[\[(!) # directive open; 2: prefix
  1285. ([-\w]+) # 3: command
  1286. ( # 4: the parameters..
  1287. \s+ # Must have space if parameters present
  1288. (?:
  1289. (?:[-\w]+=)? # named parameter key?
  1290. (?:
  1291. """.*?""" # triple-quoted value
  1292. |
  1293. "[^"]*?" # single-quoted value
  1294. |
  1295. [^"\s\]]+ # unquoted value
  1296. )
  1297. \s* # whitespace or end
  1298. # of directive
  1299. )
  1300. *)? # 0 or more parameters
  1301. \]\] # directive closed
  1302. }sx;
  1303. }
  1304. else {
  1305. $regex = qr{
  1306. (\\?) # 1: escape?
  1307. \[\[(!?) # directive open; 2: optional prefix
  1308. ([-\w]+) # 3: command
  1309. \s+
  1310. ( # 4: the parameters..
  1311. (?:
  1312. (?:[-\w]+=)? # named parameter key?
  1313. (?:
  1314. """.*?""" # triple-quoted value
  1315. |
  1316. "[^"]*?" # single-quoted value
  1317. |
  1318. [^"\s\]]+ # unquoted value
  1319. )
  1320. \s* # whitespace or end
  1321. # of directive
  1322. )
  1323. *) # 0 or more parameters
  1324. \]\] # directive closed
  1325. }sx;
  1326. }
  1327. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1328. return $content;
  1329. }
  1330. sub filter ($$$) {
  1331. my $page=shift;
  1332. my $destpage=shift;
  1333. my $content=shift;
  1334. run_hooks(filter => sub {
  1335. $content=shift->(page => $page, destpage => $destpage,
  1336. content => $content);
  1337. });
  1338. return $content;
  1339. }
  1340. sub check_canedit ($$$;$) {
  1341. my $page=shift;
  1342. my $q=shift;
  1343. my $session=shift;
  1344. my $nonfatal=shift;
  1345. my $canedit;
  1346. run_hooks(canedit => sub {
  1347. return if defined $canedit;
  1348. my $ret=shift->($page, $q, $session);
  1349. if (defined $ret) {
  1350. if ($ret eq "") {
  1351. $canedit=1;
  1352. }
  1353. elsif (ref $ret eq 'CODE') {
  1354. $ret->() unless $nonfatal;
  1355. $canedit=0;
  1356. }
  1357. elsif (defined $ret) {
  1358. error($ret) unless $nonfatal;
  1359. $canedit=0;
  1360. }
  1361. }
  1362. });
  1363. return defined $canedit ? $canedit : 1;
  1364. }
  1365. sub check_content (@) {
  1366. my %params=@_;
  1367. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1368. if (exists $pagesources{$params{page}}) {
  1369. my @diff;
  1370. my %old=map { $_ => 1 }
  1371. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1372. foreach my $line (split("\n", $params{content})) {
  1373. push @diff, $line if ! exists $old{$line};
  1374. }
  1375. $params{diff}=join("\n", @diff);
  1376. }
  1377. my $ok;
  1378. run_hooks(checkcontent => sub {
  1379. return if defined $ok;
  1380. my $ret=shift->(%params);
  1381. if (defined $ret) {
  1382. if ($ret eq "") {
  1383. $ok=1;
  1384. }
  1385. elsif (ref $ret eq 'CODE') {
  1386. $ret->() unless $params{nonfatal};
  1387. $ok=0;
  1388. }
  1389. elsif (defined $ret) {
  1390. error($ret) unless $params{nonfatal};
  1391. $ok=0;
  1392. }
  1393. }
  1394. });
  1395. return defined $ok ? $ok : 1;
  1396. }
  1397. sub check_canchange (@) {
  1398. my %params = @_;
  1399. my $cgi = $params{cgi};
  1400. my $session = $params{session};
  1401. my @changes = @{$params{changes}};
  1402. my %newfiles;
  1403. foreach my $change (@changes) {
  1404. # This untaint is safe because we check file_pruned and
  1405. # wiki_file_regexp.
  1406. my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
  1407. $file=possibly_foolish_untaint($file);
  1408. if (! defined $file || ! length $file ||
  1409. file_pruned($file)) {
  1410. error(gettext("bad file name %s"), $file);
  1411. }
  1412. my $type=pagetype($file);
  1413. my $page=pagename($file) if defined $type;
  1414. if ($change->{action} eq 'add') {
  1415. $newfiles{$file}=1;
  1416. }
  1417. if ($change->{action} eq 'change' ||
  1418. $change->{action} eq 'add') {
  1419. if (defined $page) {
  1420. check_canedit($page, $cgi, $session);
  1421. next;
  1422. }
  1423. else {
  1424. if (IkiWiki::Plugin::attachment->can("check_canattach")) {
  1425. IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
  1426. check_canedit($file, $cgi, $session);
  1427. next;
  1428. }
  1429. }
  1430. }
  1431. elsif ($change->{action} eq 'remove') {
  1432. # check_canremove tests to see if the file is present
  1433. # on disk. This will fail when a single commit adds a
  1434. # file and then removes it again. Avoid the problem
  1435. # by not testing the removal in such pairs of changes.
  1436. # (The add is still tested, just to make sure that
  1437. # no data is added to the repo that a web edit
  1438. # could not add.)
  1439. next if $newfiles{$file};
  1440. if (IkiWiki::Plugin::remove->can("check_canremove")) {
  1441. IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
  1442. check_canedit(defined $page ? $page : $file, $cgi, $session);
  1443. next;
  1444. }
  1445. }
  1446. else {
  1447. error "unknown action ".$change->{action};
  1448. }
  1449. error sprintf(gettext("you are not allowed to change %s"), $file);
  1450. }
  1451. }
  1452. my $wikilock;
  1453. sub lockwiki () {
  1454. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1455. # run issues. The lock will be dropped on program exit.
  1456. if (! -d $config{wikistatedir}) {
  1457. mkdir($config{wikistatedir});
  1458. }
  1459. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1460. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1461. if (! flock($wikilock, 2)) { # LOCK_EX
  1462. error("failed to get lock");
  1463. }
  1464. return 1;
  1465. }
  1466. sub unlockwiki () {
  1467. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1468. return close($wikilock) if $wikilock;
  1469. return;
  1470. }
  1471. my $commitlock;
  1472. sub commit_hook_enabled () {
  1473. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1474. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1475. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1476. close($commitlock) || error("failed closing commitlock: $!");
  1477. return 0;
  1478. }
  1479. close($commitlock) || error("failed closing commitlock: $!");
  1480. return 1;
  1481. }
  1482. sub disable_commit_hook () {
  1483. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1484. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1485. if (! flock($commitlock, 2)) { # LOCK_EX
  1486. error("failed to get commit lock");
  1487. }
  1488. return 1;
  1489. }
  1490. sub enable_commit_hook () {
  1491. return close($commitlock) if $commitlock;
  1492. return;
  1493. }
  1494. sub loadindex () {
  1495. %oldrenderedfiles=%pagectime=();
  1496. if (! $config{rebuild}) {
  1497. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1498. %destsources=%renderedfiles=%pagecase=%pagestate=
  1499. %depends_simple=%typedlinks=%oldtypedlinks=();
  1500. }
  1501. my $in;
  1502. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1503. if (-e "$config{wikistatedir}/index") {
  1504. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1505. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1506. }
  1507. else {
  1508. $config{gettime}=1; # first build
  1509. return;
  1510. }
  1511. }
  1512. my $index=Storable::fd_retrieve($in);
  1513. if (! defined $index) {
  1514. return 0;
  1515. }
  1516. my $pages;
  1517. if (exists $index->{version} && ! ref $index->{version}) {
  1518. $pages=$index->{page};
  1519. %wikistate=%{$index->{state}};
  1520. # Handle plugins that got disabled by loading a new setup.
  1521. if (exists $config{setupfile}) {
  1522. require IkiWiki::Setup;
  1523. IkiWiki::Setup::disabled_plugins(
  1524. grep { ! $loaded_plugins{$_} } keys %wikistate);
  1525. }
  1526. }
  1527. else {
  1528. $pages=$index;
  1529. %wikistate=();
  1530. }
  1531. foreach my $src (keys %$pages) {
  1532. my $d=$pages->{$src};
  1533. my $page=pagename($src);
  1534. $pagectime{$page}=$d->{ctime};
  1535. $pagesources{$page}=$src;
  1536. if (! $config{rebuild}) {
  1537. $pagemtime{$page}=$d->{mtime};
  1538. $renderedfiles{$page}=$d->{dest};
  1539. if (exists $d->{links} && ref $d->{links}) {
  1540. $links{$page}=$d->{links};
  1541. $oldlinks{$page}=[@{$d->{links}}];
  1542. }
  1543. if (ref $d->{depends_simple} eq 'ARRAY') {
  1544. # old format
  1545. $depends_simple{$page}={
  1546. map { $_ => 1 } @{$d->{depends_simple}}
  1547. };
  1548. }
  1549. elsif (exists $d->{depends_simple}) {
  1550. $depends_simple{$page}=$d->{depends_simple};
  1551. }
  1552. if (exists $d->{dependslist}) {
  1553. # old format
  1554. $depends{$page}={
  1555. map { $_ => $DEPEND_CONTENT }
  1556. @{$d->{dependslist}}
  1557. };
  1558. }
  1559. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1560. # old format
  1561. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1562. }
  1563. elsif (exists $d->{depends}) {
  1564. $depends{$page}=$d->{depends};
  1565. }
  1566. if (exists $d->{state}) {
  1567. $pagestate{$page}=$d->{state};
  1568. }
  1569. if (exists $d->{typedlinks}) {
  1570. $typedlinks{$page}=$d->{typedlinks};
  1571. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1572. next unless %$links;
  1573. $oldtypedlinks{$page}{$type} = {%$links};
  1574. }
  1575. }
  1576. }
  1577. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1578. }
  1579. foreach my $page (keys %pagesources) {
  1580. $pagecase{lc $page}=$page;
  1581. }
  1582. foreach my $page (keys %renderedfiles) {
  1583. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1584. }
  1585. return close($in);
  1586. }
  1587. sub saveindex () {
  1588. run_hooks(savestate => sub { shift->() });
  1589. my @plugins=keys %loaded_plugins;
  1590. if (! -d $config{wikistatedir}) {
  1591. mkdir($config{wikistatedir});
  1592. }
  1593. my $newfile="$config{wikistatedir}/indexdb.new";
  1594. my $cleanup = sub { unlink($newfile) };
  1595. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1596. my %index;
  1597. foreach my $page (keys %pagemtime) {
  1598. next unless $pagemtime{$page};
  1599. my $src=$pagesources{$page};
  1600. $index{page}{$src}={
  1601. ctime => $pagectime{$page},
  1602. mtime => $pagemtime{$page},
  1603. dest => $renderedfiles{$page},
  1604. links => $links{$page},
  1605. };
  1606. if (exists $depends{$page}) {
  1607. $index{page}{$src}{depends} = $depends{$page};
  1608. }
  1609. if (exists $depends_simple{$page}) {
  1610. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1611. }
  1612. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1613. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1614. }
  1615. if (exists $pagestate{$page}) {
  1616. foreach my $id (@plugins) {
  1617. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1618. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1619. }
  1620. }
  1621. }
  1622. }
  1623. $index{state}={};
  1624. foreach my $id (@plugins) {
  1625. $index{state}{$id}={}; # used to detect disabled plugins
  1626. foreach my $key (keys %{$wikistate{$id}}) {
  1627. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1628. }
  1629. }
  1630. $index{version}="3";
  1631. my $ret=Storable::nstore_fd(\%index, $out);
  1632. return if ! defined $ret || ! $ret;
  1633. close $out || error("failed saving to $newfile: $!", $cleanup);
  1634. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1635. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1636. return 1;
  1637. }
  1638. sub template_file ($) {
  1639. my $name=shift;
  1640. my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
  1641. my $template;
  1642. if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
  1643. $template=srcfile($pagesources{$tpage}, 1);
  1644. $name.=".tmpl";
  1645. }
  1646. else {
  1647. $template=srcfile($tpage, 1);
  1648. }
  1649. if (defined $template) {
  1650. return $template, $tpage, 1 if wantarray;
  1651. return $template;
  1652. }
  1653. else {
  1654. $name=~s:/::; # avoid path traversal
  1655. foreach my $dir ($config{templatedir},
  1656. "$installdir/share/ikiwiki/templates") {
  1657. if (-e "$dir/$name") {
  1658. $template="$dir/$name";
  1659. last;
  1660. }
  1661. }
  1662. if (defined $template) {
  1663. return $template, $tpage if wantarray;
  1664. return $template;
  1665. }
  1666. }
  1667. return;
  1668. }
  1669. sub template_depends ($$;@) {
  1670. my $name=shift;
  1671. my $page=shift;
  1672. my ($filename, $tpage, $untrusted)=template_file($name);
  1673. if (! defined $filename) {
  1674. error(sprintf(gettext("template %s not found"), $name))
  1675. }
  1676. if (defined $page && defined $tpage) {
  1677. add_depends($page, $tpage);
  1678. }
  1679. my @opts=(
  1680. filter => sub {
  1681. my $text_ref = shift;
  1682. ${$text_ref} = decode_utf8(${$text_ref});
  1683. },
  1684. loop_context_vars => 1,
  1685. die_on_bad_params => 0,
  1686. filename => $filename,
  1687. @_,
  1688. ($untrusted ? (no_includes => 1) : ()),
  1689. );
  1690. return @opts if wantarray;
  1691. require HTML::Template;
  1692. return HTML::Template->new(@opts);
  1693. }
  1694. sub template ($;@) {
  1695. template_depends(shift, undef, @_);
  1696. }
  1697. sub misctemplate ($$;@) {
  1698. my $title=shift;
  1699. my $content=shift;
  1700. my %params=@_;
  1701. my $template=template("page.tmpl");
  1702. my $page="";
  1703. if (exists $params{page}) {
  1704. $page=delete $params{page};
  1705. }
  1706. run_hooks(pagetemplate => sub {
  1707. shift->(
  1708. page => $page,
  1709. destpage => $page,
  1710. template => $template,
  1711. );
  1712. });
  1713. templateactions($template, "");
  1714. $template->param(
  1715. dynamic => 1,
  1716. title => $title,
  1717. wikiname => $config{wikiname},
  1718. content => $content,
  1719. baseurl => baseurl(),
  1720. html5 => $config{html5},
  1721. %params,
  1722. );
  1723. return $template->output;
  1724. }
  1725. sub templateactions ($$) {
  1726. my $template=shift;
  1727. my $page=shift;
  1728. my $have_actions=0;
  1729. my @actions;
  1730. run_hooks(pageactions => sub {
  1731. push @actions, map { { action => $_ } }
  1732. grep { defined } shift->(page => $page);
  1733. });
  1734. $template->param(actions => \@actions);
  1735. if ($config{cgiurl} && exists $hooks{auth}) {
  1736. $template->param(prefsurl => cgiurl(do => "prefs"));
  1737. $have_actions=1;
  1738. }
  1739. if ($have_actions || @actions) {
  1740. $template->param(have_actions => 1);
  1741. }
  1742. }
  1743. sub hook (@) {
  1744. my %param=@_;
  1745. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1746. error 'hook requires type, call, and id parameters';
  1747. }
  1748. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1749. $hooks{$param{type}}{$param{id}}=\%param;
  1750. return 1;
  1751. }
  1752. sub run_hooks ($$) {
  1753. # Calls the given sub for each hook of the given type,
  1754. # passing it the hook function to call.
  1755. my $type=shift;
  1756. my $sub=shift;
  1757. if (exists $hooks{$type}) {
  1758. my (@first, @middle, @last);
  1759. foreach my $id (keys %{$hooks{$type}}) {
  1760. if ($hooks{$type}{$id}{first}) {
  1761. push @first, $id;
  1762. }
  1763. elsif ($hooks{$type}{$id}{last}) {
  1764. push @last, $id;
  1765. }
  1766. else {
  1767. push @middle, $id;
  1768. }
  1769. }
  1770. foreach my $id (@first, @middle, @last) {
  1771. $sub->($hooks{$type}{$id}{call});
  1772. }
  1773. }
  1774. return 1;
  1775. }
  1776. sub rcs_update () {
  1777. $hooks{rcs}{rcs_update}{call}->(@_);
  1778. }
  1779. sub rcs_prepedit ($) {
  1780. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1781. }
  1782. sub rcs_commit (@) {
  1783. $hooks{rcs}{rcs_commit}{call}->(@_);
  1784. }
  1785. sub rcs_commit_staged (@) {
  1786. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1787. }
  1788. sub rcs_add ($) {
  1789. $hooks{rcs}{rcs_add}{call}->(@_);
  1790. }
  1791. sub rcs_remove ($) {
  1792. $hooks{rcs}{rcs_remove}{call}->(@_);
  1793. }
  1794. sub rcs_rename ($$) {
  1795. $hooks{rcs}{rcs_rename}{call}->(@_);
  1796. }
  1797. sub rcs_recentchanges ($) {
  1798. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1799. }
  1800. sub rcs_diff ($) {
  1801. $hooks{rcs}{rcs_diff}{call}->(@_);
  1802. }
  1803. sub rcs_getctime ($) {
  1804. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1805. }
  1806. sub rcs_getmtime ($) {
  1807. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1808. }
  1809. sub rcs_receive () {
  1810. $hooks{rcs}{rcs_receive}{call}->();
  1811. }
  1812. sub add_depends ($$;$) {
  1813. my $page=shift;
  1814. my $pagespec=shift;
  1815. my $deptype=shift || $DEPEND_CONTENT;
  1816. # Is the pagespec a simple page name?
  1817. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1818. $pagespec !~ /[\s*?()!]/) {
  1819. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1820. return 1;
  1821. }
  1822. # Add explicit dependencies for influences.
  1823. my $sub=pagespec_translate($pagespec);
  1824. return unless defined $sub;
  1825. foreach my $p (keys %pagesources) {
  1826. my $r=$sub->($p, location => $page);
  1827. my $i=$r->influences;
  1828. my $static=$r->influences_static;
  1829. foreach my $k (keys %$i) {
  1830. next unless $r || $static || $k eq $page;
  1831. $depends_simple{$page}{lc $k} |= $i->{$k};
  1832. }
  1833. last if $static;
  1834. }
  1835. $depends{$page}{$pagespec} |= $deptype;
  1836. return 1;
  1837. }
  1838. sub deptype (@) {
  1839. my $deptype=0;
  1840. foreach my $type (@_) {
  1841. if ($type eq 'presence') {
  1842. $deptype |= $DEPEND_PRESENCE;
  1843. }
  1844. elsif ($type eq 'links') {
  1845. $deptype |= $DEPEND_LINKS;
  1846. }
  1847. elsif ($type eq 'content') {
  1848. $deptype |= $DEPEND_CONTENT;
  1849. }
  1850. }
  1851. return $deptype;
  1852. }
  1853. my $file_prune_regexp;
  1854. sub file_pruned ($) {
  1855. my $file=shift;
  1856. if (defined $config{include} && length $config{include}) {
  1857. return 0 if $file =~ m/$config{include}/;
  1858. }
  1859. if (! defined $file_prune_regexp) {
  1860. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1861. $file_prune_regexp=qr/$file_prune_regexp/;
  1862. }
  1863. return $file =~ m/$file_prune_regexp/;
  1864. }
  1865. sub define_gettext () {
  1866. # If translation is needed, redefine the gettext function to do it.
  1867. # Otherwise, it becomes a quick no-op.
  1868. my $gettext_obj;
  1869. my $getobj;
  1870. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1871. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1872. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1873. $getobj=sub {
  1874. $gettext_obj=eval q{
  1875. use Locale::gettext q{textdomain};
  1876. Locale::gettext->domain('ikiwiki')
  1877. };
  1878. };
  1879. }
  1880. no warnings 'redefine';
  1881. *gettext=sub {
  1882. $getobj->() if $getobj;
  1883. if ($gettext_obj) {
  1884. $gettext_obj->get(shift);
  1885. }
  1886. else {
  1887. return shift;
  1888. }
  1889. };
  1890. *ngettext=sub {
  1891. $getobj->() if $getobj;
  1892. if ($gettext_obj) {
  1893. $gettext_obj->nget(@_);
  1894. }
  1895. else {
  1896. return ($_[2] == 1 ? $_[0] : $_[1])
  1897. }
  1898. };
  1899. }
  1900. sub gettext {
  1901. define_gettext();
  1902. gettext(@_);
  1903. }
  1904. sub ngettext {
  1905. define_gettext();
  1906. ngettext(@_);
  1907. }
  1908. sub yesno ($) {
  1909. my $val=shift;
  1910. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1911. }
  1912. sub inject {
  1913. # Injects a new function into the symbol table to replace an
  1914. # exported function.
  1915. my %params=@_;
  1916. # This is deep ugly perl foo, beware.
  1917. no strict;
  1918. no warnings;
  1919. if (! defined $params{parent}) {
  1920. $params{parent}='::';
  1921. $params{old}=\&{$params{name}};
  1922. $params{name}=~s/.*:://;
  1923. }
  1924. my $parent=$params{parent};
  1925. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1926. $ns = $params{parent} . $ns;
  1927. inject(%params, parent => $ns) unless $ns eq '::main::';
  1928. *{$ns . $params{name}} = $params{call}
  1929. if exists ${$ns}{$params{name}} &&
  1930. \&{${$ns}{$params{name}}} == $params{old};
  1931. }
  1932. use strict;
  1933. use warnings;
  1934. }
  1935. sub add_link ($$;$) {
  1936. my $page=shift;
  1937. my $link=shift;
  1938. my $type=shift;
  1939. push @{$links{$page}}, $link
  1940. unless grep { $_ eq $link } @{$links{$page}};
  1941. if (defined $type) {
  1942. $typedlinks{$page}{$type}{$link} = 1;
  1943. }
  1944. }
  1945. sub add_autofile ($$$) {
  1946. my $file=shift;
  1947. my $plugin=shift;
  1948. my $generator=shift;
  1949. $autofiles{$file}{plugin}=$plugin;
  1950. $autofiles{$file}{generator}=$generator;
  1951. }
  1952. sub sortspec_translate ($$) {
  1953. my $spec = shift;
  1954. my $reverse = shift;
  1955. my $code = "";
  1956. my @data;
  1957. while ($spec =~ m{
  1958. \s*
  1959. (-?) # group 1: perhaps negated
  1960. \s*
  1961. ( # group 2: a word
  1962. \w+\([^\)]*\) # command(params)
  1963. |
  1964. [^\s]+ # or anything else
  1965. )
  1966. \s*
  1967. }gx) {
  1968. my $negated = $1;
  1969. my $word = $2;
  1970. my $params = undef;
  1971. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1972. # command with parameters
  1973. $params = $2;
  1974. $word = $1;
  1975. }
  1976. elsif ($word !~ m/^\w+$/) {
  1977. error(sprintf(gettext("invalid sort type %s"), $word));
  1978. }
  1979. if (length $code) {
  1980. $code .= " || ";
  1981. }
  1982. if ($negated) {
  1983. $code .= "-";
  1984. }
  1985. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1986. if (defined $params) {
  1987. push @data, $params;
  1988. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1989. }
  1990. else {
  1991. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1992. }
  1993. }
  1994. else {
  1995. error(sprintf(gettext("unknown sort type %s"), $word));
  1996. }
  1997. }
  1998. if (! length $code) {
  1999. # undefined sorting method... sort arbitrarily
  2000. return sub { 0 };
  2001. }
  2002. if ($reverse) {
  2003. $code="-($code)";
  2004. }
  2005. no warnings;
  2006. return eval 'sub { '.$code.' }';
  2007. }
  2008. sub pagespec_translate ($) {
  2009. my $spec=shift;
  2010. # Convert spec to perl code.
  2011. my $code="";
  2012. my @data;
  2013. while ($spec=~m{
  2014. \s* # ignore whitespace
  2015. ( # 1: match a single word
  2016. \! # !
  2017. |
  2018. \( # (
  2019. |
  2020. \) # )
  2021. |
  2022. \w+\([^\)]*\) # command(params)
  2023. |
  2024. [^\s()]+ # any other text
  2025. )
  2026. \s* # ignore whitespace
  2027. }gx) {
  2028. my $word=$1;
  2029. if (lc $word eq 'and') {
  2030. $code.=' &';
  2031. }
  2032. elsif (lc $word eq 'or') {
  2033. $code.=' |';
  2034. }
  2035. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  2036. $code.=' '.$word;
  2037. }
  2038. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  2039. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  2040. push @data, $2;
  2041. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  2042. }
  2043. else {
  2044. push @data, qq{unknown function in pagespec "$word"};
  2045. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  2046. }
  2047. }
  2048. else {
  2049. push @data, $word;
  2050. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  2051. }
  2052. }
  2053. if (! length $code) {
  2054. $code="IkiWiki::FailReason->new('empty pagespec')";
  2055. }
  2056. no warnings;
  2057. return eval 'sub { my $page=shift; '.$code.' }';
  2058. }
  2059. sub pagespec_match ($$;@) {
  2060. my $page=shift;
  2061. my $spec=shift;
  2062. my @params=@_;
  2063. # Backwards compatability with old calling convention.
  2064. if (@params == 1) {
  2065. unshift @params, 'location';
  2066. }
  2067. my $sub=pagespec_translate($spec);
  2068. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  2069. if ! defined $sub;
  2070. return $sub->($page, @params);
  2071. }
  2072. sub pagespec_match_list ($$;@) {
  2073. my $page=shift;
  2074. my $pagespec=shift;
  2075. my %params=@_;
  2076. # Backwards compatability with old calling convention.
  2077. if (ref $page) {
  2078. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  2079. $params{list}=$page;
  2080. $page=$params{location}; # ugh!
  2081. }
  2082. my $sub=pagespec_translate($pagespec);
  2083. error "syntax error in pagespec \"$pagespec\""
  2084. if ! defined $sub;
  2085. my $sort=sortspec_translate($params{sort}, $params{reverse})
  2086. if defined $params{sort};
  2087. my @candidates;
  2088. if (exists $params{list}) {
  2089. @candidates=exists $params{filter}
  2090. ? grep { ! $params{filter}->($_) } @{$params{list}}
  2091. : @{$params{list}};
  2092. }
  2093. else {
  2094. @candidates=exists $params{filter}
  2095. ? grep { ! $params{filter}->($_) } keys %pagesources
  2096. : keys %pagesources;
  2097. }
  2098. # clear params, remainder is passed to pagespec
  2099. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  2100. my $num=$params{num};
  2101. delete @params{qw{num deptype reverse sort filter list}};
  2102. # when only the top matches will be returned, it's efficient to
  2103. # sort before matching to pagespec,
  2104. if (defined $num && defined $sort) {
  2105. @candidates=IkiWiki::SortSpec::sort_pages(
  2106. $sort, @candidates);
  2107. }
  2108. my @matches;
  2109. my $firstfail;
  2110. my $count=0;
  2111. my $accum=IkiWiki::SuccessReason->new();
  2112. foreach my $p (@candidates) {
  2113. my $r=$sub->($p, %params, location => $page);
  2114. error(sprintf(gettext("cannot match pages: %s"), $r))
  2115. if $r->isa("IkiWiki::ErrorReason");
  2116. unless ($r || $r->influences_static) {
  2117. $r->remove_influence($p);
  2118. }
  2119. $accum |= $r;
  2120. if ($r) {
  2121. push @matches, $p;
  2122. last if defined $num && ++$count == $num;
  2123. }
  2124. }
  2125. # Add simple dependencies for accumulated influences.
  2126. my $i=$accum->influences;
  2127. foreach my $k (keys %$i) {
  2128. $depends_simple{$page}{lc $k} |= $i->{$k};
  2129. }
  2130. # when all matches will be returned, it's efficient to
  2131. # sort after matching
  2132. if (! defined $num && defined $sort) {
  2133. return IkiWiki::SortSpec::sort_pages(
  2134. $sort, @matches);
  2135. }
  2136. else {
  2137. return @matches;
  2138. }
  2139. }
  2140. sub pagespec_valid ($) {
  2141. my $spec=shift;
  2142. return defined pagespec_translate($spec);
  2143. }
  2144. sub glob2re ($) {
  2145. my $re=quotemeta(shift);
  2146. $re=~s/\\\*/.*/g;
  2147. $re=~s/\\\?/./g;
  2148. return qr/^$re$/i;
  2149. }
  2150. package IkiWiki::FailReason;
  2151. use overload (
  2152. '""' => sub { $_[0][0] },
  2153. '0+' => sub { 0 },
  2154. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2155. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2156. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2157. fallback => 1,
  2158. );
  2159. our @ISA = 'IkiWiki::SuccessReason';
  2160. package IkiWiki::SuccessReason;
  2161. use overload (
  2162. '""' => sub { $_[0][0] },
  2163. '0+' => sub { 1 },
  2164. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2165. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2166. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2167. fallback => 1,
  2168. );
  2169. sub new {
  2170. my $class = shift;
  2171. my $value = shift;
  2172. return bless [$value, {@_}], $class;
  2173. }
  2174. sub influences {
  2175. my $this=shift;
  2176. $this->[1]={@_} if @_;
  2177. my %i=%{$this->[1]};
  2178. delete $i{""};
  2179. return \%i;
  2180. }
  2181. sub influences_static {
  2182. return ! $_[0][1]->{""};
  2183. }
  2184. sub merge_influences {
  2185. my $this=shift;
  2186. my $other=shift;
  2187. my $anded=shift;
  2188. if (! $anded || (($this || %{$this->[1]}) &&
  2189. ($other || %{$other->[1]}))) {
  2190. foreach my $influence (keys %{$other->[1]}) {
  2191. $this->[1]{$influence} |= $other->[1]{$influence};
  2192. }
  2193. }
  2194. else {
  2195. # influence blocker
  2196. $this->[1]={};
  2197. }
  2198. }
  2199. sub remove_influence {
  2200. my $this=shift;
  2201. my $torm=shift;
  2202. delete $this->[1]{$torm};
  2203. }
  2204. package IkiWiki::ErrorReason;
  2205. our @ISA = 'IkiWiki::FailReason';
  2206. package IkiWiki::PageSpec;
  2207. sub derel ($$) {
  2208. my $path=shift;
  2209. my $from=shift;
  2210. if ($path =~ m!^\.(/|$)!) {
  2211. if ($1) {
  2212. $from=~s#/?[^/]+$## if defined $from;
  2213. $path=~s#^\./##;
  2214. $path="$from/$path" if defined $from && length $from;
  2215. }
  2216. else {
  2217. $path = $from;
  2218. $path = "" unless defined $path;
  2219. }
  2220. }
  2221. return $path;
  2222. }
  2223. my %glob_cache;
  2224. sub match_glob ($$;@) {
  2225. my $page=shift;
  2226. my $glob=shift;
  2227. my %params=@_;
  2228. $glob=derel($glob, $params{location});
  2229. # Instead of converting the glob to a regex every time,
  2230. # cache the compiled regex to save time.
  2231. my $re=$glob_cache{$glob};
  2232. unless (defined $re) {
  2233. $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
  2234. }
  2235. if ($page =~ $re) {
  2236. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2237. return IkiWiki::SuccessReason->new("$glob matches $page");
  2238. }
  2239. else {
  2240. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2241. }
  2242. }
  2243. else {
  2244. return IkiWiki::FailReason->new("$glob does not match $page");
  2245. }
  2246. }
  2247. sub match_internal ($$;@) {
  2248. return match_glob(shift, shift, @_, internal => 1)
  2249. }
  2250. sub match_page ($$;@) {
  2251. my $page=shift;
  2252. my $match=match_glob($page, shift, @_);
  2253. if ($match) {
  2254. my $source=exists $IkiWiki::pagesources{$page} ?
  2255. $IkiWiki::pagesources{$page} :
  2256. $IkiWiki::delpagesources{$page};
  2257. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  2258. if (! defined $type) {
  2259. return IkiWiki::FailReason->new("$page is not a page");
  2260. }
  2261. }
  2262. return $match;
  2263. }
  2264. sub match_link ($$;@) {
  2265. my $page=shift;
  2266. my $link=lc(shift);
  2267. my %params=@_;
  2268. $link=derel($link, $params{location});
  2269. my $from=exists $params{location} ? $params{location} : '';
  2270. my $linktype=$params{linktype};
  2271. my $qualifier='';
  2272. if (defined $linktype) {
  2273. $qualifier=" with type $linktype";
  2274. }
  2275. my $links = $IkiWiki::links{$page};
  2276. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2277. unless $links && @{$links};
  2278. my $bestlink = IkiWiki::bestlink($from, $link);
  2279. foreach my $p (@{$links}) {
  2280. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2281. if (length $bestlink) {
  2282. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2283. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2284. }
  2285. }
  2286. else {
  2287. if (match_glob($p, $link, %params)) {
  2288. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2289. }
  2290. my ($p_rel)=$p=~/^\/?(.*)/;
  2291. $link=~s/^\///;
  2292. if (match_glob($p_rel, $link, %params)) {
  2293. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2294. }
  2295. }
  2296. }
  2297. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2298. }
  2299. sub match_backlink ($$;@) {
  2300. my $ret=match_link($_[1], $_[0], @_);
  2301. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2302. return $ret;
  2303. }
  2304. sub match_created_before ($$;@) {
  2305. my $page=shift;
  2306. my $testpage=shift;
  2307. my %params=@_;
  2308. $testpage=derel($testpage, $params{location});
  2309. if (exists $IkiWiki::pagectime{$testpage}) {
  2310. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2311. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2312. }
  2313. else {
  2314. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2315. }
  2316. }
  2317. else {
  2318. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2319. }
  2320. }
  2321. sub match_created_after ($$;@) {
  2322. my $page=shift;
  2323. my $testpage=shift;
  2324. my %params=@_;
  2325. $testpage=derel($testpage, $params{location});
  2326. if (exists $IkiWiki::pagectime{$testpage}) {
  2327. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2328. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2329. }
  2330. else {
  2331. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2332. }
  2333. }
  2334. else {
  2335. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2336. }
  2337. }
  2338. sub match_creation_day ($$;@) {
  2339. my $page=shift;
  2340. my $d=shift;
  2341. if ($d !~ /^\d+$/) {
  2342. return IkiWiki::ErrorReason->new("invalid day $d");
  2343. }
  2344. if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
  2345. return IkiWiki::SuccessReason->new('creation_day matched');
  2346. }
  2347. else {
  2348. return IkiWiki::FailReason->new('creation_day did not match');
  2349. }
  2350. }
  2351. sub match_creation_month ($$;@) {
  2352. my $page=shift;
  2353. my $m=shift;
  2354. if ($m !~ /^\d+$/) {
  2355. return IkiWiki::ErrorReason->new("invalid month $m");
  2356. }
  2357. if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
  2358. return IkiWiki::SuccessReason->new('creation_month matched');
  2359. }
  2360. else {
  2361. return IkiWiki::FailReason->new('creation_month did not match');
  2362. }
  2363. }
  2364. sub match_creation_year ($$;@) {
  2365. my $page=shift;
  2366. my $y=shift;
  2367. if ($y !~ /^\d+$/) {
  2368. return IkiWiki::ErrorReason->new("invalid year $y");
  2369. }
  2370. if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
  2371. return IkiWiki::SuccessReason->new('creation_year matched');
  2372. }
  2373. else {
  2374. return IkiWiki::FailReason->new('creation_year did not match');
  2375. }
  2376. }
  2377. sub match_user ($$;@) {
  2378. shift;
  2379. my $user=shift;
  2380. my %params=@_;
  2381. my $regexp=IkiWiki::glob2re($user);
  2382. if (! exists $params{user}) {
  2383. return IkiWiki::ErrorReason->new("no user specified");
  2384. }
  2385. if (defined $params{user} && $params{user}=~$regexp) {
  2386. return IkiWiki::SuccessReason->new("user is $user");
  2387. }
  2388. elsif (! defined $params{user}) {
  2389. return IkiWiki::FailReason->new("not logged in");
  2390. }
  2391. else {
  2392. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2393. }
  2394. }
  2395. sub match_admin ($$;@) {
  2396. shift;
  2397. shift;
  2398. my %params=@_;
  2399. if (! exists $params{user}) {
  2400. return IkiWiki::ErrorReason->new("no user specified");
  2401. }
  2402. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2403. return IkiWiki::SuccessReason->new("user is an admin");
  2404. }
  2405. elsif (! defined $params{user}) {
  2406. return IkiWiki::FailReason->new("not logged in");
  2407. }
  2408. else {
  2409. return IkiWiki::FailReason->new("user is not an admin");
  2410. }
  2411. }
  2412. sub match_ip ($$;@) {
  2413. shift;
  2414. my $ip=shift;
  2415. my %params=@_;
  2416. if (! exists $params{ip}) {
  2417. return IkiWiki::ErrorReason->new("no IP specified");
  2418. }
  2419. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2420. return IkiWiki::SuccessReason->new("IP is $ip");
  2421. }
  2422. else {
  2423. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2424. }
  2425. }
  2426. package IkiWiki::SortSpec;
  2427. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2428. # are easily available in this namespace, for cmp functions to use them.
  2429. sub sort_pages {
  2430. my $f=shift;
  2431. sort $f @_
  2432. }
  2433. sub cmp_title {
  2434. IkiWiki::pagetitle(IkiWiki::basename($a))
  2435. cmp
  2436. IkiWiki::pagetitle(IkiWiki::basename($b))
  2437. }
  2438. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2439. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2440. 1