summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: ee0b1f1ea6f3ee4665857a317eb5e68e8acd61fe (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. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  550. unless exists $config{wikistatedir} && defined $config{wikistatedir};
  551. if (defined $config{umask}) {
  552. umask(possibly_foolish_untaint($config{umask}));
  553. }
  554. run_hooks(checkconfig => sub { shift->() });
  555. return 1;
  556. }
  557. sub listplugins () {
  558. my %ret;
  559. foreach my $dir (@INC, $config{libdir}) {
  560. next unless defined $dir && length $dir;
  561. foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
  562. my ($plugin)=$file=~/.*\/(.*)\.pm$/;
  563. $ret{$plugin}=1;
  564. }
  565. }
  566. foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
  567. next unless defined $dir && length $dir;
  568. foreach my $file (glob("$dir/plugins/*")) {
  569. $ret{basename($file)}=1 if -x $file;
  570. }
  571. }
  572. return keys %ret;
  573. }
  574. sub loadplugins () {
  575. if (defined $config{libdir} && length $config{libdir}) {
  576. unshift @INC, possibly_foolish_untaint($config{libdir});
  577. }
  578. foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
  579. loadplugin($plugin);
  580. }
  581. if ($config{rcs}) {
  582. if (exists $hooks{rcs}) {
  583. error(gettext("cannot use multiple rcs plugins"));
  584. }
  585. loadplugin($config{rcs});
  586. }
  587. if (! exists $hooks{rcs}) {
  588. loadplugin("norcs");
  589. }
  590. run_hooks(getopt => sub { shift->() });
  591. if (grep /^-/, @ARGV) {
  592. print STDERR "Unknown option (or missing parameter): $_\n"
  593. foreach grep /^-/, @ARGV;
  594. usage();
  595. }
  596. return 1;
  597. }
  598. sub loadplugin ($;$) {
  599. my $plugin=shift;
  600. my $force=shift;
  601. return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
  602. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  603. "$installdir/lib/ikiwiki") {
  604. if (defined $dir && -x "$dir/plugins/$plugin") {
  605. eval { require IkiWiki::Plugin::external };
  606. if ($@) {
  607. my $reason=$@;
  608. error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
  609. }
  610. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  611. $loaded_plugins{$plugin}=1;
  612. return 1;
  613. }
  614. }
  615. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  616. eval qq{use $mod};
  617. if ($@) {
  618. error("Failed to load plugin $mod: $@");
  619. }
  620. $loaded_plugins{$plugin}=1;
  621. return 1;
  622. }
  623. sub error ($;$) {
  624. my $message=shift;
  625. my $cleaner=shift;
  626. log_message('err' => $message) if $config{syslog};
  627. if (defined $cleaner) {
  628. $cleaner->();
  629. }
  630. die $message."\n";
  631. }
  632. sub debug ($) {
  633. return unless $config{verbose};
  634. return log_message(debug => @_);
  635. }
  636. my $log_open=0;
  637. sub log_message ($$) {
  638. my $type=shift;
  639. if ($config{syslog}) {
  640. require Sys::Syslog;
  641. if (! $log_open) {
  642. Sys::Syslog::setlogsock('unix');
  643. Sys::Syslog::openlog('ikiwiki', '', 'user');
  644. $log_open=1;
  645. }
  646. return eval {
  647. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  648. };
  649. }
  650. elsif (! $config{cgi}) {
  651. return print "@_\n";
  652. }
  653. else {
  654. return print STDERR "@_\n";
  655. }
  656. }
  657. sub possibly_foolish_untaint ($) {
  658. my $tainted=shift;
  659. my ($untainted)=$tainted=~/(.*)/s;
  660. return $untainted;
  661. }
  662. sub basename ($) {
  663. my $file=shift;
  664. $file=~s!.*/+!!;
  665. return $file;
  666. }
  667. sub dirname ($) {
  668. my $file=shift;
  669. $file=~s!/*[^/]+$!!;
  670. return $file;
  671. }
  672. sub isinternal ($) {
  673. my $page=shift;
  674. return exists $pagesources{$page} &&
  675. $pagesources{$page} =~ /\._([^.]+)$/;
  676. }
  677. sub pagetype ($) {
  678. my $file=shift;
  679. if ($file =~ /\.([^.]+)$/) {
  680. return $1 if exists $hooks{htmlize}{$1};
  681. }
  682. my $base=basename($file);
  683. if (exists $hooks{htmlize}{$base} &&
  684. $hooks{htmlize}{$base}{noextension}) {
  685. return $base;
  686. }
  687. return;
  688. }
  689. my %pagename_cache;
  690. sub pagename ($) {
  691. my $file=shift;
  692. if (exists $pagename_cache{$file}) {
  693. return $pagename_cache{$file};
  694. }
  695. my $type=pagetype($file);
  696. my $page=$file;
  697. $page=~s/\Q.$type\E*$//
  698. if defined $type && !$hooks{htmlize}{$type}{keepextension}
  699. && !$hooks{htmlize}{$type}{noextension};
  700. if ($config{indexpages} && $page=~/(.*)\/index$/) {
  701. $page=$1;
  702. }
  703. $pagename_cache{$file} = $page;
  704. return $page;
  705. }
  706. sub newpagefile ($$) {
  707. my $page=shift;
  708. my $type=shift;
  709. if (! $config{indexpages} || $page eq 'index') {
  710. return $page.".".$type;
  711. }
  712. else {
  713. return $page."/index.".$type;
  714. }
  715. }
  716. sub targetpage ($$;$) {
  717. my $page=shift;
  718. my $ext=shift;
  719. my $filename=shift;
  720. if (defined $filename) {
  721. return $page."/".$filename.".".$ext;
  722. }
  723. elsif (! $config{usedirs} || $page eq 'index') {
  724. return $page.".".$ext;
  725. }
  726. else {
  727. return $page."/index.".$ext;
  728. }
  729. }
  730. sub htmlpage ($) {
  731. my $page=shift;
  732. return targetpage($page, $config{htmlext});
  733. }
  734. sub srcfile_stat {
  735. my $file=shift;
  736. my $nothrow=shift;
  737. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  738. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  739. return "$dir/$file", stat(_) if -e "$dir/$file";
  740. }
  741. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  742. return;
  743. }
  744. sub srcfile ($;$) {
  745. return (srcfile_stat(@_))[0];
  746. }
  747. sub add_underlay ($) {
  748. my $dir=shift;
  749. if ($dir !~ /^\//) {
  750. $dir="$config{underlaydirbase}/$dir";
  751. }
  752. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  753. unshift @{$config{underlaydirs}}, $dir;
  754. }
  755. return 1;
  756. }
  757. sub readfile ($;$$) {
  758. my $file=shift;
  759. my $binary=shift;
  760. my $wantfd=shift;
  761. if (-l $file) {
  762. error("cannot read a symlink ($file)");
  763. }
  764. local $/=undef;
  765. open (my $in, "<", $file) || error("failed to read $file: $!");
  766. binmode($in) if ($binary);
  767. return \*$in if $wantfd;
  768. my $ret=<$in>;
  769. # check for invalid utf-8, and toss it back to avoid crashes
  770. if (! utf8::valid($ret)) {
  771. $ret=encode_utf8($ret);
  772. }
  773. close $in || error("failed to read $file: $!");
  774. return $ret;
  775. }
  776. sub prep_writefile ($$) {
  777. my $file=shift;
  778. my $destdir=shift;
  779. my $test=$file;
  780. while (length $test) {
  781. if (-l "$destdir/$test") {
  782. error("cannot write to a symlink ($test)");
  783. }
  784. if (-f _ && $test ne $file) {
  785. # Remove conflicting file.
  786. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  787. foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  788. if ($f eq $test) {
  789. unlink("$destdir/$test");
  790. last;
  791. }
  792. }
  793. }
  794. }
  795. $test=dirname($test);
  796. }
  797. my $dir=dirname("$destdir/$file");
  798. if (! -d $dir) {
  799. my $d="";
  800. foreach my $s (split(m!/+!, $dir)) {
  801. $d.="$s/";
  802. if (! -d $d) {
  803. mkdir($d) || error("failed to create directory $d: $!");
  804. }
  805. }
  806. }
  807. return 1;
  808. }
  809. sub writefile ($$$;$$) {
  810. my $file=shift; # can include subdirs
  811. my $destdir=shift; # directory to put file in
  812. my $content=shift;
  813. my $binary=shift;
  814. my $writer=shift;
  815. prep_writefile($file, $destdir);
  816. my $newfile="$destdir/$file.ikiwiki-new";
  817. if (-l $newfile) {
  818. error("cannot write to a symlink ($newfile)");
  819. }
  820. my $cleanup = sub { unlink($newfile) };
  821. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  822. binmode($out) if ($binary);
  823. if ($writer) {
  824. $writer->(\*$out, $cleanup);
  825. }
  826. else {
  827. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  828. }
  829. close $out || error("failed saving $newfile: $!", $cleanup);
  830. rename($newfile, "$destdir/$file") ||
  831. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  832. return 1;
  833. }
  834. my %cleared;
  835. sub will_render ($$;$) {
  836. my $page=shift;
  837. my $dest=shift;
  838. my $clear=shift;
  839. # Important security check for independently created files.
  840. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  841. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  842. my $from_other_page=0;
  843. # Expensive, but rarely runs.
  844. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  845. if (grep {
  846. $_ eq $dest ||
  847. dirname($_) eq $dest
  848. } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  849. $from_other_page=1;
  850. last;
  851. }
  852. }
  853. error("$config{destdir}/$dest independently created, not overwriting with version from $page")
  854. unless $from_other_page;
  855. }
  856. # If $dest exists as a directory, remove conflicting files in it
  857. # rendered from other pages.
  858. if (-d _) {
  859. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  860. foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  861. if (dirname($f) eq $dest) {
  862. unlink("$config{destdir}/$f");
  863. rmdir(dirname("$config{destdir}/$f"));
  864. }
  865. }
  866. }
  867. }
  868. if (! $clear || $cleared{$page}) {
  869. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  870. }
  871. else {
  872. foreach my $old (@{$renderedfiles{$page}}) {
  873. delete $destsources{$old};
  874. }
  875. $renderedfiles{$page}=[$dest];
  876. $cleared{$page}=1;
  877. }
  878. $destsources{$dest}=$page;
  879. return 1;
  880. }
  881. sub bestlink ($$) {
  882. my $page=shift;
  883. my $link=shift;
  884. my $cwd=$page;
  885. if ($link=~s/^\/+//) {
  886. # absolute links
  887. $cwd="";
  888. }
  889. $link=~s/\/$//;
  890. do {
  891. my $l=$cwd;
  892. $l.="/" if length $l;
  893. $l.=$link;
  894. if (exists $pagesources{$l}) {
  895. return $l;
  896. }
  897. elsif (exists $pagecase{lc $l}) {
  898. return $pagecase{lc $l};
  899. }
  900. } while $cwd=~s{/?[^/]+$}{};
  901. if (length $config{userdir}) {
  902. my $l = "$config{userdir}/".lc($link);
  903. if (exists $pagesources{$l}) {
  904. return $l;
  905. }
  906. elsif (exists $pagecase{lc $l}) {
  907. return $pagecase{lc $l};
  908. }
  909. }
  910. #print STDERR "warning: page $page, broken link: $link\n";
  911. return "";
  912. }
  913. sub isinlinableimage ($) {
  914. my $file=shift;
  915. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  916. }
  917. sub pagetitle ($;$) {
  918. my $page=shift;
  919. my $unescaped=shift;
  920. if ($unescaped) {
  921. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  922. }
  923. else {
  924. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  925. }
  926. return $page;
  927. }
  928. sub titlepage ($) {
  929. my $title=shift;
  930. # support use w/o %config set
  931. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  932. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  933. return $title;
  934. }
  935. sub linkpage ($) {
  936. my $link=shift;
  937. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  938. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  939. return $link;
  940. }
  941. sub cgiurl (@) {
  942. my %params=@_;
  943. my $cgiurl=$local_cgiurl;
  944. if (exists $params{cgiurl}) {
  945. $cgiurl=$params{cgiurl};
  946. delete $params{cgiurl};
  947. }
  948. unless (%params) {
  949. return $cgiurl;
  950. }
  951. return $cgiurl."?".
  952. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  953. }
  954. sub baseurl (;$) {
  955. my $page=shift;
  956. return $local_url if ! defined $page;
  957. $page=htmlpage($page);
  958. $page=~s/[^\/]+$//;
  959. $page=~s/[^\/]+\//..\//g;
  960. return $page;
  961. }
  962. sub abs2rel ($$) {
  963. # Work around very innefficient behavior in File::Spec if abs2rel
  964. # is passed two relative paths. It's much faster if paths are
  965. # absolute! (Debian bug #376658; fixed in debian unstable now)
  966. my $path="/".shift;
  967. my $base="/".shift;
  968. require File::Spec;
  969. my $ret=File::Spec->abs2rel($path, $base);
  970. $ret=~s/^// if defined $ret;
  971. return $ret;
  972. }
  973. sub displaytime ($;$$) {
  974. # Plugins can override this function to mark up the time to
  975. # display.
  976. my $time=formattime($_[0], $_[1]);
  977. if ($config{html5}) {
  978. return '<time datetime="'.date_3339($_[0]).'"'.
  979. ($_[2] ? ' pubdate="pubdate"' : '').
  980. '>'.$time.'</time>';
  981. }
  982. else {
  983. return '<span class="date">'.$time.'</span>';
  984. }
  985. }
  986. sub formattime ($;$) {
  987. # Plugins can override this function to format the time.
  988. my $time=shift;
  989. my $format=shift;
  990. if (! defined $format) {
  991. $format=$config{timeformat};
  992. }
  993. # strftime doesn't know about encodings, so make sure
  994. # its output is properly treated as utf8
  995. return decode_utf8(POSIX::strftime($format, localtime($time)));
  996. }
  997. sub date_3339 ($) {
  998. my $time=shift;
  999. my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
  1000. POSIX::setlocale(&POSIX::LC_TIME, "C");
  1001. my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
  1002. POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
  1003. return $ret;
  1004. }
  1005. sub beautify_urlpath ($) {
  1006. my $url=shift;
  1007. # Ensure url is not an empty link, and if necessary,
  1008. # add ./ to avoid colon confusion.
  1009. if ($url !~ /^\// && $url !~ /^\.\.?\//) {
  1010. $url="./$url";
  1011. }
  1012. if ($config{usedirs}) {
  1013. $url =~ s!/index.$config{htmlext}$!/!;
  1014. }
  1015. return $url;
  1016. }
  1017. sub urlto ($$;$) {
  1018. my $to=shift;
  1019. my $from=shift;
  1020. my $absolute=shift;
  1021. if (! length $to) {
  1022. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  1023. }
  1024. if (! $destsources{$to}) {
  1025. $to=htmlpage($to);
  1026. }
  1027. if ($absolute) {
  1028. return $config{url}.beautify_urlpath("/".$to);
  1029. }
  1030. if (! defined $from) {
  1031. my $u = $local_url;
  1032. $u =~ s{/$}{};
  1033. return $u.beautify_urlpath("/".$to);
  1034. }
  1035. my $link = abs2rel($to, dirname(htmlpage($from)));
  1036. return beautify_urlpath($link);
  1037. }
  1038. sub isselflink ($$) {
  1039. # Plugins can override this function to support special types
  1040. # of selflinks.
  1041. my $page=shift;
  1042. my $link=shift;
  1043. return $page eq $link;
  1044. }
  1045. sub htmllink ($$$;@) {
  1046. my $lpage=shift; # the page doing the linking
  1047. my $page=shift; # the page that will contain the link (different for inline)
  1048. my $link=shift;
  1049. my %opts=@_;
  1050. $link=~s/\/$//;
  1051. my $bestlink;
  1052. if (! $opts{forcesubpage}) {
  1053. $bestlink=bestlink($lpage, $link);
  1054. }
  1055. else {
  1056. $bestlink="$lpage/".lc($link);
  1057. }
  1058. my $linktext;
  1059. if (defined $opts{linktext}) {
  1060. $linktext=$opts{linktext};
  1061. }
  1062. else {
  1063. $linktext=pagetitle(basename($link));
  1064. }
  1065. return "<span class=\"selflink\">$linktext</span>"
  1066. if length $bestlink && isselflink($page, $bestlink) &&
  1067. ! defined $opts{anchor};
  1068. if (! $destsources{$bestlink}) {
  1069. $bestlink=htmlpage($bestlink);
  1070. if (! $destsources{$bestlink}) {
  1071. my $cgilink = "";
  1072. if (length $config{cgiurl}) {
  1073. $cgilink = "<a href=\"".
  1074. cgiurl(
  1075. do => "create",
  1076. page => lc($link),
  1077. from => $lpage
  1078. )."\" rel=\"nofollow\">?</a>";
  1079. }
  1080. return "<span class=\"createlink\">$cgilink$linktext</span>"
  1081. }
  1082. }
  1083. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  1084. $bestlink=beautify_urlpath($bestlink);
  1085. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  1086. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  1087. }
  1088. if (defined $opts{anchor}) {
  1089. $bestlink.="#".$opts{anchor};
  1090. }
  1091. my @attrs;
  1092. foreach my $attr (qw{rel class title}) {
  1093. if (defined $opts{$attr}) {
  1094. push @attrs, " $attr=\"$opts{$attr}\"";
  1095. }
  1096. }
  1097. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  1098. }
  1099. sub userpage ($) {
  1100. my $user=shift;
  1101. return length $config{userdir} ? "$config{userdir}/$user" : $user;
  1102. }
  1103. sub openiduser ($) {
  1104. my $user=shift;
  1105. if ($user =~ m!^https?://! &&
  1106. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  1107. my $display;
  1108. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  1109. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  1110. }
  1111. else {
  1112. # backcompat with old version
  1113. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  1114. $display=$oid->display;
  1115. }
  1116. # Convert "user.somehost.com" to "user [somehost.com]"
  1117. # (also "user.somehost.co.uk")
  1118. if ($display !~ /\[/) {
  1119. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  1120. }
  1121. # Convert "http://somehost.com/user" to "user [somehost.com]".
  1122. # (also "https://somehost.com/user/")
  1123. if ($display !~ /\[/) {
  1124. $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
  1125. }
  1126. $display=~s!^https?://!!; # make sure this is removed
  1127. eval q{use CGI 'escapeHTML'};
  1128. error($@) if $@;
  1129. return escapeHTML($display);
  1130. }
  1131. return;
  1132. }
  1133. sub htmlize ($$$$) {
  1134. my $page=shift;
  1135. my $destpage=shift;
  1136. my $type=shift;
  1137. my $content=shift;
  1138. my $oneline = $content !~ /\n/;
  1139. if (exists $hooks{htmlize}{$type}) {
  1140. $content=$hooks{htmlize}{$type}{call}->(
  1141. page => $page,
  1142. content => $content,
  1143. );
  1144. }
  1145. else {
  1146. error("htmlization of $type not supported");
  1147. }
  1148. run_hooks(sanitize => sub {
  1149. $content=shift->(
  1150. page => $page,
  1151. destpage => $destpage,
  1152. content => $content,
  1153. );
  1154. });
  1155. if ($oneline) {
  1156. # hack to get rid of enclosing junk added by markdown
  1157. # and other htmlizers/sanitizers
  1158. $content=~s/^<p>//i;
  1159. $content=~s/<\/p>\n*$//i;
  1160. }
  1161. return $content;
  1162. }
  1163. sub linkify ($$$) {
  1164. my $page=shift;
  1165. my $destpage=shift;
  1166. my $content=shift;
  1167. run_hooks(linkify => sub {
  1168. $content=shift->(
  1169. page => $page,
  1170. destpage => $destpage,
  1171. content => $content,
  1172. );
  1173. });
  1174. return $content;
  1175. }
  1176. our %preprocessing;
  1177. our $preprocess_preview=0;
  1178. sub preprocess ($$$;$$) {
  1179. my $page=shift; # the page the data comes from
  1180. my $destpage=shift; # the page the data will appear in (different for inline)
  1181. my $content=shift;
  1182. my $scan=shift;
  1183. my $preview=shift;
  1184. # Using local because it needs to be set within any nested calls
  1185. # of this function.
  1186. local $preprocess_preview=$preview if defined $preview;
  1187. my $handle=sub {
  1188. my $escape=shift;
  1189. my $prefix=shift;
  1190. my $command=shift;
  1191. my $params=shift;
  1192. $params="" if ! defined $params;
  1193. if (length $escape) {
  1194. return "[[$prefix$command $params]]";
  1195. }
  1196. elsif (exists $hooks{preprocess}{$command}) {
  1197. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1198. # Note: preserve order of params, some plugins may
  1199. # consider it significant.
  1200. my @params;
  1201. while ($params =~ m{
  1202. (?:([-\w]+)=)? # 1: named parameter key?
  1203. (?:
  1204. """(.*?)""" # 2: triple-quoted value
  1205. |
  1206. "([^"]*?)" # 3: single-quoted value
  1207. |
  1208. (\S+) # 4: unquoted value
  1209. )
  1210. (?:\s+|$) # delimiter to next param
  1211. }sgx) {
  1212. my $key=$1;
  1213. my $val;
  1214. if (defined $2) {
  1215. $val=$2;
  1216. $val=~s/\r\n/\n/mg;
  1217. $val=~s/^\n+//g;
  1218. $val=~s/\n+$//g;
  1219. }
  1220. elsif (defined $3) {
  1221. $val=$3;
  1222. }
  1223. elsif (defined $4) {
  1224. $val=$4;
  1225. }
  1226. if (defined $key) {
  1227. push @params, $key, $val;
  1228. }
  1229. else {
  1230. push @params, $val, '';
  1231. }
  1232. }
  1233. if ($preprocessing{$page}++ > 3) {
  1234. # Avoid loops of preprocessed pages preprocessing
  1235. # other pages that preprocess them, etc.
  1236. return "[[!$command <span class=\"error\">".
  1237. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1238. $page, $preprocessing{$page}).
  1239. "</span>]]";
  1240. }
  1241. my $ret;
  1242. if (! $scan) {
  1243. $ret=eval {
  1244. $hooks{preprocess}{$command}{call}->(
  1245. @params,
  1246. page => $page,
  1247. destpage => $destpage,
  1248. preview => $preprocess_preview,
  1249. );
  1250. };
  1251. if ($@) {
  1252. my $error=$@;
  1253. chomp $error;
  1254. $ret="[[!$command <span class=\"error\">".
  1255. gettext("Error").": $error"."</span>]]";
  1256. }
  1257. }
  1258. else {
  1259. # use void context during scan pass
  1260. eval {
  1261. $hooks{preprocess}{$command}{call}->(
  1262. @params,
  1263. page => $page,
  1264. destpage => $destpage,
  1265. preview => $preprocess_preview,
  1266. );
  1267. };
  1268. $ret="";
  1269. }
  1270. $preprocessing{$page}--;
  1271. return $ret;
  1272. }
  1273. else {
  1274. return "[[$prefix$command $params]]";
  1275. }
  1276. };
  1277. my $regex;
  1278. if ($config{prefix_directives}) {
  1279. $regex = qr{
  1280. (\\?) # 1: escape?
  1281. \[\[(!) # directive open; 2: prefix
  1282. ([-\w]+) # 3: command
  1283. ( # 4: the parameters..
  1284. \s+ # Must have space if parameters present
  1285. (?:
  1286. (?:[-\w]+=)? # named parameter key?
  1287. (?:
  1288. """.*?""" # triple-quoted value
  1289. |
  1290. "[^"]*?" # single-quoted value
  1291. |
  1292. [^"\s\]]+ # unquoted value
  1293. )
  1294. \s* # whitespace or end
  1295. # of directive
  1296. )
  1297. *)? # 0 or more parameters
  1298. \]\] # directive closed
  1299. }sx;
  1300. }
  1301. else {
  1302. $regex = qr{
  1303. (\\?) # 1: escape?
  1304. \[\[(!?) # directive open; 2: optional prefix
  1305. ([-\w]+) # 3: command
  1306. \s+
  1307. ( # 4: the parameters..
  1308. (?:
  1309. (?:[-\w]+=)? # named parameter key?
  1310. (?:
  1311. """.*?""" # triple-quoted value
  1312. |
  1313. "[^"]*?" # single-quoted value
  1314. |
  1315. [^"\s\]]+ # unquoted value
  1316. )
  1317. \s* # whitespace or end
  1318. # of directive
  1319. )
  1320. *) # 0 or more parameters
  1321. \]\] # directive closed
  1322. }sx;
  1323. }
  1324. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1325. return $content;
  1326. }
  1327. sub filter ($$$) {
  1328. my $page=shift;
  1329. my $destpage=shift;
  1330. my $content=shift;
  1331. run_hooks(filter => sub {
  1332. $content=shift->(page => $page, destpage => $destpage,
  1333. content => $content);
  1334. });
  1335. return $content;
  1336. }
  1337. sub check_canedit ($$$;$) {
  1338. my $page=shift;
  1339. my $q=shift;
  1340. my $session=shift;
  1341. my $nonfatal=shift;
  1342. my $canedit;
  1343. run_hooks(canedit => sub {
  1344. return if defined $canedit;
  1345. my $ret=shift->($page, $q, $session);
  1346. if (defined $ret) {
  1347. if ($ret eq "") {
  1348. $canedit=1;
  1349. }
  1350. elsif (ref $ret eq 'CODE') {
  1351. $ret->() unless $nonfatal;
  1352. $canedit=0;
  1353. }
  1354. elsif (defined $ret) {
  1355. error($ret) unless $nonfatal;
  1356. $canedit=0;
  1357. }
  1358. }
  1359. });
  1360. return defined $canedit ? $canedit : 1;
  1361. }
  1362. sub check_content (@) {
  1363. my %params=@_;
  1364. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1365. if (exists $pagesources{$params{page}}) {
  1366. my @diff;
  1367. my %old=map { $_ => 1 }
  1368. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1369. foreach my $line (split("\n", $params{content})) {
  1370. push @diff, $line if ! exists $old{$line};
  1371. }
  1372. $params{diff}=join("\n", @diff);
  1373. }
  1374. my $ok;
  1375. run_hooks(checkcontent => sub {
  1376. return if defined $ok;
  1377. my $ret=shift->(%params);
  1378. if (defined $ret) {
  1379. if ($ret eq "") {
  1380. $ok=1;
  1381. }
  1382. elsif (ref $ret eq 'CODE') {
  1383. $ret->() unless $params{nonfatal};
  1384. $ok=0;
  1385. }
  1386. elsif (defined $ret) {
  1387. error($ret) unless $params{nonfatal};
  1388. $ok=0;
  1389. }
  1390. }
  1391. });
  1392. return defined $ok ? $ok : 1;
  1393. }
  1394. sub check_canchange (@) {
  1395. my %params = @_;
  1396. my $cgi = $params{cgi};
  1397. my $session = $params{session};
  1398. my @changes = @{$params{changes}};
  1399. my %newfiles;
  1400. foreach my $change (@changes) {
  1401. # This untaint is safe because we check file_pruned and
  1402. # wiki_file_regexp.
  1403. my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
  1404. $file=possibly_foolish_untaint($file);
  1405. if (! defined $file || ! length $file ||
  1406. file_pruned($file)) {
  1407. error(gettext("bad file name %s"), $file);
  1408. }
  1409. my $type=pagetype($file);
  1410. my $page=pagename($file) if defined $type;
  1411. if ($change->{action} eq 'add') {
  1412. $newfiles{$file}=1;
  1413. }
  1414. if ($change->{action} eq 'change' ||
  1415. $change->{action} eq 'add') {
  1416. if (defined $page) {
  1417. check_canedit($page, $cgi, $session);
  1418. next;
  1419. }
  1420. else {
  1421. if (IkiWiki::Plugin::attachment->can("check_canattach")) {
  1422. IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
  1423. check_canedit($file, $cgi, $session);
  1424. next;
  1425. }
  1426. }
  1427. }
  1428. elsif ($change->{action} eq 'remove') {
  1429. # check_canremove tests to see if the file is present
  1430. # on disk. This will fail when a single commit adds a
  1431. # file and then removes it again. Avoid the problem
  1432. # by not testing the removal in such pairs of changes.
  1433. # (The add is still tested, just to make sure that
  1434. # no data is added to the repo that a web edit
  1435. # could not add.)
  1436. next if $newfiles{$file};
  1437. if (IkiWiki::Plugin::remove->can("check_canremove")) {
  1438. IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
  1439. check_canedit(defined $page ? $page : $file, $cgi, $session);
  1440. next;
  1441. }
  1442. }
  1443. else {
  1444. error "unknown action ".$change->{action};
  1445. }
  1446. error sprintf(gettext("you are not allowed to change %s"), $file);
  1447. }
  1448. }
  1449. my $wikilock;
  1450. sub lockwiki () {
  1451. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1452. # run issues. The lock will be dropped on program exit.
  1453. if (! -d $config{wikistatedir}) {
  1454. mkdir($config{wikistatedir});
  1455. }
  1456. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1457. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1458. if (! flock($wikilock, 2)) { # LOCK_EX
  1459. error("failed to get lock");
  1460. }
  1461. return 1;
  1462. }
  1463. sub unlockwiki () {
  1464. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1465. return close($wikilock) if $wikilock;
  1466. return;
  1467. }
  1468. my $commitlock;
  1469. sub commit_hook_enabled () {
  1470. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1471. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1472. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1473. close($commitlock) || error("failed closing commitlock: $!");
  1474. return 0;
  1475. }
  1476. close($commitlock) || error("failed closing commitlock: $!");
  1477. return 1;
  1478. }
  1479. sub disable_commit_hook () {
  1480. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1481. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1482. if (! flock($commitlock, 2)) { # LOCK_EX
  1483. error("failed to get commit lock");
  1484. }
  1485. return 1;
  1486. }
  1487. sub enable_commit_hook () {
  1488. return close($commitlock) if $commitlock;
  1489. return;
  1490. }
  1491. sub loadindex () {
  1492. %oldrenderedfiles=%pagectime=();
  1493. if (! $config{rebuild}) {
  1494. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1495. %destsources=%renderedfiles=%pagecase=%pagestate=
  1496. %depends_simple=%typedlinks=%oldtypedlinks=();
  1497. }
  1498. my $in;
  1499. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1500. if (-e "$config{wikistatedir}/index") {
  1501. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1502. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1503. }
  1504. else {
  1505. $config{gettime}=1; # first build
  1506. return;
  1507. }
  1508. }
  1509. my $index=Storable::fd_retrieve($in);
  1510. if (! defined $index) {
  1511. return 0;
  1512. }
  1513. my $pages;
  1514. if (exists $index->{version} && ! ref $index->{version}) {
  1515. $pages=$index->{page};
  1516. %wikistate=%{$index->{state}};
  1517. # Handle plugins that got disabled by loading a new setup.
  1518. if (exists $config{setupfile}) {
  1519. require IkiWiki::Setup;
  1520. IkiWiki::Setup::disabled_plugins(
  1521. grep { ! $loaded_plugins{$_} } keys %wikistate);
  1522. }
  1523. }
  1524. else {
  1525. $pages=$index;
  1526. %wikistate=();
  1527. }
  1528. foreach my $src (keys %$pages) {
  1529. my $d=$pages->{$src};
  1530. my $page=pagename($src);
  1531. $pagectime{$page}=$d->{ctime};
  1532. $pagesources{$page}=$src;
  1533. if (! $config{rebuild}) {
  1534. $pagemtime{$page}=$d->{mtime};
  1535. $renderedfiles{$page}=$d->{dest};
  1536. if (exists $d->{links} && ref $d->{links}) {
  1537. $links{$page}=$d->{links};
  1538. $oldlinks{$page}=[@{$d->{links}}];
  1539. }
  1540. if (ref $d->{depends_simple} eq 'ARRAY') {
  1541. # old format
  1542. $depends_simple{$page}={
  1543. map { $_ => 1 } @{$d->{depends_simple}}
  1544. };
  1545. }
  1546. elsif (exists $d->{depends_simple}) {
  1547. $depends_simple{$page}=$d->{depends_simple};
  1548. }
  1549. if (exists $d->{dependslist}) {
  1550. # old format
  1551. $depends{$page}={
  1552. map { $_ => $DEPEND_CONTENT }
  1553. @{$d->{dependslist}}
  1554. };
  1555. }
  1556. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1557. # old format
  1558. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1559. }
  1560. elsif (exists $d->{depends}) {
  1561. $depends{$page}=$d->{depends};
  1562. }
  1563. if (exists $d->{state}) {
  1564. $pagestate{$page}=$d->{state};
  1565. }
  1566. if (exists $d->{typedlinks}) {
  1567. $typedlinks{$page}=$d->{typedlinks};
  1568. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1569. next unless %$links;
  1570. $oldtypedlinks{$page}{$type} = {%$links};
  1571. }
  1572. }
  1573. }
  1574. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1575. }
  1576. foreach my $page (keys %pagesources) {
  1577. $pagecase{lc $page}=$page;
  1578. }
  1579. foreach my $page (keys %renderedfiles) {
  1580. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1581. }
  1582. return close($in);
  1583. }
  1584. sub saveindex () {
  1585. run_hooks(savestate => sub { shift->() });
  1586. my @plugins=keys %loaded_plugins;
  1587. if (! -d $config{wikistatedir}) {
  1588. mkdir($config{wikistatedir});
  1589. }
  1590. my $newfile="$config{wikistatedir}/indexdb.new";
  1591. my $cleanup = sub { unlink($newfile) };
  1592. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1593. my %index;
  1594. foreach my $page (keys %pagemtime) {
  1595. next unless $pagemtime{$page};
  1596. my $src=$pagesources{$page};
  1597. $index{page}{$src}={
  1598. ctime => $pagectime{$page},
  1599. mtime => $pagemtime{$page},
  1600. dest => $renderedfiles{$page},
  1601. links => $links{$page},
  1602. };
  1603. if (exists $depends{$page}) {
  1604. $index{page}{$src}{depends} = $depends{$page};
  1605. }
  1606. if (exists $depends_simple{$page}) {
  1607. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1608. }
  1609. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1610. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1611. }
  1612. if (exists $pagestate{$page}) {
  1613. foreach my $id (@plugins) {
  1614. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1615. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1616. }
  1617. }
  1618. }
  1619. }
  1620. $index{state}={};
  1621. foreach my $id (@plugins) {
  1622. $index{state}{$id}={}; # used to detect disabled plugins
  1623. foreach my $key (keys %{$wikistate{$id}}) {
  1624. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1625. }
  1626. }
  1627. $index{version}="3";
  1628. my $ret=Storable::nstore_fd(\%index, $out);
  1629. return if ! defined $ret || ! $ret;
  1630. close $out || error("failed saving to $newfile: $!", $cleanup);
  1631. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1632. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1633. return 1;
  1634. }
  1635. sub template_file ($) {
  1636. my $name=shift;
  1637. my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
  1638. my $template;
  1639. if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
  1640. $template=srcfile($pagesources{$tpage}, 1);
  1641. $name.=".tmpl";
  1642. }
  1643. else {
  1644. $template=srcfile($tpage, 1);
  1645. }
  1646. if (defined $template) {
  1647. return $template, $tpage, 1 if wantarray;
  1648. return $template;
  1649. }
  1650. else {
  1651. $name=~s:/::; # avoid path traversal
  1652. foreach my $dir ($config{templatedir},
  1653. "$installdir/share/ikiwiki/templates") {
  1654. if (-e "$dir/$name") {
  1655. $template="$dir/$name";
  1656. last;
  1657. }
  1658. }
  1659. if (defined $template) {
  1660. return $template, $tpage if wantarray;
  1661. return $template;
  1662. }
  1663. }
  1664. return;
  1665. }
  1666. sub template_depends ($$;@) {
  1667. my $name=shift;
  1668. my $page=shift;
  1669. my ($filename, $tpage, $untrusted)=template_file($name);
  1670. if (! defined $filename) {
  1671. error(sprintf(gettext("template %s not found"), $name))
  1672. }
  1673. if (defined $page && defined $tpage) {
  1674. add_depends($page, $tpage);
  1675. }
  1676. my @opts=(
  1677. filter => sub {
  1678. my $text_ref = shift;
  1679. ${$text_ref} = decode_utf8(${$text_ref});
  1680. },
  1681. loop_context_vars => 1,
  1682. die_on_bad_params => 0,
  1683. filename => $filename,
  1684. @_,
  1685. ($untrusted ? (no_includes => 1) : ()),
  1686. );
  1687. return @opts if wantarray;
  1688. require HTML::Template;
  1689. return HTML::Template->new(@opts);
  1690. }
  1691. sub template ($;@) {
  1692. template_depends(shift, undef, @_);
  1693. }
  1694. sub misctemplate ($$;@) {
  1695. my $title=shift;
  1696. my $content=shift;
  1697. my %params=@_;
  1698. my $template=template("page.tmpl");
  1699. my $page="";
  1700. if (exists $params{page}) {
  1701. $page=delete $params{page};
  1702. }
  1703. run_hooks(pagetemplate => sub {
  1704. shift->(
  1705. page => $page,
  1706. destpage => $page,
  1707. template => $template,
  1708. );
  1709. });
  1710. templateactions($template, "");
  1711. $template->param(
  1712. dynamic => 1,
  1713. title => $title,
  1714. wikiname => $config{wikiname},
  1715. content => $content,
  1716. baseurl => baseurl(),
  1717. html5 => $config{html5},
  1718. %params,
  1719. );
  1720. return $template->output;
  1721. }
  1722. sub templateactions ($$) {
  1723. my $template=shift;
  1724. my $page=shift;
  1725. my $have_actions=0;
  1726. my @actions;
  1727. run_hooks(pageactions => sub {
  1728. push @actions, map { { action => $_ } }
  1729. grep { defined } shift->(page => $page);
  1730. });
  1731. $template->param(actions => \@actions);
  1732. if ($config{cgiurl} && exists $hooks{auth}) {
  1733. $template->param(prefsurl => cgiurl(do => "prefs"));
  1734. $have_actions=1;
  1735. }
  1736. if ($have_actions || @actions) {
  1737. $template->param(have_actions => 1);
  1738. }
  1739. }
  1740. sub hook (@) {
  1741. my %param=@_;
  1742. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1743. error 'hook requires type, call, and id parameters';
  1744. }
  1745. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1746. $hooks{$param{type}}{$param{id}}=\%param;
  1747. return 1;
  1748. }
  1749. sub run_hooks ($$) {
  1750. # Calls the given sub for each hook of the given type,
  1751. # passing it the hook function to call.
  1752. my $type=shift;
  1753. my $sub=shift;
  1754. if (exists $hooks{$type}) {
  1755. my (@first, @middle, @last);
  1756. foreach my $id (keys %{$hooks{$type}}) {
  1757. if ($hooks{$type}{$id}{first}) {
  1758. push @first, $id;
  1759. }
  1760. elsif ($hooks{$type}{$id}{last}) {
  1761. push @last, $id;
  1762. }
  1763. else {
  1764. push @middle, $id;
  1765. }
  1766. }
  1767. foreach my $id (@first, @middle, @last) {
  1768. $sub->($hooks{$type}{$id}{call});
  1769. }
  1770. }
  1771. return 1;
  1772. }
  1773. sub rcs_update () {
  1774. $hooks{rcs}{rcs_update}{call}->(@_);
  1775. }
  1776. sub rcs_prepedit ($) {
  1777. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1778. }
  1779. sub rcs_commit (@) {
  1780. $hooks{rcs}{rcs_commit}{call}->(@_);
  1781. }
  1782. sub rcs_commit_staged (@) {
  1783. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1784. }
  1785. sub rcs_add ($) {
  1786. $hooks{rcs}{rcs_add}{call}->(@_);
  1787. }
  1788. sub rcs_remove ($) {
  1789. $hooks{rcs}{rcs_remove}{call}->(@_);
  1790. }
  1791. sub rcs_rename ($$) {
  1792. $hooks{rcs}{rcs_rename}{call}->(@_);
  1793. }
  1794. sub rcs_recentchanges ($) {
  1795. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1796. }
  1797. sub rcs_diff ($) {
  1798. $hooks{rcs}{rcs_diff}{call}->(@_);
  1799. }
  1800. sub rcs_getctime ($) {
  1801. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1802. }
  1803. sub rcs_getmtime ($) {
  1804. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1805. }
  1806. sub rcs_receive () {
  1807. $hooks{rcs}{rcs_receive}{call}->();
  1808. }
  1809. sub add_depends ($$;$) {
  1810. my $page=shift;
  1811. my $pagespec=shift;
  1812. my $deptype=shift || $DEPEND_CONTENT;
  1813. # Is the pagespec a simple page name?
  1814. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1815. $pagespec !~ /[\s*?()!]/) {
  1816. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1817. return 1;
  1818. }
  1819. # Add explicit dependencies for influences.
  1820. my $sub=pagespec_translate($pagespec);
  1821. return unless defined $sub;
  1822. foreach my $p (keys %pagesources) {
  1823. my $r=$sub->($p, location => $page);
  1824. my $i=$r->influences;
  1825. my $static=$r->influences_static;
  1826. foreach my $k (keys %$i) {
  1827. next unless $r || $static || $k eq $page;
  1828. $depends_simple{$page}{lc $k} |= $i->{$k};
  1829. }
  1830. last if $static;
  1831. }
  1832. $depends{$page}{$pagespec} |= $deptype;
  1833. return 1;
  1834. }
  1835. sub deptype (@) {
  1836. my $deptype=0;
  1837. foreach my $type (@_) {
  1838. if ($type eq 'presence') {
  1839. $deptype |= $DEPEND_PRESENCE;
  1840. }
  1841. elsif ($type eq 'links') {
  1842. $deptype |= $DEPEND_LINKS;
  1843. }
  1844. elsif ($type eq 'content') {
  1845. $deptype |= $DEPEND_CONTENT;
  1846. }
  1847. }
  1848. return $deptype;
  1849. }
  1850. my $file_prune_regexp;
  1851. sub file_pruned ($) {
  1852. my $file=shift;
  1853. if (defined $config{include} && length $config{include}) {
  1854. return 0 if $file =~ m/$config{include}/;
  1855. }
  1856. if (! defined $file_prune_regexp) {
  1857. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1858. $file_prune_regexp=qr/$file_prune_regexp/;
  1859. }
  1860. return $file =~ m/$file_prune_regexp/;
  1861. }
  1862. sub define_gettext () {
  1863. # If translation is needed, redefine the gettext function to do it.
  1864. # Otherwise, it becomes a quick no-op.
  1865. my $gettext_obj;
  1866. my $getobj;
  1867. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1868. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1869. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1870. $getobj=sub {
  1871. $gettext_obj=eval q{
  1872. use Locale::gettext q{textdomain};
  1873. Locale::gettext->domain('ikiwiki')
  1874. };
  1875. };
  1876. }
  1877. no warnings 'redefine';
  1878. *gettext=sub {
  1879. $getobj->() if $getobj;
  1880. if ($gettext_obj) {
  1881. $gettext_obj->get(shift);
  1882. }
  1883. else {
  1884. return shift;
  1885. }
  1886. };
  1887. *ngettext=sub {
  1888. $getobj->() if $getobj;
  1889. if ($gettext_obj) {
  1890. $gettext_obj->nget(@_);
  1891. }
  1892. else {
  1893. return ($_[2] == 1 ? $_[0] : $_[1])
  1894. }
  1895. };
  1896. }
  1897. sub gettext {
  1898. define_gettext();
  1899. gettext(@_);
  1900. }
  1901. sub ngettext {
  1902. define_gettext();
  1903. ngettext(@_);
  1904. }
  1905. sub yesno ($) {
  1906. my $val=shift;
  1907. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1908. }
  1909. sub inject {
  1910. # Injects a new function into the symbol table to replace an
  1911. # exported function.
  1912. my %params=@_;
  1913. # This is deep ugly perl foo, beware.
  1914. no strict;
  1915. no warnings;
  1916. if (! defined $params{parent}) {
  1917. $params{parent}='::';
  1918. $params{old}=\&{$params{name}};
  1919. $params{name}=~s/.*:://;
  1920. }
  1921. my $parent=$params{parent};
  1922. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1923. $ns = $params{parent} . $ns;
  1924. inject(%params, parent => $ns) unless $ns eq '::main::';
  1925. *{$ns . $params{name}} = $params{call}
  1926. if exists ${$ns}{$params{name}} &&
  1927. \&{${$ns}{$params{name}}} == $params{old};
  1928. }
  1929. use strict;
  1930. use warnings;
  1931. }
  1932. sub add_link ($$;$) {
  1933. my $page=shift;
  1934. my $link=shift;
  1935. my $type=shift;
  1936. push @{$links{$page}}, $link
  1937. unless grep { $_ eq $link } @{$links{$page}};
  1938. if (defined $type) {
  1939. $typedlinks{$page}{$type}{$link} = 1;
  1940. }
  1941. }
  1942. sub add_autofile ($$$) {
  1943. my $file=shift;
  1944. my $plugin=shift;
  1945. my $generator=shift;
  1946. $autofiles{$file}{plugin}=$plugin;
  1947. $autofiles{$file}{generator}=$generator;
  1948. }
  1949. sub sortspec_translate ($$) {
  1950. my $spec = shift;
  1951. my $reverse = shift;
  1952. my $code = "";
  1953. my @data;
  1954. while ($spec =~ m{
  1955. \s*
  1956. (-?) # group 1: perhaps negated
  1957. \s*
  1958. ( # group 2: a word
  1959. \w+\([^\)]*\) # command(params)
  1960. |
  1961. [^\s]+ # or anything else
  1962. )
  1963. \s*
  1964. }gx) {
  1965. my $negated = $1;
  1966. my $word = $2;
  1967. my $params = undef;
  1968. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1969. # command with parameters
  1970. $params = $2;
  1971. $word = $1;
  1972. }
  1973. elsif ($word !~ m/^\w+$/) {
  1974. error(sprintf(gettext("invalid sort type %s"), $word));
  1975. }
  1976. if (length $code) {
  1977. $code .= " || ";
  1978. }
  1979. if ($negated) {
  1980. $code .= "-";
  1981. }
  1982. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1983. if (defined $params) {
  1984. push @data, $params;
  1985. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1986. }
  1987. else {
  1988. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1989. }
  1990. }
  1991. else {
  1992. error(sprintf(gettext("unknown sort type %s"), $word));
  1993. }
  1994. }
  1995. if (! length $code) {
  1996. # undefined sorting method... sort arbitrarily
  1997. return sub { 0 };
  1998. }
  1999. if ($reverse) {
  2000. $code="-($code)";
  2001. }
  2002. no warnings;
  2003. return eval 'sub { '.$code.' }';
  2004. }
  2005. sub pagespec_translate ($) {
  2006. my $spec=shift;
  2007. # Convert spec to perl code.
  2008. my $code="";
  2009. my @data;
  2010. while ($spec=~m{
  2011. \s* # ignore whitespace
  2012. ( # 1: match a single word
  2013. \! # !
  2014. |
  2015. \( # (
  2016. |
  2017. \) # )
  2018. |
  2019. \w+\([^\)]*\) # command(params)
  2020. |
  2021. [^\s()]+ # any other text
  2022. )
  2023. \s* # ignore whitespace
  2024. }gx) {
  2025. my $word=$1;
  2026. if (lc $word eq 'and') {
  2027. $code.=' &';
  2028. }
  2029. elsif (lc $word eq 'or') {
  2030. $code.=' |';
  2031. }
  2032. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  2033. $code.=' '.$word;
  2034. }
  2035. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  2036. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  2037. push @data, $2;
  2038. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  2039. }
  2040. else {
  2041. push @data, qq{unknown function in pagespec "$word"};
  2042. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  2043. }
  2044. }
  2045. else {
  2046. push @data, $word;
  2047. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  2048. }
  2049. }
  2050. if (! length $code) {
  2051. $code="IkiWiki::FailReason->new('empty pagespec')";
  2052. }
  2053. no warnings;
  2054. return eval 'sub { my $page=shift; '.$code.' }';
  2055. }
  2056. sub pagespec_match ($$;@) {
  2057. my $page=shift;
  2058. my $spec=shift;
  2059. my @params=@_;
  2060. # Backwards compatability with old calling convention.
  2061. if (@params == 1) {
  2062. unshift @params, 'location';
  2063. }
  2064. my $sub=pagespec_translate($spec);
  2065. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  2066. if ! defined $sub;
  2067. return $sub->($page, @params);
  2068. }
  2069. sub pagespec_match_list ($$;@) {
  2070. my $page=shift;
  2071. my $pagespec=shift;
  2072. my %params=@_;
  2073. # Backwards compatability with old calling convention.
  2074. if (ref $page) {
  2075. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  2076. $params{list}=$page;
  2077. $page=$params{location}; # ugh!
  2078. }
  2079. my $sub=pagespec_translate($pagespec);
  2080. error "syntax error in pagespec \"$pagespec\""
  2081. if ! defined $sub;
  2082. my $sort=sortspec_translate($params{sort}, $params{reverse})
  2083. if defined $params{sort};
  2084. my @candidates;
  2085. if (exists $params{list}) {
  2086. @candidates=exists $params{filter}
  2087. ? grep { ! $params{filter}->($_) } @{$params{list}}
  2088. : @{$params{list}};
  2089. }
  2090. else {
  2091. @candidates=exists $params{filter}
  2092. ? grep { ! $params{filter}->($_) } keys %pagesources
  2093. : keys %pagesources;
  2094. }
  2095. # clear params, remainder is passed to pagespec
  2096. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  2097. my $num=$params{num};
  2098. delete @params{qw{num deptype reverse sort filter list}};
  2099. # when only the top matches will be returned, it's efficient to
  2100. # sort before matching to pagespec,
  2101. if (defined $num && defined $sort) {
  2102. @candidates=IkiWiki::SortSpec::sort_pages(
  2103. $sort, @candidates);
  2104. }
  2105. my @matches;
  2106. my $firstfail;
  2107. my $count=0;
  2108. my $accum=IkiWiki::SuccessReason->new();
  2109. foreach my $p (@candidates) {
  2110. my $r=$sub->($p, %params, location => $page);
  2111. error(sprintf(gettext("cannot match pages: %s"), $r))
  2112. if $r->isa("IkiWiki::ErrorReason");
  2113. unless ($r || $r->influences_static) {
  2114. $r->remove_influence($p);
  2115. }
  2116. $accum |= $r;
  2117. if ($r) {
  2118. push @matches, $p;
  2119. last if defined $num && ++$count == $num;
  2120. }
  2121. }
  2122. # Add simple dependencies for accumulated influences.
  2123. my $i=$accum->influences;
  2124. foreach my $k (keys %$i) {
  2125. $depends_simple{$page}{lc $k} |= $i->{$k};
  2126. }
  2127. # when all matches will be returned, it's efficient to
  2128. # sort after matching
  2129. if (! defined $num && defined $sort) {
  2130. return IkiWiki::SortSpec::sort_pages(
  2131. $sort, @matches);
  2132. }
  2133. else {
  2134. return @matches;
  2135. }
  2136. }
  2137. sub pagespec_valid ($) {
  2138. my $spec=shift;
  2139. return defined pagespec_translate($spec);
  2140. }
  2141. sub glob2re ($) {
  2142. my $re=quotemeta(shift);
  2143. $re=~s/\\\*/.*/g;
  2144. $re=~s/\\\?/./g;
  2145. return qr/^$re$/i;
  2146. }
  2147. package IkiWiki::FailReason;
  2148. use overload (
  2149. '""' => sub { $_[0][0] },
  2150. '0+' => sub { 0 },
  2151. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2152. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2153. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2154. fallback => 1,
  2155. );
  2156. our @ISA = 'IkiWiki::SuccessReason';
  2157. package IkiWiki::SuccessReason;
  2158. use overload (
  2159. '""' => sub { $_[0][0] },
  2160. '0+' => sub { 1 },
  2161. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2162. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2163. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2164. fallback => 1,
  2165. );
  2166. sub new {
  2167. my $class = shift;
  2168. my $value = shift;
  2169. return bless [$value, {@_}], $class;
  2170. }
  2171. sub influences {
  2172. my $this=shift;
  2173. $this->[1]={@_} if @_;
  2174. my %i=%{$this->[1]};
  2175. delete $i{""};
  2176. return \%i;
  2177. }
  2178. sub influences_static {
  2179. return ! $_[0][1]->{""};
  2180. }
  2181. sub merge_influences {
  2182. my $this=shift;
  2183. my $other=shift;
  2184. my $anded=shift;
  2185. if (! $anded || (($this || %{$this->[1]}) &&
  2186. ($other || %{$other->[1]}))) {
  2187. foreach my $influence (keys %{$other->[1]}) {
  2188. $this->[1]{$influence} |= $other->[1]{$influence};
  2189. }
  2190. }
  2191. else {
  2192. # influence blocker
  2193. $this->[1]={};
  2194. }
  2195. }
  2196. sub remove_influence {
  2197. my $this=shift;
  2198. my $torm=shift;
  2199. delete $this->[1]{$torm};
  2200. }
  2201. package IkiWiki::ErrorReason;
  2202. our @ISA = 'IkiWiki::FailReason';
  2203. package IkiWiki::PageSpec;
  2204. sub derel ($$) {
  2205. my $path=shift;
  2206. my $from=shift;
  2207. if ($path =~ m!^\.(/|$)!) {
  2208. if ($1) {
  2209. $from=~s#/?[^/]+$## if defined $from;
  2210. $path=~s#^\./##;
  2211. $path="$from/$path" if defined $from && length $from;
  2212. }
  2213. else {
  2214. $path = $from;
  2215. $path = "" unless defined $path;
  2216. }
  2217. }
  2218. return $path;
  2219. }
  2220. my %glob_cache;
  2221. sub match_glob ($$;@) {
  2222. my $page=shift;
  2223. my $glob=shift;
  2224. my %params=@_;
  2225. $glob=derel($glob, $params{location});
  2226. # Instead of converting the glob to a regex every time,
  2227. # cache the compiled regex to save time.
  2228. my $re=$glob_cache{$glob};
  2229. unless (defined $re) {
  2230. $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
  2231. }
  2232. if ($page =~ $re) {
  2233. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2234. return IkiWiki::SuccessReason->new("$glob matches $page");
  2235. }
  2236. else {
  2237. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2238. }
  2239. }
  2240. else {
  2241. return IkiWiki::FailReason->new("$glob does not match $page");
  2242. }
  2243. }
  2244. sub match_internal ($$;@) {
  2245. return match_glob(shift, shift, @_, internal => 1)
  2246. }
  2247. sub match_page ($$;@) {
  2248. my $page=shift;
  2249. my $match=match_glob($page, shift, @_);
  2250. if ($match) {
  2251. my $source=exists $IkiWiki::pagesources{$page} ?
  2252. $IkiWiki::pagesources{$page} :
  2253. $IkiWiki::delpagesources{$page};
  2254. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  2255. if (! defined $type) {
  2256. return IkiWiki::FailReason->new("$page is not a page");
  2257. }
  2258. }
  2259. return $match;
  2260. }
  2261. sub match_link ($$;@) {
  2262. my $page=shift;
  2263. my $link=lc(shift);
  2264. my %params=@_;
  2265. $link=derel($link, $params{location});
  2266. my $from=exists $params{location} ? $params{location} : '';
  2267. my $linktype=$params{linktype};
  2268. my $qualifier='';
  2269. if (defined $linktype) {
  2270. $qualifier=" with type $linktype";
  2271. }
  2272. my $links = $IkiWiki::links{$page};
  2273. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2274. unless $links && @{$links};
  2275. my $bestlink = IkiWiki::bestlink($from, $link);
  2276. foreach my $p (@{$links}) {
  2277. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2278. if (length $bestlink) {
  2279. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2280. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2281. }
  2282. }
  2283. else {
  2284. if (match_glob($p, $link, %params)) {
  2285. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2286. }
  2287. my ($p_rel)=$p=~/^\/?(.*)/;
  2288. $link=~s/^\///;
  2289. if (match_glob($p_rel, $link, %params)) {
  2290. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2291. }
  2292. }
  2293. }
  2294. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2295. }
  2296. sub match_backlink ($$;@) {
  2297. my $ret=match_link($_[1], $_[0], @_);
  2298. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2299. return $ret;
  2300. }
  2301. sub match_created_before ($$;@) {
  2302. my $page=shift;
  2303. my $testpage=shift;
  2304. my %params=@_;
  2305. $testpage=derel($testpage, $params{location});
  2306. if (exists $IkiWiki::pagectime{$testpage}) {
  2307. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2308. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2309. }
  2310. else {
  2311. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2312. }
  2313. }
  2314. else {
  2315. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2316. }
  2317. }
  2318. sub match_created_after ($$;@) {
  2319. my $page=shift;
  2320. my $testpage=shift;
  2321. my %params=@_;
  2322. $testpage=derel($testpage, $params{location});
  2323. if (exists $IkiWiki::pagectime{$testpage}) {
  2324. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2325. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2326. }
  2327. else {
  2328. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2329. }
  2330. }
  2331. else {
  2332. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2333. }
  2334. }
  2335. sub match_creation_day ($$;@) {
  2336. my $page=shift;
  2337. my $d=shift;
  2338. if ($d !~ /^\d+$/) {
  2339. return IkiWiki::ErrorReason->new("invalid day $d");
  2340. }
  2341. if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
  2342. return IkiWiki::SuccessReason->new('creation_day matched');
  2343. }
  2344. else {
  2345. return IkiWiki::FailReason->new('creation_day did not match');
  2346. }
  2347. }
  2348. sub match_creation_month ($$;@) {
  2349. my $page=shift;
  2350. my $m=shift;
  2351. if ($m !~ /^\d+$/) {
  2352. return IkiWiki::ErrorReason->new("invalid month $m");
  2353. }
  2354. if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
  2355. return IkiWiki::SuccessReason->new('creation_month matched');
  2356. }
  2357. else {
  2358. return IkiWiki::FailReason->new('creation_month did not match');
  2359. }
  2360. }
  2361. sub match_creation_year ($$;@) {
  2362. my $page=shift;
  2363. my $y=shift;
  2364. if ($y !~ /^\d+$/) {
  2365. return IkiWiki::ErrorReason->new("invalid year $y");
  2366. }
  2367. if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
  2368. return IkiWiki::SuccessReason->new('creation_year matched');
  2369. }
  2370. else {
  2371. return IkiWiki::FailReason->new('creation_year did not match');
  2372. }
  2373. }
  2374. sub match_user ($$;@) {
  2375. shift;
  2376. my $user=shift;
  2377. my %params=@_;
  2378. my $regexp=IkiWiki::glob2re($user);
  2379. if (! exists $params{user}) {
  2380. return IkiWiki::ErrorReason->new("no user specified");
  2381. }
  2382. if (defined $params{user} && $params{user}=~$regexp) {
  2383. return IkiWiki::SuccessReason->new("user is $user");
  2384. }
  2385. elsif (! defined $params{user}) {
  2386. return IkiWiki::FailReason->new("not logged in");
  2387. }
  2388. else {
  2389. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2390. }
  2391. }
  2392. sub match_admin ($$;@) {
  2393. shift;
  2394. shift;
  2395. my %params=@_;
  2396. if (! exists $params{user}) {
  2397. return IkiWiki::ErrorReason->new("no user specified");
  2398. }
  2399. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2400. return IkiWiki::SuccessReason->new("user is an admin");
  2401. }
  2402. elsif (! defined $params{user}) {
  2403. return IkiWiki::FailReason->new("not logged in");
  2404. }
  2405. else {
  2406. return IkiWiki::FailReason->new("user is not an admin");
  2407. }
  2408. }
  2409. sub match_ip ($$;@) {
  2410. shift;
  2411. my $ip=shift;
  2412. my %params=@_;
  2413. if (! exists $params{ip}) {
  2414. return IkiWiki::ErrorReason->new("no IP specified");
  2415. }
  2416. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2417. return IkiWiki::SuccessReason->new("IP is $ip");
  2418. }
  2419. else {
  2420. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2421. }
  2422. }
  2423. package IkiWiki::SortSpec;
  2424. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2425. # are easily available in this namespace, for cmp functions to use them.
  2426. sub sort_pages {
  2427. my $f=shift;
  2428. sort $f @_
  2429. }
  2430. sub cmp_title {
  2431. IkiWiki::pagetitle(IkiWiki::basename($a))
  2432. cmp
  2433. IkiWiki::pagetitle(IkiWiki::basename($b))
  2434. }
  2435. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2436. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2437. 1