summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: df8abe2c2711281c220a604aa0ddca09ec915a02 (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 $page && defined $tpage) {
  1586. add_depends($page, $tpage);
  1587. }
  1588. return unless defined $filename;
  1589. my @opts=(
  1590. filter => sub {
  1591. my $text_ref = shift;
  1592. ${$text_ref} = decode_utf8(${$text_ref});
  1593. },
  1594. loop_context_vars => 1,
  1595. die_on_bad_params => 0,
  1596. filename => $filename,
  1597. @_,
  1598. ($untrusted ? (no_includes => 1) : ()),
  1599. );
  1600. return @opts if wantarray;
  1601. require HTML::Template;
  1602. return HTML::Template->new(@opts);
  1603. }
  1604. sub template ($;@) {
  1605. template_depends(shift, undef, @_);
  1606. }
  1607. sub misctemplate ($$;@) {
  1608. my $title=shift;
  1609. my $content=shift;
  1610. my %params=@_;
  1611. my $template=template("page.tmpl");
  1612. my $page="";
  1613. if (exists $params{page}) {
  1614. $page=delete $params{page};
  1615. }
  1616. run_hooks(pagetemplate => sub {
  1617. shift->(
  1618. page => $page,
  1619. destpage => $page,
  1620. template => $template,
  1621. );
  1622. });
  1623. templateactions($template, "");
  1624. $template->param(
  1625. dynamic => 1,
  1626. title => $title,
  1627. wikiname => $config{wikiname},
  1628. content => $content,
  1629. baseurl => baseurl(),
  1630. html5 => $config{html5},
  1631. %params,
  1632. );
  1633. return $template->output;
  1634. }
  1635. sub templateactions ($$) {
  1636. my $template=shift;
  1637. my $page=shift;
  1638. my $have_actions=0;
  1639. my @actions;
  1640. run_hooks(pageactions => sub {
  1641. push @actions, map { { action => $_ } }
  1642. grep { defined } shift->(page => $page);
  1643. });
  1644. $template->param(actions => \@actions);
  1645. if ($config{cgiurl} && exists $hooks{auth}) {
  1646. $template->param(prefsurl => cgiurl(do => "prefs"));
  1647. $have_actions=1;
  1648. }
  1649. if ($have_actions || @actions) {
  1650. $template->param(have_actions => 1);
  1651. }
  1652. }
  1653. sub hook (@) {
  1654. my %param=@_;
  1655. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1656. error 'hook requires type, call, and id parameters';
  1657. }
  1658. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1659. $hooks{$param{type}}{$param{id}}=\%param;
  1660. return 1;
  1661. }
  1662. sub run_hooks ($$) {
  1663. # Calls the given sub for each hook of the given type,
  1664. # passing it the hook function to call.
  1665. my $type=shift;
  1666. my $sub=shift;
  1667. if (exists $hooks{$type}) {
  1668. my (@first, @middle, @last);
  1669. foreach my $id (keys %{$hooks{$type}}) {
  1670. if ($hooks{$type}{$id}{first}) {
  1671. push @first, $id;
  1672. }
  1673. elsif ($hooks{$type}{$id}{last}) {
  1674. push @last, $id;
  1675. }
  1676. else {
  1677. push @middle, $id;
  1678. }
  1679. }
  1680. foreach my $id (@first, @middle, @last) {
  1681. $sub->($hooks{$type}{$id}{call});
  1682. }
  1683. }
  1684. return 1;
  1685. }
  1686. sub rcs_update () {
  1687. $hooks{rcs}{rcs_update}{call}->(@_);
  1688. }
  1689. sub rcs_prepedit ($) {
  1690. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1691. }
  1692. sub rcs_commit (@) {
  1693. $hooks{rcs}{rcs_commit}{call}->(@_);
  1694. }
  1695. sub rcs_commit_staged (@) {
  1696. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1697. }
  1698. sub rcs_add ($) {
  1699. $hooks{rcs}{rcs_add}{call}->(@_);
  1700. }
  1701. sub rcs_remove ($) {
  1702. $hooks{rcs}{rcs_remove}{call}->(@_);
  1703. }
  1704. sub rcs_rename ($$) {
  1705. $hooks{rcs}{rcs_rename}{call}->(@_);
  1706. }
  1707. sub rcs_recentchanges ($) {
  1708. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1709. }
  1710. sub rcs_diff ($) {
  1711. $hooks{rcs}{rcs_diff}{call}->(@_);
  1712. }
  1713. sub rcs_getctime ($) {
  1714. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1715. }
  1716. sub rcs_getmtime ($) {
  1717. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1718. }
  1719. sub rcs_receive () {
  1720. $hooks{rcs}{rcs_receive}{call}->();
  1721. }
  1722. sub add_depends ($$;$) {
  1723. my $page=shift;
  1724. my $pagespec=shift;
  1725. my $deptype=shift || $DEPEND_CONTENT;
  1726. # Is the pagespec a simple page name?
  1727. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1728. $pagespec !~ /[\s*?()!]/) {
  1729. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1730. return 1;
  1731. }
  1732. # Add explicit dependencies for influences.
  1733. my $sub=pagespec_translate($pagespec);
  1734. return unless defined $sub;
  1735. foreach my $p (keys %pagesources) {
  1736. my $r=$sub->($p, location => $page);
  1737. my $i=$r->influences;
  1738. my $static=$r->influences_static;
  1739. foreach my $k (keys %$i) {
  1740. next unless $r || $static || $k eq $page;
  1741. $depends_simple{$page}{lc $k} |= $i->{$k};
  1742. }
  1743. last if $static;
  1744. }
  1745. $depends{$page}{$pagespec} |= $deptype;
  1746. return 1;
  1747. }
  1748. sub deptype (@) {
  1749. my $deptype=0;
  1750. foreach my $type (@_) {
  1751. if ($type eq 'presence') {
  1752. $deptype |= $DEPEND_PRESENCE;
  1753. }
  1754. elsif ($type eq 'links') {
  1755. $deptype |= $DEPEND_LINKS;
  1756. }
  1757. elsif ($type eq 'content') {
  1758. $deptype |= $DEPEND_CONTENT;
  1759. }
  1760. }
  1761. return $deptype;
  1762. }
  1763. my $file_prune_regexp;
  1764. sub file_pruned ($) {
  1765. my $file=shift;
  1766. if (defined $config{include} && length $config{include}) {
  1767. return 0 if $file =~ m/$config{include}/;
  1768. }
  1769. if (! defined $file_prune_regexp) {
  1770. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1771. $file_prune_regexp=qr/$file_prune_regexp/;
  1772. }
  1773. return $file =~ m/$file_prune_regexp/;
  1774. }
  1775. sub define_gettext () {
  1776. # If translation is needed, redefine the gettext function to do it.
  1777. # Otherwise, it becomes a quick no-op.
  1778. my $gettext_obj;
  1779. my $getobj;
  1780. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1781. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1782. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1783. $getobj=sub {
  1784. $gettext_obj=eval q{
  1785. use Locale::gettext q{textdomain};
  1786. Locale::gettext->domain('ikiwiki')
  1787. };
  1788. };
  1789. }
  1790. no warnings 'redefine';
  1791. *gettext=sub {
  1792. $getobj->() if $getobj;
  1793. if ($gettext_obj) {
  1794. $gettext_obj->get(shift);
  1795. }
  1796. else {
  1797. return shift;
  1798. }
  1799. };
  1800. *ngettext=sub {
  1801. $getobj->() if $getobj;
  1802. if ($gettext_obj) {
  1803. $gettext_obj->nget(@_);
  1804. }
  1805. else {
  1806. return ($_[2] == 1 ? $_[0] : $_[1])
  1807. }
  1808. };
  1809. }
  1810. sub gettext {
  1811. define_gettext();
  1812. gettext(@_);
  1813. }
  1814. sub ngettext {
  1815. define_gettext();
  1816. ngettext(@_);
  1817. }
  1818. sub yesno ($) {
  1819. my $val=shift;
  1820. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1821. }
  1822. sub inject {
  1823. # Injects a new function into the symbol table to replace an
  1824. # exported function.
  1825. my %params=@_;
  1826. # This is deep ugly perl foo, beware.
  1827. no strict;
  1828. no warnings;
  1829. if (! defined $params{parent}) {
  1830. $params{parent}='::';
  1831. $params{old}=\&{$params{name}};
  1832. $params{name}=~s/.*:://;
  1833. }
  1834. my $parent=$params{parent};
  1835. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1836. $ns = $params{parent} . $ns;
  1837. inject(%params, parent => $ns) unless $ns eq '::main::';
  1838. *{$ns . $params{name}} = $params{call}
  1839. if exists ${$ns}{$params{name}} &&
  1840. \&{${$ns}{$params{name}}} == $params{old};
  1841. }
  1842. use strict;
  1843. use warnings;
  1844. }
  1845. sub add_link ($$;$) {
  1846. my $page=shift;
  1847. my $link=shift;
  1848. my $type=shift;
  1849. push @{$links{$page}}, $link
  1850. unless grep { $_ eq $link } @{$links{$page}};
  1851. if (defined $type) {
  1852. $typedlinks{$page}{$type}{$link} = 1;
  1853. }
  1854. }
  1855. sub add_autofile ($$$) {
  1856. my $file=shift;
  1857. my $plugin=shift;
  1858. my $generator=shift;
  1859. $autofiles{$file}{plugin}=$plugin;
  1860. $autofiles{$file}{generator}=$generator;
  1861. }
  1862. sub sortspec_translate ($$) {
  1863. my $spec = shift;
  1864. my $reverse = shift;
  1865. my $code = "";
  1866. my @data;
  1867. while ($spec =~ m{
  1868. \s*
  1869. (-?) # group 1: perhaps negated
  1870. \s*
  1871. ( # group 2: a word
  1872. \w+\([^\)]*\) # command(params)
  1873. |
  1874. [^\s]+ # or anything else
  1875. )
  1876. \s*
  1877. }gx) {
  1878. my $negated = $1;
  1879. my $word = $2;
  1880. my $params = undef;
  1881. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1882. # command with parameters
  1883. $params = $2;
  1884. $word = $1;
  1885. }
  1886. elsif ($word !~ m/^\w+$/) {
  1887. error(sprintf(gettext("invalid sort type %s"), $word));
  1888. }
  1889. if (length $code) {
  1890. $code .= " || ";
  1891. }
  1892. if ($negated) {
  1893. $code .= "-";
  1894. }
  1895. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1896. if (defined $params) {
  1897. push @data, $params;
  1898. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1899. }
  1900. else {
  1901. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1902. }
  1903. }
  1904. else {
  1905. error(sprintf(gettext("unknown sort type %s"), $word));
  1906. }
  1907. }
  1908. if (! length $code) {
  1909. # undefined sorting method... sort arbitrarily
  1910. return sub { 0 };
  1911. }
  1912. if ($reverse) {
  1913. $code="-($code)";
  1914. }
  1915. no warnings;
  1916. return eval 'sub { '.$code.' }';
  1917. }
  1918. sub pagespec_translate ($) {
  1919. my $spec=shift;
  1920. # Convert spec to perl code.
  1921. my $code="";
  1922. my @data;
  1923. while ($spec=~m{
  1924. \s* # ignore whitespace
  1925. ( # 1: match a single word
  1926. \! # !
  1927. |
  1928. \( # (
  1929. |
  1930. \) # )
  1931. |
  1932. \w+\([^\)]*\) # command(params)
  1933. |
  1934. [^\s()]+ # any other text
  1935. )
  1936. \s* # ignore whitespace
  1937. }gx) {
  1938. my $word=$1;
  1939. if (lc $word eq 'and') {
  1940. $code.=' &';
  1941. }
  1942. elsif (lc $word eq 'or') {
  1943. $code.=' |';
  1944. }
  1945. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1946. $code.=' '.$word;
  1947. }
  1948. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1949. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1950. push @data, $2;
  1951. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1952. }
  1953. else {
  1954. push @data, qq{unknown function in pagespec "$word"};
  1955. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1956. }
  1957. }
  1958. else {
  1959. push @data, $word;
  1960. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1961. }
  1962. }
  1963. if (! length $code) {
  1964. $code="IkiWiki::FailReason->new('empty pagespec')";
  1965. }
  1966. no warnings;
  1967. return eval 'sub { my $page=shift; '.$code.' }';
  1968. }
  1969. sub pagespec_match ($$;@) {
  1970. my $page=shift;
  1971. my $spec=shift;
  1972. my @params=@_;
  1973. # Backwards compatability with old calling convention.
  1974. if (@params == 1) {
  1975. unshift @params, 'location';
  1976. }
  1977. my $sub=pagespec_translate($spec);
  1978. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1979. if ! defined $sub;
  1980. return $sub->($page, @params);
  1981. }
  1982. sub pagespec_match_list ($$;@) {
  1983. my $page=shift;
  1984. my $pagespec=shift;
  1985. my %params=@_;
  1986. # Backwards compatability with old calling convention.
  1987. if (ref $page) {
  1988. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1989. $params{list}=$page;
  1990. $page=$params{location}; # ugh!
  1991. }
  1992. my $sub=pagespec_translate($pagespec);
  1993. error "syntax error in pagespec \"$pagespec\""
  1994. if ! defined $sub;
  1995. my $sort=sortspec_translate($params{sort}, $params{reverse})
  1996. if defined $params{sort};
  1997. my @candidates;
  1998. if (exists $params{list}) {
  1999. @candidates=exists $params{filter}
  2000. ? grep { ! $params{filter}->($_) } @{$params{list}}
  2001. : @{$params{list}};
  2002. }
  2003. else {
  2004. @candidates=exists $params{filter}
  2005. ? grep { ! $params{filter}->($_) } keys %pagesources
  2006. : keys %pagesources;
  2007. }
  2008. # clear params, remainder is passed to pagespec
  2009. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  2010. my $num=$params{num};
  2011. delete @params{qw{num deptype reverse sort filter list}};
  2012. # when only the top matches will be returned, it's efficient to
  2013. # sort before matching to pagespec,
  2014. if (defined $num && defined $sort) {
  2015. @candidates=IkiWiki::SortSpec::sort_pages(
  2016. $sort, @candidates);
  2017. }
  2018. my @matches;
  2019. my $firstfail;
  2020. my $count=0;
  2021. my $accum=IkiWiki::SuccessReason->new();
  2022. foreach my $p (@candidates) {
  2023. my $r=$sub->($p, %params, location => $page);
  2024. error(sprintf(gettext("cannot match pages: %s"), $r))
  2025. if $r->isa("IkiWiki::ErrorReason");
  2026. unless ($r || $r->influences_static) {
  2027. $r->remove_influence($p);
  2028. }
  2029. $accum |= $r;
  2030. if ($r) {
  2031. push @matches, $p;
  2032. last if defined $num && ++$count == $num;
  2033. }
  2034. }
  2035. # Add simple dependencies for accumulated influences.
  2036. my $i=$accum->influences;
  2037. foreach my $k (keys %$i) {
  2038. $depends_simple{$page}{lc $k} |= $i->{$k};
  2039. }
  2040. # when all matches will be returned, it's efficient to
  2041. # sort after matching
  2042. if (! defined $num && defined $sort) {
  2043. return IkiWiki::SortSpec::sort_pages(
  2044. $sort, @matches);
  2045. }
  2046. else {
  2047. return @matches;
  2048. }
  2049. }
  2050. sub pagespec_valid ($) {
  2051. my $spec=shift;
  2052. return defined pagespec_translate($spec);
  2053. }
  2054. sub glob2re ($) {
  2055. my $re=quotemeta(shift);
  2056. $re=~s/\\\*/.*/g;
  2057. $re=~s/\\\?/./g;
  2058. return $re;
  2059. }
  2060. package IkiWiki::FailReason;
  2061. use overload (
  2062. '""' => sub { $_[0][0] },
  2063. '0+' => sub { 0 },
  2064. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2065. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2066. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2067. fallback => 1,
  2068. );
  2069. our @ISA = 'IkiWiki::SuccessReason';
  2070. package IkiWiki::SuccessReason;
  2071. use overload (
  2072. '""' => sub { $_[0][0] },
  2073. '0+' => sub { 1 },
  2074. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2075. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2076. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2077. fallback => 1,
  2078. );
  2079. sub new {
  2080. my $class = shift;
  2081. my $value = shift;
  2082. return bless [$value, {@_}], $class;
  2083. }
  2084. sub influences {
  2085. my $this=shift;
  2086. $this->[1]={@_} if @_;
  2087. my %i=%{$this->[1]};
  2088. delete $i{""};
  2089. return \%i;
  2090. }
  2091. sub influences_static {
  2092. return ! $_[0][1]->{""};
  2093. }
  2094. sub merge_influences {
  2095. my $this=shift;
  2096. my $other=shift;
  2097. my $anded=shift;
  2098. if (! $anded || (($this || %{$this->[1]}) &&
  2099. ($other || %{$other->[1]}))) {
  2100. foreach my $influence (keys %{$other->[1]}) {
  2101. $this->[1]{$influence} |= $other->[1]{$influence};
  2102. }
  2103. }
  2104. else {
  2105. # influence blocker
  2106. $this->[1]={};
  2107. }
  2108. }
  2109. sub remove_influence {
  2110. my $this=shift;
  2111. my $torm=shift;
  2112. delete $this->[1]{$torm};
  2113. }
  2114. package IkiWiki::ErrorReason;
  2115. our @ISA = 'IkiWiki::FailReason';
  2116. package IkiWiki::PageSpec;
  2117. sub derel ($$) {
  2118. my $path=shift;
  2119. my $from=shift;
  2120. if ($path =~ m!^\./!) {
  2121. $from=~s#/?[^/]+$## if defined $from;
  2122. $path=~s#^\./##;
  2123. $path="$from/$path" if defined $from && length $from;
  2124. }
  2125. return $path;
  2126. }
  2127. sub match_glob ($$;@) {
  2128. my $page=shift;
  2129. my $glob=shift;
  2130. my %params=@_;
  2131. $glob=derel($glob, $params{location});
  2132. my $regexp=IkiWiki::glob2re($glob);
  2133. if ($page=~/^$regexp$/i) {
  2134. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2135. return IkiWiki::SuccessReason->new("$glob matches $page");
  2136. }
  2137. else {
  2138. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2139. }
  2140. }
  2141. else {
  2142. return IkiWiki::FailReason->new("$glob does not match $page");
  2143. }
  2144. }
  2145. sub match_internal ($$;@) {
  2146. return match_glob(shift, shift, @_, internal => 1)
  2147. }
  2148. sub match_page ($$;@) {
  2149. my $page=shift;
  2150. my $match=match_glob($page, shift, @_);
  2151. if ($match) {
  2152. my $source=exists $IkiWiki::pagesources{$page} ?
  2153. $IkiWiki::pagesources{$page} :
  2154. $IkiWiki::delpagesources{$page};
  2155. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  2156. if (! defined $type) {
  2157. return IkiWiki::FailReason->new("$page is not a page");
  2158. }
  2159. }
  2160. return $match;
  2161. }
  2162. sub match_link ($$;@) {
  2163. my $page=shift;
  2164. my $link=lc(shift);
  2165. my %params=@_;
  2166. $link=derel($link, $params{location});
  2167. my $from=exists $params{location} ? $params{location} : '';
  2168. my $linktype=$params{linktype};
  2169. my $qualifier='';
  2170. if (defined $linktype) {
  2171. $qualifier=" with type $linktype";
  2172. }
  2173. my $links = $IkiWiki::links{$page};
  2174. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2175. unless $links && @{$links};
  2176. my $bestlink = IkiWiki::bestlink($from, $link);
  2177. foreach my $p (@{$links}) {
  2178. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2179. if (length $bestlink) {
  2180. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2181. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2182. }
  2183. }
  2184. else {
  2185. if (match_glob($p, $link, %params)) {
  2186. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2187. }
  2188. my ($p_rel)=$p=~/^\/?(.*)/;
  2189. $link=~s/^\///;
  2190. if (match_glob($p_rel, $link, %params)) {
  2191. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2192. }
  2193. }
  2194. }
  2195. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2196. }
  2197. sub match_backlink ($$;@) {
  2198. my $ret=match_link($_[1], $_[0], @_);
  2199. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2200. return $ret;
  2201. }
  2202. sub match_created_before ($$;@) {
  2203. my $page=shift;
  2204. my $testpage=shift;
  2205. my %params=@_;
  2206. $testpage=derel($testpage, $params{location});
  2207. if (exists $IkiWiki::pagectime{$testpage}) {
  2208. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2209. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2210. }
  2211. else {
  2212. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2213. }
  2214. }
  2215. else {
  2216. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2217. }
  2218. }
  2219. sub match_created_after ($$;@) {
  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 after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2227. }
  2228. else {
  2229. return IkiWiki::FailReason->new("$page not created after $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_creation_day ($$;@) {
  2237. if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2238. return IkiWiki::SuccessReason->new('creation_day matched');
  2239. }
  2240. else {
  2241. return IkiWiki::FailReason->new('creation_day did not match');
  2242. }
  2243. }
  2244. sub match_creation_month ($$;@) {
  2245. if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2246. return IkiWiki::SuccessReason->new('creation_month matched');
  2247. }
  2248. else {
  2249. return IkiWiki::FailReason->new('creation_month did not match');
  2250. }
  2251. }
  2252. sub match_creation_year ($$;@) {
  2253. if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2254. return IkiWiki::SuccessReason->new('creation_year matched');
  2255. }
  2256. else {
  2257. return IkiWiki::FailReason->new('creation_year did not match');
  2258. }
  2259. }
  2260. sub match_user ($$;@) {
  2261. shift;
  2262. my $user=shift;
  2263. my %params=@_;
  2264. my $regexp=IkiWiki::glob2re($user);
  2265. if (! exists $params{user}) {
  2266. return IkiWiki::ErrorReason->new("no user specified");
  2267. }
  2268. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2269. return IkiWiki::SuccessReason->new("user is $user");
  2270. }
  2271. elsif (! defined $params{user}) {
  2272. return IkiWiki::FailReason->new("not logged in");
  2273. }
  2274. else {
  2275. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2276. }
  2277. }
  2278. sub match_admin ($$;@) {
  2279. shift;
  2280. shift;
  2281. my %params=@_;
  2282. if (! exists $params{user}) {
  2283. return IkiWiki::ErrorReason->new("no user specified");
  2284. }
  2285. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2286. return IkiWiki::SuccessReason->new("user is an admin");
  2287. }
  2288. elsif (! defined $params{user}) {
  2289. return IkiWiki::FailReason->new("not logged in");
  2290. }
  2291. else {
  2292. return IkiWiki::FailReason->new("user is not an admin");
  2293. }
  2294. }
  2295. sub match_ip ($$;@) {
  2296. shift;
  2297. my $ip=shift;
  2298. my %params=@_;
  2299. if (! exists $params{ip}) {
  2300. return IkiWiki::ErrorReason->new("no IP specified");
  2301. }
  2302. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2303. return IkiWiki::SuccessReason->new("IP is $ip");
  2304. }
  2305. else {
  2306. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2307. }
  2308. }
  2309. package IkiWiki::SortSpec;
  2310. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2311. # are easily available in this namespace, for cmp functions to use them.
  2312. sub sort_pages {
  2313. my $f=shift;
  2314. sort $f @_
  2315. }
  2316. sub cmp_title {
  2317. IkiWiki::pagetitle(IkiWiki::basename($a))
  2318. cmp
  2319. IkiWiki::pagetitle(IkiWiki::basename($b))
  2320. }
  2321. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2322. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2323. 1