summaryrefslogtreecommitdiff
path: root/IkiWiki/CGI.pm
blob: 0c66705469185954acf8eadf4200bb17e0e18d36 (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. #translators: The first parameter is a page name,
  40. #translators: second is the user who locked it.
  41. error(sprintf(gettext("%s is locked by %s and cannot be edited"),
  42. htmllink("", "", $page, 1),
  43. userlink($admin)));
  44. }
  45. }
  46. return 0;
  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. sub cgi_signin ($$) { #{{{
  97. my $q=shift;
  98. my $session=shift;
  99. eval q{use CGI::FormBuilder};
  100. error($@) if $@;
  101. my $form = CGI::FormBuilder->new(
  102. title => "signin",
  103. header => 1,
  104. charset => "utf-8",
  105. method => 'POST',
  106. required => 'NONE',
  107. javascript => 0,
  108. params => $q,
  109. action => $config{cgiurl},
  110. header => 0,
  111. template => scalar template_params("signin.tmpl"),
  112. stylesheet => baseurl()."style.css",
  113. );
  114. my $buttons=["Login"];
  115. $form->field(name => "do", type => "hidden");
  116. if ($q->param("do") ne "signin" && !$form->submitted) {
  117. $form->text(gettext("You need to log in first."));
  118. }
  119. run_hooks(formbuilder_setup => sub {
  120. shift->(form => $form, cgi => $q, session => $session);
  121. });
  122. decode_form_utf8($form);
  123. if (exists $hooks{formbuilder}) {
  124. run_hooks(formbuilder => sub {
  125. shift->(form => $form, cgi => $q, session => $session,
  126. buttons => $buttons);
  127. });
  128. }
  129. else {
  130. if ($form->submitted) {
  131. $form->validate;
  132. }
  133. printheader($session);
  134. print misctemplate($form->title, $form->render(submit => $buttons));
  135. }
  136. } #}}}
  137. sub cgi_postsignin ($$) { #{{{
  138. my $q=shift;
  139. my $session=shift;
  140. # Continue with whatever was being done before the signin process.
  141. if (defined $q->param("do") && $q->param("do") ne "signin" &&
  142. defined $session->param("postsignin")) {
  143. my $postsignin=CGI->new($session->param("postsignin"));
  144. $session->clear("postsignin");
  145. cgi($postsignin, $session);
  146. cgi_savesession($session);
  147. exit;
  148. }
  149. else {
  150. redirect($q, $config{url});
  151. }
  152. } #}}}
  153. sub cgi_prefs ($$) { #{{{
  154. my $q=shift;
  155. my $session=shift;
  156. eval q{use CGI::FormBuilder};
  157. error($@) if $@;
  158. my $form = CGI::FormBuilder->new(
  159. title => "preferences",
  160. header => 0,
  161. charset => "utf-8",
  162. method => 'POST',
  163. validate => {
  164. email => 'EMAIL',
  165. },
  166. required => 'NONE',
  167. javascript => 0,
  168. params => $q,
  169. action => $config{cgiurl},
  170. template => scalar 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 => scalar 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 gettext('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. push @page_locs, "$config{userdir}/$page"
  371. if length $config{userdir};
  372. @page_locs = grep {
  373. ! exists $pagecase{lc $_} &&
  374. ! page_locked($_, $session, 1)
  375. } @page_locs;
  376. if (! @page_locs) {
  377. # hmm, someone else made the page in the
  378. # meantime?
  379. redirect($q, "$config{url}/".htmlpage($page));
  380. return;
  381. }
  382. my @page_types;
  383. if (exists $hooks{htmlize}) {
  384. @page_types=keys %{$hooks{htmlize}};
  385. }
  386. $form->tmpl_param("page_select", 1);
  387. $form->field(name => "page", type => 'select',
  388. options => \@page_locs, value => $best_loc);
  389. $form->field(name => "type", type => 'select',
  390. options => \@page_types);
  391. $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
  392. }
  393. elsif ($form->field("do") eq "edit") {
  394. page_locked($page, $session);
  395. if (! defined $form->field('editcontent') ||
  396. ! length $form->field('editcontent')) {
  397. my $content="";
  398. if (exists $pagesources{$page}) {
  399. $content=readfile(srcfile($pagesources{$page}));
  400. $content=~s/\n/\r\n/g;
  401. }
  402. $form->field(name => "editcontent", value => $content,
  403. force => 1);
  404. }
  405. $form->tmpl_param("page_select", 0);
  406. $form->field(name => "page", type => 'hidden');
  407. $form->field(name => "type", type => 'hidden');
  408. $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
  409. }
  410. print $form->render(submit => \@buttons);
  411. }
  412. else {
  413. # save page
  414. page_locked($page, $session);
  415. my $content=$form->field('editcontent');
  416. $content=~s/\r\n/\n/g;
  417. $content=~s/\r/\n/g;
  418. writefile($file, $config{srcdir}, $content);
  419. if ($config{rcs}) {
  420. my $message="";
  421. if (defined $form->field('comments') &&
  422. length $form->field('comments')) {
  423. $message=$form->field('comments');
  424. }
  425. if ($newfile) {
  426. rcs_add($file);
  427. }
  428. # prevent deadlock with post-commit hook
  429. unlockwiki();
  430. # presumably the commit will trigger an update
  431. # of the wiki
  432. my $conflict=rcs_commit($file, $message,
  433. $form->field("rcsinfo"),
  434. $session->param("name"), $ENV{REMOTE_ADDR});
  435. if (defined $conflict) {
  436. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  437. force => 1);
  438. $form->tmpl_param("page_conflict", 1);
  439. $form->field("editcontent", value => $conflict, force => 1);
  440. $form->field(name => "comments", value => $form->field('comments'), force => 1);
  441. $form->field("do", "edit)");
  442. $form->tmpl_param("page_select", 0);
  443. $form->field(name => "page", type => 'hidden');
  444. $form->field(name => "type", type => 'hidden');
  445. $form->title(sprintf(gettext("editing %s"), $page));
  446. print $form->render(submit => \@buttons);
  447. return;
  448. }
  449. else {
  450. # Make sure that the repo is up-to-date;
  451. # locking prevents the post-commit hook
  452. # from updating it.
  453. rcs_update();
  454. }
  455. }
  456. else {
  457. require IkiWiki::Render;
  458. refresh();
  459. saveindex();
  460. }
  461. # The trailing question mark tries to avoid broken
  462. # caches and get the most recent version of the page.
  463. redirect($q, "$config{url}/".htmlpage($page)."?updated");
  464. }
  465. } #}}}
  466. sub cgi_getsession ($) { #{{{
  467. my $q=shift;
  468. eval q{use CGI::Session};
  469. CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
  470. my $oldmask=umask(077);
  471. my $session = CGI::Session->new("driver:DB_File", $q,
  472. { FileName => "$config{wikistatedir}/sessions.db" });
  473. umask($oldmask);
  474. return $session;
  475. } #}}}
  476. sub cgi_savesession ($) { #{{{
  477. my $session=shift;
  478. # Force session flush with safe umask.
  479. my $oldmask=umask(077);
  480. $session->flush;
  481. umask($oldmask);
  482. }
  483. sub cgi (;$$) { #{{{
  484. my $q=shift;
  485. my $session=shift;
  486. if (! $q) {
  487. eval q{use CGI};
  488. error($@) if $@;
  489. $q=CGI->new;
  490. run_hooks(cgi => sub { shift->($q) });
  491. }
  492. my $do=$q->param('do');
  493. if (! defined $do || ! length $do) {
  494. my $error = $q->cgi_error;
  495. if ($error) {
  496. error("Request not processed: $error");
  497. }
  498. else {
  499. error("\"do\" parameter missing");
  500. }
  501. }
  502. # Things that do not need a session.
  503. if ($do eq 'recentchanges') {
  504. cgi_recentchanges($q);
  505. return;
  506. }
  507. elsif ($do eq 'hyperestraier') {
  508. cgi_hyperestraier();
  509. }
  510. # Need to lock the wiki before getting a session.
  511. lockwiki();
  512. if (! $session) {
  513. $session=cgi_getsession($q);
  514. }
  515. # Auth hooks can sign a user in.
  516. if ($do ne 'signin' && ! defined $session->param("name")) {
  517. run_hooks(auth => sub {
  518. shift->($q, $session)
  519. });
  520. if (defined $session->param("name")) {
  521. # Make sure whatever user was authed is in the
  522. # userinfo db.
  523. if (! userinfo_get($session->param("name"), "regdate")) {
  524. userinfo_setall($session->param("name"), {
  525. email => "",
  526. password => "",
  527. regdate => time,
  528. });
  529. }
  530. }
  531. }
  532. # Everything below this point needs the user to be signed in.
  533. if (((! $config{anonok} || $do eq 'prefs') &&
  534. (! defined $session->param("name") ||
  535. ! userinfo_get($session->param("name"), "regdate")))
  536. || $do eq 'signin') {
  537. if ($do ne 'signin' && ! defined $session->param("postsignin")) {
  538. $session->param(postsignin => $ENV{QUERY_STRING});
  539. }
  540. cgi_signin($q, $session);
  541. cgi_savesession($session);
  542. return;
  543. }
  544. elsif (defined $session->param("postsignin")) {
  545. cgi_postsignin($q, $session);
  546. }
  547. if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
  548. print $q->header(-status => "403 Forbidden");
  549. $session->delete();
  550. print gettext("You are banned.");
  551. cgi_savesession($session);
  552. exit;
  553. }
  554. if ($do eq 'create' || $do eq 'edit') {
  555. cgi_editpage($q, $session);
  556. }
  557. elsif ($do eq 'prefs') {
  558. cgi_prefs($q, $session);
  559. }
  560. elsif ($do eq 'blog') {
  561. my $page=titlepage(decode_utf8($q->param('title')));
  562. $page=~s/(\/)/"__".ord($1)."__"/eg; # escape slashes too
  563. # if the page already exists, munge it to be unique
  564. my $from=$q->param('from');
  565. my $add="";
  566. while (exists $pagecase{lc "$from/$page$add"}) {
  567. $add=1 unless length $add;
  568. $add++;
  569. }
  570. $q->param('page', $page.$add);
  571. # now run same as create
  572. $q->param('do', 'create');
  573. cgi_editpage($q, $session);
  574. }
  575. elsif ($do eq 'postsignin') {
  576. error(gettext("login failed, perhaps you need to turn on cookies?"));
  577. }
  578. else {
  579. error("unknown do parameter");
  580. }
  581. } #}}}
  582. sub userlink ($) { #{{{
  583. my $user=shift;
  584. eval q{use CGI 'escapeHTML'};
  585. error($@) if $@;
  586. if ($user =~ m!^https?://! &&
  587. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  588. # Munge user-urls, as used by eg, OpenID.
  589. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  590. my $display=$oid->display;
  591. # Convert "user.somehost.com" to "user [somehost.com]".
  592. if ($display !~ /\[/) {
  593. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  594. }
  595. # Convert "http://somehost.com/user" to "user [somehost.com]".
  596. if ($display !~ /\[/) {
  597. $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
  598. }
  599. $display=~s!^https?://!!; # make sure this is removed
  600. return "<a href=\"$user\">".escapeHTML($display)."</a>";
  601. }
  602. else {
  603. return htmllink("", "", escapeHTML(
  604. length $config{userdir} ? $config{userdir}."/".$user : $user
  605. ), 1);
  606. }
  607. } #}}}
  608. 1