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