summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: 67004e413168f9eb417c5229318fc8e6ed1e4778 (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. push @ret, { rev => $rev, user => $user,
  372. when => $when, message => [@message],
  373. pages => [@pages] } if @pages;
  374. return @ret if @ret >= $num;
  375. $state='header';
  376. $rev=$user=$when=undef;
  377. @pages=@message=();
  378. }
  379. elsif ($state eq 'body') {
  380. push @message, {line => $_},
  381. }
  382. }
  383. }
  384. return @ret;
  385. } #}}}
  386. sub prune ($) { #{{{
  387. my $file=shift;
  388. unlink($file);
  389. my $dir=dirname($file);
  390. while (rmdir($dir)) {
  391. $dir=dirname($dir);
  392. }
  393. } #}}}
  394. sub refresh () { #{{{
  395. # Find existing pages.
  396. my %exists;
  397. my @files;
  398. find({
  399. no_chdir => 1,
  400. wanted => sub {
  401. if (/$wiki_file_prune_regexp/) {
  402. $File::Find::prune=1;
  403. }
  404. elsif (! -d $_) {
  405. my ($f)=/$wiki_file_regexp/; # untaint
  406. if (! defined $f) {
  407. warn("skipping bad filename $_\n");
  408. }
  409. else {
  410. $f=~s/^\Q$srcdir\E\/?//;
  411. push @files, $f;
  412. $exists{pagename($f)}=1;
  413. }
  414. }
  415. },
  416. }, $srcdir);
  417. my %rendered;
  418. # check for added or removed pages
  419. my @add;
  420. foreach my $file (@files) {
  421. my $page=pagename($file);
  422. if (! $oldpagemtime{$page}) {
  423. debug("new page $page");
  424. push @add, $file;
  425. $links{$page}=[];
  426. $pagesources{$page}=$file;
  427. }
  428. }
  429. my @del;
  430. foreach my $page (keys %oldpagemtime) {
  431. if (! $exists{$page}) {
  432. debug("removing old page $page");
  433. push @del, $renderedfiles{$page};
  434. prune($destdir."/".$renderedfiles{$page});
  435. delete $renderedfiles{$page};
  436. $oldpagemtime{$page}=0;
  437. delete $pagesources{$page};
  438. }
  439. }
  440. # render any updated files
  441. foreach my $file (@files) {
  442. my $page=pagename($file);
  443. if (! exists $oldpagemtime{$page} ||
  444. mtime("$srcdir/$file") > $oldpagemtime{$page}) {
  445. debug("rendering changed file $file");
  446. render($file);
  447. $rendered{$file}=1;
  448. }
  449. }
  450. # if any files were added or removed, check to see if each page
  451. # needs an update due to linking to them
  452. # TODO: inefficient; pages may get rendered above and again here;
  453. # problem is the bestlink may have changed and we won't know until
  454. # now
  455. if (@add || @del) {
  456. FILE: foreach my $file (@files) {
  457. my $page=pagename($file);
  458. foreach my $f (@add, @del) {
  459. my $p=pagename($f);
  460. foreach my $link (@{$links{$page}}) {
  461. if (bestlink($page, $link) eq $p) {
  462. debug("rendering $file, which links to $p");
  463. render($file);
  464. $rendered{$file}=1;
  465. next FILE;
  466. }
  467. }
  468. }
  469. }
  470. }
  471. # handle backlinks; if a page has added/removed links, update the
  472. # pages it links to
  473. # TODO: inefficient; pages may get rendered above and again here;
  474. # problem is the backlinks could be wrong in the first pass render
  475. # above
  476. if (%rendered) {
  477. my %linkchanged;
  478. foreach my $file (keys %rendered, @del) {
  479. my $page=pagename($file);
  480. if (exists $links{$page}) {
  481. foreach my $link (@{$links{$page}}) {
  482. $link=bestlink($page, $link);
  483. if (length $link &&
  484. ! exists $oldlinks{$page} ||
  485. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  486. $linkchanged{$link}=1;
  487. }
  488. }
  489. }
  490. if (exists $oldlinks{$page}) {
  491. foreach my $link (@{$oldlinks{$page}}) {
  492. $link=bestlink($page, $link);
  493. if (length $link &&
  494. ! exists $links{$page} ||
  495. ! grep { $_ eq $link } @{$links{$page}}) {
  496. $linkchanged{$link}=1;
  497. }
  498. }
  499. }
  500. }
  501. foreach my $link (keys %linkchanged) {
  502. my $linkfile=$pagesources{$link};
  503. if (defined $linkfile) {
  504. debug("rendering $linkfile, to update its backlinks");
  505. render($linkfile);
  506. }
  507. }
  508. }
  509. } #}}}
  510. # Generates a C wrapper program for running ikiwiki in a specific way.
  511. # The wrapper may be safely made suid.
  512. sub gen_wrapper ($$) { #{{{
  513. my ($svn, $rebuild)=@_;
  514. eval q{use Cwd 'abs_path'};
  515. $srcdir=abs_path($srcdir);
  516. $destdir=abs_path($destdir);
  517. my $this=abs_path($0);
  518. if (! -x $this) {
  519. error("$this doesn't seem to be executable");
  520. }
  521. my @params=($srcdir, $templatedir, $destdir, "--wikiname=$wikiname");
  522. push @params, "--verbose" if $verbose;
  523. push @params, "--rebuild" if $rebuild;
  524. push @params, "--nosvn" if !$svn;
  525. push @params, "--cgi" if $cgi;
  526. push @params, "--url=$url" if $url;
  527. push @params, "--cgiurl=$cgiurl" if $cgiurl;
  528. push @params, "--historyurl=$historyurl" if $historyurl;
  529. push @params, "--anonok" if $anonok;
  530. my $params=join(" ", @params);
  531. my $call='';
  532. foreach my $p ($this, $this, @params) {
  533. $call.=qq{"$p", };
  534. }
  535. $call.="NULL";
  536. my @envsave;
  537. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  538. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  539. HTTP_COOKIE} if $cgi;
  540. my $envsave="";
  541. foreach my $var (@envsave) {
  542. $envsave.=<<"EOF"
  543. if ((s=getenv("$var")))
  544. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  545. EOF
  546. }
  547. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  548. print OUT <<"EOF";
  549. /* A wrapper for ikiwiki, can be safely made suid. */
  550. #define _GNU_SOURCE
  551. #include <stdio.h>
  552. #include <unistd.h>
  553. #include <stdlib.h>
  554. #include <string.h>
  555. extern char **environ;
  556. int main (int argc, char **argv) {
  557. /* Sanitize environment. */
  558. char *s;
  559. char *newenviron[$#envsave+3];
  560. int i=0;
  561. $envsave
  562. newenviron[i++]="HOME=$ENV{HOME}";
  563. newenviron[i]=NULL;
  564. environ=newenviron;
  565. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  566. printf("$params\\n");
  567. exit(0);
  568. }
  569. execl($call);
  570. perror("failed to run $this");
  571. exit(1);
  572. }
  573. EOF
  574. close OUT;
  575. if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
  576. error("failed to compile ikiwiki-wrap.c");
  577. }
  578. unlink("ikiwiki-wrap.c");
  579. print "successfully generated ikiwiki-wrap\n";
  580. exit 0;
  581. } #}}}
  582. sub misctemplate ($$) { #{{{
  583. my $title=shift;
  584. my $pagebody=shift;
  585. my $template=HTML::Template->new(
  586. filename => "$templatedir/misc.tmpl"
  587. );
  588. $template->param(
  589. title => $title,
  590. indexlink => indexlink(),
  591. wikiname => $wikiname,
  592. pagebody => $pagebody,
  593. );
  594. return $template->output;
  595. }#}}}
  596. sub cgi_recentchanges ($) { #{{{
  597. my $q=shift;
  598. my $template=HTML::Template->new(
  599. filename => "$templatedir/recentchanges.tmpl"
  600. );
  601. $template->param(
  602. title => "RecentChanges",
  603. indexlink => indexlink(),
  604. wikiname => $wikiname,
  605. changelog => [rcs_recentchanges(100)],
  606. );
  607. print $q->header, $template->output;
  608. } #}}}
  609. sub userinfo_get ($$) { #{{
  610. my $user=shift;
  611. my $field=shift;
  612. eval q{use Storable};
  613. my $userdata=eval{ Storable::lock_retrieve("$srcdir/.ikiwiki/userdb") };
  614. if (! defined $userdata || ! ref $userdata ||
  615. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  616. return "";
  617. }
  618. return $userdata->{$user}->{$field};
  619. } #}}
  620. sub userinfo_set ($$) { #{{
  621. my $user=shift;
  622. my $info=shift;
  623. eval q{use Storable};
  624. my $userdata=eval{ Storable::lock_retrieve("$srcdir/.ikiwiki/userdb") };
  625. if (! defined $userdata || ! ref $userdata) {
  626. $userdata={};
  627. }
  628. $userdata->{$user}=$info;
  629. my $oldmask=umask(077);
  630. my $ret=Storable::lock_store($userdata, "$srcdir/.ikiwiki/userdb");
  631. umask($oldmask);
  632. return $ret;
  633. } #}}
  634. sub cgi_signin ($$) { #{{{
  635. my $q=shift;
  636. my $session=shift;
  637. eval q{use CGI::FormBuilder};
  638. my $form = CGI::FormBuilder->new(
  639. title => "$wikiname signin",
  640. fields => [qw(do page name password confirm_password email)],
  641. header => 1,
  642. method => 'POST',
  643. validate => {
  644. confirm_password => {
  645. perl => q{eq $form->field("password")},
  646. },
  647. email => 'EMAIL',
  648. },
  649. required => 'NONE',
  650. javascript => 0,
  651. params => $q,
  652. action => $q->request_uri,
  653. header => 0,
  654. template => (-e "$templatedir/signin.tmpl" ? "$templatedir/signin.tmpl" : "")
  655. );
  656. $form->field(name => "name", required => 0);
  657. $form->field(name => "do", type => "hidden");
  658. $form->field(name => "page", type => "hidden");
  659. $form->field(name => "password", type => "password", required => 0);
  660. $form->field(name => "confirm_password", type => "password", required => 0);
  661. $form->field(name => "email", required => 0);
  662. if ($q->param("do") ne "signin") {
  663. $form->text("You need to log in before you can edit pages.");
  664. }
  665. if ($form->submitted) {
  666. # Set required fields based on how form was submitted.
  667. my %required=(
  668. "Login" => [qw(name password)],
  669. "Register" => [qw(name password confirm_password email)],
  670. "Mail Password" => [qw(name)],
  671. );
  672. foreach my $opt (@{$required{$form->submitted}}) {
  673. $form->field(name => $opt, required => 1);
  674. }
  675. # Validate password differently depending on how
  676. # form was submitted.
  677. if ($form->submitted eq 'Login') {
  678. $form->field(
  679. name => "password",
  680. validate => sub {
  681. length $form->field("name") &&
  682. shift eq userinfo_get($form->field("name"), 'password');
  683. },
  684. );
  685. $form->field(name => "name", validate => '/^\w+$/');
  686. }
  687. else {
  688. $form->field(name => "password", validate => 'VALUE');
  689. }
  690. # And make sure the entered name exists when logging
  691. # in or sending email, and does not when registering.
  692. if ($form->submitted eq 'Register') {
  693. $form->field(
  694. name => "name",
  695. validate => sub {
  696. my $name=shift;
  697. length $name &&
  698. ! userinfo_get($name, "regdate");
  699. },
  700. );
  701. }
  702. else {
  703. $form->field(
  704. name => "name",
  705. validate => sub {
  706. my $name=shift;
  707. length $name &&
  708. userinfo_get($name, "regdate");
  709. },
  710. );
  711. }
  712. }
  713. else {
  714. # First time settings.
  715. $form->field(name => "name", comment => "use FirstnameLastName");
  716. $form->field(name => "confirm_password", comment => "(only needed");
  717. $form->field(name => "email", comment => "for registration)");
  718. if ($session->param("name")) {
  719. $form->field(name => "name", value => $session->param("name"));
  720. }
  721. }
  722. if ($form->submitted && $form->validate) {
  723. if ($form->submitted eq 'Login') {
  724. $session->param("name", $form->field("name"));
  725. if (defined $form->field("do") &&
  726. $form->field("do") ne 'signin') {
  727. print $q->redirect(
  728. "$cgiurl?do=".$form->field("do").
  729. "&page=".$form->field("page"));
  730. }
  731. else {
  732. print $q->redirect($url);
  733. }
  734. }
  735. elsif ($form->submitted eq 'Register') {
  736. my $user_name=$form->field('name');
  737. if (userinfo_set($user_name, {
  738. 'email' => $form->field('email'),
  739. 'password' => $form->field('password'),
  740. 'regdate' => time
  741. })) {
  742. $form->field(name => "confirm_password", type => "hidden");
  743. $form->field(name => "email", type => "hidden");
  744. $form->text("Registration successful. Now you can Login.");
  745. print $session->header();
  746. print misctemplate($form->title, $form->render(submit => ["Login"]));
  747. }
  748. else {
  749. error("Error saving registration.");
  750. }
  751. }
  752. elsif ($form->submitted eq 'Mail Password') {
  753. my $user_name=$form->field("name");
  754. my $template=HTML::Template->new(
  755. filename => "$templatedir/passwordmail.tmpl"
  756. );
  757. $template->param(
  758. user_name => $user_name,
  759. user_password => userinfo_get($user_name, "password"),
  760. wikiurl => $url,
  761. wikiname => $wikiname,
  762. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  763. );
  764. eval q{use Mail::Sendmail};
  765. my ($fromhost) = $cgiurl =~ m!/([^/]+)!;
  766. print STDERR "$< $> >>> $cgiurl ".(getpwuid($>))[0]."@".$fromhost."\n";
  767. sendmail(
  768. To => userinfo_get($user_name, "email"),
  769. From => "$wikiname admin <".(getpwuid($>))[0]."@".$fromhost.">",
  770. Subject => "$wikiname information",
  771. Message => $template->output,
  772. ) or error("Failed to send mail");
  773. $form->text("Your password has been emailed to you.");
  774. $form->field(name => "name", required => 0);
  775. print $session->header();
  776. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  777. }
  778. }
  779. else {
  780. print $session->header();
  781. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  782. }
  783. } #}}}
  784. sub cgi_editpage ($$) { #{{{
  785. my $q=shift;
  786. my $session=shift;
  787. eval q{use CGI::FormBuilder};
  788. my $form = CGI::FormBuilder->new(
  789. fields => [qw(do from page content comments)],
  790. header => 1,
  791. method => 'POST',
  792. validate => {},
  793. required => [qw{}],
  794. javascript => 0,
  795. params => $q,
  796. action => $q->request_uri,
  797. table => 0,
  798. template => "$templatedir/editpage.tmpl"
  799. );
  800. my ($page)=$form->param('page')=~/$wiki_file_regexp/;
  801. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  802. $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
  803. error("bad page name");
  804. }
  805. $page=lc($page);
  806. $form->field(name => "do", type => 'hidden');
  807. $form->field(name => "from", type => 'hidden');
  808. $form->field(name => "page", value => "$page", force => 1);
  809. $form->field(name => "comments", type => "text", size => 80);
  810. $form->field(name => "content", type => "textarea", rows => 20,
  811. cols => 80);
  812. if (! $form->submitted || ! $form->validate) {
  813. if ($form->field("do") eq "create") {
  814. if (exists $pagesources{lc($page)}) {
  815. # hmm, someone else made the page in the
  816. # meantime?
  817. print $q->redirect("$url/".htmlpage($page));
  818. return;
  819. }
  820. my @page_locs;
  821. my ($from)=$form->param('from')=~/$wiki_file_regexp/;
  822. if (! defined $from || ! length $from ||
  823. $from ne $form->param('from') ||
  824. $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
  825. @page_locs=$page;
  826. }
  827. else {
  828. my $dir=$from."/";
  829. $dir=~s![^/]+/$!!;
  830. push @page_locs, $dir.$page;
  831. push @page_locs, "$from/$page";
  832. while (length $dir) {
  833. $dir=~s![^/]+/$!!;
  834. push @page_locs, $dir.$page;
  835. }
  836. }
  837. $form->tmpl_param("page_select", 1);
  838. $form->field(name => "page", type => 'select',
  839. options => \@page_locs);
  840. $form->title("creating $page");
  841. }
  842. elsif ($form->field("do") eq "edit") {
  843. my $content="";
  844. if (exists $pagesources{lc($page)}) {
  845. $content=readfile("$srcdir/$pagesources{lc($page)}");
  846. $content=~s/\n/\r\n/g;
  847. }
  848. $form->tmpl_param("page_select", 0);
  849. $form->field(name => "content", value => $content,
  850. force => 1);
  851. $form->field(name => "page", type => 'hidden');
  852. $form->title("editing $page");
  853. }
  854. $form->tmpl_param("can_commit", $svn);
  855. $form->tmpl_param("indexlink", indexlink());
  856. print $form->render(submit => ["Save Page"]);
  857. }
  858. else {
  859. # save page
  860. my $file=$page.$default_pagetype;
  861. my $newfile=1;
  862. if (exists $pagesources{lc($page)}) {
  863. $file=$pagesources{lc($page)};
  864. $newfile=0;
  865. }
  866. my $content=$form->field('content');
  867. $content=~s/\r\n/\n/g;
  868. $content=~s/\r/\n/g;
  869. writefile("$srcdir/$file", $content);
  870. my $message="web commit ";
  871. if ($session->param("name")) {
  872. $message.="by ".$session->param("name");
  873. }
  874. else {
  875. $message.="from $ENV{REMOTE_ADDR}";
  876. }
  877. if (defined $form->field('comments') &&
  878. length $form->field('comments')) {
  879. $message.=": ".$form->field('comments');
  880. }
  881. if ($svn) {
  882. if ($newfile) {
  883. rcs_add($file);
  884. }
  885. # presumably the commit will trigger an update
  886. # of the wiki
  887. rcs_commit($message);
  888. }
  889. else {
  890. refresh();
  891. }
  892. print $q->redirect("$url/".htmlpage($page));
  893. }
  894. } #}}}
  895. sub cgi () { #{{{
  896. eval q{use CGI};
  897. eval q{use CGI::Session};
  898. my $q=CGI->new;
  899. my $do=$q->param('do');
  900. if (! defined $do || ! length $do) {
  901. error("\"do\" parameter missing");
  902. }
  903. # This does not need a session.
  904. if ($do eq 'recentchanges') {
  905. cgi_recentchanges($q);
  906. return;
  907. }
  908. CGI::Session->name("ikiwiki_session");
  909. my $oldmask=umask(077);
  910. my $session = CGI::Session->new("driver:db_file", $q,
  911. { FileName => "$srcdir/.ikiwiki/sessions.db" });
  912. umask($oldmask);
  913. # Everything below this point needs the user to be signed in.
  914. if ((! $anonok && ! defined $session->param("name") ||
  915. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  916. cgi_signin($q, $session);
  917. # Force session flush with safe umask.
  918. my $oldmask=umask(077);
  919. $session->flush;
  920. umask($oldmask);
  921. return;
  922. }
  923. if ($do eq 'create' || $do eq 'edit') {
  924. cgi_editpage($q, $session);
  925. }
  926. else {
  927. error("unknown do parameter");
  928. }
  929. } #}}}
  930. # main {{{
  931. my $rebuild=0;
  932. my $wrapper=0;
  933. if (grep /^-/, @ARGV) {
  934. eval {use Getopt::Long};
  935. GetOptions(
  936. "wikiname=s" => \$wikiname,
  937. "verbose|v" => \$verbose,
  938. "rebuild" => \$rebuild,
  939. "wrapper" => \$wrapper,
  940. "svn!" => \$svn,
  941. "anonok!" => \$anonok,
  942. "cgi" => \$cgi,
  943. "url=s" => \$url,
  944. "cgiurl=s" => \$cgiurl,
  945. "historyurl=s" => \$historyurl,
  946. ) || usage();
  947. }
  948. usage() unless @ARGV == 3;
  949. ($srcdir) = possibly_foolish_untaint(shift);
  950. ($templatedir) = possibly_foolish_untaint(shift);
  951. ($destdir) = possibly_foolish_untaint(shift);
  952. if ($cgi && ! length $url) {
  953. error("Must specify url to wiki with --url when using --cgi");
  954. }
  955. gen_wrapper($svn, $rebuild) if $wrapper;
  956. memoize('pagename');
  957. memoize('bestlink');
  958. loadindex() unless $rebuild;
  959. if ($cgi) {
  960. cgi();
  961. }
  962. else {
  963. rcs_update() if $svn;
  964. refresh();
  965. saveindex();
  966. }
  967. #}}}