summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 1102fa52a967b94f8595c56415af10bcdca9ef24 (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 (defined $config{url} && 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. $to = 'index';
  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. parent_global_vars => 1,
  1687. filename => $filename,
  1688. @_,
  1689. ($untrusted ? (no_includes => 1) : ()),
  1690. );
  1691. return @opts if wantarray;
  1692. require HTML::Template;
  1693. return HTML::Template->new(@opts);
  1694. }
  1695. sub template ($;@) {
  1696. template_depends(shift, undef, @_);
  1697. }
  1698. sub misctemplate ($$;@) {
  1699. my $title=shift;
  1700. my $content=shift;
  1701. my %params=@_;
  1702. my $template=template("page.tmpl");
  1703. my $page="";
  1704. if (exists $params{page}) {
  1705. $page=delete $params{page};
  1706. }
  1707. run_hooks(pagetemplate => sub {
  1708. shift->(
  1709. page => $page,
  1710. destpage => $page,
  1711. template => $template,
  1712. );
  1713. });
  1714. templateactions($template, "");
  1715. $template->param(
  1716. dynamic => 1,
  1717. title => $title,
  1718. wikiname => $config{wikiname},
  1719. content => $content,
  1720. baseurl => baseurl(),
  1721. html5 => $config{html5},
  1722. %params,
  1723. );
  1724. return $template->output;
  1725. }
  1726. sub templateactions ($$) {
  1727. my $template=shift;
  1728. my $page=shift;
  1729. my $have_actions=0;
  1730. my @actions;
  1731. run_hooks(pageactions => sub {
  1732. push @actions, map { { action => $_ } }
  1733. grep { defined } shift->(page => $page);
  1734. });
  1735. $template->param(actions => \@actions);
  1736. if ($config{cgiurl} && exists $hooks{auth}) {
  1737. $template->param(prefsurl => cgiurl(do => "prefs"));
  1738. $have_actions=1;
  1739. }
  1740. if ($have_actions || @actions) {
  1741. $template->param(have_actions => 1);
  1742. }
  1743. }
  1744. sub hook (@) {
  1745. my %param=@_;
  1746. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1747. error 'hook requires type, call, and id parameters';
  1748. }
  1749. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1750. $hooks{$param{type}}{$param{id}}=\%param;
  1751. return 1;
  1752. }
  1753. sub run_hooks ($$) {
  1754. # Calls the given sub for each hook of the given type,
  1755. # passing it the hook function to call.
  1756. my $type=shift;
  1757. my $sub=shift;
  1758. if (exists $hooks{$type}) {
  1759. my (@first, @middle, @last);
  1760. foreach my $id (keys %{$hooks{$type}}) {
  1761. if ($hooks{$type}{$id}{first}) {
  1762. push @first, $id;
  1763. }
  1764. elsif ($hooks{$type}{$id}{last}) {
  1765. push @last, $id;
  1766. }
  1767. else {
  1768. push @middle, $id;
  1769. }
  1770. }
  1771. foreach my $id (@first, @middle, @last) {
  1772. $sub->($hooks{$type}{$id}{call});
  1773. }
  1774. }
  1775. return 1;
  1776. }
  1777. sub rcs_update () {
  1778. $hooks{rcs}{rcs_update}{call}->(@_);
  1779. }
  1780. sub rcs_prepedit ($) {
  1781. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1782. }
  1783. sub rcs_commit (@) {
  1784. $hooks{rcs}{rcs_commit}{call}->(@_);
  1785. }
  1786. sub rcs_commit_staged (@) {
  1787. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1788. }
  1789. sub rcs_add ($) {
  1790. $hooks{rcs}{rcs_add}{call}->(@_);
  1791. }
  1792. sub rcs_remove ($) {
  1793. $hooks{rcs}{rcs_remove}{call}->(@_);
  1794. }
  1795. sub rcs_rename ($$) {
  1796. $hooks{rcs}{rcs_rename}{call}->(@_);
  1797. }
  1798. sub rcs_recentchanges ($) {
  1799. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1800. }
  1801. sub rcs_diff ($;$) {
  1802. $hooks{rcs}{rcs_diff}{call}->(@_);
  1803. }
  1804. sub rcs_getctime ($) {
  1805. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1806. }
  1807. sub rcs_getmtime ($) {
  1808. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1809. }
  1810. sub rcs_receive () {
  1811. $hooks{rcs}{rcs_receive}{call}->();
  1812. }
  1813. sub add_depends ($$;$) {
  1814. my $page=shift;
  1815. my $pagespec=shift;
  1816. my $deptype=shift || $DEPEND_CONTENT;
  1817. # Is the pagespec a simple page name?
  1818. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1819. $pagespec !~ /[\s*?()!]/) {
  1820. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1821. return 1;
  1822. }
  1823. # Add explicit dependencies for influences.
  1824. my $sub=pagespec_translate($pagespec);
  1825. return unless defined $sub;
  1826. foreach my $p (keys %pagesources) {
  1827. my $r=$sub->($p, location => $page);
  1828. my $i=$r->influences;
  1829. my $static=$r->influences_static;
  1830. foreach my $k (keys %$i) {
  1831. next unless $r || $static || $k eq $page;
  1832. $depends_simple{$page}{lc $k} |= $i->{$k};
  1833. }
  1834. last if $static;
  1835. }
  1836. $depends{$page}{$pagespec} |= $deptype;
  1837. return 1;
  1838. }
  1839. sub deptype (@) {
  1840. my $deptype=0;
  1841. foreach my $type (@_) {
  1842. if ($type eq 'presence') {
  1843. $deptype |= $DEPEND_PRESENCE;
  1844. }
  1845. elsif ($type eq 'links') {
  1846. $deptype |= $DEPEND_LINKS;
  1847. }
  1848. elsif ($type eq 'content') {
  1849. $deptype |= $DEPEND_CONTENT;
  1850. }
  1851. }
  1852. return $deptype;
  1853. }
  1854. my $file_prune_regexp;
  1855. sub file_pruned ($) {
  1856. my $file=shift;
  1857. if (defined $config{include} && length $config{include}) {
  1858. return 0 if $file =~ m/$config{include}/;
  1859. }
  1860. if (! defined $file_prune_regexp) {
  1861. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1862. $file_prune_regexp=qr/$file_prune_regexp/;
  1863. }
  1864. return $file =~ m/$file_prune_regexp/;
  1865. }
  1866. sub define_gettext () {
  1867. # If translation is needed, redefine the gettext function to do it.
  1868. # Otherwise, it becomes a quick no-op.
  1869. my $gettext_obj;
  1870. my $getobj;
  1871. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1872. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1873. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1874. $getobj=sub {
  1875. $gettext_obj=eval q{
  1876. use Locale::gettext q{textdomain};
  1877. Locale::gettext->domain('ikiwiki')
  1878. };
  1879. };
  1880. }
  1881. no warnings 'redefine';
  1882. *gettext=sub {
  1883. $getobj->() if $getobj;
  1884. if ($gettext_obj) {
  1885. $gettext_obj->get(shift);
  1886. }
  1887. else {
  1888. return shift;
  1889. }
  1890. };
  1891. *ngettext=sub {
  1892. $getobj->() if $getobj;
  1893. if ($gettext_obj) {
  1894. $gettext_obj->nget(@_);
  1895. }
  1896. else {
  1897. return ($_[2] == 1 ? $_[0] : $_[1])
  1898. }
  1899. };
  1900. }
  1901. sub gettext {
  1902. define_gettext();
  1903. gettext(@_);
  1904. }
  1905. sub ngettext {
  1906. define_gettext();
  1907. ngettext(@_);
  1908. }
  1909. sub yesno ($) {
  1910. my $val=shift;
  1911. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1912. }
  1913. sub inject {
  1914. # Injects a new function into the symbol table to replace an
  1915. # exported function.
  1916. my %params=@_;
  1917. # This is deep ugly perl foo, beware.
  1918. no strict;
  1919. no warnings;
  1920. if (! defined $params{parent}) {
  1921. $params{parent}='::';
  1922. $params{old}=\&{$params{name}};
  1923. $params{name}=~s/.*:://;
  1924. }
  1925. my $parent=$params{parent};
  1926. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1927. $ns = $params{parent} . $ns;
  1928. inject(%params, parent => $ns) unless $ns eq '::main::';
  1929. *{$ns . $params{name}} = $params{call}
  1930. if exists ${$ns}{$params{name}} &&
  1931. \&{${$ns}{$params{name}}} == $params{old};
  1932. }
  1933. use strict;
  1934. use warnings;
  1935. }
  1936. sub add_link ($$;$) {
  1937. my $page=shift;
  1938. my $link=shift;
  1939. my $type=shift;
  1940. push @{$links{$page}}, $link
  1941. unless grep { $_ eq $link } @{$links{$page}};
  1942. if (defined $type) {
  1943. $typedlinks{$page}{$type}{$link} = 1;
  1944. }
  1945. }
  1946. sub add_autofile ($$$) {
  1947. my $file=shift;
  1948. my $plugin=shift;
  1949. my $generator=shift;
  1950. $autofiles{$file}{plugin}=$plugin;
  1951. $autofiles{$file}{generator}=$generator;
  1952. }
  1953. sub sortspec_translate ($$) {
  1954. my $spec = shift;
  1955. my $reverse = shift;
  1956. my $code = "";
  1957. my @data;
  1958. while ($spec =~ m{
  1959. \s*
  1960. (-?) # group 1: perhaps negated
  1961. \s*
  1962. ( # group 2: a word
  1963. \w+\([^\)]*\) # command(params)
  1964. |
  1965. [^\s]+ # or anything else
  1966. )
  1967. \s*
  1968. }gx) {
  1969. my $negated = $1;
  1970. my $word = $2;
  1971. my $params = undef;
  1972. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1973. # command with parameters
  1974. $params = $2;
  1975. $word = $1;
  1976. }
  1977. elsif ($word !~ m/^\w+$/) {
  1978. error(sprintf(gettext("invalid sort type %s"), $word));
  1979. }
  1980. if (length $code) {
  1981. $code .= " || ";
  1982. }
  1983. if ($negated) {
  1984. $code .= "-";
  1985. }
  1986. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1987. if (defined $params) {
  1988. push @data, $params;
  1989. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1990. }
  1991. else {
  1992. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1993. }
  1994. }
  1995. else {
  1996. error(sprintf(gettext("unknown sort type %s"), $word));
  1997. }
  1998. }
  1999. if (! length $code) {
  2000. # undefined sorting method... sort arbitrarily
  2001. return sub { 0 };
  2002. }
  2003. if ($reverse) {
  2004. $code="-($code)";
  2005. }
  2006. no warnings;
  2007. return eval 'sub { '.$code.' }';
  2008. }
  2009. sub pagespec_translate ($) {
  2010. my $spec=shift;
  2011. # Convert spec to perl code.
  2012. my $code="";
  2013. my @data;
  2014. while ($spec=~m{
  2015. \s* # ignore whitespace
  2016. ( # 1: match a single word
  2017. \! # !
  2018. |
  2019. \( # (
  2020. |
  2021. \) # )
  2022. |
  2023. \w+\([^\)]*\) # command(params)
  2024. |
  2025. [^\s()]+ # any other text
  2026. )
  2027. \s* # ignore whitespace
  2028. }gx) {
  2029. my $word=$1;
  2030. if (lc $word eq 'and') {
  2031. $code.=' &';
  2032. }
  2033. elsif (lc $word eq 'or') {
  2034. $code.=' |';
  2035. }
  2036. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  2037. $code.=' '.$word;
  2038. }
  2039. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  2040. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  2041. push @data, $2;
  2042. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  2043. }
  2044. else {
  2045. push @data, qq{unknown function in pagespec "$word"};
  2046. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  2047. }
  2048. }
  2049. else {
  2050. push @data, $word;
  2051. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  2052. }
  2053. }
  2054. if (! length $code) {
  2055. $code="IkiWiki::FailReason->new('empty pagespec')";
  2056. }
  2057. no warnings;
  2058. return eval 'sub { my $page=shift; '.$code.' }';
  2059. }
  2060. sub pagespec_match ($$;@) {
  2061. my $page=shift;
  2062. my $spec=shift;
  2063. my @params=@_;
  2064. # Backwards compatability with old calling convention.
  2065. if (@params == 1) {
  2066. unshift @params, 'location';
  2067. }
  2068. my $sub=pagespec_translate($spec);
  2069. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  2070. if ! defined $sub;
  2071. return $sub->($page, @params);
  2072. }
  2073. sub pagespec_match_list ($$;@) {
  2074. my $page=shift;
  2075. my $pagespec=shift;
  2076. my %params=@_;
  2077. # Backwards compatability with old calling convention.
  2078. if (ref $page) {
  2079. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  2080. $params{list}=$page;
  2081. $page=$params{location}; # ugh!
  2082. }
  2083. my $sub=pagespec_translate($pagespec);
  2084. error "syntax error in pagespec \"$pagespec\""
  2085. if ! defined $sub;
  2086. my $sort=sortspec_translate($params{sort}, $params{reverse})
  2087. if defined $params{sort};
  2088. my @candidates;
  2089. if (exists $params{list}) {
  2090. @candidates=exists $params{filter}
  2091. ? grep { ! $params{filter}->($_) } @{$params{list}}
  2092. : @{$params{list}};
  2093. }
  2094. else {
  2095. @candidates=exists $params{filter}
  2096. ? grep { ! $params{filter}->($_) } keys %pagesources
  2097. : keys %pagesources;
  2098. }
  2099. # clear params, remainder is passed to pagespec
  2100. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  2101. my $num=$params{num};
  2102. delete @params{qw{num deptype reverse sort filter list}};
  2103. # when only the top matches will be returned, it's efficient to
  2104. # sort before matching to pagespec,
  2105. if (defined $num && defined $sort) {
  2106. @candidates=IkiWiki::SortSpec::sort_pages(
  2107. $sort, @candidates);
  2108. }
  2109. my @matches;
  2110. my $firstfail;
  2111. my $count=0;
  2112. my $accum=IkiWiki::SuccessReason->new();
  2113. foreach my $p (@candidates) {
  2114. my $r=$sub->($p, %params, location => $page);
  2115. error(sprintf(gettext("cannot match pages: %s"), $r))
  2116. if $r->isa("IkiWiki::ErrorReason");
  2117. unless ($r || $r->influences_static) {
  2118. $r->remove_influence($p);
  2119. }
  2120. $accum |= $r;
  2121. if ($r) {
  2122. push @matches, $p;
  2123. last if defined $num && ++$count == $num;
  2124. }
  2125. }
  2126. # Add simple dependencies for accumulated influences.
  2127. my $i=$accum->influences;
  2128. foreach my $k (keys %$i) {
  2129. $depends_simple{$page}{lc $k} |= $i->{$k};
  2130. }
  2131. # when all matches will be returned, it's efficient to
  2132. # sort after matching
  2133. if (! defined $num && defined $sort) {
  2134. return IkiWiki::SortSpec::sort_pages(
  2135. $sort, @matches);
  2136. }
  2137. else {
  2138. return @matches;
  2139. }
  2140. }
  2141. sub pagespec_valid ($) {
  2142. my $spec=shift;
  2143. return defined pagespec_translate($spec);
  2144. }
  2145. sub glob2re ($) {
  2146. my $re=quotemeta(shift);
  2147. $re=~s/\\\*/.*/g;
  2148. $re=~s/\\\?/./g;
  2149. return qr/^$re$/i;
  2150. }
  2151. package IkiWiki::FailReason;
  2152. use overload (
  2153. '""' => sub { $_[0][0] },
  2154. '0+' => sub { 0 },
  2155. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2156. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2157. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2158. fallback => 1,
  2159. );
  2160. our @ISA = 'IkiWiki::SuccessReason';
  2161. package IkiWiki::SuccessReason;
  2162. use overload (
  2163. '""' => sub { $_[0][0] },
  2164. '0+' => sub { 1 },
  2165. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2166. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2167. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2168. fallback => 1,
  2169. );
  2170. sub new {
  2171. my $class = shift;
  2172. my $value = shift;
  2173. return bless [$value, {@_}], $class;
  2174. }
  2175. sub influences {
  2176. my $this=shift;
  2177. $this->[1]={@_} if @_;
  2178. my %i=%{$this->[1]};
  2179. delete $i{""};
  2180. return \%i;
  2181. }
  2182. sub influences_static {
  2183. return ! $_[0][1]->{""};
  2184. }
  2185. sub merge_influences {
  2186. my $this=shift;
  2187. my $other=shift;
  2188. my $anded=shift;
  2189. if (! $anded || (($this || %{$this->[1]}) &&
  2190. ($other || %{$other->[1]}))) {
  2191. foreach my $influence (keys %{$other->[1]}) {
  2192. $this->[1]{$influence} |= $other->[1]{$influence};
  2193. }
  2194. }
  2195. else {
  2196. # influence blocker
  2197. $this->[1]={};
  2198. }
  2199. }
  2200. sub remove_influence {
  2201. my $this=shift;
  2202. my $torm=shift;
  2203. delete $this->[1]{$torm};
  2204. }
  2205. package IkiWiki::ErrorReason;
  2206. our @ISA = 'IkiWiki::FailReason';
  2207. package IkiWiki::PageSpec;
  2208. sub derel ($$) {
  2209. my $path=shift;
  2210. my $from=shift;
  2211. if ($path =~ m!^\.(/|$)!) {
  2212. if ($1) {
  2213. $from=~s#/?[^/]+$## if defined $from;
  2214. $path=~s#^\./##;
  2215. $path="$from/$path" if defined $from && length $from;
  2216. }
  2217. else {
  2218. $path = $from;
  2219. $path = "" unless defined $path;
  2220. }
  2221. }
  2222. return $path;
  2223. }
  2224. my %glob_cache;
  2225. sub match_glob ($$;@) {
  2226. my $page=shift;
  2227. my $glob=shift;
  2228. my %params=@_;
  2229. $glob=derel($glob, $params{location});
  2230. # Instead of converting the glob to a regex every time,
  2231. # cache the compiled regex to save time.
  2232. my $re=$glob_cache{$glob};
  2233. unless (defined $re) {
  2234. $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
  2235. }
  2236. if ($page =~ $re) {
  2237. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2238. return IkiWiki::SuccessReason->new("$glob matches $page");
  2239. }
  2240. else {
  2241. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2242. }
  2243. }
  2244. else {
  2245. return IkiWiki::FailReason->new("$glob does not match $page");
  2246. }
  2247. }
  2248. sub match_internal ($$;@) {
  2249. return match_glob(shift, shift, @_, internal => 1)
  2250. }
  2251. sub match_page ($$;@) {
  2252. my $page=shift;
  2253. my $match=match_glob($page, shift, @_);
  2254. if ($match) {
  2255. my $source=exists $IkiWiki::pagesources{$page} ?
  2256. $IkiWiki::pagesources{$page} :
  2257. $IkiWiki::delpagesources{$page};
  2258. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  2259. if (! defined $type) {
  2260. return IkiWiki::FailReason->new("$page is not a page");
  2261. }
  2262. }
  2263. return $match;
  2264. }
  2265. sub match_link ($$;@) {
  2266. my $page=shift;
  2267. my $link=lc(shift);
  2268. my %params=@_;
  2269. $link=derel($link, $params{location});
  2270. my $from=exists $params{location} ? $params{location} : '';
  2271. my $linktype=$params{linktype};
  2272. my $qualifier='';
  2273. if (defined $linktype) {
  2274. $qualifier=" with type $linktype";
  2275. }
  2276. my $links = $IkiWiki::links{$page};
  2277. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2278. unless $links && @{$links};
  2279. my $bestlink = IkiWiki::bestlink($from, $link);
  2280. foreach my $p (@{$links}) {
  2281. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2282. if (length $bestlink) {
  2283. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2284. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2285. }
  2286. }
  2287. else {
  2288. if (match_glob($p, $link, %params)) {
  2289. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2290. }
  2291. my ($p_rel)=$p=~/^\/?(.*)/;
  2292. $link=~s/^\///;
  2293. if (match_glob($p_rel, $link, %params)) {
  2294. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2295. }
  2296. }
  2297. }
  2298. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2299. }
  2300. sub match_backlink ($$;@) {
  2301. my $ret=match_link($_[1], $_[0], @_);
  2302. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2303. return $ret;
  2304. }
  2305. sub match_created_before ($$;@) {
  2306. my $page=shift;
  2307. my $testpage=shift;
  2308. my %params=@_;
  2309. $testpage=derel($testpage, $params{location});
  2310. if (exists $IkiWiki::pagectime{$testpage}) {
  2311. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2312. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2313. }
  2314. else {
  2315. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2316. }
  2317. }
  2318. else {
  2319. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2320. }
  2321. }
  2322. sub match_created_after ($$;@) {
  2323. my $page=shift;
  2324. my $testpage=shift;
  2325. my %params=@_;
  2326. $testpage=derel($testpage, $params{location});
  2327. if (exists $IkiWiki::pagectime{$testpage}) {
  2328. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2329. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2330. }
  2331. else {
  2332. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2333. }
  2334. }
  2335. else {
  2336. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2337. }
  2338. }
  2339. sub match_creation_day ($$;@) {
  2340. my $page=shift;
  2341. my $d=shift;
  2342. if ($d !~ /^\d+$/) {
  2343. return IkiWiki::ErrorReason->new("invalid day $d");
  2344. }
  2345. if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
  2346. return IkiWiki::SuccessReason->new('creation_day matched');
  2347. }
  2348. else {
  2349. return IkiWiki::FailReason->new('creation_day did not match');
  2350. }
  2351. }
  2352. sub match_creation_month ($$;@) {
  2353. my $page=shift;
  2354. my $m=shift;
  2355. if ($m !~ /^\d+$/) {
  2356. return IkiWiki::ErrorReason->new("invalid month $m");
  2357. }
  2358. if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
  2359. return IkiWiki::SuccessReason->new('creation_month matched');
  2360. }
  2361. else {
  2362. return IkiWiki::FailReason->new('creation_month did not match');
  2363. }
  2364. }
  2365. sub match_creation_year ($$;@) {
  2366. my $page=shift;
  2367. my $y=shift;
  2368. if ($y !~ /^\d+$/) {
  2369. return IkiWiki::ErrorReason->new("invalid year $y");
  2370. }
  2371. if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
  2372. return IkiWiki::SuccessReason->new('creation_year matched');
  2373. }
  2374. else {
  2375. return IkiWiki::FailReason->new('creation_year did not match');
  2376. }
  2377. }
  2378. sub match_user ($$;@) {
  2379. shift;
  2380. my $user=shift;
  2381. my %params=@_;
  2382. my $regexp=IkiWiki::glob2re($user);
  2383. if (! exists $params{user}) {
  2384. return IkiWiki::ErrorReason->new("no user specified");
  2385. }
  2386. if (defined $params{user} && $params{user}=~$regexp) {
  2387. return IkiWiki::SuccessReason->new("user is $user");
  2388. }
  2389. elsif (! defined $params{user}) {
  2390. return IkiWiki::FailReason->new("not logged in");
  2391. }
  2392. else {
  2393. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2394. }
  2395. }
  2396. sub match_admin ($$;@) {
  2397. shift;
  2398. shift;
  2399. my %params=@_;
  2400. if (! exists $params{user}) {
  2401. return IkiWiki::ErrorReason->new("no user specified");
  2402. }
  2403. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2404. return IkiWiki::SuccessReason->new("user is an admin");
  2405. }
  2406. elsif (! defined $params{user}) {
  2407. return IkiWiki::FailReason->new("not logged in");
  2408. }
  2409. else {
  2410. return IkiWiki::FailReason->new("user is not an admin");
  2411. }
  2412. }
  2413. sub match_ip ($$;@) {
  2414. shift;
  2415. my $ip=shift;
  2416. my %params=@_;
  2417. if (! exists $params{ip}) {
  2418. return IkiWiki::ErrorReason->new("no IP specified");
  2419. }
  2420. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2421. return IkiWiki::SuccessReason->new("IP is $ip");
  2422. }
  2423. else {
  2424. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2425. }
  2426. }
  2427. package IkiWiki::SortSpec;
  2428. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2429. # are easily available in this namespace, for cmp functions to use them.
  2430. sub sort_pages {
  2431. my $f=shift;
  2432. sort $f @_
  2433. }
  2434. sub cmp_title {
  2435. IkiWiki::pagetitle(IkiWiki::basename($a))
  2436. cmp
  2437. IkiWiki::pagetitle(IkiWiki::basename($b))
  2438. }
  2439. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2440. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2441. 1