summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 7b5fd283d6e09782c80f86361dd72e7b7b3fed72 (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 isselflink ($$) {
  967. my $page=shift;
  968. my $link=shift;
  969. return $page eq $link;
  970. }
  971. sub htmllink ($$$;@) {
  972. my $lpage=shift; # the page doing the linking
  973. my $page=shift; # the page that will contain the link (different for inline)
  974. my $link=shift;
  975. my %opts=@_;
  976. $link=~s/\/$//;
  977. my $bestlink;
  978. if (! $opts{forcesubpage}) {
  979. $bestlink=bestlink($lpage, $link);
  980. }
  981. else {
  982. $bestlink="$lpage/".lc($link);
  983. }
  984. my $linktext;
  985. if (defined $opts{linktext}) {
  986. $linktext=$opts{linktext};
  987. }
  988. else {
  989. $linktext=pagetitle(basename($link));
  990. }
  991. return "<span class=\"selflink\">$linktext</span>"
  992. if length $bestlink && isselflink($page, $bestlink) &&
  993. ! defined $opts{anchor};
  994. if (! $destsources{$bestlink}) {
  995. $bestlink=htmlpage($bestlink);
  996. if (! $destsources{$bestlink}) {
  997. my $cgilink = "";
  998. if (length $config{cgiurl}) {
  999. $cgilink = "<a href=\"".
  1000. cgiurl(
  1001. do => "create",
  1002. page => lc($link),
  1003. from => $lpage
  1004. )."\" rel=\"nofollow\">?</a>";
  1005. }
  1006. return "<span class=\"createlink\">$cgilink$linktext</span>"
  1007. }
  1008. }
  1009. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  1010. $bestlink=beautify_urlpath($bestlink);
  1011. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  1012. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  1013. }
  1014. if (defined $opts{anchor}) {
  1015. $bestlink.="#".$opts{anchor};
  1016. }
  1017. my @attrs;
  1018. foreach my $attr (qw{rel class title}) {
  1019. if (defined $opts{$attr}) {
  1020. push @attrs, " $attr=\"$opts{$attr}\"";
  1021. }
  1022. }
  1023. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  1024. }
  1025. sub userpage ($) {
  1026. my $user=shift;
  1027. return length $config{userdir} ? "$config{userdir}/$user" : $user;
  1028. }
  1029. sub openiduser ($) {
  1030. my $user=shift;
  1031. if ($user =~ m!^https?://! &&
  1032. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  1033. my $display;
  1034. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  1035. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  1036. }
  1037. else {
  1038. # backcompat with old version
  1039. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  1040. $display=$oid->display;
  1041. }
  1042. # Convert "user.somehost.com" to "user [somehost.com]"
  1043. # (also "user.somehost.co.uk")
  1044. if ($display !~ /\[/) {
  1045. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  1046. }
  1047. # Convert "http://somehost.com/user" to "user [somehost.com]".
  1048. # (also "https://somehost.com/user/")
  1049. if ($display !~ /\[/) {
  1050. $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
  1051. }
  1052. $display=~s!^https?://!!; # make sure this is removed
  1053. eval q{use CGI 'escapeHTML'};
  1054. error($@) if $@;
  1055. return escapeHTML($display);
  1056. }
  1057. return;
  1058. }
  1059. sub htmlize ($$$$) {
  1060. my $page=shift;
  1061. my $destpage=shift;
  1062. my $type=shift;
  1063. my $content=shift;
  1064. my $oneline = $content !~ /\n/;
  1065. if (exists $hooks{htmlize}{$type}) {
  1066. $content=$hooks{htmlize}{$type}{call}->(
  1067. page => $page,
  1068. content => $content,
  1069. );
  1070. }
  1071. else {
  1072. error("htmlization of $type not supported");
  1073. }
  1074. run_hooks(sanitize => sub {
  1075. $content=shift->(
  1076. page => $page,
  1077. destpage => $destpage,
  1078. content => $content,
  1079. );
  1080. });
  1081. if ($oneline) {
  1082. # hack to get rid of enclosing junk added by markdown
  1083. # and other htmlizers/sanitizers
  1084. $content=~s/^<p>//i;
  1085. $content=~s/<\/p>\n*$//i;
  1086. }
  1087. return $content;
  1088. }
  1089. sub linkify ($$$) {
  1090. my $page=shift;
  1091. my $destpage=shift;
  1092. my $content=shift;
  1093. run_hooks(linkify => sub {
  1094. $content=shift->(
  1095. page => $page,
  1096. destpage => $destpage,
  1097. content => $content,
  1098. );
  1099. });
  1100. return $content;
  1101. }
  1102. our %preprocessing;
  1103. our $preprocess_preview=0;
  1104. sub preprocess ($$$;$$) {
  1105. my $page=shift; # the page the data comes from
  1106. my $destpage=shift; # the page the data will appear in (different for inline)
  1107. my $content=shift;
  1108. my $scan=shift;
  1109. my $preview=shift;
  1110. # Using local because it needs to be set within any nested calls
  1111. # of this function.
  1112. local $preprocess_preview=$preview if defined $preview;
  1113. my $handle=sub {
  1114. my $escape=shift;
  1115. my $prefix=shift;
  1116. my $command=shift;
  1117. my $params=shift;
  1118. $params="" if ! defined $params;
  1119. if (length $escape) {
  1120. return "[[$prefix$command $params]]";
  1121. }
  1122. elsif (exists $hooks{preprocess}{$command}) {
  1123. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1124. # Note: preserve order of params, some plugins may
  1125. # consider it significant.
  1126. my @params;
  1127. while ($params =~ m{
  1128. (?:([-\w]+)=)? # 1: named parameter key?
  1129. (?:
  1130. """(.*?)""" # 2: triple-quoted value
  1131. |
  1132. "([^"]*?)" # 3: single-quoted value
  1133. |
  1134. (\S+) # 4: unquoted value
  1135. )
  1136. (?:\s+|$) # delimiter to next param
  1137. }sgx) {
  1138. my $key=$1;
  1139. my $val;
  1140. if (defined $2) {
  1141. $val=$2;
  1142. $val=~s/\r\n/\n/mg;
  1143. $val=~s/^\n+//g;
  1144. $val=~s/\n+$//g;
  1145. }
  1146. elsif (defined $3) {
  1147. $val=$3;
  1148. }
  1149. elsif (defined $4) {
  1150. $val=$4;
  1151. }
  1152. if (defined $key) {
  1153. push @params, $key, $val;
  1154. }
  1155. else {
  1156. push @params, $val, '';
  1157. }
  1158. }
  1159. if ($preprocessing{$page}++ > 3) {
  1160. # Avoid loops of preprocessed pages preprocessing
  1161. # other pages that preprocess them, etc.
  1162. return "[[!$command <span class=\"error\">".
  1163. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1164. $page, $preprocessing{$page}).
  1165. "</span>]]";
  1166. }
  1167. my $ret;
  1168. if (! $scan) {
  1169. $ret=eval {
  1170. $hooks{preprocess}{$command}{call}->(
  1171. @params,
  1172. page => $page,
  1173. destpage => $destpage,
  1174. preview => $preprocess_preview,
  1175. );
  1176. };
  1177. if ($@) {
  1178. my $error=$@;
  1179. chomp $error;
  1180. $ret="[[!$command <span class=\"error\">".
  1181. gettext("Error").": $error"."</span>]]";
  1182. }
  1183. }
  1184. else {
  1185. # use void context during scan pass
  1186. eval {
  1187. $hooks{preprocess}{$command}{call}->(
  1188. @params,
  1189. page => $page,
  1190. destpage => $destpage,
  1191. preview => $preprocess_preview,
  1192. );
  1193. };
  1194. $ret="";
  1195. }
  1196. $preprocessing{$page}--;
  1197. return $ret;
  1198. }
  1199. else {
  1200. return "[[$prefix$command $params]]";
  1201. }
  1202. };
  1203. my $regex;
  1204. if ($config{prefix_directives}) {
  1205. $regex = qr{
  1206. (\\?) # 1: escape?
  1207. \[\[(!) # directive open; 2: prefix
  1208. ([-\w]+) # 3: command
  1209. ( # 4: the parameters..
  1210. \s+ # Must have space if parameters present
  1211. (?:
  1212. (?:[-\w]+=)? # named parameter key?
  1213. (?:
  1214. """.*?""" # triple-quoted value
  1215. |
  1216. "[^"]*?" # single-quoted value
  1217. |
  1218. [^"\s\]]+ # unquoted value
  1219. )
  1220. \s* # whitespace or end
  1221. # of directive
  1222. )
  1223. *)? # 0 or more parameters
  1224. \]\] # directive closed
  1225. }sx;
  1226. }
  1227. else {
  1228. $regex = qr{
  1229. (\\?) # 1: escape?
  1230. \[\[(!?) # directive open; 2: optional prefix
  1231. ([-\w]+) # 3: command
  1232. \s+
  1233. ( # 4: the parameters..
  1234. (?:
  1235. (?:[-\w]+=)? # named parameter key?
  1236. (?:
  1237. """.*?""" # triple-quoted value
  1238. |
  1239. "[^"]*?" # single-quoted value
  1240. |
  1241. [^"\s\]]+ # unquoted value
  1242. )
  1243. \s* # whitespace or end
  1244. # of directive
  1245. )
  1246. *) # 0 or more parameters
  1247. \]\] # directive closed
  1248. }sx;
  1249. }
  1250. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1251. return $content;
  1252. }
  1253. sub filter ($$$;$) {
  1254. my $page=shift;
  1255. my $destpage=shift;
  1256. my $content=shift;
  1257. my $fullpage=shift;
  1258. $fullpage = 0 unless defined $fullpage;
  1259. run_hooks(filter => sub {
  1260. $content=shift->(page => $page, destpage => $destpage,
  1261. content => $content, fullpage => $fullpage);
  1262. });
  1263. return $content;
  1264. }
  1265. sub check_canedit ($$$;$) {
  1266. my $page=shift;
  1267. my $q=shift;
  1268. my $session=shift;
  1269. my $nonfatal=shift;
  1270. my $canedit;
  1271. run_hooks(canedit => sub {
  1272. return if defined $canedit;
  1273. my $ret=shift->($page, $q, $session);
  1274. if (defined $ret) {
  1275. if ($ret eq "") {
  1276. $canedit=1;
  1277. }
  1278. elsif (ref $ret eq 'CODE') {
  1279. $ret->() unless $nonfatal;
  1280. $canedit=0;
  1281. }
  1282. elsif (defined $ret) {
  1283. error($ret) unless $nonfatal;
  1284. $canedit=0;
  1285. }
  1286. }
  1287. });
  1288. return defined $canedit ? $canedit : 1;
  1289. }
  1290. sub check_content (@) {
  1291. my %params=@_;
  1292. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1293. if (exists $pagesources{$params{page}}) {
  1294. my @diff;
  1295. my %old=map { $_ => 1 }
  1296. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1297. foreach my $line (split("\n", $params{content})) {
  1298. push @diff, $line if ! exists $old{$line};
  1299. }
  1300. $params{diff}=join("\n", @diff);
  1301. }
  1302. my $ok;
  1303. run_hooks(checkcontent => sub {
  1304. return if defined $ok;
  1305. my $ret=shift->(%params);
  1306. if (defined $ret) {
  1307. if ($ret eq "") {
  1308. $ok=1;
  1309. }
  1310. elsif (ref $ret eq 'CODE') {
  1311. $ret->() unless $params{nonfatal};
  1312. $ok=0;
  1313. }
  1314. elsif (defined $ret) {
  1315. error($ret) unless $params{nonfatal};
  1316. $ok=0;
  1317. }
  1318. }
  1319. });
  1320. return defined $ok ? $ok : 1;
  1321. }
  1322. my $wikilock;
  1323. sub lockwiki () {
  1324. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1325. # run issues. The lock will be dropped on program exit.
  1326. if (! -d $config{wikistatedir}) {
  1327. mkdir($config{wikistatedir});
  1328. }
  1329. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1330. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1331. if (! flock($wikilock, 2)) { # LOCK_EX
  1332. error("failed to get lock");
  1333. }
  1334. return 1;
  1335. }
  1336. sub unlockwiki () {
  1337. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1338. return close($wikilock) if $wikilock;
  1339. return;
  1340. }
  1341. my $commitlock;
  1342. sub commit_hook_enabled () {
  1343. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1344. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1345. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1346. close($commitlock) || error("failed closing commitlock: $!");
  1347. return 0;
  1348. }
  1349. close($commitlock) || error("failed closing commitlock: $!");
  1350. return 1;
  1351. }
  1352. sub disable_commit_hook () {
  1353. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1354. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1355. if (! flock($commitlock, 2)) { # LOCK_EX
  1356. error("failed to get commit lock");
  1357. }
  1358. return 1;
  1359. }
  1360. sub enable_commit_hook () {
  1361. return close($commitlock) if $commitlock;
  1362. return;
  1363. }
  1364. sub loadindex () {
  1365. %oldrenderedfiles=%pagectime=();
  1366. if (! $config{rebuild}) {
  1367. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1368. %destsources=%renderedfiles=%pagecase=%pagestate=
  1369. %depends_simple=%typedlinks=%oldtypedlinks=();
  1370. }
  1371. my $in;
  1372. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1373. if (-e "$config{wikistatedir}/index") {
  1374. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1375. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1376. }
  1377. else {
  1378. $config{gettime}=1; # first build
  1379. return;
  1380. }
  1381. }
  1382. my $index=Storable::fd_retrieve($in);
  1383. if (! defined $index) {
  1384. return 0;
  1385. }
  1386. my $pages;
  1387. if (exists $index->{version} && ! ref $index->{version}) {
  1388. $pages=$index->{page};
  1389. %wikistate=%{$index->{state}};
  1390. }
  1391. else {
  1392. $pages=$index;
  1393. %wikistate=();
  1394. }
  1395. foreach my $src (keys %$pages) {
  1396. my $d=$pages->{$src};
  1397. my $page=pagename($src);
  1398. $pagectime{$page}=$d->{ctime};
  1399. $pagesources{$page}=$src;
  1400. if (! $config{rebuild}) {
  1401. $pagemtime{$page}=$d->{mtime};
  1402. $renderedfiles{$page}=$d->{dest};
  1403. if (exists $d->{links} && ref $d->{links}) {
  1404. $links{$page}=$d->{links};
  1405. $oldlinks{$page}=[@{$d->{links}}];
  1406. }
  1407. if (ref $d->{depends_simple} eq 'ARRAY') {
  1408. # old format
  1409. $depends_simple{$page}={
  1410. map { $_ => 1 } @{$d->{depends_simple}}
  1411. };
  1412. }
  1413. elsif (exists $d->{depends_simple}) {
  1414. $depends_simple{$page}=$d->{depends_simple};
  1415. }
  1416. if (exists $d->{dependslist}) {
  1417. # old format
  1418. $depends{$page}={
  1419. map { $_ => $DEPEND_CONTENT }
  1420. @{$d->{dependslist}}
  1421. };
  1422. }
  1423. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1424. # old format
  1425. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1426. }
  1427. elsif (exists $d->{depends}) {
  1428. $depends{$page}=$d->{depends};
  1429. }
  1430. if (exists $d->{state}) {
  1431. $pagestate{$page}=$d->{state};
  1432. }
  1433. if (exists $d->{typedlinks}) {
  1434. $typedlinks{$page}=$d->{typedlinks};
  1435. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1436. next unless %$links;
  1437. $oldtypedlinks{$page}{$type} = {%$links};
  1438. }
  1439. }
  1440. }
  1441. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1442. }
  1443. foreach my $page (keys %pagesources) {
  1444. $pagecase{lc $page}=$page;
  1445. }
  1446. foreach my $page (keys %renderedfiles) {
  1447. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1448. }
  1449. return close($in);
  1450. }
  1451. sub saveindex () {
  1452. run_hooks(savestate => sub { shift->() });
  1453. my %hookids;
  1454. foreach my $type (keys %hooks) {
  1455. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1456. }
  1457. my @hookids=keys %hookids;
  1458. if (! -d $config{wikistatedir}) {
  1459. mkdir($config{wikistatedir});
  1460. }
  1461. my $newfile="$config{wikistatedir}/indexdb.new";
  1462. my $cleanup = sub { unlink($newfile) };
  1463. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1464. my %index;
  1465. foreach my $page (keys %pagemtime) {
  1466. next unless $pagemtime{$page};
  1467. my $src=$pagesources{$page};
  1468. $index{page}{$src}={
  1469. ctime => $pagectime{$page},
  1470. mtime => $pagemtime{$page},
  1471. dest => $renderedfiles{$page},
  1472. links => $links{$page},
  1473. };
  1474. if (exists $depends{$page}) {
  1475. $index{page}{$src}{depends} = $depends{$page};
  1476. }
  1477. if (exists $depends_simple{$page}) {
  1478. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1479. }
  1480. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1481. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1482. }
  1483. if (exists $pagestate{$page}) {
  1484. foreach my $id (@hookids) {
  1485. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1486. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1487. }
  1488. }
  1489. }
  1490. }
  1491. $index{state}={};
  1492. foreach my $id (@hookids) {
  1493. foreach my $key (keys %{$wikistate{$id}}) {
  1494. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1495. }
  1496. }
  1497. $index{version}="3";
  1498. my $ret=Storable::nstore_fd(\%index, $out);
  1499. return if ! defined $ret || ! $ret;
  1500. close $out || error("failed saving to $newfile: $!", $cleanup);
  1501. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1502. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1503. return 1;
  1504. }
  1505. sub template_file ($) {
  1506. my $name=shift;
  1507. my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
  1508. if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
  1509. $tpage=$pagesources{$tpage};
  1510. $name.=".tmpl";
  1511. }
  1512. my $template=srcfile($tpage, 1);
  1513. if (defined $template) {
  1514. return $template, $tpage, 1 if wantarray;
  1515. return $template;
  1516. }
  1517. else {
  1518. $name=~s:/::; # avoid path traversal
  1519. foreach my $dir ($config{templatedir},
  1520. "$installdir/share/ikiwiki/templates") {
  1521. if (-e "$dir/$name") {
  1522. $template="$dir/$name";
  1523. last;
  1524. }
  1525. }
  1526. if (defined $template) {
  1527. return $template, $tpage if wantarray;
  1528. return $template;
  1529. }
  1530. }
  1531. return;
  1532. }
  1533. sub template_depends ($$;@) {
  1534. my $name=shift;
  1535. my $page=shift;
  1536. my ($filename, $tpage, $untrusted)=template_file($name);
  1537. if (defined $page && defined $tpage) {
  1538. add_depends($page, $tpage);
  1539. }
  1540. return unless defined $filename;
  1541. my @opts=(
  1542. filter => sub {
  1543. my $text_ref = shift;
  1544. ${$text_ref} = decode_utf8(${$text_ref});
  1545. },
  1546. loop_context_vars => 1,
  1547. die_on_bad_params => 0,
  1548. filename => $filename,
  1549. @_,
  1550. ($untrusted ? (no_includes => 1) : ()),
  1551. );
  1552. return @opts if wantarray;
  1553. require HTML::Template;
  1554. return HTML::Template->new(@opts);
  1555. }
  1556. sub template ($;@) {
  1557. template_depends(shift, undef, @_);
  1558. }
  1559. sub misctemplate ($$;@) {
  1560. my $title=shift;
  1561. my $content=shift;
  1562. my %params=@_;
  1563. my $template=template("page.tmpl");
  1564. my $page="";
  1565. if (exists $params{page}) {
  1566. $page=delete $params{page};
  1567. }
  1568. run_hooks(pagetemplate => sub {
  1569. shift->(
  1570. page => $page,
  1571. destpage => $page,
  1572. template => $template,
  1573. );
  1574. });
  1575. templateactions($template, "");
  1576. $template->param(
  1577. dynamic => 1,
  1578. title => $title,
  1579. wikiname => $config{wikiname},
  1580. content => $content,
  1581. baseurl => baseurl(),
  1582. html5 => $config{html5},
  1583. %params,
  1584. );
  1585. return $template->output;
  1586. }
  1587. sub templateactions ($$) {
  1588. my $template=shift;
  1589. my $page=shift;
  1590. my $have_actions=0;
  1591. my @actions;
  1592. run_hooks(pageactions => sub {
  1593. push @actions, map { { action => $_ } }
  1594. grep { defined } shift->(page => $page);
  1595. });
  1596. $template->param(actions => \@actions);
  1597. if ($config{cgiurl} && exists $hooks{auth}) {
  1598. $template->param(prefsurl => cgiurl(do => "prefs"));
  1599. $have_actions=1;
  1600. }
  1601. if ($have_actions || @actions) {
  1602. $template->param(have_actions => 1);
  1603. }
  1604. }
  1605. sub hook (@) {
  1606. my %param=@_;
  1607. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1608. error 'hook requires type, call, and id parameters';
  1609. }
  1610. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1611. $hooks{$param{type}}{$param{id}}=\%param;
  1612. return 1;
  1613. }
  1614. sub run_hooks ($$) {
  1615. # Calls the given sub for each hook of the given type,
  1616. # passing it the hook function to call.
  1617. my $type=shift;
  1618. my $sub=shift;
  1619. if (exists $hooks{$type}) {
  1620. my (@first, @middle, @last);
  1621. foreach my $id (keys %{$hooks{$type}}) {
  1622. if ($hooks{$type}{$id}{first}) {
  1623. push @first, $id;
  1624. }
  1625. elsif ($hooks{$type}{$id}{last}) {
  1626. push @last, $id;
  1627. }
  1628. else {
  1629. push @middle, $id;
  1630. }
  1631. }
  1632. foreach my $id (@first, @middle, @last) {
  1633. $sub->($hooks{$type}{$id}{call});
  1634. }
  1635. }
  1636. return 1;
  1637. }
  1638. sub rcs_update () {
  1639. $hooks{rcs}{rcs_update}{call}->(@_);
  1640. }
  1641. sub rcs_prepedit ($) {
  1642. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1643. }
  1644. sub rcs_commit (@) {
  1645. $hooks{rcs}{rcs_commit}{call}->(@_);
  1646. }
  1647. sub rcs_commit_staged (@) {
  1648. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1649. }
  1650. sub rcs_add ($) {
  1651. $hooks{rcs}{rcs_add}{call}->(@_);
  1652. }
  1653. sub rcs_remove ($) {
  1654. $hooks{rcs}{rcs_remove}{call}->(@_);
  1655. }
  1656. sub rcs_rename ($$) {
  1657. $hooks{rcs}{rcs_rename}{call}->(@_);
  1658. }
  1659. sub rcs_recentchanges ($) {
  1660. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1661. }
  1662. sub rcs_diff ($) {
  1663. $hooks{rcs}{rcs_diff}{call}->(@_);
  1664. }
  1665. sub rcs_getctime ($) {
  1666. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1667. }
  1668. sub rcs_getmtime ($) {
  1669. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1670. }
  1671. sub rcs_receive () {
  1672. $hooks{rcs}{rcs_receive}{call}->();
  1673. }
  1674. sub add_depends ($$;$) {
  1675. my $page=shift;
  1676. my $pagespec=shift;
  1677. my $deptype=shift || $DEPEND_CONTENT;
  1678. # Is the pagespec a simple page name?
  1679. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1680. $pagespec !~ /[\s*?()!]/) {
  1681. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1682. return 1;
  1683. }
  1684. # Add explicit dependencies for influences.
  1685. my $sub=pagespec_translate($pagespec);
  1686. return unless defined $sub;
  1687. foreach my $p (keys %pagesources) {
  1688. my $r=$sub->($p, location => $page);
  1689. my $i=$r->influences;
  1690. my $static=$r->influences_static;
  1691. foreach my $k (keys %$i) {
  1692. next unless $r || $static || $k eq $page;
  1693. $depends_simple{$page}{lc $k} |= $i->{$k};
  1694. }
  1695. last if $static;
  1696. }
  1697. $depends{$page}{$pagespec} |= $deptype;
  1698. return 1;
  1699. }
  1700. sub deptype (@) {
  1701. my $deptype=0;
  1702. foreach my $type (@_) {
  1703. if ($type eq 'presence') {
  1704. $deptype |= $DEPEND_PRESENCE;
  1705. }
  1706. elsif ($type eq 'links') {
  1707. $deptype |= $DEPEND_LINKS;
  1708. }
  1709. elsif ($type eq 'content') {
  1710. $deptype |= $DEPEND_CONTENT;
  1711. }
  1712. }
  1713. return $deptype;
  1714. }
  1715. my $file_prune_regexp;
  1716. sub file_pruned ($) {
  1717. my $file=shift;
  1718. if (defined $config{include} && length $config{include}) {
  1719. return 0 if $file =~ m/$config{include}/;
  1720. }
  1721. if (! defined $file_prune_regexp) {
  1722. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1723. $file_prune_regexp=qr/$file_prune_regexp/;
  1724. }
  1725. return $file =~ m/$file_prune_regexp/;
  1726. }
  1727. sub define_gettext () {
  1728. # If translation is needed, redefine the gettext function to do it.
  1729. # Otherwise, it becomes a quick no-op.
  1730. my $gettext_obj;
  1731. my $getobj;
  1732. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1733. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1734. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1735. $getobj=sub {
  1736. $gettext_obj=eval q{
  1737. use Locale::gettext q{textdomain};
  1738. Locale::gettext->domain('ikiwiki')
  1739. };
  1740. };
  1741. }
  1742. no warnings 'redefine';
  1743. *gettext=sub {
  1744. $getobj->() if $getobj;
  1745. if ($gettext_obj) {
  1746. $gettext_obj->get(shift);
  1747. }
  1748. else {
  1749. return shift;
  1750. }
  1751. };
  1752. *ngettext=sub {
  1753. $getobj->() if $getobj;
  1754. if ($gettext_obj) {
  1755. $gettext_obj->nget(@_);
  1756. }
  1757. else {
  1758. return ($_[2] == 1 ? $_[0] : $_[1])
  1759. }
  1760. };
  1761. }
  1762. sub gettext {
  1763. define_gettext();
  1764. gettext(@_);
  1765. }
  1766. sub ngettext {
  1767. define_gettext();
  1768. ngettext(@_);
  1769. }
  1770. sub yesno ($) {
  1771. my $val=shift;
  1772. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1773. }
  1774. sub inject {
  1775. # Injects a new function into the symbol table to replace an
  1776. # exported function.
  1777. my %params=@_;
  1778. # This is deep ugly perl foo, beware.
  1779. no strict;
  1780. no warnings;
  1781. if (! defined $params{parent}) {
  1782. $params{parent}='::';
  1783. $params{old}=\&{$params{name}};
  1784. $params{name}=~s/.*:://;
  1785. }
  1786. my $parent=$params{parent};
  1787. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1788. $ns = $params{parent} . $ns;
  1789. inject(%params, parent => $ns) unless $ns eq '::main::';
  1790. *{$ns . $params{name}} = $params{call}
  1791. if exists ${$ns}{$params{name}} &&
  1792. \&{${$ns}{$params{name}}} == $params{old};
  1793. }
  1794. use strict;
  1795. use warnings;
  1796. }
  1797. sub add_link ($$;$) {
  1798. my $page=shift;
  1799. my $link=shift;
  1800. my $type=shift;
  1801. push @{$links{$page}}, $link
  1802. unless grep { $_ eq $link } @{$links{$page}};
  1803. if (defined $type) {
  1804. $typedlinks{$page}{$type}{$link} = 1;
  1805. }
  1806. }
  1807. sub add_autofile ($$$) {
  1808. my $file=shift;
  1809. my $plugin=shift;
  1810. my $generator=shift;
  1811. $autofiles{$file}{plugin}=$plugin;
  1812. $autofiles{$file}{generator}=$generator;
  1813. }
  1814. sub sortspec_translate ($$) {
  1815. my $spec = shift;
  1816. my $reverse = shift;
  1817. my $code = "";
  1818. my @data;
  1819. while ($spec =~ m{
  1820. \s*
  1821. (-?) # group 1: perhaps negated
  1822. \s*
  1823. ( # group 2: a word
  1824. \w+\([^\)]*\) # command(params)
  1825. |
  1826. [^\s]+ # or anything else
  1827. )
  1828. \s*
  1829. }gx) {
  1830. my $negated = $1;
  1831. my $word = $2;
  1832. my $params = undef;
  1833. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1834. # command with parameters
  1835. $params = $2;
  1836. $word = $1;
  1837. }
  1838. elsif ($word !~ m/^\w+$/) {
  1839. error(sprintf(gettext("invalid sort type %s"), $word));
  1840. }
  1841. if (length $code) {
  1842. $code .= " || ";
  1843. }
  1844. if ($negated) {
  1845. $code .= "-";
  1846. }
  1847. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1848. if (defined $params) {
  1849. push @data, $params;
  1850. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1851. }
  1852. else {
  1853. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1854. }
  1855. }
  1856. else {
  1857. error(sprintf(gettext("unknown sort type %s"), $word));
  1858. }
  1859. }
  1860. if (! length $code) {
  1861. # undefined sorting method... sort arbitrarily
  1862. return sub { 0 };
  1863. }
  1864. if ($reverse) {
  1865. $code="-($code)";
  1866. }
  1867. no warnings;
  1868. return eval 'sub { '.$code.' }';
  1869. }
  1870. sub pagespec_translate ($) {
  1871. my $spec=shift;
  1872. # Convert spec to perl code.
  1873. my $code="";
  1874. my @data;
  1875. while ($spec=~m{
  1876. \s* # ignore whitespace
  1877. ( # 1: match a single word
  1878. \! # !
  1879. |
  1880. \( # (
  1881. |
  1882. \) # )
  1883. |
  1884. \w+\([^\)]*\) # command(params)
  1885. |
  1886. [^\s()]+ # any other text
  1887. )
  1888. \s* # ignore whitespace
  1889. }gx) {
  1890. my $word=$1;
  1891. if (lc $word eq 'and') {
  1892. $code.=' &';
  1893. }
  1894. elsif (lc $word eq 'or') {
  1895. $code.=' |';
  1896. }
  1897. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1898. $code.=' '.$word;
  1899. }
  1900. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1901. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1902. push @data, $2;
  1903. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1904. }
  1905. else {
  1906. push @data, qq{unknown function in pagespec "$word"};
  1907. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1908. }
  1909. }
  1910. else {
  1911. push @data, $word;
  1912. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1913. }
  1914. }
  1915. if (! length $code) {
  1916. $code="IkiWiki::FailReason->new('empty pagespec')";
  1917. }
  1918. no warnings;
  1919. return eval 'sub { my $page=shift; '.$code.' }';
  1920. }
  1921. sub pagespec_match ($$;@) {
  1922. my $page=shift;
  1923. my $spec=shift;
  1924. my @params=@_;
  1925. # Backwards compatability with old calling convention.
  1926. if (@params == 1) {
  1927. unshift @params, 'location';
  1928. }
  1929. my $sub=pagespec_translate($spec);
  1930. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1931. if ! defined $sub;
  1932. return $sub->($page, @params);
  1933. }
  1934. sub pagespec_match_list ($$;@) {
  1935. my $page=shift;
  1936. my $pagespec=shift;
  1937. my %params=@_;
  1938. # Backwards compatability with old calling convention.
  1939. if (ref $page) {
  1940. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1941. $params{list}=$page;
  1942. $page=$params{location}; # ugh!
  1943. }
  1944. my $sub=pagespec_translate($pagespec);
  1945. error "syntax error in pagespec \"$pagespec\""
  1946. if ! defined $sub;
  1947. my $sort=sortspec_translate($params{sort}, $params{reverse})
  1948. if defined $params{sort};
  1949. my @candidates;
  1950. if (exists $params{list}) {
  1951. @candidates=exists $params{filter}
  1952. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1953. : @{$params{list}};
  1954. }
  1955. else {
  1956. @candidates=exists $params{filter}
  1957. ? grep { ! $params{filter}->($_) } keys %pagesources
  1958. : keys %pagesources;
  1959. }
  1960. # clear params, remainder is passed to pagespec
  1961. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1962. my $num=$params{num};
  1963. delete @params{qw{num deptype reverse sort filter list}};
  1964. # when only the top matches will be returned, it's efficient to
  1965. # sort before matching to pagespec,
  1966. if (defined $num && defined $sort) {
  1967. @candidates=IkiWiki::SortSpec::sort_pages(
  1968. $sort, @candidates);
  1969. }
  1970. my @matches;
  1971. my $firstfail;
  1972. my $count=0;
  1973. my $accum=IkiWiki::SuccessReason->new();
  1974. foreach my $p (@candidates) {
  1975. my $r=$sub->($p, %params, location => $page);
  1976. error(sprintf(gettext("cannot match pages: %s"), $r))
  1977. if $r->isa("IkiWiki::ErrorReason");
  1978. unless ($r || $r->influences_static) {
  1979. $r->remove_influence($p);
  1980. }
  1981. $accum |= $r;
  1982. if ($r) {
  1983. push @matches, $p;
  1984. last if defined $num && ++$count == $num;
  1985. }
  1986. }
  1987. # Add simple dependencies for accumulated influences.
  1988. my $i=$accum->influences;
  1989. foreach my $k (keys %$i) {
  1990. $depends_simple{$page}{lc $k} |= $i->{$k};
  1991. }
  1992. # when all matches will be returned, it's efficient to
  1993. # sort after matching
  1994. if (! defined $num && defined $sort) {
  1995. return IkiWiki::SortSpec::sort_pages(
  1996. $sort, @matches);
  1997. }
  1998. else {
  1999. return @matches;
  2000. }
  2001. }
  2002. sub pagespec_valid ($) {
  2003. my $spec=shift;
  2004. return defined pagespec_translate($spec);
  2005. }
  2006. sub glob2re ($) {
  2007. my $re=quotemeta(shift);
  2008. $re=~s/\\\*/.*/g;
  2009. $re=~s/\\\?/./g;
  2010. return $re;
  2011. }
  2012. package IkiWiki::FailReason;
  2013. use overload (
  2014. '""' => sub { $_[0][0] },
  2015. '0+' => sub { 0 },
  2016. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2017. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2018. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2019. fallback => 1,
  2020. );
  2021. our @ISA = 'IkiWiki::SuccessReason';
  2022. package IkiWiki::SuccessReason;
  2023. use overload (
  2024. '""' => sub { $_[0][0] },
  2025. '0+' => sub { 1 },
  2026. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2027. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2028. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2029. fallback => 1,
  2030. );
  2031. sub new {
  2032. my $class = shift;
  2033. my $value = shift;
  2034. return bless [$value, {@_}], $class;
  2035. }
  2036. sub influences {
  2037. my $this=shift;
  2038. $this->[1]={@_} if @_;
  2039. my %i=%{$this->[1]};
  2040. delete $i{""};
  2041. return \%i;
  2042. }
  2043. sub influences_static {
  2044. return ! $_[0][1]->{""};
  2045. }
  2046. sub merge_influences {
  2047. my $this=shift;
  2048. my $other=shift;
  2049. my $anded=shift;
  2050. if (! $anded || (($this || %{$this->[1]}) &&
  2051. ($other || %{$other->[1]}))) {
  2052. foreach my $influence (keys %{$other->[1]}) {
  2053. $this->[1]{$influence} |= $other->[1]{$influence};
  2054. }
  2055. }
  2056. else {
  2057. # influence blocker
  2058. $this->[1]={};
  2059. }
  2060. }
  2061. sub remove_influence {
  2062. my $this=shift;
  2063. my $torm=shift;
  2064. delete $this->[1]{$torm};
  2065. }
  2066. package IkiWiki::ErrorReason;
  2067. our @ISA = 'IkiWiki::FailReason';
  2068. package IkiWiki::PageSpec;
  2069. sub derel ($$) {
  2070. my $path=shift;
  2071. my $from=shift;
  2072. if ($path =~ m!^\./!) {
  2073. $from=~s#/?[^/]+$## if defined $from;
  2074. $path=~s#^\./##;
  2075. $path="$from/$path" if defined $from && length $from;
  2076. }
  2077. return $path;
  2078. }
  2079. sub match_glob ($$;@) {
  2080. my $page=shift;
  2081. my $glob=shift;
  2082. my %params=@_;
  2083. $glob=derel($glob, $params{location});
  2084. my $regexp=IkiWiki::glob2re($glob);
  2085. if ($page=~/^$regexp$/i) {
  2086. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2087. return IkiWiki::SuccessReason->new("$glob matches $page");
  2088. }
  2089. else {
  2090. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2091. }
  2092. }
  2093. else {
  2094. return IkiWiki::FailReason->new("$glob does not match $page");
  2095. }
  2096. }
  2097. sub match_internal ($$;@) {
  2098. return match_glob(shift, shift, @_, internal => 1)
  2099. }
  2100. sub match_page ($$;@) {
  2101. my $page=shift;
  2102. my $match=match_glob($page, shift, @_);
  2103. if ($match && ! (exists $IkiWiki::pagesources{$page}
  2104. && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
  2105. return IkiWiki::FailReason->new("$page is not a page");
  2106. }
  2107. else {
  2108. return $match;
  2109. }
  2110. }
  2111. sub match_link ($$;@) {
  2112. my $page=shift;
  2113. my $link=lc(shift);
  2114. my %params=@_;
  2115. $link=derel($link, $params{location});
  2116. my $from=exists $params{location} ? $params{location} : '';
  2117. my $linktype=$params{linktype};
  2118. my $qualifier='';
  2119. if (defined $linktype) {
  2120. $qualifier=" with type $linktype";
  2121. }
  2122. my $links = $IkiWiki::links{$page};
  2123. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2124. unless $links && @{$links};
  2125. my $bestlink = IkiWiki::bestlink($from, $link);
  2126. foreach my $p (@{$links}) {
  2127. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2128. if (length $bestlink) {
  2129. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2130. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2131. }
  2132. }
  2133. else {
  2134. if (match_glob($p, $link, %params)) {
  2135. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2136. }
  2137. my ($p_rel)=$p=~/^\/?(.*)/;
  2138. $link=~s/^\///;
  2139. if (match_glob($p_rel, $link, %params)) {
  2140. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2141. }
  2142. }
  2143. }
  2144. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2145. }
  2146. sub match_backlink ($$;@) {
  2147. my $ret=match_link($_[1], $_[0], @_);
  2148. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2149. return $ret;
  2150. }
  2151. sub match_created_before ($$;@) {
  2152. my $page=shift;
  2153. my $testpage=shift;
  2154. my %params=@_;
  2155. $testpage=derel($testpage, $params{location});
  2156. if (exists $IkiWiki::pagectime{$testpage}) {
  2157. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2158. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2159. }
  2160. else {
  2161. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2162. }
  2163. }
  2164. else {
  2165. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2166. }
  2167. }
  2168. sub match_created_after ($$;@) {
  2169. my $page=shift;
  2170. my $testpage=shift;
  2171. my %params=@_;
  2172. $testpage=derel($testpage, $params{location});
  2173. if (exists $IkiWiki::pagectime{$testpage}) {
  2174. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2175. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2176. }
  2177. else {
  2178. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2179. }
  2180. }
  2181. else {
  2182. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2183. }
  2184. }
  2185. sub match_creation_day ($$;@) {
  2186. if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2187. return IkiWiki::SuccessReason->new('creation_day matched');
  2188. }
  2189. else {
  2190. return IkiWiki::FailReason->new('creation_day did not match');
  2191. }
  2192. }
  2193. sub match_creation_month ($$;@) {
  2194. if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2195. return IkiWiki::SuccessReason->new('creation_month matched');
  2196. }
  2197. else {
  2198. return IkiWiki::FailReason->new('creation_month did not match');
  2199. }
  2200. }
  2201. sub match_creation_year ($$;@) {
  2202. if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2203. return IkiWiki::SuccessReason->new('creation_year matched');
  2204. }
  2205. else {
  2206. return IkiWiki::FailReason->new('creation_year did not match');
  2207. }
  2208. }
  2209. sub match_user ($$;@) {
  2210. shift;
  2211. my $user=shift;
  2212. my %params=@_;
  2213. my $regexp=IkiWiki::glob2re($user);
  2214. if (! exists $params{user}) {
  2215. return IkiWiki::ErrorReason->new("no user specified");
  2216. }
  2217. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2218. return IkiWiki::SuccessReason->new("user is $user");
  2219. }
  2220. elsif (! defined $params{user}) {
  2221. return IkiWiki::FailReason->new("not logged in");
  2222. }
  2223. else {
  2224. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2225. }
  2226. }
  2227. sub match_admin ($$;@) {
  2228. shift;
  2229. shift;
  2230. my %params=@_;
  2231. if (! exists $params{user}) {
  2232. return IkiWiki::ErrorReason->new("no user specified");
  2233. }
  2234. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2235. return IkiWiki::SuccessReason->new("user is an admin");
  2236. }
  2237. elsif (! defined $params{user}) {
  2238. return IkiWiki::FailReason->new("not logged in");
  2239. }
  2240. else {
  2241. return IkiWiki::FailReason->new("user is not an admin");
  2242. }
  2243. }
  2244. sub match_ip ($$;@) {
  2245. shift;
  2246. my $ip=shift;
  2247. my %params=@_;
  2248. if (! exists $params{ip}) {
  2249. return IkiWiki::ErrorReason->new("no IP specified");
  2250. }
  2251. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2252. return IkiWiki::SuccessReason->new("IP is $ip");
  2253. }
  2254. else {
  2255. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2256. }
  2257. }
  2258. package IkiWiki::SortSpec;
  2259. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2260. # are easily available in this namespace, for cmp functions to use them.
  2261. sub sort_pages {
  2262. my $f=shift;
  2263. sort $f @_
  2264. }
  2265. sub cmp_title {
  2266. IkiWiki::pagetitle(IkiWiki::basename($a))
  2267. cmp
  2268. IkiWiki::pagetitle(IkiWiki::basename($b))
  2269. }
  2270. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2271. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2272. 1