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