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