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