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