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