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