summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: 167b9d43aa64832343a144d554e7d14cd03fe2f3 (plain)
  1. #!/usr/bin/perl -T
  2. $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
  3. use warnings;
  4. use strict;
  5. use Memoize;
  6. use File::Spec;
  7. use HTML::Template;
  8. use Getopt::Long;
  9. my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
  10. # Holds global config settings, also used by some modules.
  11. our %config=( #{{{
  12. wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
  13. wiki_link_regexp => qr/\[\[([^\s]+)\]\]/,
  14. wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
  15. verbose => 0,
  16. wikiname => "wiki",
  17. default_pageext => ".mdwn",
  18. cgi => 0,
  19. svn => 1,
  20. url => '',
  21. cgiurl => '',
  22. historyurl => '',
  23. anonok => 0,
  24. rebuild => 0,
  25. wrapper => undef,
  26. wrappermode => undef,
  27. srcdir => undef,
  28. destdir => undef,
  29. templatedir => undef,
  30. setup => undef,
  31. ); #}}}
  32. GetOptions( #{{{
  33. "setup=s" => \$config{setup},
  34. "wikiname=s" => \$config{wikiname},
  35. "verbose|v!" => \$config{verbose},
  36. "rebuild!" => \$config{rebuild},
  37. "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
  38. "wrappermode=i" => \$config{wrappermode},
  39. "svn!" => \$config{svn},
  40. "anonok!" => \$config{anonok},
  41. "cgi!" => \$config{cgi},
  42. "url=s" => \$config{url},
  43. "cgiurl=s" => \$config{cgiurl},
  44. "historyurl=s" => \$config{historyurl},
  45. "exclude=s@" => sub {
  46. $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
  47. },
  48. ) || usage();
  49. if (! $config{setup}) {
  50. usage() unless @ARGV == 3;
  51. $config{srcdir} = possibly_foolish_untaint(shift);
  52. $config{templatedir} = possibly_foolish_untaint(shift);
  53. $config{destdir} = possibly_foolish_untaint(shift);
  54. if ($config{cgi} && ! length $config{url}) {
  55. error("Must specify url to wiki with --url when using --cgi");
  56. }
  57. }
  58. #}}}
  59. sub usage { #{{{
  60. die "usage: ikiwiki [options] source templates dest\n";
  61. } #}}}
  62. sub error { #{{{
  63. if ($config{cgi}) {
  64. print "Content-type: text/html\n\n";
  65. print misctemplate("Error", "<p>Error: @_</p>");
  66. }
  67. die @_;
  68. } #}}}
  69. sub debug ($) { #{{{
  70. return unless $config{verbose};
  71. if (! $config{cgi}) {
  72. print "@_\n";
  73. }
  74. else {
  75. print STDERR "@_\n";
  76. }
  77. } #}}}
  78. sub mtime ($) { #{{{
  79. my $page=shift;
  80. return (stat($page))[9];
  81. } #}}}
  82. sub possibly_foolish_untaint { #{{{
  83. my $tainted=shift;
  84. my ($untainted)=$tainted=~/(.*)/;
  85. return $untainted;
  86. } #}}}
  87. sub basename ($) { #{{{
  88. my $file=shift;
  89. $file=~s!.*/!!;
  90. return $file;
  91. } #}}}
  92. sub dirname ($) { #{{{
  93. my $file=shift;
  94. $file=~s!/?[^/]+$!!;
  95. return $file;
  96. } #}}}
  97. sub pagetype ($) { #{{{
  98. my $page=shift;
  99. if ($page =~ /\.mdwn$/) {
  100. return ".mdwn";
  101. }
  102. else {
  103. return "unknown";
  104. }
  105. } #}}}
  106. sub pagename ($) { #{{{
  107. my $file=shift;
  108. my $type=pagetype($file);
  109. my $page=$file;
  110. $page=~s/\Q$type\E*$// unless $type eq 'unknown';
  111. return $page;
  112. } #}}}
  113. sub htmlpage ($) { #{{{
  114. my $page=shift;
  115. return $page.".html";
  116. } #}}}
  117. sub readfile ($) { #{{{
  118. my $file=shift;
  119. local $/=undef;
  120. open (IN, "$file") || error("failed to read $file: $!");
  121. my $ret=<IN>;
  122. close IN;
  123. return $ret;
  124. } #}}}
  125. sub writefile ($$) { #{{{
  126. my $file=shift;
  127. my $content=shift;
  128. my $dir=dirname($file);
  129. if (! -d $dir) {
  130. my $d="";
  131. foreach my $s (split(m!/+!, $dir)) {
  132. $d.="$s/";
  133. if (! -d $d) {
  134. mkdir($d) || error("failed to create directory $d: $!");
  135. }
  136. }
  137. }
  138. open (OUT, ">$file") || error("failed to write $file: $!");
  139. print OUT $content;
  140. close OUT;
  141. } #}}}
  142. sub findlinks ($$) { #{{{
  143. my $content=shift;
  144. my $page=shift;
  145. my @links;
  146. while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
  147. push @links, lc($1);
  148. }
  149. # Discussion links are a special case since they're not in the text
  150. # of the page, but on its template.
  151. return @links, "$page/discussion";
  152. } #}}}
  153. sub bestlink ($$) { #{{{
  154. # Given a page and the text of a link on the page, determine which
  155. # existing page that link best points to. Prefers pages under a
  156. # subdirectory with the same name as the source page, failing that
  157. # goes down the directory tree to the base looking for matching
  158. # pages.
  159. my $page=shift;
  160. my $link=lc(shift);
  161. my $cwd=$page;
  162. do {
  163. my $l=$cwd;
  164. $l.="/" if length $l;
  165. $l.=$link;
  166. if (exists $links{$l}) {
  167. #debug("for $page, \"$link\", use $l");
  168. return $l;
  169. }
  170. } while $cwd=~s!/?[^/]+$!!;
  171. #print STDERR "warning: page $page, broken link: $link\n";
  172. return "";
  173. } #}}}
  174. sub isinlinableimage ($) { #{{{
  175. my $file=shift;
  176. $file=~/\.(png|gif|jpg|jpeg)$/;
  177. } #}}}
  178. sub htmllink { #{{{
  179. my $page=shift;
  180. my $link=shift;
  181. my $noimageinline=shift; # don't turn links into inline html images
  182. my $forcesubpage=shift; # force a link to a subpage
  183. my $bestlink;
  184. if (! $forcesubpage) {
  185. $bestlink=bestlink($page, $link);
  186. }
  187. else {
  188. $bestlink="$page/".lc($link);
  189. }
  190. return $link if length $bestlink && $page eq $bestlink;
  191. # TODO BUG: %renderedfiles may not have it, if the linked to page
  192. # was also added and isn't yet rendered! Note that this bug is
  193. # masked by the bug mentioned below that makes all new files
  194. # be rendered twice.
  195. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  196. $bestlink=htmlpage($bestlink);
  197. }
  198. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  199. return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
  200. }
  201. $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
  202. if (! $noimageinline && isinlinableimage($bestlink)) {
  203. return "<img src=\"$bestlink\">";
  204. }
  205. return "<a href=\"$bestlink\">$link</a>";
  206. } #}}}
  207. sub linkify ($$) { #{{{
  208. my $content=shift;
  209. my $page=shift;
  210. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  211. $1 ? "[[$2]]" : htmllink($page, $2)
  212. }eg;
  213. return $content;
  214. } #}}}
  215. sub htmlize ($$) { #{{{
  216. my $type=shift;
  217. my $content=shift;
  218. if (! $INC{"/usr/bin/markdown"}) {
  219. no warnings 'once';
  220. $blosxom::version="is a proper perl module too much to ask?";
  221. use warnings 'all';
  222. do "/usr/bin/markdown";
  223. }
  224. if ($type eq '.mdwn') {
  225. return Markdown::Markdown($content);
  226. }
  227. else {
  228. error("htmlization of $type not supported");
  229. }
  230. } #}}}
  231. sub backlinks ($) { #{{{
  232. my $page=shift;
  233. my @links;
  234. foreach my $p (keys %links) {
  235. next if bestlink($page, $p) eq $page;
  236. if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
  237. my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
  238. # Trim common dir prefixes from both pages.
  239. my $p_trimmed=$p;
  240. my $page_trimmed=$page;
  241. my $dir;
  242. 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
  243. defined $dir &&
  244. $p_trimmed=~s/^\Q$dir\E// &&
  245. $page_trimmed=~s/^\Q$dir\E//;
  246. push @links, { url => $href, page => $p_trimmed };
  247. }
  248. }
  249. return sort { $a->{page} cmp $b->{page} } @links;
  250. } #}}}
  251. sub parentlinks ($) { #{{{
  252. my $page=shift;
  253. my @ret;
  254. my $pagelink="";
  255. my $path="";
  256. my $skip=1;
  257. foreach my $dir (reverse split("/", $page)) {
  258. if (! $skip) {
  259. $path.="../";
  260. unshift @ret, { url => "$path$dir.html", page => $dir };
  261. }
  262. else {
  263. $skip=0;
  264. }
  265. }
  266. unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
  267. return @ret;
  268. } #}}}
  269. sub indexlink () { #{{{
  270. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  271. } #}}}
  272. sub finalize ($$$) { #{{{
  273. my $content=shift;
  274. my $page=shift;
  275. my $mtime=shift;
  276. my $title=basename($page);
  277. $title=~s/_/ /g;
  278. my $template=HTML::Template->new(blind_cache => 1,
  279. filename => "$config{templatedir}/page.tmpl");
  280. if (length $config{cgiurl}) {
  281. $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
  282. if ($config{svn}) {
  283. $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
  284. }
  285. }
  286. if (length $config{historyurl}) {
  287. my $u=$config{historyurl};
  288. $u=~s/\[\[\]\]/$pagesources{$page}/g;
  289. $template->param(historyurl => $u);
  290. }
  291. $template->param(
  292. title => $title,
  293. wikiname => $config{wikiname},
  294. parentlinks => [parentlinks($page)],
  295. content => $content,
  296. backlinks => [backlinks($page)],
  297. discussionlink => htmllink($page, "Discussion", 1, 1),
  298. mtime => scalar(gmtime($mtime)),
  299. );
  300. return $template->output;
  301. } #}}}
  302. sub check_overwrite ($$) { #{{{
  303. # Important security check. Make sure to call this before saving
  304. # any files to the source directory.
  305. my $dest=shift;
  306. my $src=shift;
  307. if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
  308. error("$dest already exists and was rendered from ".
  309. join(" ",(grep { $renderedfiles{$_} eq $dest } keys
  310. %renderedfiles)).
  311. ", before, so not rendering from $src");
  312. }
  313. } #}}}
  314. sub render ($) { #{{{
  315. my $file=shift;
  316. my $type=pagetype($file);
  317. my $content=readfile("$config{srcdir}/$file");
  318. if ($type ne 'unknown') {
  319. my $page=pagename($file);
  320. $links{$page}=[findlinks($content, $page)];
  321. $content=linkify($content, $page);
  322. $content=htmlize($type, $content);
  323. $content=finalize($content, $page,
  324. mtime("$config{srcdir}/$file"));
  325. check_overwrite("$config{destdir}/".htmlpage($page), $page);
  326. writefile("$config{destdir}/".htmlpage($page), $content);
  327. $oldpagemtime{$page}=time;
  328. $renderedfiles{$page}=htmlpage($page);
  329. }
  330. else {
  331. $links{$file}=[];
  332. check_overwrite("$config{destdir}/$file", $file);
  333. writefile("$config{destdir}/$file", $content);
  334. $oldpagemtime{$file}=time;
  335. $renderedfiles{$file}=$file;
  336. }
  337. } #}}}
  338. sub lockwiki () { #{{{
  339. # Take an exclusive lock on the wiki to prevent multiple concurrent
  340. # run issues. The lock will be dropped on program exit.
  341. if (! -d "$config{srcdir}/.ikiwiki") {
  342. mkdir("$config{srcdir}/.ikiwiki");
  343. }
  344. open(WIKILOCK, ">$config{srcdir}/.ikiwiki/lockfile") || error ("cannot write to lockfile: $!");
  345. if (! flock(WIKILOCK, 2 | 4)) {
  346. debug("wiki seems to be locked, waiting for lock");
  347. my $wait=600; # arbitrary, but don't hang forever to
  348. # prevent process pileup
  349. for (1..600) {
  350. return if flock(WIKILOCK, 2 | 4);
  351. sleep 1;
  352. }
  353. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  354. }
  355. } #}}}
  356. sub unlockwiki () { #{{{
  357. close WIKILOCK;
  358. } #}}}
  359. sub loadindex () { #{{{
  360. open (IN, "$config{srcdir}/.ikiwiki/index") || return;
  361. while (<IN>) {
  362. $_=possibly_foolish_untaint($_);
  363. chomp;
  364. my ($mtime, $file, $rendered, @links)=split(' ', $_);
  365. my $page=pagename($file);
  366. $pagesources{$page}=$file;
  367. $oldpagemtime{$page}=$mtime;
  368. $oldlinks{$page}=[@links];
  369. $links{$page}=[@links];
  370. $renderedfiles{$page}=$rendered;
  371. }
  372. close IN;
  373. } #}}}
  374. sub saveindex () { #{{{
  375. if (! -d "$config{srcdir}/.ikiwiki") {
  376. mkdir("$config{srcdir}/.ikiwiki");
  377. }
  378. open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
  379. foreach my $page (keys %oldpagemtime) {
  380. print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
  381. join(" ", @{$links{$page}})."\n"
  382. if $oldpagemtime{$page};
  383. }
  384. close OUT;
  385. } #}}}
  386. sub rcs_update () { #{{{
  387. if (-d "$config{srcdir}/.svn") {
  388. if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
  389. warn("svn update failed\n");
  390. }
  391. }
  392. } #}}}
  393. sub rcs_prepedit ($) { #{{{
  394. # Prepares to edit a file under revision control. Returns a token
  395. # that must be passed into rcs_commit when the file is ready
  396. # for committing.
  397. # The file is relative to the srcdir.
  398. my $file=shift;
  399. if (-d "$config{srcdir}/.svn") {
  400. # For subversion, return the revision of the file when
  401. # editing begins.
  402. my $rev=svn_info("Revision", "$config{srcdir}/$file");
  403. return defined $rev ? $rev : "";
  404. }
  405. } #}}}
  406. sub rcs_commit ($$$) { #{{{
  407. # Tries to commit the page; returns undef on _success_ and
  408. # a version of the page with the rcs's conflict markers on failure.
  409. # The file is relative to the srcdir.
  410. my $file=shift;
  411. my $message=shift;
  412. my $rcstoken=shift;
  413. if (-d "$config{srcdir}/.svn") {
  414. # Check to see if the page has been changed by someone
  415. # else since rcs_prepedit was called.
  416. my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
  417. my $rev=svn_info("Revision", "$config{srcdir}/$file");
  418. if (defined $rev && defined $oldrev && $rev != $oldrev) {
  419. # Merge their changes into the file that we've
  420. # changed.
  421. chdir($config{srcdir}); # svn merge wants to be here
  422. if (system("svn", "merge", "--quiet", "-r$oldrev:$rev",
  423. "$config{srcdir}/$file") != 0) {
  424. warn("svn merge -r$oldrev:$rev failed\n");
  425. }
  426. }
  427. if (system("svn", "commit", "--quiet", "-m",
  428. possibly_foolish_untaint($message),
  429. "$config{srcdir}") != 0) {
  430. my $conflict=readfile("$config{srcdir}/$file");
  431. if (system("svn", "revert", "--quiet", "$config{srcdir}/$file") != 0) {
  432. warn("svn revert failed\n");
  433. }
  434. return $conflict;
  435. }
  436. }
  437. return undef # success
  438. } #}}}
  439. sub rcs_add ($) { #{{{
  440. # filename is relative to the root of the srcdir
  441. my $file=shift;
  442. if (-d "$config{srcdir}/.svn") {
  443. my $parent=dirname($file);
  444. while (! -d "$config{srcdir}/$parent/.svn") {
  445. $file=$parent;
  446. $parent=dirname($file);
  447. }
  448. if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
  449. warn("svn add failed\n");
  450. }
  451. }
  452. } #}}}
  453. sub svn_info ($$) { #{{{
  454. my $field=shift;
  455. my $file=shift;
  456. my $info=`LANG=C svn info $file`;
  457. my ($ret)=$info=~/^$field: (.*)$/m;
  458. return $ret;
  459. } #}}}
  460. sub rcs_recentchanges ($) { #{{{
  461. my $num=shift;
  462. my @ret;
  463. eval q{use CGI 'escapeHTML'};
  464. eval q{use Date::Parse};
  465. eval q{use Time::Duration};
  466. if (-d "$config{srcdir}/.svn") {
  467. my $svn_url=svn_info("URL", $config{srcdir});
  468. # FIXME: currently assumes that the wiki is somewhere
  469. # under trunk in svn, doesn't support other layouts.
  470. my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
  471. my $div=qr/^--------------------+$/;
  472. my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
  473. my $state='start';
  474. my ($rev, $user, $when, @pages, @message);
  475. foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
  476. chomp;
  477. if ($state eq 'start' && /$div/) {
  478. $state='header';
  479. }
  480. elsif ($state eq 'header' && /$infoline/) {
  481. $rev=$1;
  482. $user=$2;
  483. $when=concise(ago(time - str2time($3)));
  484. }
  485. elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/([^ ]+)(?:$|\s)/) {
  486. push @pages, { link => htmllink("", pagename($1), 1) }
  487. if length $1;
  488. }
  489. elsif ($state eq 'header' && /^$/) {
  490. $state='body';
  491. }
  492. elsif ($state eq 'body' && /$div/) {
  493. my $committype="web";
  494. if (defined $message[0] &&
  495. $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
  496. $user="$1";
  497. $message[0]->{line}=$2;
  498. }
  499. else {
  500. $committype="svn";
  501. }
  502. push @ret, { rev => $rev,
  503. user => htmllink("", $user, 1),
  504. committype => $committype,
  505. when => $when, message => [@message],
  506. pages => [@pages] } if @pages;
  507. return @ret if @ret >= $num;
  508. $state='header';
  509. $rev=$user=$when=undef;
  510. @pages=@message=();
  511. }
  512. elsif ($state eq 'body') {
  513. push @message, {line => escapeHTML($_)},
  514. }
  515. }
  516. }
  517. return @ret;
  518. } #}}}
  519. sub prune ($) { #{{{
  520. my $file=shift;
  521. unlink($file);
  522. my $dir=dirname($file);
  523. while (rmdir($dir)) {
  524. $dir=dirname($dir);
  525. }
  526. } #}}}
  527. sub refresh () { #{{{
  528. # find existing pages
  529. my %exists;
  530. my @files;
  531. eval q{use File::Find};
  532. find({
  533. no_chdir => 1,
  534. wanted => sub {
  535. if (/$config{wiki_file_prune_regexp}/) {
  536. no warnings 'once';
  537. $File::Find::prune=1;
  538. use warnings "all";
  539. }
  540. elsif (! -d $_ && ! -l $_) {
  541. my ($f)=/$config{wiki_file_regexp}/; # untaint
  542. if (! defined $f) {
  543. warn("skipping bad filename $_\n");
  544. }
  545. else {
  546. $f=~s/^\Q$config{srcdir}\E\/?//;
  547. push @files, $f;
  548. $exists{pagename($f)}=1;
  549. }
  550. }
  551. },
  552. }, $config{srcdir});
  553. my %rendered;
  554. # check for added or removed pages
  555. my @add;
  556. foreach my $file (@files) {
  557. my $page=pagename($file);
  558. if (! $oldpagemtime{$page}) {
  559. debug("new page $page");
  560. push @add, $file;
  561. $links{$page}=[];
  562. $pagesources{$page}=$file;
  563. }
  564. }
  565. my @del;
  566. foreach my $page (keys %oldpagemtime) {
  567. if (! $exists{$page}) {
  568. debug("removing old page $page");
  569. push @del, $pagesources{$page};
  570. prune($config{destdir}."/".$renderedfiles{$page});
  571. delete $renderedfiles{$page};
  572. $oldpagemtime{$page}=0;
  573. delete $pagesources{$page};
  574. }
  575. }
  576. # render any updated files
  577. foreach my $file (@files) {
  578. my $page=pagename($file);
  579. if (! exists $oldpagemtime{$page} ||
  580. mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
  581. debug("rendering changed file $file");
  582. render($file);
  583. $rendered{$file}=1;
  584. }
  585. }
  586. # if any files were added or removed, check to see if each page
  587. # needs an update due to linking to them
  588. # TODO: inefficient; pages may get rendered above and again here;
  589. # problem is the bestlink may have changed and we won't know until
  590. # now
  591. if (@add || @del) {
  592. FILE: foreach my $file (@files) {
  593. my $page=pagename($file);
  594. foreach my $f (@add, @del) {
  595. my $p=pagename($f);
  596. foreach my $link (@{$links{$page}}) {
  597. if (bestlink($page, $link) eq $p) {
  598. debug("rendering $file, which links to $p");
  599. render($file);
  600. $rendered{$file}=1;
  601. next FILE;
  602. }
  603. }
  604. }
  605. }
  606. }
  607. # handle backlinks; if a page has added/removed links, update the
  608. # pages it links to
  609. # TODO: inefficient; pages may get rendered above and again here;
  610. # problem is the backlinks could be wrong in the first pass render
  611. # above
  612. if (%rendered) {
  613. my %linkchanged;
  614. foreach my $file (keys %rendered, @del) {
  615. my $page=pagename($file);
  616. if (exists $links{$page}) {
  617. foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
  618. if (length $link &&
  619. ! exists $oldlinks{$page} ||
  620. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  621. $linkchanged{$link}=1;
  622. }
  623. }
  624. }
  625. if (exists $oldlinks{$page}) {
  626. foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
  627. if (length $link &&
  628. ! exists $links{$page} ||
  629. ! grep { $_ eq $link } @{$links{$page}}) {
  630. $linkchanged{$link}=1;
  631. }
  632. }
  633. }
  634. }
  635. foreach my $link (keys %linkchanged) {
  636. my $linkfile=$pagesources{$link};
  637. if (defined $linkfile) {
  638. debug("rendering $linkfile, to update its backlinks");
  639. render($linkfile);
  640. }
  641. }
  642. }
  643. } #}}}
  644. sub gen_wrapper (@) { #{{{
  645. my %config=(@_);
  646. eval q{use Cwd 'abs_path'};
  647. $config{srcdir}=abs_path($config{srcdir});
  648. $config{destdir}=abs_path($config{destdir});
  649. my $this=abs_path($0);
  650. if (! -x $this) {
  651. error("$this doesn't seem to be executable");
  652. }
  653. if ($config{setup}) {
  654. error("cannot create a wrapper that uses a setup file");
  655. }
  656. my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
  657. "--wikiname=$config{wikiname}");
  658. push @params, "--verbose" if $config{verbose};
  659. push @params, "--rebuild" if $config{rebuild};
  660. push @params, "--nosvn" if !$config{svn};
  661. push @params, "--cgi" if $config{cgi};
  662. push @params, "--url=$config{url}" if length $config{url};
  663. push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
  664. push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
  665. push @params, "--anonok" if $config{anonok};
  666. my $params=join(" ", @params);
  667. my $call='';
  668. foreach my $p ($this, $this, @params) {
  669. $call.=qq{"$p", };
  670. }
  671. $call.="NULL";
  672. my @envsave;
  673. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  674. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  675. HTTP_COOKIE} if $config{cgi};
  676. my $envsave="";
  677. foreach my $var (@envsave) {
  678. $envsave.=<<"EOF"
  679. if ((s=getenv("$var")))
  680. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  681. EOF
  682. }
  683. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  684. print OUT <<"EOF";
  685. /* A wrapper for ikiwiki, can be safely made suid. */
  686. #define _GNU_SOURCE
  687. #include <stdio.h>
  688. #include <unistd.h>
  689. #include <stdlib.h>
  690. #include <string.h>
  691. extern char **environ;
  692. int main (int argc, char **argv) {
  693. /* Sanitize environment. */
  694. char *s;
  695. char *newenviron[$#envsave+3];
  696. int i=0;
  697. $envsave
  698. newenviron[i++]="HOME=$ENV{HOME}";
  699. newenviron[i]=NULL;
  700. environ=newenviron;
  701. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  702. printf("$params\\n");
  703. exit(0);
  704. }
  705. execl($call);
  706. perror("failed to run $this");
  707. exit(1);
  708. }
  709. EOF
  710. close OUT;
  711. if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
  712. error("failed to compile ikiwiki-wrap.c");
  713. }
  714. unlink("ikiwiki-wrap.c");
  715. if (defined $config{wrappermode} &&
  716. ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
  717. error("chmod $config{wrapper}: $!");
  718. }
  719. print "successfully generated $config{wrapper}\n";
  720. } #}}}
  721. sub misctemplate ($$) { #{{{
  722. my $title=shift;
  723. my $pagebody=shift;
  724. my $template=HTML::Template->new(
  725. filename => "$config{templatedir}/misc.tmpl"
  726. );
  727. $template->param(
  728. title => $title,
  729. indexlink => indexlink(),
  730. wikiname => $config{wikiname},
  731. pagebody => $pagebody,
  732. );
  733. return $template->output;
  734. }#}}}
  735. sub cgi_recentchanges ($) { #{{{
  736. my $q=shift;
  737. my $template=HTML::Template->new(
  738. filename => "$config{templatedir}/recentchanges.tmpl"
  739. );
  740. $template->param(
  741. title => "RecentChanges",
  742. indexlink => indexlink(),
  743. wikiname => $config{wikiname},
  744. changelog => [rcs_recentchanges(100)],
  745. );
  746. print $q->header, $template->output;
  747. } #}}}
  748. sub userinfo_get ($$) { #{{{
  749. my $user=shift;
  750. my $field=shift;
  751. eval q{use Storable};
  752. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  753. if (! defined $userdata || ! ref $userdata ||
  754. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  755. return "";
  756. }
  757. return $userdata->{$user}->{$field};
  758. } #}}}
  759. sub userinfo_set ($$) { #{{{
  760. my $user=shift;
  761. my $info=shift;
  762. eval q{use Storable};
  763. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  764. if (! defined $userdata || ! ref $userdata) {
  765. $userdata={};
  766. }
  767. $userdata->{$user}=$info;
  768. my $oldmask=umask(077);
  769. my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
  770. umask($oldmask);
  771. return $ret;
  772. } #}}}
  773. sub cgi_signin ($$) { #{{{
  774. my $q=shift;
  775. my $session=shift;
  776. eval q{use CGI::FormBuilder};
  777. my $form = CGI::FormBuilder->new(
  778. title => "$config{wikiname} signin",
  779. fields => [qw(do page from name password confirm_password email)],
  780. header => 1,
  781. method => 'POST',
  782. validate => {
  783. confirm_password => {
  784. perl => q{eq $form->field("password")},
  785. },
  786. email => 'EMAIL',
  787. },
  788. required => 'NONE',
  789. javascript => 0,
  790. params => $q,
  791. action => $q->request_uri,
  792. header => 0,
  793. template => (-e "$config{templatedir}/signin.tmpl" ?
  794. "$config{templatedir}/signin.tmpl" : "")
  795. );
  796. $form->field(name => "name", required => 0);
  797. $form->field(name => "do", type => "hidden");
  798. $form->field(name => "page", type => "hidden");
  799. $form->field(name => "from", type => "hidden");
  800. $form->field(name => "password", type => "password", required => 0);
  801. $form->field(name => "confirm_password", type => "password", required => 0);
  802. $form->field(name => "email", required => 0);
  803. if ($q->param("do") ne "signin") {
  804. $form->text("You need to log in before you can edit pages.");
  805. }
  806. if ($form->submitted) {
  807. # Set required fields based on how form was submitted.
  808. my %required=(
  809. "Login" => [qw(name password)],
  810. "Register" => [qw(name password confirm_password email)],
  811. "Mail Password" => [qw(name)],
  812. );
  813. foreach my $opt (@{$required{$form->submitted}}) {
  814. $form->field(name => $opt, required => 1);
  815. }
  816. # Validate password differently depending on how
  817. # form was submitted.
  818. if ($form->submitted eq 'Login') {
  819. $form->field(
  820. name => "password",
  821. validate => sub {
  822. length $form->field("name") &&
  823. shift eq userinfo_get($form->field("name"), 'password');
  824. },
  825. );
  826. $form->field(name => "name", validate => '/^\w+$/');
  827. }
  828. else {
  829. $form->field(name => "password", validate => 'VALUE');
  830. }
  831. # And make sure the entered name exists when logging
  832. # in or sending email, and does not when registering.
  833. if ($form->submitted eq 'Register') {
  834. $form->field(
  835. name => "name",
  836. validate => sub {
  837. my $name=shift;
  838. length $name &&
  839. ! userinfo_get($name, "regdate");
  840. },
  841. );
  842. }
  843. else {
  844. $form->field(
  845. name => "name",
  846. validate => sub {
  847. my $name=shift;
  848. length $name &&
  849. userinfo_get($name, "regdate");
  850. },
  851. );
  852. }
  853. }
  854. else {
  855. # First time settings.
  856. $form->field(name => "name", comment => "use FirstnameLastName");
  857. $form->field(name => "confirm_password", comment => "(only needed");
  858. $form->field(name => "email", comment => "for registration)");
  859. if ($session->param("name")) {
  860. $form->field(name => "name", value => $session->param("name"));
  861. }
  862. }
  863. if ($form->submitted && $form->validate) {
  864. if ($form->submitted eq 'Login') {
  865. $session->param("name", $form->field("name"));
  866. if (defined $form->field("do") &&
  867. $form->field("do") ne 'signin') {
  868. print $q->redirect(
  869. "$config{cgiurl}?do=".$form->field("do").
  870. "&page=".$form->field("page").
  871. "&from=".$form->field("from"));;
  872. }
  873. else {
  874. print $q->redirect($config{url});
  875. }
  876. }
  877. elsif ($form->submitted eq 'Register') {
  878. my $user_name=$form->field('name');
  879. if (userinfo_set($user_name, {
  880. 'email' => $form->field('email'),
  881. 'password' => $form->field('password'),
  882. 'regdate' => time
  883. })) {
  884. $form->field(name => "confirm_password", type => "hidden");
  885. $form->field(name => "email", type => "hidden");
  886. $form->text("Registration successful. Now you can Login.");
  887. print $session->header();
  888. print misctemplate($form->title, $form->render(submit => ["Login"]));
  889. }
  890. else {
  891. error("Error saving registration.");
  892. }
  893. }
  894. elsif ($form->submitted eq 'Mail Password') {
  895. my $user_name=$form->field("name");
  896. my $template=HTML::Template->new(
  897. filename => "$config{templatedir}/passwordmail.tmpl"
  898. );
  899. $template->param(
  900. user_name => $user_name,
  901. user_password => userinfo_get($user_name, "password"),
  902. wikiurl => $config{url},
  903. wikiname => $config{wikiname},
  904. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  905. );
  906. eval q{use Mail::Sendmail};
  907. my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
  908. sendmail(
  909. To => userinfo_get($user_name, "email"),
  910. From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
  911. Subject => "$config{wikiname} information",
  912. Message => $template->output,
  913. ) or error("Failed to send mail");
  914. $form->text("Your password has been emailed to you.");
  915. $form->field(name => "name", required => 0);
  916. print $session->header();
  917. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  918. }
  919. }
  920. else {
  921. print $session->header();
  922. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  923. }
  924. } #}}}
  925. sub cgi_editpage ($$) { #{{{
  926. my $q=shift;
  927. my $session=shift;
  928. eval q{use CGI::FormBuilder};
  929. my $form = CGI::FormBuilder->new(
  930. fields => [qw(do rcsinfo from page content comments)],
  931. header => 1,
  932. method => 'POST',
  933. validate => {
  934. content => '/.+/',
  935. },
  936. required => [qw{content}],
  937. javascript => 0,
  938. params => $q,
  939. action => $q->request_uri,
  940. table => 0,
  941. template => "$config{templatedir}/editpage.tmpl"
  942. );
  943. my @buttons=("Save Page", "Preview", "Cancel");
  944. my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
  945. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  946. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  947. error("bad page name");
  948. }
  949. $page=lc($page);
  950. my $file=$page.$config{default_pageext};
  951. my $newfile=1;
  952. if (exists $pagesources{lc($page)}) {
  953. $file=$pagesources{lc($page)};
  954. $newfile=0;
  955. }
  956. $form->field(name => "do", type => 'hidden');
  957. $form->field(name => "from", type => 'hidden');
  958. $form->field(name => "rcsinfo", type => 'hidden');
  959. $form->field(name => "page", value => "$page", force => 1);
  960. $form->field(name => "comments", type => "text", size => 80);
  961. $form->field(name => "content", type => "textarea", rows => 20,
  962. cols => 80);
  963. $form->tmpl_param("can_commit", $config{svn});
  964. $form->tmpl_param("indexlink", indexlink());
  965. $form->tmpl_param("helponformattinglink",
  966. htmllink("", "HelpOnFormatting", 1));
  967. if (! $form->submitted) {
  968. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  969. force => 1);
  970. }
  971. if ($form->submitted eq "Cancel") {
  972. print $q->redirect("$config{url}/".htmlpage($page));
  973. return;
  974. }
  975. elsif ($form->submitted eq "Preview") {
  976. $form->tmpl_param("page_preview",
  977. htmlize($config{default_pageext},
  978. linkify($form->field('content'), $page)));
  979. }
  980. else {
  981. $form->tmpl_param("page_preview", "");
  982. }
  983. $form->tmpl_param("page_conflict", "");
  984. if (! $form->submitted || $form->submitted eq "Preview" ||
  985. ! $form->validate) {
  986. if ($form->field("do") eq "create") {
  987. if (exists $pagesources{lc($page)}) {
  988. # hmm, someone else made the page in the
  989. # meantime?
  990. print $q->redirect("$config{url}/".htmlpage($page));
  991. return;
  992. }
  993. my @page_locs;
  994. my $best_loc;
  995. my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
  996. if (! defined $from || ! length $from ||
  997. $from ne $form->param('from') ||
  998. $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
  999. @page_locs=$best_loc=$page;
  1000. }
  1001. else {
  1002. my $dir=$from."/";
  1003. $dir=~s![^/]+/$!!;
  1004. if ($page eq 'discussion') {
  1005. $best_loc="$from/$page";
  1006. }
  1007. else {
  1008. $best_loc=$dir.$page;
  1009. }
  1010. push @page_locs, $dir.$page;
  1011. push @page_locs, "$from/$page";
  1012. while (length $dir) {
  1013. $dir=~s![^/]+/$!!;
  1014. push @page_locs, $dir.$page;
  1015. }
  1016. @page_locs = grep { ! exists
  1017. $pagesources{lc($_)} } @page_locs;
  1018. }
  1019. $form->tmpl_param("page_select", 1);
  1020. $form->field(name => "page", type => 'select',
  1021. options => \@page_locs, value => $best_loc);
  1022. $form->title("creating $page");
  1023. }
  1024. elsif ($form->field("do") eq "edit") {
  1025. if (! defined $form->field('content') ||
  1026. ! length $form->field('content')) {
  1027. my $content="";
  1028. if (exists $pagesources{lc($page)}) {
  1029. $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
  1030. $content=~s/\n/\r\n/g;
  1031. }
  1032. $form->field(name => "content", value => $content,
  1033. force => 1);
  1034. }
  1035. $form->tmpl_param("page_select", 0);
  1036. $form->field(name => "page", type => 'hidden');
  1037. $form->title("editing $page");
  1038. }
  1039. print $form->render(submit => \@buttons);
  1040. }
  1041. else {
  1042. # save page
  1043. my $content=$form->field('content');
  1044. $content=~s/\r\n/\n/g;
  1045. $content=~s/\r/\n/g;
  1046. writefile("$config{srcdir}/$file", $content);
  1047. my $message="web commit ";
  1048. if ($session->param("name")) {
  1049. $message.="by ".$session->param("name");
  1050. }
  1051. else {
  1052. $message.="from $ENV{REMOTE_ADDR}";
  1053. }
  1054. if (defined $form->field('comments') &&
  1055. length $form->field('comments')) {
  1056. $message.=": ".$form->field('comments');
  1057. }
  1058. if ($config{svn}) {
  1059. if ($newfile) {
  1060. rcs_add($file);
  1061. }
  1062. # prevent deadlock with post-commit hook
  1063. unlockwiki();
  1064. # presumably the commit will trigger an update
  1065. # of the wiki
  1066. my $conflict=rcs_commit($file, $message,
  1067. $form->field("rcsinfo"));
  1068. if (defined $conflict) {
  1069. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  1070. force => 1);
  1071. $form->tmpl_param("page_conflict", 1);
  1072. $form->field("content", value => $conflict, force => 1);
  1073. $form->field("do", "edit)");
  1074. $form->tmpl_param("page_select", 0);
  1075. $form->field(name => "page", type => 'hidden');
  1076. $form->title("editing $page");
  1077. print $form->render(submit => \@buttons);
  1078. return;
  1079. }
  1080. }
  1081. else {
  1082. loadindex();
  1083. refresh();
  1084. saveindex();
  1085. }
  1086. # The trailing question mark tries to avoid broken
  1087. # caches and get the most recent version of the page.
  1088. print $q->redirect("$config{url}/".htmlpage($page)."?updated");
  1089. }
  1090. } #}}}
  1091. sub cgi () { #{{{
  1092. eval q{use CGI};
  1093. eval q{use CGI::Session};
  1094. my $q=CGI->new;
  1095. my $do=$q->param('do');
  1096. if (! defined $do || ! length $do) {
  1097. error("\"do\" parameter missing");
  1098. }
  1099. # This does not need a session.
  1100. if ($do eq 'recentchanges') {
  1101. cgi_recentchanges($q);
  1102. return;
  1103. }
  1104. CGI::Session->name("ikiwiki_session");
  1105. my $oldmask=umask(077);
  1106. my $session = CGI::Session->new("driver:db_file", $q,
  1107. { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
  1108. umask($oldmask);
  1109. # Everything below this point needs the user to be signed in.
  1110. if ((! $config{anonok} && ! defined $session->param("name") ||
  1111. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  1112. cgi_signin($q, $session);
  1113. # Force session flush with safe umask.
  1114. my $oldmask=umask(077);
  1115. $session->flush;
  1116. umask($oldmask);
  1117. return;
  1118. }
  1119. if ($do eq 'create' || $do eq 'edit') {
  1120. cgi_editpage($q, $session);
  1121. }
  1122. else {
  1123. error("unknown do parameter");
  1124. }
  1125. } #}}}
  1126. sub setup () { # {{{
  1127. my $setup=possibly_foolish_untaint($config{setup});
  1128. delete $config{setup};
  1129. open (IN, $setup) || error("read $setup: $!\n");
  1130. local $/=undef;
  1131. my $code=<IN>;
  1132. ($code)=$code=~/(.*)/s;
  1133. close IN;
  1134. eval $code;
  1135. error($@) if $@;
  1136. exit;
  1137. } #}}}
  1138. # main {{{
  1139. setup() if $config{setup};
  1140. lockwiki();
  1141. if ($config{wrapper}) {
  1142. gen_wrapper(%config);
  1143. exit;
  1144. }
  1145. memoize('pagename');
  1146. memoize('bestlink');
  1147. loadindex() unless $config{rebuild};
  1148. if ($config{cgi}) {
  1149. cgi();
  1150. }
  1151. else {
  1152. rcs_update() if $config{svn};
  1153. refresh();
  1154. saveindex();
  1155. }
  1156. #}}}