summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: db0056aa4dcad553704468fe90aac778534a647a (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 unlockwiki () { #{{{
  354. close WIKILOCK;
  355. } #}}}
  356. sub loadindex () { #{{{
  357. open (IN, "$config{srcdir}/.ikiwiki/index") || return;
  358. while (<IN>) {
  359. $_=possibly_foolish_untaint($_);
  360. chomp;
  361. my ($mtime, $file, $rendered, @links)=split(' ', $_);
  362. my $page=pagename($file);
  363. $pagesources{$page}=$file;
  364. $oldpagemtime{$page}=$mtime;
  365. $oldlinks{$page}=[@links];
  366. $links{$page}=[@links];
  367. $renderedfiles{$page}=$rendered;
  368. }
  369. close IN;
  370. } #}}}
  371. sub saveindex () { #{{{
  372. if (! -d "$config{srcdir}/.ikiwiki") {
  373. mkdir("$config{srcdir}/.ikiwiki");
  374. }
  375. open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
  376. foreach my $page (keys %oldpagemtime) {
  377. print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
  378. join(" ", @{$links{$page}})."\n"
  379. if $oldpagemtime{$page};
  380. }
  381. close OUT;
  382. } #}}}
  383. sub rcs_update () { #{{{
  384. if (-d "$config{srcdir}/.svn") {
  385. if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
  386. warn("svn update failed\n");
  387. }
  388. }
  389. } #}}}
  390. sub rcs_commit ($$) { #{{{
  391. # Tries to commit the page; returns undef on _success_ and
  392. # a version of the page with the rcs's conflict markers on failure.
  393. # The file is relative to the srcdir.
  394. my $message=shift;
  395. my $file=shift;
  396. if (-d "$config{srcdir}/.svn") {
  397. # svn up to let svn merge in other changes
  398. if (system("svn", "update", "$config{srcdir}/$file") != 0) {
  399. warn("svn update failed\n");
  400. }
  401. if (system("svn", "commit", "--quiet", "-m",
  402. possibly_foolish_untaint($message),
  403. "$config{srcdir}/$file") != 0) {
  404. warn("svn commit failed\n");
  405. my $conflict=readfile("$config{srcdir}/$file");
  406. if (system("svn", "revert", "$config{srcdir}/$file") != 0) {
  407. warn("svn revert failed\n");
  408. }
  409. return $conflict;
  410. }
  411. }
  412. return undef # success
  413. } #}}}
  414. sub rcs_add ($) { #{{{
  415. # filename is relative to the root of the srcdir
  416. my $file=shift;
  417. if (-d "$config{srcdir}/.svn") {
  418. my $parent=dirname($file);
  419. while (! -d "$config{srcdir}/$parent/.svn") {
  420. $file=$parent;
  421. $parent=dirname($file);
  422. }
  423. if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
  424. warn("svn add failed\n");
  425. }
  426. }
  427. } #}}}
  428. sub rcs_recentchanges ($) { #{{{
  429. my $num=shift;
  430. my @ret;
  431. eval q{use CGI 'escapeHTML'};
  432. eval q{use Date::Parse};
  433. eval q{use Time::Duration};
  434. if (-d "$config{srcdir}/.svn") {
  435. my $info=`LANG=C svn info $config{srcdir}`;
  436. my ($svn_url)=$info=~/^URL: (.*)$/m;
  437. # FIXME: currently assumes that the wiki is somewhere
  438. # under trunk in svn, doesn't support other layouts.
  439. my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
  440. my $div=qr/^--------------------+$/;
  441. my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
  442. my $state='start';
  443. my ($rev, $user, $when, @pages, @message);
  444. foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
  445. chomp;
  446. if ($state eq 'start' && /$div/) {
  447. $state='header';
  448. }
  449. elsif ($state eq 'header' && /$infoline/) {
  450. $rev=$1;
  451. $user=$2;
  452. $when=concise(ago(time - str2time($3)));
  453. }
  454. elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
  455. push @pages, { link => htmllink("", pagename($1), 1) }
  456. if length $1;
  457. }
  458. elsif ($state eq 'header' && /^$/) {
  459. $state='body';
  460. }
  461. elsif ($state eq 'body' && /$div/) {
  462. my $committype="web";
  463. if (defined $message[0] &&
  464. $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
  465. $user="$1";
  466. $message[0]->{line}=$2;
  467. }
  468. else {
  469. $committype="svn";
  470. }
  471. push @ret, { rev => $rev,
  472. user => htmllink("", $user, 1),
  473. committype => $committype,
  474. when => $when, message => [@message],
  475. pages => [@pages] } if @pages;
  476. return @ret if @ret >= $num;
  477. $state='header';
  478. $rev=$user=$when=undef;
  479. @pages=@message=();
  480. }
  481. elsif ($state eq 'body') {
  482. push @message, {line => escapeHTML($_)},
  483. }
  484. }
  485. }
  486. return @ret;
  487. } #}}}
  488. sub prune ($) { #{{{
  489. my $file=shift;
  490. unlink($file);
  491. my $dir=dirname($file);
  492. while (rmdir($dir)) {
  493. $dir=dirname($dir);
  494. }
  495. } #}}}
  496. sub refresh () { #{{{
  497. # find existing pages
  498. my %exists;
  499. my @files;
  500. eval q{use File::Find};
  501. find({
  502. no_chdir => 1,
  503. wanted => sub {
  504. if (/$config{wiki_file_prune_regexp}/) {
  505. no warnings 'once';
  506. $File::Find::prune=1;
  507. use warnings "all";
  508. }
  509. elsif (! -d $_ && ! -l $_) {
  510. my ($f)=/$config{wiki_file_regexp}/; # untaint
  511. if (! defined $f) {
  512. warn("skipping bad filename $_\n");
  513. }
  514. else {
  515. $f=~s/^\Q$config{srcdir}\E\/?//;
  516. push @files, $f;
  517. $exists{pagename($f)}=1;
  518. }
  519. }
  520. },
  521. }, $config{srcdir});
  522. my %rendered;
  523. # check for added or removed pages
  524. my @add;
  525. foreach my $file (@files) {
  526. my $page=pagename($file);
  527. if (! $oldpagemtime{$page}) {
  528. debug("new page $page");
  529. push @add, $file;
  530. $links{$page}=[];
  531. $pagesources{$page}=$file;
  532. }
  533. }
  534. my @del;
  535. foreach my $page (keys %oldpagemtime) {
  536. if (! $exists{$page}) {
  537. debug("removing old page $page");
  538. push @del, $pagesources{$page};
  539. prune($config{destdir}."/".$renderedfiles{$page});
  540. delete $renderedfiles{$page};
  541. $oldpagemtime{$page}=0;
  542. delete $pagesources{$page};
  543. }
  544. }
  545. # render any updated files
  546. foreach my $file (@files) {
  547. my $page=pagename($file);
  548. if (! exists $oldpagemtime{$page} ||
  549. mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
  550. debug("rendering changed file $file");
  551. render($file);
  552. $rendered{$file}=1;
  553. }
  554. }
  555. # if any files were added or removed, check to see if each page
  556. # needs an update due to linking to them
  557. # TODO: inefficient; pages may get rendered above and again here;
  558. # problem is the bestlink may have changed and we won't know until
  559. # now
  560. if (@add || @del) {
  561. FILE: foreach my $file (@files) {
  562. my $page=pagename($file);
  563. foreach my $f (@add, @del) {
  564. my $p=pagename($f);
  565. foreach my $link (@{$links{$page}}) {
  566. if (bestlink($page, $link) eq $p) {
  567. debug("rendering $file, which links to $p");
  568. render($file);
  569. $rendered{$file}=1;
  570. next FILE;
  571. }
  572. }
  573. }
  574. }
  575. }
  576. # handle backlinks; if a page has added/removed links, update the
  577. # pages it links to
  578. # TODO: inefficient; pages may get rendered above and again here;
  579. # problem is the backlinks could be wrong in the first pass render
  580. # above
  581. if (%rendered) {
  582. my %linkchanged;
  583. foreach my $file (keys %rendered, @del) {
  584. my $page=pagename($file);
  585. if (exists $links{$page}) {
  586. foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
  587. if (length $link &&
  588. ! exists $oldlinks{$page} ||
  589. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  590. $linkchanged{$link}=1;
  591. }
  592. }
  593. }
  594. if (exists $oldlinks{$page}) {
  595. foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
  596. if (length $link &&
  597. ! exists $links{$page} ||
  598. ! grep { $_ eq $link } @{$links{$page}}) {
  599. $linkchanged{$link}=1;
  600. }
  601. }
  602. }
  603. }
  604. foreach my $link (keys %linkchanged) {
  605. my $linkfile=$pagesources{$link};
  606. if (defined $linkfile) {
  607. debug("rendering $linkfile, to update its backlinks");
  608. render($linkfile);
  609. }
  610. }
  611. }
  612. } #}}}
  613. sub gen_wrapper (@) { #{{{
  614. my %config=(@_);
  615. eval q{use Cwd 'abs_path'};
  616. $config{srcdir}=abs_path($config{srcdir});
  617. $config{destdir}=abs_path($config{destdir});
  618. my $this=abs_path($0);
  619. if (! -x $this) {
  620. error("$this doesn't seem to be executable");
  621. }
  622. if ($config{setup}) {
  623. error("cannot create a wrapper that uses a setup file");
  624. }
  625. my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
  626. "--wikiname=$config{wikiname}");
  627. push @params, "--verbose" if $config{verbose};
  628. push @params, "--rebuild" if $config{rebuild};
  629. push @params, "--nosvn" if !$config{svn};
  630. push @params, "--cgi" if $config{cgi};
  631. push @params, "--url=$config{url}" if length $config{url};
  632. push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
  633. push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
  634. push @params, "--anonok" if $config{anonok};
  635. my $params=join(" ", @params);
  636. my $call='';
  637. foreach my $p ($this, $this, @params) {
  638. $call.=qq{"$p", };
  639. }
  640. $call.="NULL";
  641. my @envsave;
  642. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  643. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  644. HTTP_COOKIE} if $config{cgi};
  645. my $envsave="";
  646. foreach my $var (@envsave) {
  647. $envsave.=<<"EOF"
  648. if ((s=getenv("$var")))
  649. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  650. EOF
  651. }
  652. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  653. print OUT <<"EOF";
  654. /* A wrapper for ikiwiki, can be safely made suid. */
  655. #define _GNU_SOURCE
  656. #include <stdio.h>
  657. #include <unistd.h>
  658. #include <stdlib.h>
  659. #include <string.h>
  660. extern char **environ;
  661. int main (int argc, char **argv) {
  662. /* Sanitize environment. */
  663. char *s;
  664. char *newenviron[$#envsave+3];
  665. int i=0;
  666. $envsave
  667. newenviron[i++]="HOME=$ENV{HOME}";
  668. newenviron[i]=NULL;
  669. environ=newenviron;
  670. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  671. printf("$params\\n");
  672. exit(0);
  673. }
  674. execl($call);
  675. perror("failed to run $this");
  676. exit(1);
  677. }
  678. EOF
  679. close OUT;
  680. if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
  681. error("failed to compile ikiwiki-wrap.c");
  682. }
  683. unlink("ikiwiki-wrap.c");
  684. if (defined $config{wrappermode} &&
  685. ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
  686. error("chmod $config{wrapper}: $!");
  687. }
  688. print "successfully generated $config{wrapper}\n";
  689. } #}}}
  690. sub misctemplate ($$) { #{{{
  691. my $title=shift;
  692. my $pagebody=shift;
  693. my $template=HTML::Template->new(
  694. filename => "$config{templatedir}/misc.tmpl"
  695. );
  696. $template->param(
  697. title => $title,
  698. indexlink => indexlink(),
  699. wikiname => $config{wikiname},
  700. pagebody => $pagebody,
  701. );
  702. return $template->output;
  703. }#}}}
  704. sub cgi_recentchanges ($) { #{{{
  705. my $q=shift;
  706. my $template=HTML::Template->new(
  707. filename => "$config{templatedir}/recentchanges.tmpl"
  708. );
  709. $template->param(
  710. title => "RecentChanges",
  711. indexlink => indexlink(),
  712. wikiname => $config{wikiname},
  713. changelog => [rcs_recentchanges(100)],
  714. );
  715. print $q->header, $template->output;
  716. } #}}}
  717. sub userinfo_get ($$) { #{{{
  718. my $user=shift;
  719. my $field=shift;
  720. eval q{use Storable};
  721. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  722. if (! defined $userdata || ! ref $userdata ||
  723. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  724. return "";
  725. }
  726. return $userdata->{$user}->{$field};
  727. } #}}}
  728. sub userinfo_set ($$) { #{{{
  729. my $user=shift;
  730. my $info=shift;
  731. eval q{use Storable};
  732. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  733. if (! defined $userdata || ! ref $userdata) {
  734. $userdata={};
  735. }
  736. $userdata->{$user}=$info;
  737. my $oldmask=umask(077);
  738. my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
  739. umask($oldmask);
  740. return $ret;
  741. } #}}}
  742. sub cgi_signin ($$) { #{{{
  743. my $q=shift;
  744. my $session=shift;
  745. eval q{use CGI::FormBuilder};
  746. my $form = CGI::FormBuilder->new(
  747. title => "$config{wikiname} signin",
  748. fields => [qw(do page from name password confirm_password email)],
  749. header => 1,
  750. method => 'POST',
  751. validate => {
  752. confirm_password => {
  753. perl => q{eq $form->field("password")},
  754. },
  755. email => 'EMAIL',
  756. },
  757. required => 'NONE',
  758. javascript => 0,
  759. params => $q,
  760. action => $q->request_uri,
  761. header => 0,
  762. template => (-e "$config{templatedir}/signin.tmpl" ?
  763. "$config{templatedir}/signin.tmpl" : "")
  764. );
  765. $form->field(name => "name", required => 0);
  766. $form->field(name => "do", type => "hidden");
  767. $form->field(name => "page", type => "hidden");
  768. $form->field(name => "from", type => "hidden");
  769. $form->field(name => "password", type => "password", required => 0);
  770. $form->field(name => "confirm_password", type => "password", required => 0);
  771. $form->field(name => "email", required => 0);
  772. if ($q->param("do") ne "signin") {
  773. $form->text("You need to log in before you can edit pages.");
  774. }
  775. if ($form->submitted) {
  776. # Set required fields based on how form was submitted.
  777. my %required=(
  778. "Login" => [qw(name password)],
  779. "Register" => [qw(name password confirm_password email)],
  780. "Mail Password" => [qw(name)],
  781. );
  782. foreach my $opt (@{$required{$form->submitted}}) {
  783. $form->field(name => $opt, required => 1);
  784. }
  785. # Validate password differently depending on how
  786. # form was submitted.
  787. if ($form->submitted eq 'Login') {
  788. $form->field(
  789. name => "password",
  790. validate => sub {
  791. length $form->field("name") &&
  792. shift eq userinfo_get($form->field("name"), 'password');
  793. },
  794. );
  795. $form->field(name => "name", validate => '/^\w+$/');
  796. }
  797. else {
  798. $form->field(name => "password", validate => 'VALUE');
  799. }
  800. # And make sure the entered name exists when logging
  801. # in or sending email, and does not when registering.
  802. if ($form->submitted eq 'Register') {
  803. $form->field(
  804. name => "name",
  805. validate => sub {
  806. my $name=shift;
  807. length $name &&
  808. ! userinfo_get($name, "regdate");
  809. },
  810. );
  811. }
  812. else {
  813. $form->field(
  814. name => "name",
  815. validate => sub {
  816. my $name=shift;
  817. length $name &&
  818. userinfo_get($name, "regdate");
  819. },
  820. );
  821. }
  822. }
  823. else {
  824. # First time settings.
  825. $form->field(name => "name", comment => "use FirstnameLastName");
  826. $form->field(name => "confirm_password", comment => "(only needed");
  827. $form->field(name => "email", comment => "for registration)");
  828. if ($session->param("name")) {
  829. $form->field(name => "name", value => $session->param("name"));
  830. }
  831. }
  832. if ($form->submitted && $form->validate) {
  833. if ($form->submitted eq 'Login') {
  834. $session->param("name", $form->field("name"));
  835. if (defined $form->field("do") &&
  836. $form->field("do") ne 'signin') {
  837. print $q->redirect(
  838. "$config{cgiurl}?do=".$form->field("do").
  839. "&page=".$form->field("page").
  840. "&from=".$form->field("from"));;
  841. }
  842. else {
  843. print $q->redirect($config{url});
  844. }
  845. }
  846. elsif ($form->submitted eq 'Register') {
  847. my $user_name=$form->field('name');
  848. if (userinfo_set($user_name, {
  849. 'email' => $form->field('email'),
  850. 'password' => $form->field('password'),
  851. 'regdate' => time
  852. })) {
  853. $form->field(name => "confirm_password", type => "hidden");
  854. $form->field(name => "email", type => "hidden");
  855. $form->text("Registration successful. Now you can Login.");
  856. print $session->header();
  857. print misctemplate($form->title, $form->render(submit => ["Login"]));
  858. }
  859. else {
  860. error("Error saving registration.");
  861. }
  862. }
  863. elsif ($form->submitted eq 'Mail Password') {
  864. my $user_name=$form->field("name");
  865. my $template=HTML::Template->new(
  866. filename => "$config{templatedir}/passwordmail.tmpl"
  867. );
  868. $template->param(
  869. user_name => $user_name,
  870. user_password => userinfo_get($user_name, "password"),
  871. wikiurl => $config{url},
  872. wikiname => $config{wikiname},
  873. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  874. );
  875. eval q{use Mail::Sendmail};
  876. my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
  877. sendmail(
  878. To => userinfo_get($user_name, "email"),
  879. From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
  880. Subject => "$config{wikiname} information",
  881. Message => $template->output,
  882. ) or error("Failed to send mail");
  883. $form->text("Your password has been emailed to you.");
  884. $form->field(name => "name", required => 0);
  885. print $session->header();
  886. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  887. }
  888. }
  889. else {
  890. print $session->header();
  891. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  892. }
  893. } #}}}
  894. sub cgi_editpage ($$) { #{{{
  895. my $q=shift;
  896. my $session=shift;
  897. eval q{use CGI::FormBuilder};
  898. my $form = CGI::FormBuilder->new(
  899. fields => [qw(do from page content comments)],
  900. header => 1,
  901. method => 'POST',
  902. validate => {
  903. content => '/.+/',
  904. },
  905. required => [qw{content}],
  906. javascript => 0,
  907. params => $q,
  908. action => $q->request_uri,
  909. table => 0,
  910. template => "$config{templatedir}/editpage.tmpl"
  911. );
  912. my @buttons=("Save Page", "Preview", "Cancel");
  913. my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
  914. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  915. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  916. error("bad page name");
  917. }
  918. $page=lc($page);
  919. $form->field(name => "do", type => 'hidden');
  920. $form->field(name => "from", type => 'hidden');
  921. $form->field(name => "page", value => "$page", force => 1);
  922. $form->field(name => "comments", type => "text", size => 80);
  923. $form->field(name => "content", type => "textarea", rows => 20,
  924. cols => 80);
  925. if ($form->submitted eq "Cancel") {
  926. print $q->redirect("$config{url}/".htmlpage($page));
  927. return;
  928. }
  929. elsif ($form->submitted eq "Preview") {
  930. $form->tmpl_param("page_preview",
  931. htmlize($config{default_pageext},
  932. linkify($form->field('content'), $page)));
  933. }
  934. else {
  935. $form->tmpl_param("page_preview", "");
  936. }
  937. $form->tmpl_param("page_conflict", "");
  938. if (! $form->submitted || $form->submitted eq "Preview" ||
  939. ! $form->validate) {
  940. if ($form->field("do") eq "create") {
  941. if (exists $pagesources{lc($page)}) {
  942. # hmm, someone else made the page in the
  943. # meantime?
  944. print $q->redirect("$config{url}/".htmlpage($page));
  945. return;
  946. }
  947. my @page_locs;
  948. my $best_loc;
  949. my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
  950. if (! defined $from || ! length $from ||
  951. $from ne $form->param('from') ||
  952. $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
  953. @page_locs=$best_loc=$page;
  954. }
  955. else {
  956. my $dir=$from."/";
  957. $dir=~s![^/]+/$!!;
  958. push @page_locs, $dir.$page;
  959. push @page_locs, "$from/$page";
  960. $best_loc="$from/$page";
  961. while (length $dir) {
  962. $dir=~s![^/]+/$!!;
  963. push @page_locs, $dir.$page;
  964. }
  965. @page_locs = grep { ! exists
  966. $pagesources{lc($_)} } @page_locs;
  967. }
  968. $form->tmpl_param("page_select", 1);
  969. $form->field(name => "page", type => 'select',
  970. options => \@page_locs, value => $best_loc);
  971. $form->title("creating $page");
  972. }
  973. elsif ($form->field("do") eq "edit") {
  974. if (! length $form->field('content')) {
  975. my $content="";
  976. if (exists $pagesources{lc($page)}) {
  977. $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
  978. $content=~s/\n/\r\n/g;
  979. }
  980. $form->field(name => "content", value => $content,
  981. force => 1);
  982. }
  983. $form->tmpl_param("page_select", 0);
  984. $form->field(name => "page", type => 'hidden');
  985. $form->title("editing $page");
  986. }
  987. $form->tmpl_param("can_commit", $config{svn});
  988. $form->tmpl_param("indexlink", indexlink());
  989. print $form->render(submit => \@buttons);
  990. }
  991. else {
  992. # save page
  993. my $file=$page.$config{default_pageext};
  994. my $newfile=1;
  995. if (exists $pagesources{lc($page)}) {
  996. $file=$pagesources{lc($page)};
  997. $newfile=0;
  998. }
  999. my $content=$form->field('content');
  1000. $content=~s/\r\n/\n/g;
  1001. $content=~s/\r/\n/g;
  1002. writefile("$config{srcdir}/$file", $content);
  1003. my $message="web commit ";
  1004. if ($session->param("name")) {
  1005. $message.="by ".$session->param("name");
  1006. }
  1007. else {
  1008. $message.="from $ENV{REMOTE_ADDR}";
  1009. }
  1010. if (defined $form->field('comments') &&
  1011. length $form->field('comments')) {
  1012. $message.=": ".$form->field('comments');
  1013. }
  1014. if ($config{svn}) {
  1015. if ($newfile) {
  1016. rcs_add($file);
  1017. }
  1018. # prevent deadlock with post-commit hook
  1019. unlockwiki();
  1020. # presumably the commit will trigger an update
  1021. # of the wiki
  1022. my $conflict=rcs_commit($file, $message);
  1023. if (defined $conflict) {
  1024. $form->tmpl_param("page_conflict", 1);
  1025. $form->field("content", $conflict);
  1026. $form->field("do", "edit)");
  1027. print $form->render(submit => \@buttons);
  1028. return;
  1029. }
  1030. }
  1031. else {
  1032. loadindex();
  1033. refresh();
  1034. saveindex();
  1035. }
  1036. # The trailing question mark tries to avoid broken
  1037. # caches and get the most recent version of the page.
  1038. print $q->redirect("$config{url}/".htmlpage($page)."?updated");
  1039. }
  1040. } #}}}
  1041. sub cgi () { #{{{
  1042. eval q{use CGI};
  1043. eval q{use CGI::Session};
  1044. my $q=CGI->new;
  1045. my $do=$q->param('do');
  1046. if (! defined $do || ! length $do) {
  1047. error("\"do\" parameter missing");
  1048. }
  1049. # This does not need a session.
  1050. if ($do eq 'recentchanges') {
  1051. cgi_recentchanges($q);
  1052. return;
  1053. }
  1054. CGI::Session->name("ikiwiki_session");
  1055. my $oldmask=umask(077);
  1056. my $session = CGI::Session->new("driver:db_file", $q,
  1057. { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
  1058. umask($oldmask);
  1059. # Everything below this point needs the user to be signed in.
  1060. if ((! $config{anonok} && ! defined $session->param("name") ||
  1061. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  1062. cgi_signin($q, $session);
  1063. # Force session flush with safe umask.
  1064. my $oldmask=umask(077);
  1065. $session->flush;
  1066. umask($oldmask);
  1067. return;
  1068. }
  1069. if ($do eq 'create' || $do eq 'edit') {
  1070. cgi_editpage($q, $session);
  1071. }
  1072. else {
  1073. error("unknown do parameter");
  1074. }
  1075. } #}}}
  1076. sub setup () { # {{{
  1077. my $setup=possibly_foolish_untaint($config{setup});
  1078. delete $config{setup};
  1079. open (IN, $setup) || error("read $setup: $!\n");
  1080. local $/=undef;
  1081. my $code=<IN>;
  1082. ($code)=$code=~/(.*)/s;
  1083. close IN;
  1084. eval $code;
  1085. error($@) if $@;
  1086. exit;
  1087. } #}}}
  1088. # main {{{
  1089. lockwiki();
  1090. setup() if $config{setup};
  1091. if ($config{wrapper}) {
  1092. gen_wrapper(%config);
  1093. exit;
  1094. }
  1095. memoize('pagename');
  1096. memoize('bestlink');
  1097. loadindex() unless $config{rebuild};
  1098. if ($config{cgi}) {
  1099. cgi();
  1100. }
  1101. else {
  1102. rcs_update() if $config{svn};
  1103. refresh();
  1104. saveindex();
  1105. }
  1106. #}}}