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