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