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