summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: 72b4ab77192cb4248739e1cadbc9775cdb03256c (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. }
  66. die @_;
  67. } #}}}
  68. sub debug ($) { #{{{
  69. return unless $config{verbose};
  70. if (! $config{cgi}) {
  71. print "@_\n";
  72. }
  73. else {
  74. print STDERR "@_\n";
  75. }
  76. } #}}}
  77. sub mtime ($) { #{{{
  78. my $page=shift;
  79. return (stat($page))[9];
  80. } #}}}
  81. sub possibly_foolish_untaint { #{{{
  82. my $tainted=shift;
  83. my ($untainted)=$tainted=~/(.*)/;
  84. return $untainted;
  85. } #}}}
  86. sub basename ($) { #{{{
  87. my $file=shift;
  88. $file=~s!.*/!!;
  89. return $file;
  90. } #}}}
  91. sub dirname ($) { #{{{
  92. my $file=shift;
  93. $file=~s!/?[^/]+$!!;
  94. return $file;
  95. } #}}}
  96. sub pagetype ($) { #{{{
  97. my $page=shift;
  98. if ($page =~ /\.mdwn$/) {
  99. return ".mdwn";
  100. }
  101. else {
  102. return "unknown";
  103. }
  104. } #}}}
  105. sub pagename ($) { #{{{
  106. my $file=shift;
  107. my $type=pagetype($file);
  108. my $page=$file;
  109. $page=~s/\Q$type\E*$// unless $type eq 'unknown';
  110. return $page;
  111. } #}}}
  112. sub htmlpage ($) { #{{{
  113. my $page=shift;
  114. return $page.".html";
  115. } #}}}
  116. sub readfile ($) { #{{{
  117. my $file=shift;
  118. local $/=undef;
  119. open (IN, "$file") || error("failed to read $file: $!");
  120. my $ret=<IN>;
  121. close IN;
  122. return $ret;
  123. } #}}}
  124. sub writefile ($$) { #{{{
  125. my $file=shift;
  126. my $content=shift;
  127. my $dir=dirname($file);
  128. if (! -d $dir) {
  129. my $d="";
  130. foreach my $s (split(m!/+!, $dir)) {
  131. $d.="$s/";
  132. if (! -d $d) {
  133. mkdir($d) || error("failed to create directory $d: $!");
  134. }
  135. }
  136. }
  137. open (OUT, ">$file") || error("failed to write $file: $!");
  138. print OUT $content;
  139. close OUT;
  140. } #}}}
  141. sub findlinks ($$) { #{{{
  142. my $content=shift;
  143. my $page=shift;
  144. my @links;
  145. while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
  146. push @links, lc($1);
  147. }
  148. # Discussion links are a special case since they're not in the text
  149. # of the page, but on its template.
  150. return @links, "$page/discussion";
  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 $forcesubpage=shift; # force a link to a subpage
  182. my $bestlink;
  183. if (! $forcesubpage) {
  184. $bestlink=bestlink($page, $link);
  185. }
  186. else {
  187. $bestlink="$page/".lc($link);
  188. }
  189. return $link if length $bestlink && $page eq $bestlink;
  190. # TODO BUG: %renderedfiles may not have it, if the linked to page
  191. # was also added and isn't yet rendered! Note that this bug is
  192. # masked by the bug mentioned below that makes all new files
  193. # be rendered twice.
  194. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  195. $bestlink=htmlpage($bestlink);
  196. }
  197. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  198. return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
  199. }
  200. $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
  201. if (! $noimageinline && isinlinableimage($bestlink)) {
  202. return "<img src=\"$bestlink\">";
  203. }
  204. return "<a href=\"$bestlink\">$link</a>";
  205. } #}}}
  206. sub linkify ($$) { #{{{
  207. my $content=shift;
  208. my $file=shift;
  209. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  210. $1 ? "[[$2]]" : htmllink(pagename($file), $2)
  211. }eg;
  212. return $content;
  213. } #}}}
  214. sub htmlize ($$) { #{{{
  215. my $type=shift;
  216. my $content=shift;
  217. if (! $INC{"/usr/bin/markdown"}) {
  218. no warnings 'once';
  219. $blosxom::version="is a proper perl module too much to ask?";
  220. use warnings 'all';
  221. do "/usr/bin/markdown";
  222. }
  223. if ($type eq '.mdwn') {
  224. return Markdown::Markdown($content);
  225. }
  226. else {
  227. error("htmlization of $type not supported");
  228. }
  229. } #}}}
  230. sub backlinks ($) { #{{{
  231. my $page=shift;
  232. my @links;
  233. foreach my $p (keys %links) {
  234. next if bestlink($page, $p) eq $page;
  235. if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
  236. my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
  237. # Trim common dir prefixes from both pages.
  238. my $p_trimmed=$p;
  239. my $page_trimmed=$page;
  240. my $dir;
  241. 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
  242. defined $dir &&
  243. $p_trimmed=~s/^\Q$dir\E// &&
  244. $page_trimmed=~s/^\Q$dir\E//;
  245. push @links, { url => $href, page => $p_trimmed };
  246. }
  247. }
  248. return sort { $a->{page} cmp $b->{page} } @links;
  249. } #}}}
  250. sub parentlinks ($) { #{{{
  251. my $page=shift;
  252. my @ret;
  253. my $pagelink="";
  254. my $path="";
  255. my $skip=1;
  256. foreach my $dir (reverse split("/", $page)) {
  257. if (! $skip) {
  258. $path.="../";
  259. unshift @ret, { url => "$path$dir.html", page => $dir };
  260. }
  261. else {
  262. $skip=0;
  263. }
  264. }
  265. unshift @ret, { url => length $path ? $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 already exists and was rendered from ".
  306. join(" ",(grep { $renderedfiles{$_} eq $dest } keys
  307. %renderedfiles)).
  308. ", before, so not rendering from $src");
  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, $page)];
  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 (map { bestlink($page, $_) } @{$links{$page}}) {
  549. if (length $link &&
  550. ! exists $oldlinks{$page} ||
  551. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  552. $linkchanged{$link}=1;
  553. }
  554. }
  555. }
  556. if (exists $oldlinks{$page}) {
  557. foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
  558. if (length $link &&
  559. ! exists $links{$page} ||
  560. ! grep { $_ eq $link } @{$links{$page}}) {
  561. $linkchanged{$link}=1;
  562. }
  563. }
  564. }
  565. }
  566. foreach my $link (keys %linkchanged) {
  567. my $linkfile=$pagesources{$link};
  568. if (defined $linkfile) {
  569. debug("rendering $linkfile, to update its backlinks");
  570. render($linkfile);
  571. }
  572. }
  573. }
  574. } #}}}
  575. sub gen_wrapper (@) { #{{{
  576. my %config=(@_);
  577. eval q{use Cwd 'abs_path'};
  578. $config{srcdir}=abs_path($config{srcdir});
  579. $config{destdir}=abs_path($config{destdir});
  580. my $this=abs_path($0);
  581. if (! -x $this) {
  582. error("$this doesn't seem to be executable");
  583. }
  584. if ($config{setup}) {
  585. error("cannot create a wrapper that uses a setup file");
  586. }
  587. my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
  588. "--wikiname=$config{wikiname}");
  589. push @params, "--verbose" if $config{verbose};
  590. push @params, "--rebuild" if $config{rebuild};
  591. push @params, "--nosvn" if !$config{svn};
  592. push @params, "--cgi" if $config{cgi};
  593. push @params, "--url=$config{url}" if length $config{url};
  594. push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
  595. push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
  596. push @params, "--anonok" if $config{anonok};
  597. my $params=join(" ", @params);
  598. my $call='';
  599. foreach my $p ($this, $this, @params) {
  600. $call.=qq{"$p", };
  601. }
  602. $call.="NULL";
  603. my @envsave;
  604. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  605. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  606. HTTP_COOKIE} if $config{cgi};
  607. my $envsave="";
  608. foreach my $var (@envsave) {
  609. $envsave.=<<"EOF"
  610. if ((s=getenv("$var")))
  611. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  612. EOF
  613. }
  614. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  615. print OUT <<"EOF";
  616. /* A wrapper for ikiwiki, can be safely made suid. */
  617. #define _GNU_SOURCE
  618. #include <stdio.h>
  619. #include <unistd.h>
  620. #include <stdlib.h>
  621. #include <string.h>
  622. extern char **environ;
  623. int main (int argc, char **argv) {
  624. /* Sanitize environment. */
  625. char *s;
  626. char *newenviron[$#envsave+3];
  627. int i=0;
  628. $envsave
  629. newenviron[i++]="HOME=$ENV{HOME}";
  630. newenviron[i]=NULL;
  631. environ=newenviron;
  632. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  633. printf("$params\\n");
  634. exit(0);
  635. }
  636. execl($call);
  637. perror("failed to run $this");
  638. exit(1);
  639. }
  640. EOF
  641. close OUT;
  642. if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
  643. error("failed to compile ikiwiki-wrap.c");
  644. }
  645. unlink("ikiwiki-wrap.c");
  646. if (defined $config{wrappermode} &&
  647. ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
  648. error("chmod $config{wrapper}: $!");
  649. }
  650. print "successfully generated $config{wrapper}\n";
  651. } #}}}
  652. sub misctemplate ($$) { #{{{
  653. my $title=shift;
  654. my $pagebody=shift;
  655. my $template=HTML::Template->new(
  656. filename => "$config{templatedir}/misc.tmpl"
  657. );
  658. $template->param(
  659. title => $title,
  660. indexlink => indexlink(),
  661. wikiname => $config{wikiname},
  662. pagebody => $pagebody,
  663. );
  664. return $template->output;
  665. }#}}}
  666. sub cgi_recentchanges ($) { #{{{
  667. my $q=shift;
  668. my $template=HTML::Template->new(
  669. filename => "$config{templatedir}/recentchanges.tmpl"
  670. );
  671. $template->param(
  672. title => "RecentChanges",
  673. indexlink => indexlink(),
  674. wikiname => $config{wikiname},
  675. changelog => [rcs_recentchanges(100)],
  676. );
  677. print $q->header, $template->output;
  678. } #}}}
  679. sub userinfo_get ($$) { #{{{
  680. my $user=shift;
  681. my $field=shift;
  682. eval q{use Storable};
  683. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  684. if (! defined $userdata || ! ref $userdata ||
  685. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  686. return "";
  687. }
  688. return $userdata->{$user}->{$field};
  689. } #}}}
  690. sub userinfo_set ($$) { #{{{
  691. my $user=shift;
  692. my $info=shift;
  693. eval q{use Storable};
  694. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  695. if (! defined $userdata || ! ref $userdata) {
  696. $userdata={};
  697. }
  698. $userdata->{$user}=$info;
  699. my $oldmask=umask(077);
  700. my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
  701. umask($oldmask);
  702. return $ret;
  703. } #}}}
  704. sub cgi_signin ($$) { #{{{
  705. my $q=shift;
  706. my $session=shift;
  707. eval q{use CGI::FormBuilder};
  708. my $form = CGI::FormBuilder->new(
  709. title => "$config{wikiname} signin",
  710. fields => [qw(do page from name password confirm_password email)],
  711. header => 1,
  712. method => 'POST',
  713. validate => {
  714. confirm_password => {
  715. perl => q{eq $form->field("password")},
  716. },
  717. email => 'EMAIL',
  718. },
  719. required => 'NONE',
  720. javascript => 0,
  721. params => $q,
  722. action => $q->request_uri,
  723. header => 0,
  724. template => (-e "$config{templatedir}/signin.tmpl" ?
  725. "$config{templatedir}/signin.tmpl" : "")
  726. );
  727. $form->field(name => "name", required => 0);
  728. $form->field(name => "do", type => "hidden");
  729. $form->field(name => "page", type => "hidden");
  730. $form->field(name => "from", type => "hidden");
  731. $form->field(name => "password", type => "password", required => 0);
  732. $form->field(name => "confirm_password", type => "password", required => 0);
  733. $form->field(name => "email", required => 0);
  734. if ($q->param("do") ne "signin") {
  735. $form->text("You need to log in before you can edit pages.");
  736. }
  737. if ($form->submitted) {
  738. # Set required fields based on how form was submitted.
  739. my %required=(
  740. "Login" => [qw(name password)],
  741. "Register" => [qw(name password confirm_password email)],
  742. "Mail Password" => [qw(name)],
  743. );
  744. foreach my $opt (@{$required{$form->submitted}}) {
  745. $form->field(name => $opt, required => 1);
  746. }
  747. # Validate password differently depending on how
  748. # form was submitted.
  749. if ($form->submitted eq 'Login') {
  750. $form->field(
  751. name => "password",
  752. validate => sub {
  753. length $form->field("name") &&
  754. shift eq userinfo_get($form->field("name"), 'password');
  755. },
  756. );
  757. $form->field(name => "name", validate => '/^\w+$/');
  758. }
  759. else {
  760. $form->field(name => "password", validate => 'VALUE');
  761. }
  762. # And make sure the entered name exists when logging
  763. # in or sending email, and does not when registering.
  764. if ($form->submitted eq 'Register') {
  765. $form->field(
  766. name => "name",
  767. validate => sub {
  768. my $name=shift;
  769. length $name &&
  770. ! userinfo_get($name, "regdate");
  771. },
  772. );
  773. }
  774. else {
  775. $form->field(
  776. name => "name",
  777. validate => sub {
  778. my $name=shift;
  779. length $name &&
  780. userinfo_get($name, "regdate");
  781. },
  782. );
  783. }
  784. }
  785. else {
  786. # First time settings.
  787. $form->field(name => "name", comment => "use FirstnameLastName");
  788. $form->field(name => "confirm_password", comment => "(only needed");
  789. $form->field(name => "email", comment => "for registration)");
  790. if ($session->param("name")) {
  791. $form->field(name => "name", value => $session->param("name"));
  792. }
  793. }
  794. if ($form->submitted && $form->validate) {
  795. if ($form->submitted eq 'Login') {
  796. $session->param("name", $form->field("name"));
  797. if (defined $form->field("do") &&
  798. $form->field("do") ne 'signin') {
  799. print $q->redirect(
  800. "$config{cgiurl}?do=".$form->field("do").
  801. "&page=".$form->field("page").
  802. "&from=".$form->field("from"));;
  803. }
  804. else {
  805. print $q->redirect($config{url});
  806. }
  807. }
  808. elsif ($form->submitted eq 'Register') {
  809. my $user_name=$form->field('name');
  810. if (userinfo_set($user_name, {
  811. 'email' => $form->field('email'),
  812. 'password' => $form->field('password'),
  813. 'regdate' => time
  814. })) {
  815. $form->field(name => "confirm_password", type => "hidden");
  816. $form->field(name => "email", type => "hidden");
  817. $form->text("Registration successful. Now you can Login.");
  818. print $session->header();
  819. print misctemplate($form->title, $form->render(submit => ["Login"]));
  820. }
  821. else {
  822. error("Error saving registration.");
  823. }
  824. }
  825. elsif ($form->submitted eq 'Mail Password') {
  826. my $user_name=$form->field("name");
  827. my $template=HTML::Template->new(
  828. filename => "$config{templatedir}/passwordmail.tmpl"
  829. );
  830. $template->param(
  831. user_name => $user_name,
  832. user_password => userinfo_get($user_name, "password"),
  833. wikiurl => $config{url},
  834. wikiname => $config{wikiname},
  835. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  836. );
  837. eval q{use Mail::Sendmail};
  838. my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
  839. sendmail(
  840. To => userinfo_get($user_name, "email"),
  841. From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
  842. Subject => "$config{wikiname} information",
  843. Message => $template->output,
  844. ) or error("Failed to send mail");
  845. $form->text("Your password has been emailed to you.");
  846. $form->field(name => "name", required => 0);
  847. print $session->header();
  848. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  849. }
  850. }
  851. else {
  852. print $session->header();
  853. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  854. }
  855. } #}}}
  856. sub cgi_editpage ($$) { #{{{
  857. my $q=shift;
  858. my $session=shift;
  859. eval q{use CGI::FormBuilder};
  860. my $form = CGI::FormBuilder->new(
  861. fields => [qw(do from page content comments)],
  862. header => 1,
  863. method => 'POST',
  864. validate => {
  865. content => '/.+/',
  866. },
  867. required => [qw{content}],
  868. javascript => 0,
  869. params => $q,
  870. action => $q->request_uri,
  871. table => 0,
  872. template => "$config{templatedir}/editpage.tmpl"
  873. );
  874. my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
  875. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  876. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  877. error("bad page name");
  878. }
  879. $page=lc($page);
  880. $form->field(name => "do", type => 'hidden');
  881. $form->field(name => "from", type => 'hidden');
  882. $form->field(name => "page", value => "$page", force => 1);
  883. $form->field(name => "comments", type => "text", size => 80);
  884. $form->field(name => "content", type => "textarea", rows => 20,
  885. cols => 80);
  886. if ($form->submitted eq "Cancel") {
  887. print $q->redirect("$config{url}/".htmlpage($page));
  888. return;
  889. }
  890. if (! $form->submitted || ! $form->validate) {
  891. if ($form->field("do") eq "create") {
  892. if (exists $pagesources{lc($page)}) {
  893. # hmm, someone else made the page in the
  894. # meantime?
  895. print $q->redirect("$config{url}/".htmlpage($page));
  896. return;
  897. }
  898. my @page_locs;
  899. my $best_loc;
  900. my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
  901. if (! defined $from || ! length $from ||
  902. $from ne $form->param('from') ||
  903. $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
  904. @page_locs=$best_loc=$page;
  905. }
  906. else {
  907. my $dir=$from."/";
  908. $dir=~s![^/]+/$!!;
  909. push @page_locs, $dir.$page;
  910. push @page_locs, "$from/$page";
  911. $best_loc="$from/$page";
  912. while (length $dir) {
  913. $dir=~s![^/]+/$!!;
  914. push @page_locs, $dir.$page;
  915. }
  916. @page_locs = grep { ! exists
  917. $pagesources{lc($_)} } @page_locs;
  918. }
  919. $form->tmpl_param("page_select", 1);
  920. $form->field(name => "page", type => 'select',
  921. options => \@page_locs, value => $best_loc);
  922. $form->title("creating $page");
  923. }
  924. elsif ($form->field("do") eq "edit") {
  925. my $content="";
  926. if (exists $pagesources{lc($page)}) {
  927. $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
  928. $content=~s/\n/\r\n/g;
  929. }
  930. $form->tmpl_param("page_select", 0);
  931. $form->field(name => "content", value => $content,
  932. force => 1);
  933. $form->field(name => "page", type => 'hidden');
  934. $form->title("editing $page");
  935. }
  936. $form->tmpl_param("can_commit", $config{svn});
  937. $form->tmpl_param("indexlink", indexlink());
  938. print $form->render(submit => ["Save Page", "Cancel"]);
  939. }
  940. else {
  941. # save page
  942. my $file=$page.$config{default_pageext};
  943. my $newfile=1;
  944. if (exists $pagesources{lc($page)}) {
  945. $file=$pagesources{lc($page)};
  946. $newfile=0;
  947. }
  948. my $content=$form->field('content');
  949. $content=~s/\r\n/\n/g;
  950. $content=~s/\r/\n/g;
  951. writefile("$config{srcdir}/$file", $content);
  952. my $message="web commit ";
  953. if ($session->param("name")) {
  954. $message.="by ".$session->param("name");
  955. }
  956. else {
  957. $message.="from $ENV{REMOTE_ADDR}";
  958. }
  959. if (defined $form->field('comments') &&
  960. length $form->field('comments')) {
  961. $message.=": ".$form->field('comments');
  962. }
  963. if ($config{svn}) {
  964. if ($newfile) {
  965. rcs_add($file);
  966. }
  967. # presumably the commit will trigger an update
  968. # of the wiki
  969. rcs_commit($message);
  970. }
  971. else {
  972. loadindex();
  973. refresh();
  974. saveindex();
  975. }
  976. # The trailing question mark tries to avoid broken
  977. # caches and get the most recent version of the page.
  978. print $q->redirect("$config{url}/".htmlpage($page)."?updated");
  979. }
  980. } #}}}
  981. sub cgi () { #{{{
  982. eval q{use CGI};
  983. eval q{use CGI::Session};
  984. my $q=CGI->new;
  985. my $do=$q->param('do');
  986. if (! defined $do || ! length $do) {
  987. error("\"do\" parameter missing");
  988. }
  989. # This does not need a session.
  990. if ($do eq 'recentchanges') {
  991. cgi_recentchanges($q);
  992. return;
  993. }
  994. CGI::Session->name("ikiwiki_session");
  995. my $oldmask=umask(077);
  996. my $session = CGI::Session->new("driver:db_file", $q,
  997. { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
  998. umask($oldmask);
  999. # Everything below this point needs the user to be signed in.
  1000. if ((! $config{anonok} && ! defined $session->param("name") ||
  1001. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  1002. cgi_signin($q, $session);
  1003. # Force session flush with safe umask.
  1004. my $oldmask=umask(077);
  1005. $session->flush;
  1006. umask($oldmask);
  1007. return;
  1008. }
  1009. if ($do eq 'create' || $do eq 'edit') {
  1010. cgi_editpage($q, $session);
  1011. }
  1012. else {
  1013. error("unknown do parameter");
  1014. }
  1015. } #}}}
  1016. sub setup () { # {{{
  1017. my $setup=possibly_foolish_untaint($config{setup});
  1018. delete $config{setup};
  1019. open (IN, $setup) || error("read $setup: $!\n");
  1020. local $/=undef;
  1021. my $code=<IN>;
  1022. ($code)=$code=~/(.*)/s;
  1023. close IN;
  1024. my (%setup);
  1025. eval $code;
  1026. error($@) if $@;
  1027. gen_wrapper(%config, %setup, %{$setup{cgiwrapper}}) if $setup{cgiwrapper};
  1028. gen_wrapper(%config, %setup, %{$setup{svnwrapper}}) if $setup{svnwrapper};
  1029. print "$setup{wikiname} setup complete, now forcing a rebuild\n";
  1030. foreach my $c (keys %setup) {
  1031. $config{$c}=possibly_foolish_untaint($setup{$c})
  1032. if defined $setup{$c} && ! ref $setup{$c};
  1033. }
  1034. $config{rebuild}=1;
  1035. refresh();
  1036. saveindex();
  1037. exit;
  1038. } #}}}
  1039. # main {{{
  1040. setup() if $config{setup};
  1041. if ($config{wrapper}) {
  1042. gen_wrapper(%config);
  1043. exit;
  1044. }
  1045. memoize('pagename');
  1046. memoize('bestlink');
  1047. loadindex() unless $config{rebuild};
  1048. if ($config{cgi}) {
  1049. cgi();
  1050. }
  1051. else {
  1052. rcs_update() if $config{svn};
  1053. refresh();
  1054. saveindex();
  1055. }
  1056. #}}}