summaryrefslogtreecommitdiff
path: root/IkiWiki/CGI.pm
blob: 71a3299a47ce4807947c227e8242df0cb9610bc7 (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);
  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. }
  450. else {
  451. require IkiWiki::Render;
  452. refresh();
  453. saveindex();
  454. }
  455. # The trailing question mark tries to avoid broken
  456. # caches and get the most recent version of the page.
  457. redirect($q, "$config{url}/".htmlpage($page)."?updated");
  458. }
  459. } #}}}
  460. sub cgi_getsession ($) { #{{{
  461. my $q=shift;
  462. eval q{use CGI::Session};
  463. CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
  464. my $oldmask=umask(077);
  465. my $session = CGI::Session->new("driver:DB_File", $q,
  466. { FileName => "$config{wikistatedir}/sessions.db" });
  467. umask($oldmask);
  468. return $session;
  469. } #}}}
  470. sub cgi_savesession ($) { #{{{
  471. my $session=shift;
  472. # Force session flush with safe umask.
  473. my $oldmask=umask(077);
  474. $session->flush;
  475. umask($oldmask);
  476. }
  477. sub cgi (;$$) { #{{{
  478. my $q=shift;
  479. my $session=shift;
  480. if (! $q) {
  481. eval q{use CGI};
  482. error($@) if $@;
  483. $q=CGI->new;
  484. run_hooks(cgi => sub { shift->($q) });
  485. }
  486. my $do=$q->param('do');
  487. if (! defined $do || ! length $do) {
  488. my $error = $q->cgi_error;
  489. if ($error) {
  490. error("Request not processed: $error");
  491. }
  492. else {
  493. error("\"do\" parameter missing");
  494. }
  495. }
  496. # Things that do not need a session.
  497. if ($do eq 'recentchanges') {
  498. cgi_recentchanges($q);
  499. return;
  500. }
  501. elsif ($do eq 'hyperestraier') {
  502. cgi_hyperestraier();
  503. }
  504. # Need to lock the wiki before getting a session.
  505. lockwiki();
  506. if (! $session) {
  507. $session=cgi_getsession($q);
  508. }
  509. # Auth hooks can sign a user in.
  510. if ($do ne 'signin' && ! defined $session->param("name")) {
  511. run_hooks(auth => sub {
  512. shift->($q, $session)
  513. });
  514. if (defined $session->param("name")) {
  515. # Make sure whatever user was authed is in the
  516. # userinfo db.
  517. if (! userinfo_get($session->param("name"), "regdate")) {
  518. userinfo_setall($session->param("name"), {
  519. email => "",
  520. password => "",
  521. regdate => time,
  522. });
  523. }
  524. }
  525. }
  526. # Everything below this point needs the user to be signed in.
  527. if (((! $config{anonok} || $do eq 'prefs') &&
  528. (! defined $session->param("name") ||
  529. ! userinfo_get($session->param("name"), "regdate")))
  530. || $do eq 'signin') {
  531. if ($do ne 'signin' && ! defined $session->param("postsignin")) {
  532. $session->param(postsignin => $ENV{QUERY_STRING});
  533. }
  534. cgi_signin($q, $session);
  535. cgi_savesession($session);
  536. return;
  537. }
  538. elsif (defined $session->param("postsignin")) {
  539. cgi_postsignin($q, $session);
  540. }
  541. if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
  542. print $q->header(-status => "403 Forbidden");
  543. $session->delete();
  544. print gettext("You are banned.");
  545. cgi_savesession($session);
  546. exit;
  547. }
  548. if ($do eq 'create' || $do eq 'edit') {
  549. cgi_editpage($q, $session);
  550. }
  551. elsif ($do eq 'prefs') {
  552. cgi_prefs($q, $session);
  553. }
  554. elsif ($do eq 'blog') {
  555. my $page=titlepage(decode_utf8($q->param('title')));
  556. $page=~s/(\/)/"__".ord($1)."__"/eg; # escape slashes too
  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. elsif ($do eq 'postsignin') {
  570. error(gettext("login failed, perhaps you need to turn on cookies?"));
  571. }
  572. else {
  573. error("unknown do parameter");
  574. }
  575. } #}}}
  576. sub userlink ($) { #{{{
  577. my $user=shift;
  578. eval q{use CGI 'escapeHTML'};
  579. error($@) if $@;
  580. if ($user =~ m!^https?://! &&
  581. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  582. # Munge user-urls, as used by eg, OpenID.
  583. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  584. my $display=$oid->display;
  585. # Convert "user.somehost.com" to "user [somehost.com]".
  586. if ($display !~ /\[/) {
  587. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  588. }
  589. # Convert "http://somehost.com/user" to "user [somehost.com]".
  590. if ($display !~ /\[/) {
  591. $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
  592. }
  593. $display=~s!^https?://!!; # make sure this is removed
  594. return "<a href=\"$user\">".escapeHTML($display)."</a>";
  595. }
  596. else {
  597. return htmllink("", "", escapeHTML(
  598. length $config{userdir} ? $config{userdir}."/".$user : $user
  599. ), 1);
  600. }
  601. } #}}}
  602. 1