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