summaryrefslogtreecommitdiff
path: root/IkiWiki/CGI.pm
blob: a41349be518a648fa9f71cd5df83b4810a3ce98c (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 || file_pruned($page, $config{srcdir}) || $page=~/^\//) {
  265. error("bad page name");
  266. }
  267. my $from;
  268. if (defined $form->field('from')) {
  269. ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
  270. }
  271. my $file;
  272. my $type;
  273. if (exists $pagesources{$page}) {
  274. $file=$pagesources{$page};
  275. $type=pagetype($file);
  276. }
  277. else {
  278. $type=$form->param('type');
  279. if (defined $type && length $type && $hooks{htmlize}{$type}) {
  280. $type=possibly_foolish_untaint($type);
  281. }
  282. elsif (defined $from) {
  283. # favor the type of linking page
  284. $type=pagetype($pagesources{$from});
  285. }
  286. $type=$config{default_pageext} unless defined $type;
  287. $file=$page.".".$type;
  288. }
  289. my $newfile=0;
  290. if (! -e "$config{srcdir}/$file") {
  291. $newfile=1;
  292. }
  293. $form->field(name => "do", type => 'hidden');
  294. $form->field(name => "from", type => 'hidden');
  295. $form->field(name => "rcsinfo", type => 'hidden');
  296. $form->field(name => "subpage", type => 'hidden');
  297. $form->field(name => "page", value => $page, force => 1);
  298. $form->field(name => "type", value => $type, force => 1);
  299. $form->field(name => "comments", type => "text", size => 80);
  300. $form->field(name => "editcontent", type => "textarea", rows => 20,
  301. cols => 80);
  302. $form->tmpl_param("can_commit", $config{rcs});
  303. $form->tmpl_param("indexlink", indexlink());
  304. $form->tmpl_param("helponformattinglink",
  305. htmllink("", "", "HelpOnFormatting", 1));
  306. $form->tmpl_param("baseurl", baseurl());
  307. if (! $form->submitted) {
  308. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  309. force => 1);
  310. }
  311. if ($form->submitted eq "Cancel") {
  312. if ($newfile && defined $from) {
  313. redirect($q, "$config{url}/".htmlpage($from));
  314. }
  315. elsif ($newfile) {
  316. redirect($q, $config{url});
  317. }
  318. else {
  319. redirect($q, "$config{url}/".htmlpage($page));
  320. }
  321. return;
  322. }
  323. elsif ($form->submitted eq "Preview") {
  324. my $content=$form->field('editcontent');
  325. my $comments=$form->field('comments');
  326. $form->field(name => "editcontent",
  327. value => $content, force => 1);
  328. $form->field(name => "comments",
  329. value => $comments, force => 1);
  330. $config{rss}=$config{atom}=0; # avoid preview writing a feed!
  331. $form->tmpl_param("page_preview",
  332. htmlize($page, $type,
  333. linkify($page, "",
  334. preprocess($page, $page,
  335. filter($page, $content)))));
  336. }
  337. else {
  338. $form->tmpl_param("page_preview", "");
  339. }
  340. $form->tmpl_param("page_conflict", "");
  341. if (! $form->submitted || $form->submitted eq "Preview" ||
  342. ! $form->validate) {
  343. if ($form->field("do") eq "create") {
  344. my @page_locs;
  345. my $best_loc;
  346. if (! defined $from || ! length $from ||
  347. $from ne $form->field('from') ||
  348. file_pruned($from, $config{srcdir}) ||
  349. $from=~/^\// ||
  350. $form->submitted eq "Preview") {
  351. @page_locs=$best_loc=$page;
  352. }
  353. else {
  354. my $dir=$from."/";
  355. $dir=~s![^/]+/+$!!;
  356. if ((defined $form->field('subpage') && length $form->field('subpage')) ||
  357. $page eq 'discussion') {
  358. $best_loc="$from/$page";
  359. }
  360. else {
  361. $best_loc=$dir.$page;
  362. }
  363. push @page_locs, $dir.$page;
  364. push @page_locs, "$from/$page";
  365. while (length $dir) {
  366. $dir=~s![^/]+/+$!!;
  367. push @page_locs, $dir.$page;
  368. }
  369. }
  370. @page_locs = grep {
  371. ! exists $pagecase{lc $_} &&
  372. ! page_locked($_, $session, 1)
  373. } @page_locs;
  374. if (! @page_locs) {
  375. # hmm, someone else made the page in the
  376. # meantime?
  377. redirect($q, "$config{url}/".htmlpage($page));
  378. return;
  379. }
  380. my @page_types;
  381. if (exists $hooks{htmlize}) {
  382. @page_types=keys %{$hooks{htmlize}};
  383. }
  384. $form->tmpl_param("page_select", 1);
  385. $form->field(name => "page", type => 'select',
  386. options => \@page_locs, value => $best_loc);
  387. $form->field(name => "type", type => 'select',
  388. options => \@page_types);
  389. $form->title("creating ".pagetitle($page));
  390. }
  391. elsif ($form->field("do") eq "edit") {
  392. page_locked($page, $session);
  393. if (! defined $form->field('editcontent') ||
  394. ! length $form->field('editcontent')) {
  395. my $content="";
  396. if (exists $pagesources{$page}) {
  397. $content=readfile(srcfile($pagesources{$page}));
  398. $content=~s/\n/\r\n/g;
  399. }
  400. $form->field(name => "editcontent", value => $content,
  401. force => 1);
  402. }
  403. $form->tmpl_param("page_select", 0);
  404. $form->field(name => "page", type => 'hidden');
  405. $form->field(name => "type", type => 'hidden');
  406. $form->title("editing ".pagetitle($page));
  407. }
  408. print $form->render(submit => \@buttons);
  409. }
  410. else {
  411. # save page
  412. page_locked($page, $session);
  413. my $content=$form->field('editcontent');
  414. $content=~s/\r\n/\n/g;
  415. $content=~s/\r/\n/g;
  416. writefile($file, $config{srcdir}, $content);
  417. if ($config{rcs}) {
  418. my $message="";
  419. if (defined $form->field('comments') &&
  420. length $form->field('comments')) {
  421. $message=$form->field('comments');
  422. }
  423. if ($newfile) {
  424. rcs_add($file);
  425. }
  426. # prevent deadlock with post-commit hook
  427. unlockwiki();
  428. # presumably the commit will trigger an update
  429. # of the wiki
  430. my $conflict=rcs_commit($file, $message,
  431. $form->field("rcsinfo"),
  432. $session->param("name"), $ENV{REMOTE_ADDR});
  433. if (defined $conflict) {
  434. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  435. force => 1);
  436. $form->tmpl_param("page_conflict", 1);
  437. $form->field("editcontent", value => $conflict, force => 1);
  438. $form->field(name => "comments", value => $form->field('comments'), force => 1);
  439. $form->field("do", "edit)");
  440. $form->tmpl_param("page_select", 0);
  441. $form->field(name => "page", type => 'hidden');
  442. $form->field(name => "type", type => 'hidden');
  443. $form->title("editing $page");
  444. print $form->render(submit => \@buttons);
  445. return;
  446. }
  447. }
  448. else {
  449. require IkiWiki::Render;
  450. refresh();
  451. saveindex();
  452. }
  453. # The trailing question mark tries to avoid broken
  454. # caches and get the most recent version of the page.
  455. redirect($q, "$config{url}/".htmlpage($page)."?updated");
  456. }
  457. } #}}}
  458. sub cgi_getsession ($) { #{{{
  459. my $q=shift;
  460. eval q{use CGI::Session};
  461. CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
  462. my $oldmask=umask(077);
  463. my $session = CGI::Session->new("driver:DB_File", $q,
  464. { FileName => "$config{wikistatedir}/sessions.db" });
  465. umask($oldmask);
  466. return $session;
  467. } #}}}
  468. sub cgi_savesession ($) { #{{{
  469. my $session=shift;
  470. # Force session flush with safe umask.
  471. my $oldmask=umask(077);
  472. $session->flush;
  473. umask($oldmask);
  474. }
  475. sub cgi (;$$) { #{{{
  476. my $q=shift;
  477. my $session=shift;
  478. if (! $q) {
  479. eval q{use CGI};
  480. error($@) if $@;
  481. $q=CGI->new;
  482. run_hooks(cgi => sub { shift->($q) });
  483. }
  484. my $do=$q->param('do');
  485. if (! defined $do || ! length $do) {
  486. my $error = $q->cgi_error;
  487. if ($error) {
  488. error("Request not processed: $error");
  489. }
  490. else {
  491. error("\"do\" parameter missing");
  492. }
  493. }
  494. # Things that do not need a session.
  495. if ($do eq 'recentchanges') {
  496. cgi_recentchanges($q);
  497. return;
  498. }
  499. elsif ($do eq 'hyperestraier') {
  500. cgi_hyperestraier();
  501. }
  502. # Need to lock the wiki before getting a session.
  503. lockwiki();
  504. if (! $session) {
  505. $session=cgi_getsession($q);
  506. }
  507. # Auth hooks can sign a user in.
  508. if ($do ne 'signin' && ! defined $session->param("name")) {
  509. run_hooks(auth => sub {
  510. shift->($q, $session)
  511. });
  512. if (defined $session->param("name")) {
  513. # Make sure whatever user was authed is in the
  514. # userinfo db.
  515. if (! userinfo_get($session->param("name"), "regdate")) {
  516. userinfo_setall($session->param("name"), {
  517. email => "",
  518. password => "",
  519. regdate => time,
  520. });
  521. }
  522. }
  523. }
  524. # Everything below this point needs the user to be signed in.
  525. if (((! $config{anonok} || $do eq 'prefs') &&
  526. (! defined $session->param("name") ||
  527. ! userinfo_get($session->param("name"), "regdate")))
  528. || $do eq 'signin') {
  529. if ($do ne 'signin' && ! defined $session->param("postsignin")) {
  530. $session->param(postsignin => $ENV{QUERY_STRING});
  531. }
  532. cgi_signin($q, $session);
  533. cgi_savesession($session);
  534. return;
  535. }
  536. elsif (defined $session->param("postsignin")) {
  537. cgi_postsignin($q, $session);
  538. }
  539. if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
  540. print $q->header(-status => "403 Forbidden");
  541. $session->delete();
  542. print "You are banned.";
  543. cgi_savesession($session);
  544. exit;
  545. }
  546. if ($do eq 'create' || $do eq 'edit') {
  547. cgi_editpage($q, $session);
  548. }
  549. elsif ($do eq 'prefs') {
  550. cgi_prefs($q, $session);
  551. }
  552. elsif ($do eq 'blog') {
  553. my $page=titlepage(decode_utf8($q->param('title')));
  554. # if the page already exists, munge it to be unique
  555. my $from=$q->param('from');
  556. my $add="";
  557. while (exists $pagecase{lc "$from/$page$add"}) {
  558. $add=1 unless length $add;
  559. $add++;
  560. }
  561. $q->param('page', $page.$add);
  562. # now run same as create
  563. $q->param('do', 'create');
  564. cgi_editpage($q, $session);
  565. }
  566. else {
  567. error("unknown do parameter");
  568. }
  569. } #}}}
  570. sub userlink ($) { #{{{
  571. my $user=shift;
  572. eval q{use CGI 'escapeHTML'};
  573. error($@) if $@;
  574. if ($user =~ m!^https?://! &&
  575. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  576. # Munge user-urls, as used by eg, OpenID.
  577. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  578. my $display=$oid->display;
  579. # Convert "user.somehost.com" to "user [somehost.com]".
  580. if ($display !~ /\[/) {
  581. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  582. }
  583. $display=~s!^https?://!!; # make sure this is removed
  584. return "<a href=\"$user\">".escapeHTML($display)."</a>";
  585. }
  586. else {
  587. return htmllink("", "", escapeHTML(
  588. length $config{userdir} ? $config{userdir}."/".$user : $user
  589. ), 1);
  590. }
  591. } #}}}
  592. 1