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