summaryrefslogtreecommitdiff
path: root/IkiWiki/CGI.pm
blob: 9b5ee6c19b980d491773b027afb6bc4d9a8cd95f (plain)
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use IkiWiki;
  5. use IkiWiki::UserInfo;
  6. use open qw{:utf8 :std};
  7. use Encode;
  8. package IkiWiki;
  9. sub printheader ($) { #{{{
  10. my $session=shift;
  11. if ($config{sslcookie}) {
  12. print $session->header(-charset => 'utf-8',
  13. -cookie => $session->cookie(-secure => 1));
  14. } else {
  15. print $session->header(-charset => 'utf-8');
  16. }
  17. } #}}}
  18. sub redirect ($$) { #{{{
  19. my $q=shift;
  20. my $url=shift;
  21. if (! $config{w3mmode}) {
  22. print $q->redirect($url);
  23. }
  24. else {
  25. print "Content-type: text/plain\n";
  26. print "W3m-control: GOTO $url\n\n";
  27. }
  28. } #}}}
  29. sub page_locked ($$;$) { #{{{
  30. my $page=shift;
  31. my $session=shift;
  32. my $nonfatal=shift;
  33. my $user=$session->param("name");
  34. return if defined $user && is_admin($user);
  35. foreach my $admin (@{$config{adminuser}}) {
  36. my $locked_pages=userinfo_get($admin, "locked_pages");
  37. if (pagespec_match($page, userinfo_get($admin, "locked_pages"))) {
  38. return 1 if $nonfatal;
  39. error(htmllink("", "", $page, 1)." is locked by ".
  40. userlink($admin)." and cannot be edited.");
  41. }
  42. }
  43. return 0;
  44. } #}}}
  45. sub decode_form_utf8 ($) { #{{{
  46. my $form = shift;
  47. foreach my $f ($form->field) {
  48. next if Encode::is_utf8(scalar $form->field($f));
  49. $form->field(name => $f,
  50. value => decode_utf8($form->field($f)),
  51. force => 1,
  52. );
  53. }
  54. } #}}}
  55. sub cgi_recentchanges ($) { #{{{
  56. my $q=shift;
  57. # Optimisation: building recentchanges means calculating lots of
  58. # links. Memoizing htmllink speeds it up a lot (can't be memoized
  59. # during page builds as the return values may change, but they
  60. # won't here.)
  61. eval q{use Memoize};
  62. error($@) if $@;
  63. memoize("htmllink");
  64. eval q{use Time::Duration};
  65. error($@) if $@;
  66. my $changelog=[rcs_recentchanges(100)];
  67. foreach my $change (@$changelog) {
  68. $change->{when} = concise(ago($change->{when}));
  69. $change->{user} = userlink($change->{user});
  70. my $is_excess = exists $change->{pages}[10]; # limit pages to first 10
  71. delete @{$change->{pages}}[10 .. @{$change->{pages}}] if $is_excess;
  72. $change->{pages} = [
  73. map {
  74. $_->{link} = htmllink("", "", $_->{page}, 1);
  75. $_;
  76. } @{$change->{pages}}
  77. ];
  78. push @{$change->{pages}}, { link => '...' } if $is_excess;
  79. }
  80. my $template=template("recentchanges.tmpl");
  81. $template->param(
  82. title => "RecentChanges",
  83. indexlink => indexlink(),
  84. wikiname => $config{wikiname},
  85. changelog => $changelog,
  86. baseurl => baseurl(),
  87. );
  88. run_hooks(pagetemplate => sub {
  89. shift->(page => "", destpage => "", template => $template);
  90. });
  91. print $q->header(-charset => 'utf-8'), $template->output;
  92. } #}}}
  93. sub cgi_signin ($$) { #{{{
  94. my $q=shift;
  95. my $session=shift;
  96. eval q{use CGI::FormBuilder};
  97. error($@) if $@;
  98. my $form = CGI::FormBuilder->new(
  99. title => "signin",
  100. header => 1,
  101. charset => "utf-8",
  102. method => 'POST',
  103. required => 'NONE',
  104. javascript => 0,
  105. params => $q,
  106. action => $config{cgiurl},
  107. header => 0,
  108. template => (-e "$config{templatedir}/signin.tmpl" ?
  109. {template_params("signin.tmpl")} : ""),
  110. stylesheet => baseurl()."style.css",
  111. );
  112. my $buttons=["Login"];
  113. $form->field(name => "do", type => "hidden");
  114. if ($q->param("do") ne "signin" && !$form->submitted) {
  115. $form->text("You need to log in first.");
  116. }
  117. run_hooks(formbuilder_setup => sub {
  118. shift->(form => $form, cgi => $q, session => $session);
  119. });
  120. decode_form_utf8($form);
  121. if (exists $hooks{formbuilder}) {
  122. run_hooks(formbuilder => sub {
  123. shift->(form => $form, cgi => $q, session => $session,
  124. buttons => $buttons);
  125. });
  126. }
  127. else {
  128. if ($form->submitted) {
  129. $form->validate;
  130. }
  131. printheader($session);
  132. print misctemplate($form->title, $form->render(submit => $buttons));
  133. }
  134. } #}}}
  135. sub cgi_postsignin ($$) { #{{{
  136. my $q=shift;
  137. my $session=shift;
  138. # Continue with whatever was being done before the signin process.
  139. if (defined $q->param("do") && $q->param("do") ne "signin" &&
  140. defined $session->param("postsignin")) {
  141. my $postsignin=CGI->new($session->param("postsignin"));
  142. $session->clear("postsignin");
  143. cgi($postsignin, $session);
  144. cgi_savesession($session);
  145. exit;
  146. }
  147. else {
  148. redirect($q, $config{url});
  149. }
  150. } #}}}
  151. sub cgi_prefs ($$) { #{{{
  152. my $q=shift;
  153. my $session=shift;
  154. eval q{use CGI::FormBuilder};
  155. error($@) if $@;
  156. my $form = CGI::FormBuilder->new(
  157. title => "preferences",
  158. header => 0,
  159. charset => "utf-8",
  160. method => 'POST',
  161. validate => {
  162. email => 'EMAIL',
  163. },
  164. required => 'NONE',
  165. javascript => 0,
  166. params => $q,
  167. action => $config{cgiurl},
  168. template => (-e "$config{templatedir}/prefs.tmpl" ?
  169. {template_params("prefs.tmpl")} : ""),
  170. stylesheet => baseurl()."style.css",
  171. );
  172. my $buttons=["Save Preferences", "Logout", "Cancel"];
  173. run_hooks(formbuilder_setup => sub {
  174. shift->(form => $form, cgi => $q, session => $session);
  175. });
  176. $form->field(name => "do", type => "hidden");
  177. $form->field(name => "email", size => 50);
  178. $form->field(name => "subscriptions", size => 50,
  179. comment => "(".htmllink("", "", "PageSpec", 1).")");
  180. $form->field(name => "locked_pages", size => 50,
  181. comment => "(".htmllink("", "", "PageSpec", 1).")");
  182. $form->field(name => "banned_users", size => 50);
  183. my $user_name=$session->param("name");
  184. if (! is_admin($user_name)) {
  185. $form->field(name => "locked_pages", type => "hidden");
  186. $form->field(name => "banned_users", type => "hidden");
  187. }
  188. if (! $form->submitted) {
  189. $form->field(name => "email", force => 1,
  190. value => userinfo_get($user_name, "email"));
  191. $form->field(name => "subscriptions", force => 1,
  192. value => userinfo_get($user_name, "subscriptions"));
  193. $form->field(name => "locked_pages", force => 1,
  194. value => userinfo_get($user_name, "locked_pages"));
  195. if (is_admin($user_name)) {
  196. $form->field(name => "banned_users", force => 1,
  197. value => join(" ", get_banned_users()));
  198. }
  199. }
  200. decode_form_utf8($form);
  201. if ($form->submitted eq 'Logout') {
  202. $session->delete();
  203. redirect($q, $config{url});
  204. return;
  205. }
  206. elsif ($form->submitted eq 'Cancel') {
  207. redirect($q, $config{url});
  208. return;
  209. }
  210. elsif ($form->submitted eq "Save Preferences" && $form->validate) {
  211. foreach my $field (qw(email subscriptions locked_pages)) {
  212. if (defined $form->field($field) && length $form->field($field)) {
  213. userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
  214. }
  215. }
  216. if (is_admin($user_name)) {
  217. set_banned_users(grep { ! is_admin($_) }
  218. split(' ', $form->field("banned_users")));
  219. }
  220. $form->text("Preferences saved.");
  221. }
  222. if (exists $hooks{formbuilder}) {
  223. run_hooks(formbuilder => sub {
  224. shift->(form => $form, cgi => $q, session => $session,
  225. buttons => $buttons);
  226. });
  227. }
  228. else {
  229. printheader($session);
  230. print misctemplate($form->title, $form->render(submit => $buttons));
  231. }
  232. } #}}}
  233. sub cgi_editpage ($$) { #{{{
  234. my $q=shift;
  235. my $session=shift;
  236. my @fields=qw(do rcsinfo subpage from page type editcontent comments);
  237. my @buttons=("Save Page", "Preview", "Cancel");
  238. eval q{use CGI::FormBuilder};
  239. error($@) if $@;
  240. my $form = CGI::FormBuilder->new(
  241. fields => \@fields,
  242. header => 1,
  243. charset => "utf-8",
  244. method => 'POST',
  245. validate => {
  246. editcontent => '/.+/',
  247. },
  248. required => [qw{editcontent}],
  249. javascript => 0,
  250. params => $q,
  251. action => $config{cgiurl},
  252. table => 0,
  253. template => (-e "$config{templatedir}/editpage.tmpl" ?
  254. {template_params("editpage.tmpl")} : ""),
  255. );
  256. run_hooks(formbuilder_setup => sub {
  257. shift->(form => $form, cgi => $q, session => $session);
  258. });
  259. decode_form_utf8($form);
  260. # This untaint is safe because titlepage removes any problematic
  261. # characters.
  262. my ($page)=$form->field('page');
  263. $page=titlepage(possibly_foolish_untaint($page));
  264. if (! defined $page || ! length $page ||
  265. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  266. error("bad page name");
  267. }
  268. my $from;
  269. if (defined $form->field('from')) {
  270. ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
  271. }
  272. my $file;
  273. my $type;
  274. if (exists $pagesources{$page}) {
  275. $file=$pagesources{$page};
  276. $type=pagetype($file);
  277. }
  278. else {
  279. $type=$form->param('type');
  280. if (defined $type && length $type && $hooks{htmlize}{$type}) {
  281. $type=possibly_foolish_untaint($type);
  282. }
  283. elsif (defined $from) {
  284. # favor the type of linking page
  285. $type=pagetype($pagesources{$from});
  286. }
  287. $type=$config{default_pageext} unless defined $type;
  288. $file=$page.".".$type;
  289. }
  290. my $newfile=0;
  291. if (! -e "$config{srcdir}/$file") {
  292. $newfile=1;
  293. }
  294. $form->field(name => "do", type => 'hidden');
  295. $form->field(name => "from", type => 'hidden');
  296. $form->field(name => "rcsinfo", type => 'hidden');
  297. $form->field(name => "subpage", type => 'hidden');
  298. $form->field(name => "page", value => $page, force => 1);
  299. $form->field(name => "type", value => $type, force => 1);
  300. $form->field(name => "comments", type => "text", size => 80);
  301. $form->field(name => "editcontent", type => "textarea", rows => 20,
  302. cols => 80);
  303. $form->tmpl_param("can_commit", $config{rcs});
  304. $form->tmpl_param("indexlink", indexlink());
  305. $form->tmpl_param("helponformattinglink",
  306. htmllink("", "", "HelpOnFormatting", 1));
  307. $form->tmpl_param("baseurl", baseurl());
  308. if (! $form->submitted) {
  309. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  310. force => 1);
  311. }
  312. if ($form->submitted eq "Cancel") {
  313. if ($newfile && defined $from) {
  314. redirect($q, "$config{url}/".htmlpage($from));
  315. }
  316. elsif ($newfile) {
  317. redirect($q, $config{url});
  318. }
  319. else {
  320. redirect($q, "$config{url}/".htmlpage($page));
  321. }
  322. return;
  323. }
  324. elsif ($form->submitted eq "Preview") {
  325. my $content=$form->field('editcontent');
  326. my $comments=$form->field('comments');
  327. $form->field(name => "editcontent",
  328. value => $content, force => 1);
  329. $form->field(name => "comments",
  330. value => $comments, force => 1);
  331. $config{rss}=$config{atom}=0; # avoid preview writing a feed!
  332. $form->tmpl_param("page_preview",
  333. htmlize($page, $type,
  334. linkify($page, "",
  335. preprocess($page, $page,
  336. filter($page, $content)))));
  337. }
  338. else {
  339. $form->tmpl_param("page_preview", "");
  340. }
  341. $form->tmpl_param("page_conflict", "");
  342. if (! $form->submitted || $form->submitted eq "Preview" ||
  343. ! $form->validate) {
  344. if ($form->field("do") eq "create") {
  345. my @page_locs;
  346. my $best_loc;
  347. if (! defined $from || ! length $from ||
  348. $from ne $form->field('from') ||
  349. $from=~/$config{wiki_file_prune_regexp}/ ||
  350. $from=~/^\// ||
  351. $form->submitted eq "Preview") {
  352. @page_locs=$best_loc=$page;
  353. }
  354. else {
  355. my $dir=$from."/";
  356. $dir=~s![^/]+/+$!!;
  357. if ((defined $form->field('subpage') && length $form->field('subpage')) ||
  358. $page eq 'discussion') {
  359. $best_loc="$from/$page";
  360. }
  361. else {
  362. $best_loc=$dir.$page;
  363. }
  364. push @page_locs, $dir.$page;
  365. push @page_locs, "$from/$page";
  366. while (length $dir) {
  367. $dir=~s![^/]+/+$!!;
  368. push @page_locs, $dir.$page;
  369. }
  370. }
  371. @page_locs = grep {
  372. ! exists $pagecase{lc $_} &&
  373. ! page_locked($_, $session, 1)
  374. } @page_locs;
  375. if (! @page_locs) {
  376. # hmm, someone else made the page in the
  377. # meantime?
  378. redirect($q, "$config{url}/".htmlpage($page));
  379. return;
  380. }
  381. my @page_types;
  382. if (exists $hooks{htmlize}) {
  383. @page_types=keys %{$hooks{htmlize}};
  384. }
  385. $form->tmpl_param("page_select", 1);
  386. $form->field(name => "page", type => 'select',
  387. options => \@page_locs, value => $best_loc);
  388. $form->field(name => "type", type => 'select',
  389. options => \@page_types);
  390. $form->title("creating ".pagetitle($page));
  391. }
  392. elsif ($form->field("do") eq "edit") {
  393. page_locked($page, $session);
  394. if (! defined $form->field('editcontent') ||
  395. ! length $form->field('editcontent')) {
  396. my $content="";
  397. if (exists $pagesources{$page}) {
  398. $content=readfile(srcfile($pagesources{$page}));
  399. $content=~s/\n/\r\n/g;
  400. }
  401. $form->field(name => "editcontent", value => $content,
  402. force => 1);
  403. }
  404. $form->tmpl_param("page_select", 0);
  405. $form->field(name => "page", type => 'hidden');
  406. $form->field(name => "type", type => 'hidden');
  407. $form->title("editing ".pagetitle($page));
  408. }
  409. print $form->render(submit => \@buttons);
  410. }
  411. else {
  412. # save page
  413. page_locked($page, $session);
  414. my $content=$form->field('editcontent');
  415. $content=~s/\r\n/\n/g;
  416. $content=~s/\r/\n/g;
  417. writefile($file, $config{srcdir}, $content);
  418. if ($config{rcs}) {
  419. my $message="";
  420. if (defined $form->field('comments') &&
  421. length $form->field('comments')) {
  422. $message=$form->field('comments');
  423. }
  424. if ($newfile) {
  425. rcs_add($file);
  426. }
  427. # prevent deadlock with post-commit hook
  428. unlockwiki();
  429. # presumably the commit will trigger an update
  430. # of the wiki
  431. my $conflict=rcs_commit($file, $message,
  432. $form->field("rcsinfo"),
  433. $session->param("name"), $ENV{REMOTE_ADDR});
  434. if (defined $conflict) {
  435. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  436. force => 1);
  437. $form->tmpl_param("page_conflict", 1);
  438. $form->field("editcontent", value => $conflict, force => 1);
  439. $form->field(name => "comments", value => $form->field('comments'), force => 1);
  440. $form->field("do", "edit)");
  441. $form->tmpl_param("page_select", 0);
  442. $form->field(name => "page", type => 'hidden');
  443. $form->field(name => "type", type => 'hidden');
  444. $form->title("editing $page");
  445. print $form->render(submit => \@buttons);
  446. return;
  447. }
  448. }
  449. else {
  450. require IkiWiki::Render;
  451. refresh();
  452. saveindex();
  453. }
  454. # The trailing question mark tries to avoid broken
  455. # caches and get the most recent version of the page.
  456. redirect($q, "$config{url}/".htmlpage($page)."?updated");
  457. }
  458. } #}}}
  459. sub cgi_getsession ($) { #{{{
  460. my $q=shift;
  461. eval q{use CGI::Session};
  462. CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
  463. my $oldmask=umask(077);
  464. my $session = CGI::Session->new("driver:DB_File", $q,
  465. { FileName => "$config{wikistatedir}/sessions.db" });
  466. umask($oldmask);
  467. return $session;
  468. } #}}}
  469. sub cgi_savesession ($) { #{{{
  470. my $session=shift;
  471. # Force session flush with safe umask.
  472. my $oldmask=umask(077);
  473. $session->flush;
  474. umask($oldmask);
  475. }
  476. sub cgi (;$$) { #{{{
  477. my $q=shift;
  478. my $session=shift;
  479. if (! $q) {
  480. eval q{use CGI};
  481. error($@) if $@;
  482. $q=CGI->new;
  483. run_hooks(cgi => sub { shift->($q) });
  484. }
  485. my $do=$q->param('do');
  486. if (! defined $do || ! length $do) {
  487. my $error = $q->cgi_error;
  488. if ($error) {
  489. error("Request not processed: $error");
  490. }
  491. else {
  492. error("\"do\" parameter missing");
  493. }
  494. }
  495. # Things that do not need a session.
  496. if ($do eq 'recentchanges') {
  497. cgi_recentchanges($q);
  498. return;
  499. }
  500. elsif ($do eq 'hyperestraier') {
  501. cgi_hyperestraier();
  502. }
  503. # Need to lock the wiki before getting a session.
  504. lockwiki();
  505. if (! $session) {
  506. $session=cgi_getsession($q);
  507. }
  508. # Auth hooks can sign a user in.
  509. if ($do ne 'signin' && ! defined $session->param("name")) {
  510. run_hooks(auth => sub {
  511. shift->($q, $session)
  512. });
  513. if (defined $session->param("name")) {
  514. # Make sure whatever user was authed is in the
  515. # userinfo db.
  516. if (! userinfo_get($session->param("name"), "regdate")) {
  517. userinfo_setall($session->param("name"), {
  518. email => "",
  519. password => "",
  520. regdate => time,
  521. });
  522. }
  523. }
  524. }
  525. # Everything below this point needs the user to be signed in.
  526. if (((! $config{anonok} || $do eq 'prefs') &&
  527. (! defined $session->param("name") ||
  528. ! userinfo_get($session->param("name"), "regdate")))
  529. || $do eq 'signin') {
  530. if ($do ne 'signin' && ! defined $session->param("postsignin")) {
  531. $session->param(postsignin => $ENV{QUERY_STRING});
  532. }
  533. cgi_signin($q, $session);
  534. cgi_savesession($session);
  535. return;
  536. }
  537. elsif (defined $session->param("postsignin")) {
  538. cgi_postsignin($q, $session);
  539. }
  540. if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
  541. print $q->header(-status => "403 Forbidden");
  542. $session->delete();
  543. print "You are banned.";
  544. cgi_savesession($session);
  545. exit;
  546. }
  547. if ($do eq 'create' || $do eq 'edit') {
  548. cgi_editpage($q, $session);
  549. }
  550. elsif ($do eq 'prefs') {
  551. cgi_prefs($q, $session);
  552. }
  553. elsif ($do eq 'blog') {
  554. my $page=titlepage(decode_utf8($q->param('title')));
  555. # if the page already exists, munge it to be unique
  556. my $from=$q->param('from');
  557. my $add="";
  558. while (exists $pagecase{lc "$from/$page$add"}) {
  559. $add=1 unless length $add;
  560. $add++;
  561. }
  562. $q->param('page', $page.$add);
  563. # now run same as create
  564. $q->param('do', 'create');
  565. cgi_editpage($q, $session);
  566. }
  567. else {
  568. error("unknown do parameter");
  569. }
  570. } #}}}
  571. sub userlink ($) { #{{{
  572. my $user=shift;
  573. eval q{use CGI 'escapeHTML'};
  574. error($@) if $@;
  575. if ($user =~ m!^https?://! &&
  576. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  577. # Munge user-urls, as used by eg, OpenID.
  578. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  579. my $display=$oid->display;
  580. # Convert "user.somehost.com" to "user [somehost.com]".
  581. if ($display !~ /\[/) {
  582. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  583. }
  584. $display=~s!^https?://!!; # make sure this is removed
  585. return "<a href=\"$user\">".escapeHTML($display)."</a>";
  586. }
  587. else {
  588. return htmllink("", "", escapeHTML(
  589. length $config{userdir} ? $config{userdir}."/".$user : $user
  590. ), 1);
  591. }
  592. } #}}}
  593. 1