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