summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 31e175d2ac7195ac7f49f80d50f49c0a67dba7e3 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use URI::Escape q{uri_escape_utf8};
  8. use POSIX;
  9. use open qw{:utf8 :std};
  10. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  11. %renderedfiles %oldrenderedfiles %pagesources %destsources
  12. %depends %hooks %forcerebuild $gettext_obj};
  13. use Exporter q{import};
  14. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  15. bestlink htmllink readfile writefile pagetype srcfile pagename
  16. displaytime will_render gettext urlto targetpage
  17. %config %links %renderedfiles %pagesources %destsources);
  18. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  19. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  20. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  21. # Optimisation.
  22. use Memoize;
  23. memoize("abs2rel");
  24. memoize("pagespec_translate");
  25. memoize("file_pruned");
  26. sub defaultconfig () { #{{{
  27. wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
  28. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  29. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  30. qr/\.dpkg-tmp$/],
  31. wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
  32. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  33. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  34. verbose => 0,
  35. syslog => 0,
  36. wikiname => "wiki",
  37. default_pageext => "mdwn",
  38. cgi => 0,
  39. post_commit => 0,
  40. rcs => '',
  41. notify => 0,
  42. url => '',
  43. cgiurl => '',
  44. historyurl => '',
  45. diffurl => '',
  46. rss => 0,
  47. atom => 0,
  48. discussion => 1,
  49. rebuild => 0,
  50. refresh => 0,
  51. getctime => 0,
  52. w3mmode => 0,
  53. wrapper => undef,
  54. wrappermode => undef,
  55. svnrepo => undef,
  56. svnpath => "trunk",
  57. gitorigin_branch => "origin",
  58. gitmaster_branch => "master",
  59. srcdir => undef,
  60. destdir => undef,
  61. pingurl => [],
  62. templatedir => "$installdir/share/ikiwiki/templates",
  63. underlaydir => "$installdir/share/ikiwiki/basewiki",
  64. setup => undef,
  65. adminuser => undef,
  66. adminemail => undef,
  67. plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
  68. lockedit conditional}],
  69. timeformat => '%c',
  70. locale => undef,
  71. sslcookie => 0,
  72. httpauth => 0,
  73. userdir => "",
  74. usedirs => 1,
  75. numbacklinks => 10,
  76. account_creation_password => "",
  77. } #}}}
  78. sub checkconfig () { #{{{
  79. # locale stuff; avoid LC_ALL since it overrides everything
  80. if (defined $ENV{LC_ALL}) {
  81. $ENV{LANG} = $ENV{LC_ALL};
  82. delete $ENV{LC_ALL};
  83. }
  84. if (defined $config{locale}) {
  85. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  86. $ENV{LANG}=$config{locale};
  87. $gettext_obj=undef;
  88. }
  89. }
  90. if ($config{w3mmode}) {
  91. eval q{use Cwd q{abs_path}};
  92. error($@) if $@;
  93. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  94. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  95. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  96. unless $config{cgiurl} =~ m!file:///!;
  97. $config{url}="file://".$config{destdir};
  98. }
  99. if ($config{cgi} && ! length $config{url}) {
  100. error(gettext("Must specify url to wiki with --url when using --cgi"));
  101. }
  102. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  103. unless exists $config{wikistatedir};
  104. if ($config{rcs}) {
  105. eval qq{require IkiWiki::Rcs::$config{rcs}};
  106. if ($@) {
  107. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  108. }
  109. }
  110. else {
  111. require IkiWiki::Rcs::Stub;
  112. }
  113. run_hooks(checkconfig => sub { shift->() });
  114. } #}}}
  115. sub loadplugins () { #{{{
  116. loadplugin($_) foreach @{$config{plugin}};
  117. run_hooks(getopt => sub { shift->() });
  118. if (grep /^-/, @ARGV) {
  119. print STDERR "Unknown option: $_\n"
  120. foreach grep /^-/, @ARGV;
  121. usage();
  122. }
  123. } #}}}
  124. sub loadplugin ($) { #{{{
  125. my $plugin=shift;
  126. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  127. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  128. eval qq{use $mod};
  129. if ($@) {
  130. error("Failed to load plugin $mod: $@");
  131. }
  132. } #}}}
  133. sub error ($;$) { #{{{
  134. my $message=shift;
  135. my $cleaner=shift;
  136. if ($config{cgi}) {
  137. print "Content-type: text/html\n\n";
  138. print misctemplate(gettext("Error"),
  139. "<p>".gettext("Error").": $message</p>");
  140. }
  141. log_message('err' => $message) if $config{syslog};
  142. if (defined $cleaner) {
  143. $cleaner->();
  144. }
  145. die $message."\n";
  146. } #}}}
  147. sub debug ($) { #{{{
  148. return unless $config{verbose};
  149. log_message(debug => @_);
  150. } #}}}
  151. my $log_open=0;
  152. sub log_message ($$) { #{{{
  153. my $type=shift;
  154. if ($config{syslog}) {
  155. require Sys::Syslog;
  156. unless ($log_open) {
  157. Sys::Syslog::setlogsock('unix');
  158. Sys::Syslog::openlog('ikiwiki', '', 'user');
  159. $log_open=1;
  160. }
  161. eval {
  162. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  163. };
  164. }
  165. elsif (! $config{cgi}) {
  166. print "@_\n";
  167. }
  168. else {
  169. print STDERR "@_\n";
  170. }
  171. } #}}}
  172. sub possibly_foolish_untaint ($) { #{{{
  173. my $tainted=shift;
  174. my ($untainted)=$tainted=~/(.*)/;
  175. return $untainted;
  176. } #}}}
  177. sub basename ($) { #{{{
  178. my $file=shift;
  179. $file=~s!.*/+!!;
  180. return $file;
  181. } #}}}
  182. sub dirname ($) { #{{{
  183. my $file=shift;
  184. $file=~s!/*[^/]+$!!;
  185. return $file;
  186. } #}}}
  187. sub pagetype ($) { #{{{
  188. my $page=shift;
  189. if ($page =~ /\.([^.]+)$/) {
  190. return $1 if exists $hooks{htmlize}{$1};
  191. }
  192. return undef;
  193. } #}}}
  194. sub pagename ($) { #{{{
  195. my $file=shift;
  196. my $type=pagetype($file);
  197. my $page=$file;
  198. $page=~s/\Q.$type\E*$// if defined $type;
  199. return $page;
  200. } #}}}
  201. sub targetpage ($$) { #{{{
  202. my $page=shift;
  203. my $ext=shift;
  204. if (! $config{usedirs} || $page =~ /^index$/ ) {
  205. return $page.".".$ext;
  206. } else {
  207. return $page."/index.".$ext;
  208. }
  209. } #}}}
  210. sub htmlpage ($) { #{{{
  211. my $page=shift;
  212. return targetpage($page, "html");
  213. } #}}}
  214. sub srcfile ($) { #{{{
  215. my $file=shift;
  216. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  217. return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
  218. error("internal error: $file cannot be found in $config{srcdir} or $config{underlaydir}");
  219. } #}}}
  220. sub readfile ($;$$) { #{{{
  221. my $file=shift;
  222. my $binary=shift;
  223. my $wantfd=shift;
  224. if (-l $file) {
  225. error("cannot read a symlink ($file)");
  226. }
  227. local $/=undef;
  228. open (IN, $file) || error("failed to read $file: $!");
  229. binmode(IN) if ($binary);
  230. return \*IN if $wantfd;
  231. my $ret=<IN>;
  232. close IN || error("failed to read $file: $!");
  233. return $ret;
  234. } #}}}
  235. sub writefile ($$$;$$) { #{{{
  236. my $file=shift; # can include subdirs
  237. my $destdir=shift; # directory to put file in
  238. my $content=shift;
  239. my $binary=shift;
  240. my $writer=shift;
  241. my $test=$file;
  242. while (length $test) {
  243. if (-l "$destdir/$test") {
  244. error("cannot write to a symlink ($test)");
  245. }
  246. $test=dirname($test);
  247. }
  248. my $newfile="$destdir/$file.ikiwiki-new";
  249. if (-l $newfile) {
  250. error("cannot write to a symlink ($newfile)");
  251. }
  252. my $dir=dirname($newfile);
  253. if (! -d $dir) {
  254. my $d="";
  255. foreach my $s (split(m!/+!, $dir)) {
  256. $d.="$s/";
  257. if (! -d $d) {
  258. mkdir($d) || error("failed to create directory $d: $!");
  259. }
  260. }
  261. }
  262. my $cleanup = sub { unlink($newfile) };
  263. open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
  264. binmode(OUT) if ($binary);
  265. if ($writer) {
  266. $writer->(\*OUT, $cleanup);
  267. }
  268. else {
  269. print OUT $content or error("failed writing to $newfile: $!", $cleanup);
  270. }
  271. close OUT || error("failed saving $newfile: $!", $cleanup);
  272. rename($newfile, "$destdir/$file") ||
  273. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  274. } #}}}
  275. my %cleared;
  276. sub will_render ($$;$) { #{{{
  277. my $page=shift;
  278. my $dest=shift;
  279. my $clear=shift;
  280. # Important security check.
  281. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  282. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  283. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  284. }
  285. if (! $clear || $cleared{$page}) {
  286. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  287. }
  288. else {
  289. foreach my $old (@{$renderedfiles{$page}}) {
  290. delete $destsources{$old};
  291. }
  292. $renderedfiles{$page}=[$dest];
  293. $cleared{$page}=1;
  294. }
  295. $destsources{$dest}=$page;
  296. } #}}}
  297. sub bestlink ($$) { #{{{
  298. my $page=shift;
  299. my $link=shift;
  300. my $cwd=$page;
  301. if ($link=~s/^\/+//) {
  302. # absolute links
  303. $cwd="";
  304. }
  305. do {
  306. my $l=$cwd;
  307. $l.="/" if length $l;
  308. $l.=$link;
  309. if (exists $links{$l}) {
  310. return $l;
  311. }
  312. elsif (exists $pagecase{lc $l}) {
  313. return $pagecase{lc $l};
  314. }
  315. } while $cwd=~s!/?[^/]+$!!;
  316. if (length $config{userdir}) {
  317. my $l = "$config{userdir}/".lc($link);
  318. if (exists $links{$l}) {
  319. return $l;
  320. }
  321. elsif (exists $pagecase{lc $l}) {
  322. return $pagecase{lc $l};
  323. }
  324. }
  325. #print STDERR "warning: page $page, broken link: $link\n";
  326. return "";
  327. } #}}}
  328. sub isinlinableimage ($) { #{{{
  329. my $file=shift;
  330. $file=~/\.(png|gif|jpg|jpeg)$/i;
  331. } #}}}
  332. sub pagetitle ($;$) { #{{{
  333. my $page=shift;
  334. my $unescaped=shift;
  335. if ($unescaped) {
  336. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  337. }
  338. else {
  339. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  340. }
  341. return $page;
  342. } #}}}
  343. sub titlepage ($) { #{{{
  344. my $title=shift;
  345. $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  346. return $title;
  347. } #}}}
  348. sub linkpage ($) { #{{{
  349. my $link=shift;
  350. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  351. return $link;
  352. } #}}}
  353. sub cgiurl (@) { #{{{
  354. my %params=@_;
  355. return $config{cgiurl}."?".
  356. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  357. } #}}}
  358. sub baseurl (;$) { #{{{
  359. my $page=shift;
  360. return "$config{url}/" if ! defined $page;
  361. $page=htmlpage($page);
  362. $page=~s/[^\/]+$//;
  363. $page=~s/[^\/]+\//..\//g;
  364. return $page;
  365. } #}}}
  366. sub abs2rel ($$) { #{{{
  367. # Work around very innefficient behavior in File::Spec if abs2rel
  368. # is passed two relative paths. It's much faster if paths are
  369. # absolute! (Debian bug #376658; fixed in debian unstable now)
  370. my $path="/".shift;
  371. my $base="/".shift;
  372. require File::Spec;
  373. my $ret=File::Spec->abs2rel($path, $base);
  374. $ret=~s/^// if defined $ret;
  375. return $ret;
  376. } #}}}
  377. sub displaytime ($) { #{{{
  378. my $time=shift;
  379. # strftime doesn't know about encodings, so make sure
  380. # its output is properly treated as utf8
  381. return decode_utf8(POSIX::strftime(
  382. $config{timeformat}, localtime($time)));
  383. } #}}}
  384. sub beautify_url ($) { #{{{
  385. my $url=shift;
  386. $url =~ s!/index.html$!/!;
  387. $url =~ s!^$!./!; # Browsers don't like empty links...
  388. return $url;
  389. } #}}}
  390. sub urlto ($$) { #{{{
  391. my $to=shift;
  392. my $from=shift;
  393. if (! length $to) {
  394. return beautify_url(baseurl($from));
  395. }
  396. if (! $destsources{$to}) {
  397. $to=htmlpage($to);
  398. }
  399. my $link = abs2rel($to, dirname(htmlpage($from)));
  400. return beautify_url($link);
  401. } #}}}
  402. sub htmllink ($$$;@) { #{{{
  403. my $lpage=shift; # the page doing the linking
  404. my $page=shift; # the page that will contain the link (different for inline)
  405. my $link=shift;
  406. my %opts=@_;
  407. my $bestlink;
  408. if (! $opts{forcesubpage}) {
  409. $bestlink=bestlink($lpage, $link);
  410. }
  411. else {
  412. $bestlink="$lpage/".lc($link);
  413. }
  414. my $linktext;
  415. if (defined $opts{linktext}) {
  416. $linktext=$opts{linktext};
  417. }
  418. else {
  419. $linktext=pagetitle(basename($link));
  420. }
  421. return "<span class=\"selflink\">$linktext</span>"
  422. if length $bestlink && $page eq $bestlink;
  423. if (! $destsources{$bestlink}) {
  424. $bestlink=htmlpage($bestlink);
  425. if (! $destsources{$bestlink}) {
  426. return $linktext unless length $config{cgiurl};
  427. return "<span><a href=\"".
  428. cgiurl(
  429. do => "create",
  430. page => pagetitle(lc($link), 1),
  431. from => $lpage
  432. ).
  433. "\">?</a>$linktext</span>"
  434. }
  435. }
  436. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  437. $bestlink=beautify_url($bestlink);
  438. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  439. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  440. }
  441. if (defined $opts{anchor}) {
  442. $bestlink.="#".$opts{anchor};
  443. }
  444. return "<a href=\"$bestlink\">$linktext</a>";
  445. } #}}}
  446. sub htmlize ($$$) { #{{{
  447. my $page=shift;
  448. my $type=shift;
  449. my $content=shift;
  450. if (exists $hooks{htmlize}{$type}) {
  451. $content=$hooks{htmlize}{$type}{call}->(
  452. page => $page,
  453. content => $content,
  454. );
  455. }
  456. else {
  457. error("htmlization of $type not supported");
  458. }
  459. run_hooks(sanitize => sub {
  460. $content=shift->(
  461. page => $page,
  462. content => $content,
  463. );
  464. });
  465. return $content;
  466. } #}}}
  467. sub linkify ($$$) { #{{{
  468. my $lpage=shift; # the page containing the links
  469. my $page=shift; # the page the link will end up on (different for inline)
  470. my $content=shift;
  471. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  472. defined $2
  473. ? ( $1
  474. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  475. : htmllink($lpage, $page, linkpage($3),
  476. anchor => $4, linktext => pagetitle($2)))
  477. : ( $1
  478. ? "[[$3".($4 ? "#$4" : "")."]]"
  479. : htmllink($lpage, $page, linkpage($3),
  480. anchor => $4))
  481. }eg;
  482. return $content;
  483. } #}}}
  484. my %preprocessing;
  485. our $preprocess_preview=0;
  486. sub preprocess ($$$;$$) { #{{{
  487. my $page=shift; # the page the data comes from
  488. my $destpage=shift; # the page the data will appear in (different for inline)
  489. my $content=shift;
  490. my $scan=shift;
  491. my $preview=shift;
  492. # Using local because it needs to be set within any nested calls
  493. # of this function.
  494. local $preprocess_preview=$preview if defined $preview;
  495. my $handle=sub {
  496. my $escape=shift;
  497. my $command=shift;
  498. my $params=shift;
  499. if (length $escape) {
  500. return "[[$command $params]]";
  501. }
  502. elsif (exists $hooks{preprocess}{$command}) {
  503. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  504. # Note: preserve order of params, some plugins may
  505. # consider it significant.
  506. my @params;
  507. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  508. my $key=$1;
  509. my $val;
  510. if (defined $2) {
  511. $val=$2;
  512. $val=~s/\r\n/\n/mg;
  513. $val=~s/^\n+//g;
  514. $val=~s/\n+$//g;
  515. }
  516. elsif (defined $3) {
  517. $val=$3;
  518. }
  519. elsif (defined $4) {
  520. $val=$4;
  521. }
  522. if (defined $key) {
  523. push @params, $key, $val;
  524. }
  525. else {
  526. push @params, $val, '';
  527. }
  528. }
  529. if ($preprocessing{$page}++ > 3) {
  530. # Avoid loops of preprocessed pages preprocessing
  531. # other pages that preprocess them, etc.
  532. #translators: The first parameter is a
  533. #translators: preprocessor directive name,
  534. #translators: the second a page name, the
  535. #translators: third a number.
  536. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  537. $command, $page, $preprocessing{$page}).
  538. "]]";
  539. }
  540. my $ret=$hooks{preprocess}{$command}{call}->(
  541. @params,
  542. page => $page,
  543. destpage => $destpage,
  544. preview => $preprocess_preview,
  545. );
  546. $preprocessing{$page}--;
  547. return $ret;
  548. }
  549. else {
  550. return "[[$command $params]]";
  551. }
  552. };
  553. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  554. return $content;
  555. } #}}}
  556. sub filter ($$$) { #{{{
  557. my $page=shift;
  558. my $destpage=shift;
  559. my $content=shift;
  560. run_hooks(filter => sub {
  561. $content=shift->(page => $page, destpage => $destpage,
  562. content => $content);
  563. });
  564. return $content;
  565. } #}}}
  566. sub indexlink () { #{{{
  567. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  568. } #}}}
  569. sub lockwiki (;$) { #{{{
  570. my $wait=@_ ? shift : 1;
  571. # Take an exclusive lock on the wiki to prevent multiple concurrent
  572. # run issues. The lock will be dropped on program exit.
  573. if (! -d $config{wikistatedir}) {
  574. mkdir($config{wikistatedir});
  575. }
  576. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  577. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  578. if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
  579. if ($wait) {
  580. debug("wiki seems to be locked, waiting for lock");
  581. my $wait=600; # arbitrary, but don't hang forever to
  582. # prevent process pileup
  583. for (1..$wait) {
  584. return if flock(WIKILOCK, 2 | 4);
  585. sleep 1;
  586. }
  587. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  588. }
  589. else {
  590. debug("wiki is locked");
  591. return 0;
  592. }
  593. }
  594. return 1;
  595. } #}}}
  596. sub unlockwiki () { #{{{
  597. close WIKILOCK;
  598. } #}}}
  599. sub commit_hook_enabled () { #{{{
  600. open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
  601. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  602. if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  603. close COMMITLOCK;
  604. return 0;
  605. }
  606. close COMMITLOCK;
  607. return 1;
  608. } #}}}
  609. sub disable_commit_hook () { #{{{
  610. open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
  611. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  612. if (! flock(COMMITLOCK, 2)) { # LOCK_EX
  613. error("failed to get commit lock");
  614. }
  615. } #}}}
  616. sub enable_commit_hook () { #{{{
  617. close COMMITLOCK;
  618. } #}}}
  619. sub loadindex () { #{{{
  620. open (IN, "$config{wikistatedir}/index") || return;
  621. while (<IN>) {
  622. $_=possibly_foolish_untaint($_);
  623. chomp;
  624. my %items;
  625. $items{link}=[];
  626. $items{dest}=[];
  627. foreach my $i (split(/ /, $_)) {
  628. my ($item, $val)=split(/=/, $i, 2);
  629. push @{$items{$item}}, decode_entities($val);
  630. }
  631. next unless exists $items{src}; # skip bad lines for now
  632. my $page=pagename($items{src}[0]);
  633. if (! $config{rebuild}) {
  634. $pagesources{$page}=$items{src}[0];
  635. $pagemtime{$page}=$items{mtime}[0];
  636. $oldlinks{$page}=[@{$items{link}}];
  637. $links{$page}=[@{$items{link}}];
  638. $depends{$page}=$items{depends}[0] if exists $items{depends};
  639. $destsources{$_}=$page foreach @{$items{dest}};
  640. $renderedfiles{$page}=[@{$items{dest}}];
  641. $oldrenderedfiles{$page}=[@{$items{dest}}];
  642. $pagecase{lc $page}=$page;
  643. }
  644. $pagectime{$page}=$items{ctime}[0];
  645. }
  646. close IN;
  647. } #}}}
  648. sub saveindex () { #{{{
  649. run_hooks(savestate => sub { shift->() });
  650. if (! -d $config{wikistatedir}) {
  651. mkdir($config{wikistatedir});
  652. }
  653. my $newfile="$config{wikistatedir}/index.new";
  654. my $cleanup = sub { unlink($newfile) };
  655. open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
  656. foreach my $page (keys %pagemtime) {
  657. next unless $pagemtime{$page};
  658. my $line="mtime=$pagemtime{$page} ".
  659. "ctime=$pagectime{$page} ".
  660. "src=$pagesources{$page}";
  661. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  662. my %count;
  663. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  664. if (exists $depends{$page}) {
  665. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  666. }
  667. print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  668. }
  669. close OUT || error("failed saving to $newfile: $!", $cleanup);
  670. rename($newfile, "$config{wikistatedir}/index") ||
  671. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  672. } #}}}
  673. sub template_file ($) { #{{{
  674. my $template=shift;
  675. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  676. return "$dir/$template" if -e "$dir/$template";
  677. }
  678. return undef;
  679. } #}}}
  680. sub template_params (@) { #{{{
  681. my $filename=template_file(shift);
  682. if (! defined $filename) {
  683. return if wantarray;
  684. return "";
  685. }
  686. require HTML::Template;
  687. my @ret=(
  688. filter => sub {
  689. my $text_ref = shift;
  690. $$text_ref=&Encode::decode_utf8($$text_ref);
  691. },
  692. filename => $filename,
  693. loop_context_vars => 1,
  694. die_on_bad_params => 0,
  695. @_
  696. );
  697. return wantarray ? @ret : {@ret};
  698. } #}}}
  699. sub template ($;@) { #{{{
  700. HTML::Template->new(template_params(@_));
  701. } #}}}
  702. sub misctemplate ($$;@) { #{{{
  703. my $title=shift;
  704. my $pagebody=shift;
  705. my $template=template("misc.tmpl");
  706. $template->param(
  707. title => $title,
  708. indexlink => indexlink(),
  709. wikiname => $config{wikiname},
  710. pagebody => $pagebody,
  711. baseurl => baseurl(),
  712. @_,
  713. );
  714. run_hooks(pagetemplate => sub {
  715. shift->(page => "", destpage => "", template => $template);
  716. });
  717. return $template->output;
  718. }#}}}
  719. sub hook (@) { # {{{
  720. my %param=@_;
  721. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  722. error "hook requires type, call, and id parameters";
  723. }
  724. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  725. $hooks{$param{type}}{$param{id}}=\%param;
  726. } # }}}
  727. sub run_hooks ($$) { # {{{
  728. # Calls the given sub for each hook of the given type,
  729. # passing it the hook function to call.
  730. my $type=shift;
  731. my $sub=shift;
  732. if (exists $hooks{$type}) {
  733. my @deferred;
  734. foreach my $id (keys %{$hooks{$type}}) {
  735. if ($hooks{$type}{$id}{last}) {
  736. push @deferred, $id;
  737. next;
  738. }
  739. $sub->($hooks{$type}{$id}{call});
  740. }
  741. foreach my $id (@deferred) {
  742. $sub->($hooks{$type}{$id}{call});
  743. }
  744. }
  745. } #}}}
  746. sub globlist_to_pagespec ($) { #{{{
  747. my @globlist=split(' ', shift);
  748. my (@spec, @skip);
  749. foreach my $glob (@globlist) {
  750. if ($glob=~/^!(.*)/) {
  751. push @skip, $glob;
  752. }
  753. else {
  754. push @spec, $glob;
  755. }
  756. }
  757. my $spec=join(" or ", @spec);
  758. if (@skip) {
  759. my $skip=join(" and ", @skip);
  760. if (length $spec) {
  761. $spec="$skip and ($spec)";
  762. }
  763. else {
  764. $spec=$skip;
  765. }
  766. }
  767. return $spec;
  768. } #}}}
  769. sub is_globlist ($) { #{{{
  770. my $s=shift;
  771. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  772. } #}}}
  773. sub safequote ($) { #{{{
  774. my $s=shift;
  775. $s=~s/[{}]//g;
  776. return "q{$s}";
  777. } #}}}
  778. sub add_depends ($$) { #{{{
  779. my $page=shift;
  780. my $pagespec=shift;
  781. if (! exists $depends{$page}) {
  782. $depends{$page}=$pagespec;
  783. }
  784. else {
  785. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  786. }
  787. } # }}}
  788. sub file_pruned ($$) { #{{{
  789. require File::Spec;
  790. my $file=File::Spec->canonpath(shift);
  791. my $base=File::Spec->canonpath(shift);
  792. $file=~s#^\Q$base\E/*##;
  793. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  794. $file =~ m/$regexp/;
  795. } #}}}
  796. sub gettext { #{{{
  797. # Only use gettext in the rare cases it's needed.
  798. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  799. if (! $gettext_obj) {
  800. $gettext_obj=eval q{
  801. use Locale::gettext q{textdomain};
  802. Locale::gettext->domain('ikiwiki')
  803. };
  804. if ($@) {
  805. print STDERR "$@";
  806. $gettext_obj=undef;
  807. return shift;
  808. }
  809. }
  810. return $gettext_obj->get(shift);
  811. }
  812. else {
  813. return shift;
  814. }
  815. } #}}}
  816. sub pagespec_merge ($$) { #{{{
  817. my $a=shift;
  818. my $b=shift;
  819. return $a if $a eq $b;
  820. # Support for old-style GlobLists.
  821. if (is_globlist($a)) {
  822. $a=globlist_to_pagespec($a);
  823. }
  824. if (is_globlist($b)) {
  825. $b=globlist_to_pagespec($b);
  826. }
  827. return "($a) or ($b)";
  828. } #}}}
  829. sub pagespec_translate ($) { #{{{
  830. # This assumes that $page is in scope in the function
  831. # that evalulates the translated pagespec code.
  832. my $spec=shift;
  833. # Support for old-style GlobLists.
  834. if (is_globlist($spec)) {
  835. $spec=globlist_to_pagespec($spec);
  836. }
  837. # Convert spec to perl code.
  838. my $code="";
  839. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  840. my $word=$1;
  841. if (lc $word eq "and") {
  842. $code.=" &&";
  843. }
  844. elsif (lc $word eq "or") {
  845. $code.=" ||";
  846. }
  847. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  848. $code.=" ".$word;
  849. }
  850. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  851. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  852. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
  853. }
  854. else {
  855. $code.=" 0";
  856. }
  857. }
  858. else {
  859. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
  860. }
  861. }
  862. return $code;
  863. } #}}}
  864. sub pagespec_match ($$;@) { #{{{
  865. my $page=shift;
  866. my $spec=shift;
  867. my @params=@_;
  868. # Backwards compatability with old calling convention.
  869. if (@params == 1) {
  870. unshift @params, "location";
  871. }
  872. my $ret=eval pagespec_translate($spec);
  873. return IkiWiki::FailReason->new("syntax error") if $@;
  874. return $ret;
  875. } #}}}
  876. package IkiWiki::FailReason;
  877. use overload ( #{{{
  878. '""' => sub { ${$_[0]} },
  879. '0+' => sub { 0 },
  880. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  881. fallback => 1,
  882. ); #}}}
  883. sub new { #{{{
  884. bless \$_[1], $_[0];
  885. } #}}}
  886. package IkiWiki::SuccessReason;
  887. use overload ( #{{{
  888. '""' => sub { ${$_[0]} },
  889. '0+' => sub { 1 },
  890. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  891. fallback => 1,
  892. ); #}}}
  893. sub new { #{{{
  894. bless \$_[1], $_[0];
  895. }; #}}}
  896. package IkiWiki::PageSpec;
  897. sub match_glob ($$;@) { #{{{
  898. my $page=shift;
  899. my $glob=shift;
  900. my %params=@_;
  901. my $from=exists $params{location} ? $params{location} : "";
  902. # relative matching
  903. if ($glob =~ m!^\./!) {
  904. $from=~s!/?[^/]+$!!;
  905. $glob=~s!^\./!!;
  906. $glob="$from/$glob" if length $from;
  907. }
  908. # turn glob into safe regexp
  909. $glob=quotemeta($glob);
  910. $glob=~s/\\\*/.*/g;
  911. $glob=~s/\\\?/./g;
  912. if ($page=~/^$glob$/i) {
  913. return IkiWiki::SuccessReason->new("$glob matches $page");
  914. }
  915. else {
  916. return IkiWiki::FailReason->new("$glob does not match $page");
  917. }
  918. } #}}}
  919. sub match_link ($$;@) { #{{{
  920. my $page=shift;
  921. my $link=lc(shift);
  922. my %params=@_;
  923. my $from=exists $params{location} ? $params{location} : "";
  924. # relative matching
  925. if ($link =~ m!^\.! && defined $from) {
  926. $from=~s!/?[^/]+$!!;
  927. $link=~s!^\./!!;
  928. $link="$from/$link" if length $from;
  929. }
  930. my $links = $IkiWiki::links{$page} or return undef;
  931. return IkiWiki::FailReason->new("$page has no links") unless @$links;
  932. my $bestlink = IkiWiki::bestlink($from, $link);
  933. return IkiWiki::FailReason->new("no such link") unless length $bestlink;
  934. foreach my $p (@$links) {
  935. return IkiWiki::SuccessReason->new("$page links to $link")
  936. if $bestlink eq IkiWiki::bestlink($page, $p);
  937. }
  938. return IkiWiki::FailReason->new("$page does not link to $link");
  939. } #}}}
  940. sub match_backlink ($$;@) { #{{{
  941. match_link($_[1], $_[0], @_);
  942. } #}}}
  943. sub match_created_before ($$;@) { #{{{
  944. my $page=shift;
  945. my $testpage=shift;
  946. if (exists $IkiWiki::pagectime{$testpage}) {
  947. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  948. IkiWiki::SuccessReason->new("$page created before $testpage");
  949. }
  950. else {
  951. IkiWiki::FailReason->new("$page not created before $testpage");
  952. }
  953. }
  954. else {
  955. return IkiWiki::FailReason->new("$testpage has no ctime");
  956. }
  957. } #}}}
  958. sub match_created_after ($$;@) { #{{{
  959. my $page=shift;
  960. my $testpage=shift;
  961. if (exists $IkiWiki::pagectime{$testpage}) {
  962. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  963. IkiWiki::SuccessReason->new("$page created after $testpage");
  964. }
  965. else {
  966. IkiWiki::FailReason->new("$page not created after $testpage");
  967. }
  968. }
  969. else {
  970. return IkiWiki::FailReason->new("$testpage has no ctime");
  971. }
  972. } #}}}
  973. sub match_creation_day ($$;@) { #{{{
  974. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  975. return IkiWiki::SuccessReason->new("creation_day matched");
  976. }
  977. else {
  978. return IkiWiki::FailReason->new("creation_day did not match");
  979. }
  980. } #}}}
  981. sub match_creation_month ($$;@) { #{{{
  982. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  983. return IkiWiki::SuccessReason->new("creation_month matched");
  984. }
  985. else {
  986. return IkiWiki::FailReason->new("creation_month did not match");
  987. }
  988. } #}}}
  989. sub match_creation_year ($$;@) { #{{{
  990. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  991. return IkiWiki::SuccessReason->new("creation_year matched");
  992. }
  993. else {
  994. return IkiWiki::FailReason->new("creation_year did not match");
  995. }
  996. } #}}}
  997. sub match_user ($$;@) { #{{{
  998. shift;
  999. my $user=shift;
  1000. my %params=@_;
  1001. return IkiWiki::FailReason->new("cannot match user") unless exists $params{user};
  1002. if ($user eq $params{user}) {
  1003. return IkiWiki::SuccessReason->new("user is $user")
  1004. }
  1005. else {
  1006. return IkiWiki::FailReason->new("user is not $user");
  1007. }
  1008. } #}}}
  1009. 1