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