/[pub]/suikawiki/script/wiki.cgi
Suika

Diff of /suikawiki/script/wiki.cgi

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.44 by w, Wed Jan 1 12:30:24 2003 UTC revision 1.51 by w, Sun Jan 26 02:30:24 2003 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl  #!/usr/bin/perl
2  # wiki.cgi - This is YukiWiki, yet another Wiki clone.  ## wiki.cgi - This is SuikaWiki, yet another WikiEngine
 #  
 # This program is free software; you can redistribute it and/or  
 # modify it under the same terms as Perl itself.  
3    
4  use strict;  use strict;
5  use lib qw(./lib);  use lib qw(./lib);
6  use CGI::Carp qw(fatalsToBrowser);  use CGI::Carp qw(fatalsToBrowser);
7    binmode STDOUT; binmode STDIN;
8  require 'wikidata/suikawiki-config.ph';  our $VERSION = do{my @r=(q$Revision$=~/\d+/g);sprintf "%d."."%02d" x $#r,@r};
9  use Yuki::DiffText qw(difftext);  require 'wikidata/suikawiki-config.ph'; ## site configuration script
10    require Yuki::YukiWikiCache;
11  use Fcntl;  use Fcntl;
12  ##############################  our %fmt;       ## formatter objects
13  my %fmt;        ## formatter objects  our %embed_command = (
 my %embed_command = (  
14          searched        => '^\[\[#searched:([^\]]+)\]\]$',          searched        => '^\[\[#searched:([^\]]+)\]\]$',
15          form    => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,          form    => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
16  );  );
17  our ($modifier_dbtype,$url_cgi,%uri,%PathTo,$use_exists);  our ($modifier_dbtype,$url_cgi,%uri,%PathTo);
18  our (%PageName,$kanjicode,$lang,%fixedpage);  our (%PageName,$kanjicode,$lang,%ViewDefinition);
19    
 ##############################  
 my $info_LastModified = 'LastModified';  
 my $info_IsFrozen = 'IsFrozen';  
 ##############################  
20  my %form;  my %form;
21  my %database;  our %database;
22  my %infobase;  our $database = bless {}, 'wiki::dummy';
 my %diffbase;  
23  my %interwiki;  my %interwiki;
 ##############################  
 my %page_command = (  
     $PageName{IndexPage} => 'index',  
     $PageName{RssPage} => 'rss',  
     AdminChangePassword => 'adminchangepasswordform',  
 );  
24  my %command_do = (  my %command_do = (
25      read => \&do_read,      default => \&do_view,
     TEXT_CSS => \&do_output_css,  
     edit => \&do_edit,  
     adminedit => \&do_adminedit,  
     adminchangepasswordform => \&do_adminchangepasswordform,  
26      adminchangepassword => \&do_adminchangepassword,      adminchangepassword => \&do_adminchangepassword,
27      write => \&do_write,      write => \&do_write,
     index => \&do_index,  
28      searchform => \&do_searchform,      searchform => \&do_searchform,
29      comment => \&do_comment,      comment => \&do_comment,
30      RandomJump  => \&do_random_jump,      RandomJump  => \&do_random_jump,
     rss => \&do_rss,  
     diff => \&do_diff,  
31      wikiform    => \&do_wikiform,      wikiform    => \&do_wikiform,
     map => \&do_map,  
32  );  );
33  my $UA = '';  ## User agent name  our $UA = '';  ## User agent name
34  $| = 1;  $| = 1;
 ##############################  
35    
36  sub main {  sub main {
37      $UA = $main::ENV{HTTP_USER_AGENT};      $UA = $main::ENV{HTTP_USER_AGENT};
# Line 63  sub main { Line 40  sub main {
40      if ($command_do{$form{mycmd}}) {      if ($command_do{$form{mycmd}}) {
41          &{$command_do{$form{mycmd}}};          &{$command_do{$form{mycmd}}};
42      } else {      } else {
43          &{$command_do{read}};          &{$command_do{default}};
44      }      }
45      &close_db;      &close_db;
46  }  }
47    
48  sub do_read {  sub do_view {
49    my $content = $database{$form{mypage}};    my $content = $database{$form{mypage}};
50    #print "content-type:text/plain;charset=euc-jp\n\n".gmtime."Get Lastmodified\n";    my $lm = $database->mtime ($form{mypage});
   my $lm = &get_info($form{mypage}, $info_LastModified);  
51    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
52    wiki::useragent::add ($ENV{HTTP_USER_AGENT});    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
53    #print gmtime."Search...\n";    &load_formatter ('view');
54    my ($r, $c) = get_search_result ($form{mypage});      my $view = $form{mycmd};
55    my $rl = wiki::referer::list_html ($form{mypage});      if ($view eq 'edit') {
56    my @toc;        $view = 'adminedit' if $form{admin};
57    push @toc, qq(-<a href="#wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</a>) if $c;      } elsif ($view =~ /[^0-9A-Za-z]/) {
58    push @toc, qq(-<a href="#wikipage-referer">@{[&Resource('Referers',escape=>1)]}</a>) if $rl;        $view = 'default'
59      my $cf = 'SuikaWiki/0.9';      }
60      ## Should be support at least:      if ($view eq 'default' || !$view) {
61      ## - 'SuikaWiki/0.9' CRLF        ## BUG: this code is not strict
62      ## - 'H2H/' ("0.9" / "1.0" / "1.1") CRLF        if ($main::ENV{HTTP_COOKIE} =~ /SelectedMode=([0-9A-Za-z]+)/) {
63      ## - "/*" WSP* 'W3C-CSS/' ("1.0" / "2.0") "*/" CRLF          $view = $1;
64      $cf = $1 if $content =~ s#^(?:/\*\s*|[\#<]\?)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+##s;        } else {
65      if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {          $view = 'read';
66      #print gmtime."Header...\n";        }
       &print_header ($form{mypage}, -last_modified => $lm, -expires => time + 120,  
         -content_format => $cf, -noindex => ($cf =~ /obsoleted="yes"/ ? 1 : 0));  
         #print "\n". gmtime."Body...\n";  
       &print_content ($content, content_format => $cf, last_modified => $lm,  
         -toc => \@toc);  
       print &text_to_html (q([[#comment]])) if $cf !~ /obsoleted="yes"/ && !$fixedpage{$form{mypage}};  
     } else {  
       &print_header($form{mypage}, -expires => time + 120, -last_modified => $lm);  
       print "<pre>@{[&escape($content)]}</pre>";  
     }  
     if ($c) {  
       print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};  
       print $r;  
     }  
     if ($rl) {  
       print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);  
67      }      }
68          #print "\n". gmtime."Footer...\n";    my ($magic, $content) = &SuikaWiki::Plugin::magic_and_content (undef, $content);
69    &print_footer($form{mypage}, $lm);    $magic ||= '#?SuikaWiki/0.9';
70          #print "\n". gmtime."Fin...\n";    my $o = bless {param => \%form, page => $form{mypage}, toc => [],
71                     magic => $magic, content => $content,
72                     formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin';
73      if (!ref $ViewDefinition{$view} || !&{$ViewDefinition{$view}->{check}} ($o)) {
74        print "Status: 406 Unsupported Media Type\n";
75        $view = '-UnsupportedMediaType';
76      }
77      my $media = $ViewDefinition{$view}->{media};
78      if ($ViewDefinition{$view}->{xmedia} && $UA =~ /Gecko/) {
79        $media = $ViewDefinition{$view}->{xmedia};
80        $o->{media} = $media;
81      } elsif ($UA =~ m#Mozilla/0\..+Windows#) {
82        $kanjicode = 'shift_jis';
83      }
84        if ($magic =~ m!^\#\?SuikaWiki/0.9!) {
85          &print_header ($form{mypage}, -last_modified => ($magic =~ /interactive="yes"/ ? time : $lm),
86            -expires => ($magic =~ /interactive="yes"/ ? 1 : undef), o => $o,
87            -media => $media, -magic => $magic,  content => $content);
88        } else {
89          &print_header($form{mypage}, -media => $media,
90                                       -magic => $magic, -last_modified => $lm, o => $o);
91        }
92      if ($kanjicode ne 'euc') {
93        my $s = $fmt{view}->replace ($ViewDefinition{$view}->{template} => $o);
94        print &code_convert (\$s => $kanjicode);
95      } else {
96        print $fmt{view}->replace ($ViewDefinition{$view}->{template} => $o);
97      }
98  }  }
99    
100  sub do_output_css {  sub _do_view_msg (%) {
101    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});    my %option = @_;
102    wiki::useragent::add ($ENV{HTTP_USER_AGENT});    &load_formatter ('view');
103    my $content = $database{$form{mypage}};    my $o = bless {param => \%form, page => $option{-page}, toc => [], condition => \%option,
104    if ($content =~ m#^\s*/\*\s*W3C-CSS#) {                   formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin';
105      my $lm = gmtime &get_info($form{mypage}, $info_LastModified);    unless (&{$ViewDefinition{$option{-view}}->{check}} ($o)) {
     print "Content-Type: text/css; charset=@{[&get_charset_name($kanjicode)]}\n";  
     print "Last-Modified: $lm\n";  
     print "Expires: @{[scalar gmtime time+3600]}\n";    ## TODO: don't use asctime  
     print "\n";  
     print $content;  
   } else {  
106      print "Status: 406 Unsupported Media Type\n";      print "Status: 406 Unsupported Media Type\n";
107      &print_header('WikiPageIsNotCSS', -noindex => 1);      $option{-view} = '-UnsupportedMediaType';
108      &print_content($database{WikiPageIsNotCSS});    }
109      &print_footer('WikiPageIsNotCSS');    my $media = $ViewDefinition{$option{-view}}->{media};
110      if ($ViewDefinition{$option{-view}}->{xmedia} && $UA =~ /Gecko/) {
111        $media = $ViewDefinition{$option{-view}}->{xmedia};
112        $o->{media} = $media;
113    }    }
114      &print_header($option{-page}, -media => $media, o => $o, -goto => $option{-goto});
115      print $fmt{view}->replace ($ViewDefinition{$option{-view}}->{template} => $o);
116  }  }
117    
118  sub id_and_name ($) {  sub id_and_name ($) {
# Line 138  sub id_and_name ($) { Line 124  sub id_and_name ($) {
124      }      }
125  }  }
126    
 sub do_edit {  
     my ($page) = &unarmor_name(&armor_name($form{mypage}));  
     if (not &is_editable($page)) {  
         &print_header($page, -noindex => 1);  
         &print_message(&Resource('Error:ThisPageIsUneditable'));  
     } elsif (&is_frozen($page)) {  
         &print_header($page, -noindex => 1);  
         &print_message(&Resource('Error:ThisPageIsUneditable'));  
     } else {  
         &print_header($page, -noindex => 1, -expires => time+60);  
         &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);  
     }  
     wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});  
     wiki::useragent::add ($ENV{HTTP_USER_AGENT});  
     my ($r, $c) = get_search_result ($form{mypage});  
     my $rl = wiki::referer::list_html ($form{mypage});  
     if ($c) {  
       print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};  
       print $r;  
     }  
     if ($rl) {  
       print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);  
     }  
     &print_footer($page);  
 }  
   
 sub do_adminedit {  
     my ($page) = &unarmor_name(&armor_name($form{mypage}));  
     &print_header($page, -noindex => 1);  
     if (not &is_editable($page)) {  
         &print_message(&Resource('Error:ThisPageIsUneditable'));  
     } else {  
         &print_message(&Resource('Error:PasswordIsNotSpecified'));  
         &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);  
     }  
     &print_footer($page);  
 }  
   
 sub do_adminchangepasswordform {  
     &print_header('AdminChangePassword', -noindex => 1);  
     &print_passwordform;  
     &print_footer('AdminChangePassword');  
 }  
   
127  sub do_adminchangepassword {  sub do_adminchangepassword {
128      if ($form{mynewpassword} ne $form{mynewpassword2}) {      if ($form{mynewpassword} ne $form{mynewpassword2}) {
129          &print_error(&Resource('Error:PasswordMismatch'));          &_do_view_msg (-view => '-error', -page => $form{mypage},
130                           error_message => &Resource ('Error:PasswordMismatch'));
131            return;
132      }      }
133      my ($validpassword_crypt) = &get_info($PageName{AdminSpecialPage}, 'AdminPassword');      my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
134      if ($validpassword_crypt) {      if ($validpassword_crypt) {
135          if (not &valid_password($form{myoldpassword})) {          if (not &valid_password($form{myoldpassword})) {
136  #            &send_mail_to_admin(<<"EOD", "AdminChangePassword");              &_do_view_msg (-view => '-error', -page => $form{mypage},
137  #myoldpassword=$form{myoldpassword}                             error_message => &Resource ('Error:PasswordIsIncorrect'));
138  #mynewpassword=$form{mynewpassword}              return;
 #mynewpassword2=$form{mynewpassword2}  
 #EOD  
             &print_error(&Resource('Error:PasswordIsIncorrect'));  
139          }          }
140      }      }
141      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
# Line 202  sub do_adminchangepassword { Line 143  sub do_adminchangepassword {
143      my $salt1 = $token[(time | $$) % scalar(@token)];      my $salt1 = $token[(time | $$) % scalar(@token)];
144      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
145      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
146      &set_info($PageName{AdminSpecialPage}, 'AdminPassword', $crypted);      $database->meta (AdminPassword => $PageName{AdminSpecialPage} => $crypted);
147        
148      &print_header('CompletedSuccessfully', -noindex => 1);      &_do_view_msg (-view => '-wrote', -page => $form{mypage});
     &print_message(&Resource('Error:PasswordIsChanged'));  
     &print_footer('CompletedSuccessfully');  
149  }  }
150    
151  sub do_index {  sub valid_password ($) {
152    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});      my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
153    wiki::useragent::add ($ENV{HTTP_USER_AGENT});      return crypt (shift, $validpassword_crypt) eq $validpassword_crypt ? 1 : 0;
     &print_header($PageName{IndexPage});  
     print qq(<ul>);  
     foreach my $page (sort keys %database) {  
         if (&is_editable($page)) {  
             print qq(<li><a href="$url_cgi?@{[&encode($page)]}">@{[&escape($page)]}</a>@{[&escape(&get_subjectline($page))]}</li>);  
         }  
     }  
     print qq(</ul>);  
     my ($r, $c) = get_search_result ($form{mypage});  
     if ($c) {  
       print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};  
       print $r;  
     }  
     my $rl = wiki::referer::list_html ($form{mypage});  
     if ($rl) {  
         print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);  
     }  
     &print_footer($PageName{IndexPage});  
154  }  }
155    
156  sub do_write {  sub do_write {
# Line 238  sub do_write { Line 159  sub do_write {
159      }      }
160    
161      if (not &is_editable($form{mypage})) {      if (not &is_editable($form{mypage})) {
162          &print_header($form{mypage}, -noindex => 1);          &_do_view_msg (-view => '-error', -page => $form{mypage},
163          &print_message(&Resource('Error:ThisPageIsUneditable'));                         error_message => &Resource ('Error:ThisPageIsUneditable'));
         &print_footer($form{mypage});  
164          return;          return;
165      }      }
166    
167      if (&conflict($form{mypage}, $form{mymsg})) {      ## Check confliction
168          return;      if ($form{myLastModified} ne $database->mtime ($form{mypage})) {
169      }        &_do_view_msg (-view => '-conflict', -page => $form{mypage});
170          return;
     # Making diff  
     {  
         &open_diff;  
         my @msg1 = split(/\n/, $database{$form{mypage}});  
         my @msg2 = split(/\n/, $form{mymsg});  
         $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);  
         &close_diff;  
171      }      }
172    
173      if ($form{mymsg}) {      if ($form{mymsg}) {
174          $database{$form{mypage}} = $form{mymsg};          if ($form{mytouch} || !ref $database) {
175          #&send_mail_to_admin($form{mypage}, "Modify");            $database{$form{mypage}} = $form{mymsg};
176          if ($form{mytouch}) {          } else {
177              &set_info($form{mypage}, $info_LastModified, time);            $database->STORE ($form{mypage} => $form{mymsg}, -touch => 0);
             &update_recent_changes;  
178          }          }
179          &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});          $database->meta (IsFrozen => $form{mypage} => 0 + $form{myfrozen});
180          my $fragment = '';          my $fragment = '';
181          $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};          $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
182          if ($form{__comment_anchor_index}) {          if ($form{__comment_anchor_index}) {
# Line 272  sub do_write { Line 184  sub do_write {
184          } elsif ($form{__wikiform_anchor_index}) {          } elsif ($form{__wikiform_anchor_index}) {
185              $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});              $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
186          }          }
187          &print_header('CompletedSuccessfully', -noindex => 1, -goto => $url_cgi.'?mycmd='.&encode($form{after_edit_cmd}||'read').';mypage='.&encode($form{mypage}).qq(;x-param=@{[time.[0..9]->[rand 10]]}$fragment));          &_do_view_msg (-view => '-wrote', -page => $form{mypage}, -goto => $url_cgi.'?mycmd='.&encode($form{after_edit_cmd}||'default').';mypage='.&encode($form{mypage}).qq(;x-param=@{[time.[0..9]->[rand 10]]}$fragment));
         &print_message(&Resource('Error:SavedSuccessfully'));  
         &print_content(&Resource('Error:ContinueReading')." @{[&armor_name($form{mypage})]}");  
         &print_footer('CompletedSuccessfully');  
188      } else {      } else {
         #&send_mail_to_admin($form{mypage}, "Delete");  
189          delete $database{$form{mypage}};          delete $database{$form{mypage}};
190          delete $infobase{$form{mypage}};          &_do_view_msg (-view => '-deleted', -page => $form{mypage});
         if ($form{mytouch}) {  
             &update_recent_changes;  
         }  
         &print_header($form{mypage}, -noindex => 1);  
         &print_message(&Resource('Error:PageIsDeletedSuccessfully'));  
         &print_footer($form{mypage});  
191      }      }
192  }  }
193    
194    sub _compatible_options () {
195      (use_anchor_name => ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer# ? 1 : 0));
196    }
197    
198  sub get_search_result ($;%) {  sub get_search_result ($;%) {
199    my $word = lc shift;    my $word = lc shift;
200      my $SearchResult = SuikaWiki::Plugin->cache ('search');
201    my %option = @_;    my %option = @_;
202    my @r;    my @r;
203    foreach my $page (keys %database) {    unless (defined $SearchResult->{$word}) {
204      next if !$option{-match_myself} && ($page eq $word);      for my $page (keys %database) {
205      my $content = lc $database{$page};        next if !$option{-match_myself} && ($page eq $word);
206      if (index (lc $page, $word) > -1) {        my $content = lc $database{$page};
207        my $c = $content =~ s/\Q$word\E//g;        $content =~ s/^[^\x0A\x0D]+[\x0D\x0A]+//s;
208        push @r, [$page, $c+20];        if (index (lc $page, $word) > -1) {
209      } elsif (index ($word, lc $page) > -1) {          my $c = $content =~ s/\Q$word\E//g;
210        my $c = $content =~ s/\Q$word\E//g;          push @r, [$page, $c+20];
211        push @r, [$page, $c+10];        } elsif (index ($word, lc $page) > -1) {
212      } elsif (my $c = $content =~ s/\Q$word\E//g) {          my $c = $content =~ s/\Q$word\E//g;
213        push @r, [$page, $c];          push @r, [$page, $c+10];
214          } elsif (my $c = $content =~ s/\Q$word\E//g) {
215            push @r, [$page, $c];
216          }
217      }      }
218        @r = sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]} @r;
219        $SearchResult->{$word} = join "\x1E", map {$_->[0]."\x1F".$_->[1]} @r;
220      } else {
221        @r = map {[split /\x1F/, $_, 2]} split /\x1E/, $SearchResult->{$word};
222    }    }
223    #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };    #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
224    my $r = join "\n", map {qq(<li>[$_->[1]] <a href ="$url_cgi?@{[&encode($_->[0])]}" class="wiki">@{[&escape($_->[0])]}</a> <span class="wikipage-summary">@{[&escape(&get_subjectline($_->[0]))]}</span></li>)} sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]} @r;    my $r = join "\n", map {qq(<li>[$_->[1]] <a href ="$url_cgi?@{[&encode($_->[0])]}" class="wiki">@{[&escape($_->[0])]}</a> <span class="wikipage-summary">@{[&escape(&get_subjectline($_->[0]))]}</span></li>)} @r;
225    $r = qq|<ul class="search-result">$r</ul>| if $r;    $r = qq|<ul class="search-result">$r</ul>| if $r;
226    wantarray? ($r, scalar @r): $r;    wantarray? ($r, scalar @r): $r;
227  }  }
# Line 315  sub get_search_result ($;%) { Line 229  sub get_search_result ($;%) {
229  sub do_random_jump {  sub do_random_jump {
230    my @list = keys %database;    my @list = keys %database;
231    my $name = &encode ($list[rand @list]);    my $name = &encode ($list[rand @list]);
232    my $scheme = 'http';    print "Location: $uri{wiki}?$name\n";
   $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;  
   print "Location: $scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi?$name\n";  
233    print "\n";    print "\n";
234  }  }
235    
 sub print_error {  
     my ($msg) = @_;  
     &print_header($PageName{ErrorPage}, -noindex => 1);  
     print qq(<p><strong class="error">$msg</strong></p>);  
     &print_footer($PageName{ErrorPage});  
     exit(0);  
 }  
   
236  sub print_header ($;%) {  sub print_header ($;%) {
237      my ($page, %option) = @_;      my ($page, %option) = @_;
238      my @head;      my @head;
239      $option{body_class} = &is_frozen($page) ? 'frozen' : 'normal';      $option{o}->{-header}->{class} = &is_frozen($page) ? 'frozen' : '';
240      $option{body_class} .= " wiki-page-obsoleted" if $option{-content_format} =~ /obsoleted="yes"/;      $option{o}->{-header}->{class} .= " wiki-page-obsoleted" if $option{-magic} =~ /obsoleted="yes"/;
241      if ($option{-goto}) {      if ($option{-goto}) {
242        if ($UA =~ m#Opera|MSIE 2\.#) {        if ($UA =~ m#Opera|MSIE 2\.#) {
243            ## WARNING: This code may output unsafe HTML document if            ## WARNING: This code may output unsafe HTML document if
# Line 341  sub print_header ($;%) { Line 245  sub print_header ($;%) {
245            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
246            print qq{Refresh: 0; url=$option{-goto}\n};            print qq{Refresh: 0; url=$option{-goto}\n};
247            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
248          } elsif ($UA =~ /Gecko/) {
249              print qq{Refresh: 0; url="$option{-goto}"\n};
250              push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;" />);
251        } else {        } else {
252            $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;            $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
253            print qq{Refresh: 0; url="$option{-goto}"\n};            print qq{Refresh: 0; url="$option{-goto}"\n};
# Line 348  sub print_header ($;%) { Line 255  sub print_header ($;%) {
255        }        }
256      }      }
257      print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};      print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
258      if ($option{-expires}) {      if ($option{-expires} != -1) {
259        print qq{Expires: @{[scalar gmtime $option{-expires}]}\n};        if (defined $option{-expires}) {  ## TODO: Don't use asctime
260            print qq{Expires: @{[scalar gmtime (time + $option{-expires})]}\n};
261          } elsif ($option{-media}->{expires} != -1) {
262            print qq{Expires: @{[scalar gmtime (time + $option{-media}->{expires})]}\n};
263          }
264      }      }
265      if ($UA =~ m#Mozilla/2#) {      if ($option{-media}->{charset} && $UA =~ m#Mozilla/[12]\.#) {
266          my $ct = qq{text/html; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};          my $ct = qq{$option{-media}->{type}; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
267          print qq{Content-Type: $ct\n};          print qq{Content-Type: $ct\n};
268          push @head, qq{<meta http-equiv="content-type" content="$ct">};          $option{o}->{-header}->{meta_ct} = qq{<meta http-equiv="content-type" content="$ct">\n};
269      } elsif ($UA =~ m#Infomosaic#) {      } elsif (!$option{-media}->{charset} || $UA =~ m#Infomosaic|Mozilla/0\.#) {
270          print qq{Content-Type: text/html\n};          print qq{Content-Type: $option{-media}->{type}\n};
271      } else {          $option{o}->{-header}->{meta_ct} = qq{<meta http-equiv="content-type" content="$option{-media}->{type}; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}">\n};
272          print qq{Content-Type: text/html; charset=@{[&get_charset_name($kanjicode)]}\n};      } else {
273            my $type = $option{-media}->{type};
274            $type = 'application/xml' if $type eq 'application/rss+xml';
275            print qq{Content-Type: $type; charset=@{[&get_charset_name($kanjicode)]}\n};
276      }      }
277      push @head, qq(<title>@{[&escape($page)]}</title>);      print <<"EOD";      ## TODO:
     if ($UA !~ m#Mozilla/[1-4]\.# || $UA =~ m#MSIE (?:[4-9]\.|\d\d)#) {  
       push @head, qq(<link rel="stylesheet" type="text/css" href="@{[&escape($uri{wiki}.'?mycmd=TEXT_CSS;mypage='.&encode($PageName{DefaultStyleForHTML}).';x-lm='.&get_info($PageName{DefaultStyleForHTML}, $info_LastModified))]}");  
     }  
     push @head, q(<meta name="ROBOTS" content="NOINDEX">) if $option{-noindex};  
     my ($Links, $links) = &make_navigate_links ($page);  
     #print $Links;      ## Link: fields  
     $links = join "\n", (@head, $links);  
     print <<"EOD";  
278  Content-Language: $lang  Content-Language: $lang
279  Content-Style-Type: text/css  Content-Style-Type: text/css
280    
 <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
 "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->  
 <html lang="$lang" class="$option{body_class}">  
 <head profile="http://suika.fam.cx/~wakaba/-temp/wiki/wiki?WikiHTMLMetaProfile">  
 $links  
 </head>  
 <body class="$option{body_class}">  
 EOD  
     &print_navigate_links ($page);  
     print <<EOD;  
 <h1 class="header">@{[&escape($page)]}</h1>  
281  EOD  EOD
282      $option{o}->{-header}->{links} = join "\n", (@head);
283  }  }
284    
285  sub get_charset_name ($;%) {  sub get_charset_name ($;%) {
# Line 398  sub get_charset_name ($;%) { Line 294  sub get_charset_name ($;%) {
294      $charset;      $charset;
295  }  }
296    
 sub print_navigate_links (@) {  
   my ($page) = @_;  
   my $editable = (&is_editable($page) && !&is_frozen($page)) ? 1 : 0;  
   my $cookedpage = &encode($page);  
   print <<EOH;  
 <div class="tools">  
     @{[ $editable  
         ? qq(<a title="@{[&Resource('EditThisPageLong',escape=>1)]}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E" class="wiki-cmd">@{[&Resource('EditThisPage',escape=>1)]}</a> | )  
         : qq()  
     ]}  
     <a href="$url_cgi?mycmd=read;mypage=$cookedpage;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki-cmd" title="@{[&Resource('ViewThisPageLong',escape=>1)]}">@{[&Resource('ViewThisPage',escape=>1)]}</a> |  
     <a href="$url_cgi?mycmd=map;mypage=$cookedpage" class="wiki-cmd" title="@{[&Resource('ShowMapOfThisPageLong',escape=>1)]}">@{[&Resource('ShowMapOfThisPage',escape=>1)]}</a> |  
     <a href="$url_cgi?$PageName{CreatePage}" class="wiki" title="@{[&Resource('GoToCreatePageLong',escape=>1)]}">@{[&Resource('GoToCreatePage',escape=>1)]}</a> |  
     <a href="$url_cgi?$PageName{IndexPage}" class="wiki" title="@{[&Resource('GoToIndexPageLong',escape=>1)]}">@{[&Resource('GoToIndexPage',escape=>1)]}</a> |  
     <a href="$url_cgi?$PageName{FrontPage}" class="wiki" title="@{[&Resource('GoToHomePageLong',escape=>1)]}">@{[&Resource('GoToHomePage',escape=>1)]}</a> |  
     <a href="$url_cgi?$PageName{SearchPage}" class="wiki" title="@{[&Resource('GoToSearchPageLong',escape=>1)]}">@{[&Resource('GoToSearchPage',escape=>1)]}</a> |  
     <a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink" title="@{[&Resource('GoSomewhereLong',escape=>1)]}">@{[&Resource('GoSomewhere',escape=>1)]}</a> |  
     <a href="$url_cgi?RecentChanges" class="wiki" title="@{[&Resource('GoToRecentChangesLong',escape=>1)]}">@{[&Resource('GoToRecentChanges',escape=>1)]}</a>  
 </div>  
 EOH  
 }  
   
 sub make_navigate_links ($) {  
     my $page = shift;  
     my @link;  
     push @link, {rel=>'edit', href=>"$url_cgi?mycmd=edit;mypage=@{[&encode($page)]}", class=>"wiki-command", title=>&Resource('EditThisPageLink')} if &is_editable ($page) && !&is_frozen ($page);  
     push @link, {rel=>'edit', href=>"$url_cgi?mycmd=adminedit;mypage=@{[&encode($page)]}", class=>"wiki-command", title=>&Resource('AdminEditThisPageLink')} if &is_editable ($page) || &is_frozen ($page);  
     push @link, {rel=>'view', href=>"$url_cgi?mycmd=read;mypage=@{[&encode($page)]};x-p=@{[time.[0..9]->[rand 10]]}", class=>'wiki-command', title=>&Resource('ViewThisPageLink')};  
     push @link, {rel=>'myself', href=>"$url_cgi?@{[&encode($page)]}", class=>'wiki', title=>&Resource('GoToMyselfLink')};  
     push @link, {rel=>'index', href=>"$url_cgi?$PageName{IndexPage}", class=>'wiki', title=>&Resource('GoToIndexPageLink')};  
     push @link, {rel=>'home', href=>"$url_cgi?$PageName{FrontPage}", class=>'wiki', title=>&Resource('GoToHomePageLink')};  
     push @link, {rel=>'News', href=>"$url_cgi?WikiNews", class=>'wiki', title=>&Resource('GoToWikiNewsLink')};  
     push @link, {rel=>'News', href=>"$url_cgi?RecentChanges", class=>"wiki", title=>&Resource('GoToRecentChangesLink')};  
     push @link, {rel=>'News', href=>"$url_cgi?$PageName{RssPage}", class=>"wiki", title=>&Resource('GoToRssPageLink'), type=>'application/xml'};  
     push @link, {rel=>'search', href=>"$url_cgi?$PageName{SearchPage}", class=>'wiki', title=>&Resource('GoToSearchPageLink')};  
     push @link, {rel=>'help', href=>"$url_cgi?WikiHelp", class=>'wiki', title=>&Resource('GoToWikiHelpLink')};  
     push @link, {rel=>'copyright', href=>"$url_cgi?WikiPageLicense", class=>'wiki', title=>&Resource('GoToWikiPageLicenseLink')};  
     push @link, {rel=>'jump', href=>qq(javascript:var%20WikiName=prompt('Please%20input%20the%20WikiName:','','Jump%20to%20SuikaWiki');if(WikiName)%7B_content.location.href='$url_cgi%3F'+encodeURIComponent(WikiName)%7D), class=>'wiki-cmd', title=>&Resource('JumpToLink')};  
     push @link, {rel=>'jump', href=>qq(javascript:var%20WikiName=prompt('Please%20input%20the%20WikiName:','','Jump%20to%20SuikaWiki');if(WikiName)%7B_content.location.href='$url_cgi%3Fmycmd=edit;mypage='+encodeURIComponent(WikiName)%7D), class=>'wiki-cmd', title=>&Resource('JumpToEditLink')};  
     push @link, {rel=>'lucky', href=>"$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}", class=>'wiki randomlink', title=>&Resource('GoSomewhereLink')};  
     push @link, {rel=>'history', href=>$uri{cvs_wikipage}.do{my $s=$page;$s=~s/(.)/sprintf '%02X', ord $1/ges;$s}.'.txt', title=>&Resource('ViewHistoryOfThisPageLink'),hreflang=>'en'} if $uri{cvs_wikipage};  
     push @link, {rel=>'history', href=>"$url_cgi?mycmd=diff;mypage=@{[&encode($page)]}", title=>&Resource('ViewDiffOfThisPageLink'), class=>'wiki-command'};  
     push @link, {rel=>'contents', href=>"$url_cgi?mycmd=map;mypage=@{[&encode($page)]}", title=>&Resource('ShowMapOfThisPageLink'), class=>'wiki-command'};  
     my ($Links, $links) = ('', '');  
     for my $e (@link) {  
         $links .= qq(<link);  
         $Links .= qq(Link: <$e->{href}>);  
         for my $attr (qw/rel rev href title class type hreflang charset/) {  
             $links .= qq( $attr="@{[&escape($e->{$attr})]}") if $e->{$attr};  
         }  
         for my $attr (qw/rel rev title/) {  
             $Links .= qq(; $attr="@{[do{$e->{$attr} =~ s/([\\\"])/\\$1/g; $e->{$attr}}]}") if $e->{$attr};  
         }  
         $links .= qq(>\n);  
         $Links .= qq(\n);  
     }  
     wantarray ? ($Links, $links) : $Links;  
 }  
   
 sub print_footer {  
     my ($page, $lm) = @_;  
     my $epage = &encode ($page);  
   my $cvslog1 = q$Revision$;  
   my $cvslog2 = q$Date$;  
   print_navigate_links ($page);  
   print <<"EOD";  
 @{[ $lm ? qq(<div id="wikipage-last-modified">@{[&Resource('LastModified=',escape=>1)]}@{[&_rfc3339_date ($lm)]}</div>) : '' ]}  
 <div class="footer">  
 <a href="http://www.hyuki.com/yukiwiki/" title="YukiWiki 2.0.beta1.2002-05-29 &copy; 2000-2002 by Hiroshi Yuki">@{[&Resource('About:Name:YukiWiki',escape=>1)]}</a> <a href="http://digit.que.ne.jp/work/" title="WalWiki 2.0.beta1.wal.1 &copy; 2000-2002 by Makio Tsukamoto">@{[&Resource('About:Name:WalWiki',escape=>1)]}</a>  
 <a href="/gate/cvs/wakaba/wiki/" title="@{[&Resource('About:SuikaWiki:JumpToCVS',escape=>1)]} ($cvslog2)">@{[&Resource('About:Name:SuikaWiki',escape=>1)]} $cvslog1</a>  
 </div>  
 </body>  
 </html>  
 EOD  
 }  
   
297  sub escape {  sub escape {
298      my $s = shift;      my $s = shift;
299      $s =~ s|\r\n|\n|g;      $s =~ s|\x0D\x0A|\x0A|g;
300      $s =~ s|&|&amp;|g;      $s =~ s|&|&amp;|g;
301      $s =~ s|<|&lt;|g;      $s =~ s|<|&lt;|g;
302      $s =~ s|>|&gt;|g;      $s =~ s|>|&gt;|g;
# Line 494  sub unescape { Line 314  sub unescape {
314      return $s;      return $s;
315  }  }
316    
317  sub print_content ($;$) {  sub convert_format ($$$;%) {
318      my ($rawcontent, %option) = @_;    my ($content, $d => $t, %option) = @_;
319      print &text_to_html($rawcontent, toc=>1, %option);    &load_formatter ('format');
320      my $f = SuikaWiki::Plugin->format_converter ($d => $t);
321      if (ref $f) {
322        $option{content} = $content;
323        $option{from} = $d;
324        $option{to} = $t;
325        &$f ({}, bless (\%option, 'SuikaWiki::Plugin'));
326      } elsif ($t =~ /HTML|xml/) {
327        length $content ? '<pre>'.&escape($content).'</pre>' : '';
328      } else {
329        $content;
330      }
331  }  }
332    
333  sub text_to_html {  sub text_to_html {
334      my ($txt, %option) = @_;      my ($txt, %option) = @_;
335      my @toc;      my $toc = $option{-toc} || (ref $option{toc} ? $option{toc} : []);
     my @toc2 = @{$option{-toc}||[]};  
336      my $tocnum = 0;      my $tocnum = 0;
337            
338      ## Load constants      ## Load constants
339      my %const;      my %const;
340      if ($option{content_format} =~ /import="([^"]+)"/) {      if ($option{magic} =~ /import="([^"]+)"/) {
341        for (split /\s*,\s*/, $1) {        for (split /\s*,\s*/, $1) {
342          my $wp = $database{$_};          my $wp = $database{$_};
343          if ($wp =~ m!^\#\?SuikaWikiConst/1.0!) {          if ($wp =~ m!^\#\?SuikaWikiConst/(?:0.9|1.0)!) {
344            wiki::suikawikiconst::to_hash ($wp => \%const);            wiki::suikawikiconst::to_hash ($wp => \%const);
345          }          }
346        }        }
# Line 524  sub text_to_html { Line 354  sub text_to_html {
354      foreach (@txt) {      foreach (@txt) {
355          chomp;          chomp;
356          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
357              push(@toc, qq(----- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [5, "i$tocnum" => ($1 || $tocnum)];
358              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h6>');              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h6>');
359              $tocnum++;              $tocnum++;
360          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
361              push(@toc, qq(---- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [4, "i$tocnum" => ($1 || $tocnum)];
362              push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h5>');              push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h5>');
363              $tocnum++;              $tocnum++;
364          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
365              push(@toc, qq(--- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [3, "i$tocnum" => ($1 || $tocnum)];
366              push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h4>');              push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h4>');
367              $tocnum++;              $tocnum++;
368          } elsif (/^\*\*([^\x0D\x0A]*)/) {          } elsif (/^\*\*([^\x0D\x0A]*)/) {
369          # if (/^\*\*(.*)/) {          # if (/^\*\*(.*)/) {
370          # Walrus mod (6) end          # Walrus mod (6) end
371              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [2, "i$tocnum" => ($1 || $tocnum)];
372              push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h3>');              push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h3>');
373              $tocnum++;              $tocnum++;
374          } elsif (/^\*([^\x0D\x0A]*)/) {          } elsif (/^\*([^\x0D\x0A]*)/) {
375              push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [1, "i$tocnum" => ($1 || $tocnum)];
376              push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h2>');              push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h2>');
377              $tocnum++;              $tocnum++;
378          } elsif (/^(={1,6})(.*)/) {          } elsif (/^(={1,6})(.*)/) {
379              &back_push('ol', length($1), \@saved, \@result);              &back_push('ol', length($1), \@saved, \@result);
380              push(@result, '<li>' . &inline($2, const => \%const) . '</li>');              push(@result, '<li>' . &inline($2, %option, const => \%const) . '</li>');
381          } elsif (/^(-{1,6})(.*)/) {          } elsif (/^(-{1,6})(.*)/) {
382            &back_push('ul', length($1), \@saved, \@result);            &back_push('ul', length($1), \@saved, \@result);
383            my ($pf, $l) = ('', $2);            my ($pf, $l) = ('', $2);
# Line 555  sub text_to_html { Line 385  sub text_to_html {
385              my $num = 0+$1;              my $num = 0+$1;
386              $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);              $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
387            }            }
388            push(@result, '<li>' . $pf . &inline ($l, const => \%const) . '</li>');            push(@result, '<li>' . $pf . &inline ($l, %option, const => \%const) . '</li>');
389          } elsif (/^:([^:]+):(.*)/) {          } elsif (/^:([^:]+):(.*)/) {
390              &back_push('dl', 1, \@saved, \@result);              &back_push('dl', 1, \@saved, \@result);
391              push(@result, '<dt>' . &inline($1, const => \%const) . '</dt>', '<dd>' . &inline($2, const => \%const) . '</dd>');              push(@result, '<dt>' . &inline($1, %option, const => \%const) . '</dt>', '<dd>' . &inline($2, %option, const => \%const) . '</dd>');
392          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
393              &back_push('blockquote', length($1), \@saved, \@result);              &back_push('blockquote', length($1), \@saved, \@result);
394              push @result, "<p>";              push @result, "<p>";
395              push(@result, &inline($2, const => \%const));              push(@result, &inline($2, %option, const => \%const));
396              unshift @saved, "</p>";              unshift @saved, "</p>";
397          } elsif (/^\s*$/) {          } elsif (/^\s*$/) {
398              push(@result, splice(@saved));              push(@result, splice(@saved));
# Line 570  sub text_to_html { Line 400  sub text_to_html {
400              unshift(@saved, "</p>");              unshift(@saved, "</p>");
401          } elsif (/^(\s+.*)$/) {          } elsif (/^(\s+.*)$/) {
402              &back_push('pre', 1, \@saved, \@result);              &back_push('pre', 1, \@saved, \@result);
403              push(@result, &inline($1, const => \%const));              push(@result, &inline($1, %option, const => \%const));
404          } elsif (/^\,(.*?)[\x0D\x0A]*$/) {          } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
405              &back_push('table', 1, \@saved, \@result);              &back_push('table', 1, \@saved, \@result);
406              #######              #######
# Line 586  sub text_to_html { Line 416  sub text_to_html {
416                          $colspan[$i]++;                          $colspan[$i]++;
417                      }                      }
418                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
419                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], const => \%const));                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], %option, const => \%const));
420                  } else {                  } else {
421                      $value[$i] = '';                      $value[$i] = '';
422                  }                  }
# Line 603  sub text_to_html { Line 433  sub text_to_html {
433          } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {          } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
434            my $num = 0+$1;            my $num = 0+$1;
435            push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);            push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
436            push @result, &inline ($2, const => \%const);            push @result, &inline ($2, %option, const => \%const);
437          } else {          } else {
438              push(@result, &inline($_, const => \%const));              push(@result, &inline($_, %option, const => \%const));
439          }          }
440      }      }
441      push(@result, splice(@saved));      push(@result, splice(@saved));
442            
443      my $toc = '';      my $r = join("\n", @result);
444      if ($option{toc}) {      $r =~ s#<p>\x0D?\x0A</p>##g;
445          # Convert @toc (table of contents) to HTML.      $r =~ s#[\x0D\x0A]+</#</#g;
446          # This part is taken from Makio Tsukamoto's WalWiki.      $r =~ s#<pre>\x0D?\x0A#<pre>#g;
447          my (@tocsaved, @tocresult);      $r;
         foreach (@toc,@toc2) {  
             if (/^(-{1,6})(.*)$/) {  
                 &back_push('ul', length($1), \@tocsaved, \@tocresult);  
                 push(@tocresult, '<li>' . $2 . '</li>');  
             }  
         }  
         push(@tocresult, splice(@tocsaved));  
         $toc = join("\n", @tocresult);  
         $toc = $toc ? qq(<div id="wikipage-toc">$toc</div>) : '';  
     }  
     $toc .= join("\n", @result);  
     $toc =~ s#<p>\n</p>##g;  
     $toc =~ s#[\x0D\x0A]+</#</#g;  
     $toc =~ s#<pre>\n#<pre>#g;  
     $toc;  
448  }  }
449    
450  sub back_push {  sub back_push {
# Line 649  sub back_push { Line 464  sub back_push {
464  sub inline ($;%) {  sub inline ($;%) {
465      my ($line, %option) = @_;      my ($line, %option) = @_;
466      $line = &escape($line);      $line = &escape($line);
467      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4)}ge;      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4, \%option)}ge;
468      $line =~ s{\[(INS|DEL|SUP|SUB|VAR|CODE|KBD|SAMP|DFN)(?:\(([A-Za-z0-9\x20-]+)\))?\[(.+?)\]\]}{<@{[lc $1]}@{[$2 ? qq( class="$2") : '']}>$3</@{[lc $1]}>}g;      $line =~ s{\[(INS|DEL|SUP|SUB|VAR|CODE|KBD|SAMP|DFN)(?:\(([A-Za-z0-9\x20-]+)\))?\[(.+?)\]\]}{<@{[lc $1]}@{[$2 ? qq( class="$2") : '']}>$3</@{[lc $1]}>}g;
469      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
470      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
471      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><ruby class="rb"><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby><span class="rp"> (</span><span class="rt-below">$3</span><span class="rp">) </span></span>:g;      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><ruby class="rb"><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby><span class="rp"> (</span><span class="rt-below">$3</span><span class="rp">) </span></span>:g;
472      $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;      $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
473      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><span class="rb">$1</span><span class="rp"> (</span><span class="rt-below">$2</span><span class="rp">) </span></span>:g;      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><span class="rb">$1</span><span class="rp"> (</span><span class="rt-below">$2</span><span class="rp">) </span></span>:g;
     $line =~ s%\[Q\[([^]]+)\](?: \[&lt;([\x21-\x5A\x5E-\x7E]+)&gt;\])?\]%¡Ö<q@{[$2?qq( cite="$2"):'']}>$1</q>¡×%g;  
474      $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;      $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
475      $line =~ s|''([^']+)''|<em>$1</em>|g;      $line =~ s|''([^']+)''|<em>$1</em>|g;
476      $line =~ s{      $line =~ s{
# Line 667  sub inline ($;%) { Line 481  sub inline ($;%) {
481      }{      }{
482        my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);        my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
483        if ($l) {        if ($l) {
484          return &embedded_to_html($1);          &embedded_to_html($1);
485        } elsif (defined $page) {        } elsif (defined $page) {
486          &make_wikilink ($page, anchor => 0+$anchor);          &make_wikilink ($page, anchor => 0+$anchor);
487        } elsif ($anum) {        } elsif ($anum) {
# Line 682  sub inline ($;%) { Line 496  sub inline ($;%) {
496  sub make_wikilink ($%) {  sub make_wikilink ($%) {
497    my ($ename, %option) = @_;    my ($ename, %option) = @_;
498    my $name = &unescape ($ename);    my $name = &unescape ($ename);
499      $option{latest} = $option{latest} ? qq(mycmd=default;x-param=@{[time.[0..9]->[rand 10]]};mypage=) : '';
500    if ($database{$name}) {    if ($database{$name}) {
501      my $subject = &escape (&get_subjectline ($name, delimiter => ''));      my $subject = &escape (&get_subjectline ($name, delimiter => ''));
502      if ($option{anchor}) {      if ($option{anchor}) {
503        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);        return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
504      } else {      } else {
505        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}" class="wiki">$ename</a>);        return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}" class="wiki">$ename</a>);
506      }      }
507    } else {    } else {
508      return qq(<a title="@{[&Resource('JumpAndEditWikiPage',escape=>1)]}" href="$url_cgi?@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">@{[&Resource('JumpAndEditWikiPageMark',escape=>1)]}</span></a>);      return qq(<a title="@{[&Resource('JumpAndEditWikiPage',escape=>1)]}" href="$uri{wiki}?$option{latest}@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">@{[&Resource('JumpAndEditWikiPageMark',escape=>1)]}</span></a>);
509    }    }
510  }  }
511    
# Line 733  sub make_urilink ($;%) { Line 548  sub make_urilink ($;%) {
548    }    }
549  }  }
550    
551  {my $FormIndex = 0;  {my %FormIndex;
552  sub make_custom_form ($$$$) {  sub make_custom_form ($$$$%) {
553      my ($wfname, $definition, $template, $option) = @_;      my ($wfname, $definition, $template, $foption, $option) = @_;
554      ## $template and $option is currently not used in this procedure.      ## $template is currently not used in this procedure.
555      unless ($main::_EMBEDED) {      #unless ($main::_EMBEDED) {
556          $FormIndex++;          $FormIndex{$option->{page}}++;
557          if (length $definition) {          if (length $definition) {
558              my $param = bless {}, 'SuikaWiki::Plugin';              my $param = bless {depth=>10}, 'SuikaWiki::Plugin';
559              my $lastmodified = &get_info($form{mypage}, $info_LastModified);              my $lastmodified = $database->mtime ($option->{page});
560              &load_formatter (qw/form_input form_option/);              &load_formatter (qw/form_input form_option/);
561              $definition = &unescape ($definition);              $definition = &unescape ($definition);
562              $definition =~ s/\\(.)/$1/g;              $definition =~ s/\\(.)/$1/g;
563              $option = &unescape ($option);              $foption = &unescape ($foption);
564              $option =~ s/\\(.)/$1/g;              $foption =~ s/\\(.)/$1/g;
565              $fmt{form_option}->replace ($option, $param);              $fmt{form_option}->replace ($foption, $param);
566              $param->{output}->{form} = 1 unless defined $param->{output}->{form};              $param->{output}->{form} = 1 unless defined $param->{output}->{form};
567                $param->{output}->{form} = 0 if $main::_EMBEDED;
568              $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};              $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
569              my $target_page = $param->{output}->{page} || $form{mypage};              $param->{output}->{page} ||= $option->{page};
570              $param->{form_disabled} = 1 if $fixedpage{$target_page};              $param->{form_disabled} = 1 if $database->meta (IsFrozen => $option->{page});
571              my $target_form = $param->{output}->{id};              my $target_form = $param->{output}->{id};
572              my $r = '';              my $r = '';
573              $r = <<EOH if $param->{output}->{form};              $r = <<EOH if $param->{output}->{form};
574  <form method="post" action="$url_cgi" id="wikiform-$FormIndex" class="wikiform">  <form method="post" action="$url_cgi" id="wikiform-$FormIndex{$option->{page}}" class="wikiform">
575    <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'read':'wikiform']}">    <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'default':'wikiform']}" />
576    <input type="hidden" name="mypage" value="@{[&escape($target_page)]}">    <input type="hidden" name="mypage" value="@{[&escape($param->{output}->{page})]}" />
577    <input type="hidden" name="myLastModified" value="$lastmodified">    <input type="hidden" name="myLastModified" value="$lastmodified" />
578    <input type="hidden" name="mytouch" value="on">    <input type="hidden" name="mytouch" value="on" />
579    <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex)]}">    <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex{$option->{page}})]}" />
580  EOH  EOH
581              $r .= qq(<a name="wikiform-$FormIndex"></a>) if $UA =~ m#Mozilla/[12]\.#;              $r .= qq(<a name="wikiform-$FormIndex{$option->{page}}"></a>) if $UA =~ m#Mozilla/[12]\.#;
582              $r .= $fmt{form_input}->replace ($definition, $param);              $r .= $fmt{form_input}->replace ($definition, $param);
583              $r .= "</form>\n" if $param->{output}->{form};              $r .= "</form>\n" if $param->{output}->{form};
584              $r;              $r;
585         } else {  ## No input-interface WikiForm         } else {  ## No input-interface WikiForm
586             qq(<a id="wikiform-$FormIndex" name="wikiform-$FormIndex"><!-- #form --></a>);           qq(<a id="wikiform-$FormIndex{$option->{page}}" name="wikiform-$FormIndex{$option->{page}}"><!-- #form --></a>);
587         }         }
588      } else {      #} else {
589          qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);      #    qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
590      }      #}
591  }}  }}
592    
 sub print_message {  
     my ($msg) = @_;  
     print qq(<p><strong>@{[&escape($msg)]}</strong></p>);  
 }  
   
593  sub init_form {  sub init_form {
594      ## TODO: Support multipart/form-data      ## TODO: Support multipart/form-data
595      my $query = '';      my $query = '';
# Line 789  sub init_form { Line 600  sub init_form {
600      if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {      if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
601        my $query = &decode($main::ENV{QUERY_STRING});        my $query = &decode($main::ENV{QUERY_STRING});
602        $query = &code_convert(\$query, $kanjicode);        $query = &code_convert(\$query, $kanjicode);
       if ($page_command{$query}) {  
         $form{mycmd} = $page_command{$query};  
603          $form{mypage} = $query;          $form{mypage} = $query;
604        } else {          $form{mycmd} = 'default';
         $form{mypage} = $query;  
         $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';  
       }  
605      } else {      } else {
606        for (split /[;&]/, $query) {        for (split /[;&]/, $query) {
607          if (my ($n, $v) = split /=/, $_, 2) {          if (my ($n, $v) = split /=/, $_, 2) {
# Line 807  sub init_form { Line 613  sub init_form {
613          $form{mypage} = $form{epage};          $form{mypage} = $form{epage};
614          $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;          $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;
615        }        }
       if ($page_command{$form{mypage}} && $form{mycmd} eq 'read') {  
         $form{mypage} = &code_convert(\$form{mypage}, $kanjicode);  
         $form{mycmd} = $page_command{$form{mypage}};  
       }  
616      }      }
617      $form{mypage} ||= 'HomePage';      $form{mypage} ||= $PageName{FrontPage};
618      $form{mycmd} ||= 'read';      $form{mypage} =~ tr/\x00-\x1F\x7F//d;
619        $form{mycmd} ||= 'default';
620    
621      # mypreview_edit        -> do_edit, with preview.      # mypreview_edit        -> do_edit, with preview.
622      # mypreview_adminedit   -> do_adminedit, with preview.      # mypreview_adminedit   -> do_adminedit, with preview.
# Line 836  sub init_form { Line 639  sub init_form {
639      $form{myname} = &code_convert(\$form{myname}, $kanjicode);      $form{myname} = &code_convert(\$form{myname}, $kanjicode);
640  }  }
641    
 sub update_recent_changes {  
     my $update = "- @{[&get_now]} [[$form{mypage}]] @{[&get_subjectline($form{mypage})]}";  
     my @oldupdates = split(/\x0D?\x0A/, $database{RecentChanges});  
     shift @oldupdates; ## '#?' magic line  
     my @updates;  
     foreach (@oldupdates) {  
         /^\- \d\d\d\d\-\d\d\-\d\d \d\d:\d\d \[\[([^]]+)\]\]/;  
         my $name = $1;  
         if ($name ne $form{mypage}) {  
             push @updates, $_;  
         }  
     }  
     if (&is_exist_page($form{mypage})) {  
       unshift @updates, $update;  
     }  
     splice @updates, (&Resource ('RecentChanges:Max') || 50) + 1;  
     $database{RecentChanges} = "#?SuikaWiki/0.9\n" . join("\n", @updates);  
     if ($PathTo{TouchFile}) {  
         open(FILE, "> ".$PathTo{TouchFile});  
         print FILE localtime() . "\n";  
         close(FILE);  
     }  
 }  
   
 {my %SubjectLine;  
642  sub get_subjectline {  sub get_subjectline {
643      my ($page, %option) = @_;      my ($page, %option) = @_;
644      unless (defined $SubjectLine{$page}) {      my $SubjectLine = SuikaWiki::Plugin->cache ('headline');
645        unless (defined $SubjectLine->{$page}) {
646        if (not &is_editable($page)) {        if (not &is_editable($page)) {
647          $SubjectLine{$page} = "";          $SubjectLine->{$page} = "";
648        } else {        } else {
649          $SubjectLine{$page} = $database{$page};          $SubjectLine->{$page} = do {
650          $SubjectLine{$page} =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;            my $s=$database{$page};
651          $SubjectLine{$page} =~ s/\x0D?\x0A.*//s;            $s =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
652              $s =~ s/\x0D?\x0A.*//s;
653            $s};
654        }        }
655      }      }
656      if (length $SubjectLine{$page}) {      if (length $SubjectLine->{$page}) {
657        $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');        $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
658        $option{delimiter}.$SubjectLine{$page}.$option{tail};        $option{delimiter}.$SubjectLine->{$page}.$option{tail};
659      } else {      } else {
660        '';        '';
661      }      }
662  }}  }
663    
664  sub open_db {  sub open_db {
665      if ($modifier_dbtype eq 'dbmopen') {      if ($modifier_dbtype eq 'dbmopen') {
666          dbmopen(%database, $PathTo{WikiDataBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDataBase}");          dbmopen(%database, $PathTo{WikiDataBase}, 0666) or die "(dbmopen) $PathTo{WikiDataBase}";
         dbmopen(%infobase, $PathTo{WikiInfoBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiInfoBase}");  
667      } elsif ($modifier_dbtype eq 'AnyDBM_File') {      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
668          eval q{use AnyDBM_File};          eval q{use AnyDBM_File};
669          tie(%database, "AnyDBM_File", $PathTo{WikiDataBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDataBase}");          tie(%database, "AnyDBM_File", $PathTo{WikiDataBase}, O_RDWR|O_CREAT, 0666) or die ("(tie AnyDBM_File) $PathTo{WikiDataBase}");
670          tie(%infobase, "AnyDBM_File", $PathTo{WikiInfoBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiInfoBase}");      } elsif ($modifier_dbtype eq 'Yuki::YukiWikiDB') {
     } else {  
671          eval q{use Yuki::YukiWikiDB};          eval q{use Yuki::YukiWikiDB};
672          tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");          tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or die ("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");
673          tie(%infobase, "Yuki::YukiWikiDB", $PathTo{WikiInfoBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiInfoBase}");      } else {    ## Yuki::YukiWikiDB || Yuki::YukiWikiDBMeta
674            eval qq{use $modifier_dbtype};
675            $database = tie(%database, $modifier_dbtype => $PathTo{WikiDataBase}, -lock => 2, -backup => $wiki::diff::UseDiff) or die ("(tie $modifier_dbtype) $PathTo{WikiDataBase}");
676      }      }
677  }  }
678    
679  sub close_db {  sub close_db {
680      if ($modifier_dbtype eq 'dbmopen') {      if ($modifier_dbtype eq 'dbmopen') {
681          dbmclose(%database);          dbmclose(%database);
         dbmclose(%infobase);  
     } elsif ($modifier_dbtype eq 'AnyDBM_File') {  
         untie(%database);  
         untie(%infobase);  
682      } else {      } else {
683          untie(%database);          untie(%database);
         untie(%infobase);  
     }  
 }  
   
 sub open_diff {  
     if ($modifier_dbtype eq 'dbmopen') {  
         dbmopen(%diffbase, $PathTo{WikiDiffBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDiffBase}");  
     } elsif ($modifier_dbtype eq 'AnyDBM_File') {  
         tie(%diffbase, "AnyDBM_File", $PathTo{WikiDiffBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDiffBase}");  
     } else {  
         tie(%diffbase, "Yuki::YukiWikiDB", $PathTo{WikiDiffBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDiffBase}");  
     }  
 }  
   
 sub close_diff {  
     if ($modifier_dbtype eq 'dbmopen') {  
         dbmclose(%diffbase);  
     } elsif ($modifier_dbtype eq 'AnyDBM_File') {  
         untie(%diffbase);  
     } else {  
         untie(%diffbase);  
684      }      }
685  }  }
686    
687  sub print_editform {  sub editform (@) {
688      my ($mymsg, $lastmodified, %mode) = @_;    my %option = @_;
689      my $frozen = &is_frozen($form{mypage});    my $frozen = &is_frozen ($option{page});
690      $option{content} = $database{$option{page}} unless defined $option{content};
691      if ($form{mypreview}) {    $option{content} = $database{NewPageTemplate} unless length $option{content};
692          if ($form{mymsg}) {    $option{last_modified} = $database->mtime ($option{page}) unless defined $option{last_modified};
693              unless ($mode{conflict}) {    my $f = '';
694                  print qq(<h3>@{[&Resource('Preview:Title',escape=>1)]}</h3>\n);    my $magic = '';
695                  print qq(<p>@{[&Resource('Preview:Notice',escape=>1)]}</p>\n);    $magic = $1 if $option{content} =~ m/^([^\x0A\x0D]+)/s;
696                  print qq(<div class="preview">\n);    
697                  &print_content($form{mymsg});    my $selected = 'default';
698                  print qq(</div>\n);    if ($form{after_edit_cmd}) {
699              }      $selected = $form{after_edit_cmd};
700          } else {    } elsif ($magic =~ /Const|Config|CSS/) {
701              print @{[&Resource('Preview:Empty',escape=>1)]};      $selected = 'edit';
702          }    }
703          $mymsg = &escape($form{mymsg});    my $afteredit = <<EOH;
     } else {  
         $mymsg = &escape($mymsg || $database{NewPageTemplate});  
     }  
     my $magic = '';  
     $magic = $1 if $mymsg =~ m/^([^\x0A\x0D]+)/s;  
   
     my $edit = $mode{admin} ? 'adminedit' : 'edit';  
     my $escapedmypage = &escape($form{mypage});  
     my $escapedmypassword = &escape($form{mypassword});  
     my $selected = 'read';  
     if ($form{after_edit_cmd}) {  
         $selected = $form{after_edit_cmd};  
     } elsif ($magic =~ /Const|Config|CSS/) {  
         $selected = 'edit';  
     }  
     my $afteredit = <<EOH;  
704  <select name="after_edit_cmd">  <select name="after_edit_cmd">
705    <option value="default" label="@{[&Resource('Edit:SaveAndDefault',escape=>1)]}"@{[$selected eq 'default' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndDefault',escape=>1)]}</option>
706  <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>  <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
707  <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>  <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
708  </select>  </select>
709  EOH  EOH
710      $f .= <<"EOD";
711      print <<"EOD";  <form action="$uri{wiki}" method="post">
712  <form action="$url_cgi" method="post">      @{[ $option{conflict} ? '' : qq(<label><input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" /><kbd>S</kbd></label>) ]}
713  <h2>@{[&Resource('Edit:Title',escape=>1)]}</h2>      @{[ $option{admin} ? qq(<label>@{[&Resource('Edit:Password=',escape=>1)]}<input type="password" name="mypassword" value="" size="10" /></label>) : "" ]} [@{[&get_new_anchor_index($option{content})]}]<br />
714      @{[ $mode{conflict} ? '' : qq(<input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}"><kbd>S</kbd>) ]}      <input type="hidden" name="myLastModified" value="$option{last_modified}" />
715      @{[ $mode{admin} ? qq(<label>@{[&Resource('Edit:Password=',escape=>1)]}<input type="password" name="mypassword" value="$escapedmypassword" size="10"></label>) : "" ]} [@{[do {my $n = 0;      <input type="hidden" name="mypage" value="@{[&escape($form{mypage})]}" />
716                 $mymsg =~ s/(?:-+\s)?\[([0-9]+)\]/$n = $1 if $1 > $n; $&/mge;      <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">@{[&escape($option{content})]}</textarea><br />
                ++$n}]}]<br>  
     <input type="hidden" name="myLastModified" value="$lastmodified">  
     <input type="hidden" name="mypage" value="$escapedmypage">  
     <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">$mymsg</textarea><br>  
717  @{[  @{[
718      $mode{admin} ?      $option{admin} ?
719      qq(      qq(
720      <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>@{[&Resource('Edit:Freeze',escape=>1)]}</label>      <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]} />@{[&Resource('Edit:Freeze',escape=>1)]}</label>
721      <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br>)      <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]} />@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br />)
722      : ""      : ""
723  ]}  ]}
724  @{[  @{[
725      $mode{conflict} ? "" :      $option{conflict} ? "" :
726      qq(      qq(
727          <input type="checkbox" name="mytouch" value="on" checked="checked">@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}<br>          <label><input type="checkbox" name="mytouch" value="on" checked="checked" />@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}</label><br />
728          <input type="submit" name="mypreview_$edit" value="@{[&Resource('Edit:Preview',escape=>1)]}">          <label><input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S" /><kbd>S</kbd></label>
         <input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S"><kbd>S</kbd>  
729         $afteredit         $afteredit
        <br>  
730      )      )
731  ]}  ]}
732  </form>  </form>
733  EOD  EOD
734      unless ($mode{conflict}) {      $f;
         ## Show help text  
         my $help = $database{WikiEditHelp};  
         $help =~ s!^\#\?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;  
         print &text_to_html ($help, toc => 0);  
     }  
 }  
   
 sub print_passwordform {  
         print <<"EOD";  
 <form action="$url_cgi" method="post">  
     <input type="hidden" name="mycmd" value="adminchangepassword">  
     <label>@{[&Resource('Password:Old=',escape=>1)]}<input type="password" name="myoldpassword" size="10"></label><br>  
     <label>@{[&Resource('Password:New1=',escape=>1)]}<input type="password" name="mynewpassword" size="10"></label><br>  
     <label>@{[&Resource('Password:New2=',escape=>1)]}<input type="password" name="mynewpassword2" size="10"></label><br>  
     <input type="submit" value="@{[&Resource('WikiForm:Change',escape=>1)]}"><br>  
 </form>  
 EOD  
735  }  }
736    
737  sub is_editable {  sub is_editable {
738      my ($page) = @_;      my ($page) = @_;
739      if ($fixedpage{$page} || $page =~ /\s/ || $page =~ /^\#/) {      $page =~ /[\x00-\x20\x7F]/ ? 0 : 1;
         return 0;  
     } else {  
         return 1;  
     }  
 }  
   
 # armor_name:  
 #   WikiName -> WikiName  
 #   not_wiki_name -> [[not_wiki_name]]  
 sub armor_name { qq([[$_[0]]]) }  
   
 # unarmor_name:  
 #   [[bracket_name]] -> bracket_name  
 #   WikiName -> WikiName  
 sub unarmor_name {  
     my ($name) = @_;  
     if ($name =~ /^\[\[(\S+?)\]\]$/) {  
         return $1;  
     } else {  
         return $name;  
     }  
740  }  }
741    
742  sub decode {  sub decode {
# Line 1050  sub decode { Line 747  sub decode {
747  }  }
748    
749  sub encode {  sub encode {
750      my ($s) = @_;    my $s = shift;
751      my $encoded = '';    $s =~ s/([^0-9A-Za-z_-])/sprintf '%%%02X', ord $1/ge;
752      foreach my $ch (split(//, $s)) {    $s;
         if ($ch =~ /[A-Za-z0-9_]/) {  
             $encoded .= $ch;  
         } else {  
             $encoded .= '%' . sprintf("%02X", ord($ch));  
         }  
     }  
     return $encoded;  
 }  
   
 sub conflict {  
     my ($page, $rawmsg) = @_;  
     if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {  
         return 0;  
     }  
     &print_header($page, -noindex => 1);  
     &print_content(&Resource('Error:Conflict'));  
     &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);  
     &print_footer($page);  
     return 1;  
753  }  }
754    
755  sub get_now {  sub get_now {
# Line 1096  sub init_InterWikiName { Line 774  sub init_InterWikiName {
774    $interwiki{'[[]]'} = 1;       ## dummy    $interwiki{'[[]]'} = 1;       ## dummy
775  }  }
776    
   
 sub get_info {  
     my ($page, $key) = @_;  
     my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});  
     return $info{$key};  
 }  
   
 sub set_info {  
     my ($page, $key, $value) = @_;  
     my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});  
     $info{$key} = $value;  
     my $s = '';  
     for (keys %info) {  
         $s .= "$_=$info{$_}\n";  
     }  
     $infobase{$page} = $s;  
 }  
   
777  sub frozen_reject {  sub frozen_reject {
778      my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);      my ($isfrozen) = $database->meta (IsFrozen => $form{mypage});
779      my ($willbefrozen) = $form{myfrozen};      my ($willbefrozen) = $form{myfrozen};
780      if (not $isfrozen and not $willbefrozen) {      if (not $isfrozen and not $willbefrozen) {
781          # You need no check.          # You need no check.
# Line 1124  sub frozen_reject { Line 784  sub frozen_reject {
784          # You are admin.          # You are admin.
785          return 0;          return 0;
786      } else {      } else {
787          &print_error(&Resource('Error:PasswordIsIncorrect'));          &_do_view_msg (-view => '-error', -page => $form{mypage},
788          return 1;                         error_message => &Resource ('Error:PasswordIsIncorrect'));
789            exit;
790      }      }
791  }  }
792    
793  sub valid_password {  sub is_frozen ($) { $database->meta (IsFrozen => $_[0]) ? 1 : 0 }
     my ($givenpassword) = @_;  
     my ($validpassword_crypt) = &get_info($PageName{AdminSpecialPage}, 'AdminPassword');  
     if (crypt($givenpassword, $validpassword_crypt) eq $validpassword_crypt) {  
         return 1;  
     } else {  
         return 0;  
     }  
 }  
   
 sub is_frozen {  
     my ($page) = @_;  
     if (&get_info($page, $info_IsFrozen)) {  
         return 1;  
     } else {  
         return 0;  
     }  
 }  
794    
795  sub do_comment {  sub do_comment {
796      my ($content) = $database{$form{mypage}};      my ($content) = $database{$form{mypage}};
797      my $default_name;   ## this code does not strict.      my $default_name;   ## this code is not strict.
798      $default_name = $1 if $content =~ /default-name="([^"]+)"/;      $default_name = $1 if $content =~ /default-name="([^"]+)"/;
799      my $datestr = '[WEAK['.&get_now.']]';      my $datestr = '[WEAK['.&get_now.']]';
800      my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');      my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
# Line 1183  sub do_comment { Line 827  sub do_comment {
827          $form{mymsg} = $content;          $form{mymsg} = $content;
828          $form{mytouch} = 'on';          $form{mytouch} = 'on';
829          &do_write;          &do_write;
830      } else {      } else {    ## Don't write
831          $form{mycmd} = 'read';          $form{mycmd} = 'default';
832          &do_read;          &do_view;
833      }      }
834  }  }
835    
# Line 1201  sub embedded_to_html { Line 845  sub embedded_to_html {
845      my ($embedded) = @_;      my ($embedded) = @_;
846      if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {      if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
847        unless ($main::_EMBEDED) {        unless ($main::_EMBEDED) {
848          my $lastmodified = &get_info($form{mypage}, $info_LastModified);          my $lastmodified = $database->mtime ($form{mypage});
849          return <<"EOD";          return <<"EOD";
850  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
851      <input type="hidden" name="mycmd" value="comment">      <input type="hidden" name="mycmd" value="comment" />
852      <input type="hidden" name="mypage" value="$form{mypage}">      <input type="hidden" name="mypage" value="$form{mypage}" />
853      <input type="hidden" name="myLastModified" value="$lastmodified">      <input type="hidden" name="myLastModified" value="$lastmodified" />
854      <input type="hidden" name="mytouch" value="on">      <input type="hidden" name="mytouch" value="on" />
855      <input type="hidden" name="comment_index" value="$CommentIndex">      <input type="hidden" name="comment_index" value="$CommentIndex" />
856      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
857      <input type="text" name="myname" value="" size="10" class="comment-name">      <input type="text" name="myname" value="" size="10" class="comment-name" />
858      <input type="text" name="mymsg" value="" size="60" class="comment-msg">      <input type="text" name="mymsg" value="" size="60" class="comment-msg" />
859      <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit">      <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit" />
860  </p></form>  </p></form>
861  EOD  EOD
862       } else {       } else {
863          return <<"EOD";          return <<"EOD";
864  <del><form action="$url_cgi" method="get">  <del><form action="$url_cgi" method="get">
865      <input type="hidden" name="mycmd" value="read">      <input type="hidden" name="mycmd" value="default" />
866      <input type="hidden" name="mypage" value="$form{mypage}">      <input type="hidden" name="mypage" value="$form{mypage}" />
867      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
868      <input type="text" name="myname" value="" size="10" disabled="disabled">      <input type="text" name="myname" value="" size="10" disabled="disabled" />
869      <input type="text" name="mymsg" value="" size="60" disabled="disabled">      <input type="text" name="mymsg" value="" size="60" disabled="disabled" />
870  </form></del>  </form></del>
871  EOD  EOD
872      }      }
# Line 1231  EOD Line 875  EOD
875    } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {    } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
876      my ($name, $r) = ($1, '');      my ($name, $r) = ($1, '');
877      if ($main::_EMBEDED != 1) {      if ($main::_EMBEDED != 1) {
878        my ($content, $cf) = ($database{$name}, 'SuikaWiki/0.9');        my ($cf, $content) = SuikaWiki::Plugin->magic_and_conten ($database{$name});
879        $cf = $1 if $content =~ s!^(?:[\#<]\?|/\*\s*)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;        $cf ||= '#?SuikaWiki/0.9';
880        if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {        if ($cf =~ m!^#\?SuikaWiki/0.9(?:$|\s)!) {
881          $main::_EMBEDED = 1;          $main::_EMBEDED = 1;
882          $r = &text_to_html ($content, content_format => $cf);          $r = &text_to_html ($content, magic => $cf, page => $name);
883          $main::_EMBEDED = 0;          $main::_EMBEDED = 0;
884        } elsif (length $content) {        } elsif (length $content) {
885          $r = "<pre>@{[&escape ($content)]}</pre>";          $r = "<pre>@{[&escape ($content)]}</pre>";
886        } else {        } else {
887          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", content_format => 'SuikaWiki/0.9');          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", magic => '#?SuikaWiki/0.9');
888        }        }
889      } else {    ## nested #EMBED      } else {    ## nested #EMBED
890        $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", content_format => 'SuikaWiki/0.9');        $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", magic => '#?SuikaWiki/0.9');
891      }      }
892      return qq(<blockquote title="@{[&escape($name)]}" class="wiki-embed">$r<div class="cite-note">¡Ø<cite><a href="$url_cgi?@{[&encode($name)]}" class="wiki">@{[&escape($name)]}</a></cite>¡Ù</div></blockquote>);      return qq(<blockquote title="@{[&escape($name)]}" class="wiki-embed">$r<div class="cite-note">¡Ø<cite><a href="$url_cgi?@{[&encode($name)]}" class="wiki">@{[&escape($name)]}</a></cite>¡Ù</div></blockquote>);
893    } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {    } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
# Line 1277  sub do_wikiform { Line 921  sub do_wikiform {
921              || $i == $form{wikiform_index}) {              || $i == $form{wikiform_index}) {
922              $template =~ s/\\(.)/$1/g;              $template =~ s/\\(.)/$1/g;
923              $option =~ s/\\(.)/$1/g;              $option =~ s/\\(.)/$1/g;
924              my $param = bless {}, 'SuikaWiki::Plugin';              my $param = bless {depth=>10}, 'SuikaWiki::Plugin';
925              $param->{page} = $form{mypage};              $param->{page} = $form{mypage};
926              $param->{form_index} = $i;              $param->{form_index} = $i;
927              $param->{form_name} = $wfname;              $param->{form_name} = $wfname;
# Line 1287  sub do_wikiform { Line 931  sub do_wikiform {
931              $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');              $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
932              $fmt{form_option}->replace ($option, $param);              $fmt{form_option}->replace ($option, $param);
933              my $t = 1;              my $t = 1;
934              for (@{$param->{require}||[]}) {              for (keys %{$param->{require}||{}}) {
935                  (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};                  (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
936              }              }
937              $t = $fmt{form_template}->replace ($template, $param) if $t;              $t = $fmt{form_template}->replace ($template, $param) if $t;
# Line 1302  sub do_wikiform { Line 946  sub do_wikiform {
946                    if $param->{anchor_index_};  ## $anchor is used!                    if $param->{anchor_index_};  ## $anchor is used!
947              }              }
948              $form{__wikiform_anchor_index} = $i;              $form{__wikiform_anchor_index} = $i;
949              undef $form{wikiform_targetform};  ## make sure never to match              undef $form{wikiform_targetform};  ## Make sure never to match
950              undef $form{wikiform_index};       ## with WikiForm in rest of page              undef $form{wikiform_index};       ## with WikiForm in rest of page!
951          }          }
952          $i++; $embed;          $i++; $embed;
953      }ge;      }ge;
# Line 1316  sub do_wikiform { Line 960  sub do_wikiform {
960          $form{mymsg} = $content;          $form{mymsg} = $content;
961          $form{mytouch} = 'on';          $form{mytouch} = 'on';
962          &do_write;          &do_write;
963      } else {      } else {    ## Don't write!
964          $form{mycmd} = 'read';          $form{mycmd} = 'default';
965          &do_read;          &do_view;
966      }      }
967  }  }
968    
969  sub code_convert {  sub code_convert {
970    require Jcode;    require Jcode;
971      my ($contentref, $code) = (shift, shift || $kanjicode);      my ($contentref, $code) = (shift, shift || $kanjicode);
972      $code = 'jis' if $code =~ /iso/;      if    ($code =~ /euc/) { $code = 'euc' }
973      $code = 'euc' if $code =~ /euc/;      elsif ($code =~ /iso/) { $code = 'jis' }
974      $code = 'sjis' if $code =~ /shift/;      elsif ($code =~ /shi/) { $code = 'sjis' }
975      $code = 'utf8' if $code =~ /utf/;      elsif ($code =~ /utf/) { $code = 'utf8' }
     #&Jcode::convert($contentref, $code);       # for Jcode.pm  
 #    &jcode::convert($contentref, $code);       # for jcode.pl  
     #&Jcode::tr ($contentref, "\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA\xA1\xF5\xA1\xA4\xA1\xA5\xA1\xA7\xA1\xA8\xA1\xA9\xA1\xAA\xA1\xAE\xA1\xB0\xA1\xB2\xA1\xBF\xA1\xC3\xA1\xCA\xA1\xCB\xA1\xCE\xA1\xCF\xA1\xD0\xA1\xD1\xA1\xDC\xA1\xF0\xA1\xF3\xA1\xF4\xA1\xF6\xA1\xF7\xA1\xE1\xA2\xAF\xA2\xB0\xA2\xB2\xA2\xB1\xA1\xE4\xA1\xE3\xA1\xC0\xA1\xA1" => q(0-9A-Za-z&,.:;?!`^_/|()[]{}+$%#*@='"~-><\ )) if $code eq 'euc';  
976      $$contentref = Jcode->new ($contentref)->tr ("\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA\xA1\xF5\xA1\xA4\xA1\xA5\xA1\xA7\xA1\xA8\xA1\xA9\xA1\xAA\xA1\xAE\xA1\xB0\xA1\xB2\xA1\xBF\xA1\xC3\xA1\xCA\xA1\xCB\xA1\xCE\xA1\xCF\xA1\xD0\xA1\xD1\xA1\xDC\xA1\xF0\xA1\xF3\xA1\xF4\xA1\xF6\xA1\xF7\xA1\xE1\xA2\xAF\xA2\xB0\xA2\xB2\xA2\xB1\xA1\xE4\xA1\xE3\xA1\xC0\xA1\xA1" => q(0-9A-Za-z&,.:;?!`^_/|()[]{}+$%#*@='"~-><\ ))->$code;      $$contentref = Jcode->new ($contentref)->tr ("\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA\xA1\xF5\xA1\xA4\xA1\xA5\xA1\xA7\xA1\xA8\xA1\xA9\xA1\xAA\xA1\xAE\xA1\xB0\xA1\xB2\xA1\xBF\xA1\xC3\xA1\xCA\xA1\xCB\xA1\xCE\xA1\xCF\xA1\xD0\xA1\xD1\xA1\xDC\xA1\xF0\xA1\xF3\xA1\xF4\xA1\xF6\xA1\xF7\xA1\xE1\xA2\xAF\xA2\xB0\xA2\xB2\xA2\xB1\xA1\xE4\xA1\xE3\xA1\xC0\xA1\xA1" => q(0-9A-Za-z&,.:;?!`^_/|()[]{}+$%#*@='"~-><\ ))->$code;
977      return $$contentref;      return $$contentref;
978  }  }
979    
 sub do_diff {  
     if (not &is_editable($form{mypage})) {  
         &do_read;  
         return;  
     }  
     &open_diff;  
     my $title = $form{mypage};  
     &print_header($title, -noindex => 1);  
     $_ = &escape($diffbase{$form{mypage}});  
     &close_diff;  
     print qq(<h3>@{[&Resource('Diff:Title',escape=>1)]}</h3>);  
     print qq(<p>@{[&Resource('Diff:Notice',escape=>1)]}</p>);  
     print qq(<pre class="diff">);  
     foreach (split(/\n/, $_)) {  
         if (/^\+(.*)/) {  
             print qq(<ins class="added">$1</ins>\n);  
         } elsif (/^\-(.*)/) {  
             print qq(<del class="deleted">$1</del>\n);  
         } elsif (/^\=(.*)/) {  
             print qq(<span class="same">$1</span>\n);  
         } else {  
             print qq|??? $_\n|;  
         }  
     }  
     print qq(</pre>);  
     &print_footer($title);  
 }  
   
 sub do_rss {  
     eval q{use Yuki::RSS};  
     my $rss = new Yuki::RSS(  
         version => '1.0',  
         encoding => &get_charset_name ($kanjicode),  
     );  
     my $scheme = 'http';  
     $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;  
     my $myuri = "$scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi";  
     $rss->stylesheet (  
       href      => $myuri . "?mycmd=TEXT_CSS;mypage=WikiStyle:RSS",  
       type      => 'text/css',  
     );  
     $rss->channel(  
         title   => &Resource ('RSS:WikiTitle'),  
         link    => $myuri,  
         description     => &Resource ('RSS:WikiDescription'),  
         'dc:language'   => $lang,  
     );  
     my $recentchanges = $database{RecentChanges};  
     my $count = 0;  
     foreach (split(/\n/, $recentchanges)) {  
         last if ($count >= 15);  
         if (/\[\[([^]]+)\]\]/) {  
           my $title = $1;  
           $rss->add_item (  
             title       => &escape($title),  
             link        => $myuri . '?' . &encode($title),  
             description => &escape(&get_subjectline($title,delimiter=>'')),  
             'dc:date'   => &get_info ($title, $info_LastModified),  
           );  
           $count++;  
         }  
     }  
     # print RSS information (as XML).  
     print <<"EOD"  
 Content-type: application/xml; charset=@{[&get_charset_name ($kanjicode)]}  
   
 @{[$rss->as_string]}  
 EOD  
 }  
   
980  sub _rfc3339_date ($) {  sub _rfc3339_date ($) {
981    my @time = gmtime (shift);    my @time = gmtime (shift);
982    sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];    sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
983  }  }
984    
 sub is_exist_page {  
     my ($name) = @_;  
     if ($use_exists) {  
         return exists($database{$name});  
     } else {  
         return $database{$name};  
     }  
 }  
   
 sub __get_database ($) { $database{ $_[0] } }  
 sub __set_database ($$) { $database{ $_[0] } = $_[1] }  
   
 sub do_map {  
     my $page = $form{mypage};  
     &print_header ($page);  
     wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});  
     wiki::useragent::add ($ENV{HTTP_USER_AGENT});  
     my ($r, $c) = get_search_result ($form{mypage});  
     my $rl = wiki::referer::list_html ($form{mypage});  
     print "<h2>@{[&Resource('Map:Title',escape=>1)]}</h2>\n<p>@{[&Resource('Map:Description',escape=>1)]}</p>\n";  
     my %option = (level => 0+&Resource('Map:Depth'), weight_list => {}, not_exist => {},  
       map_from_here => &Resource('Map:FromHere'),  
       map_from_here_description => &Resource('Map:FromHereLong'));  
     &wiki::map::make_list ($page, %option);  
     print &wiki::map::list_to_html ($page, $option{weight_list}, %option);  
     if ($c) {  
       print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};  
       print $r;  
     }  
     if ($rl) {  
       print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);  
     }  
     &print_footer ($page);  
 }  
   
985  my %_Resource;  my %_Resource;
986  sub Resource ($;%) {  sub Resource ($;%) {
987    my ($s, %o) = @_;    my ($s, %o) = @_;
# Line 1475  sub add ($$) { Line 1011  sub add ($$) {
1011    $list{ $uri }++;    $list{ $uri }++;
1012    set ($page, \%list);    set ($page, \%list);
1013  }  }
1014  sub get ($) {  sub get ($) { split /"/, $main::database->meta (Referer => $_[0]) }
   my $page = shift;  
   split /"/, main::get_info ($page, 'Referer');  
 }  
1015  sub set ($%) {  sub set ($%) {
1016    my $page = shift;    my $page = shift;
1017    my $list = shift;    my $list = shift;
1018    main::set_info ($page, Referer => join '"', %$list);    $main::database->meta (Referer => $page => join '"', %$list);
1019  }  }
1020    
1021  sub get_dont_record () {  sub get_dont_record () {
1022    map {s/\$/\\\$/g; s/\@/\\\@/g; $_}    map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1023    grep !/^#/,    grep !/^#/,
1024    split /[\x0D\x0A]+/, &main::__get_database ('RefererDontRecord');    split /[\x0D\x0A]+/, $main::database{RefererDontRecord};
1025  }  }
1026  sub get_site_name () {  sub get_site_name () {
1027    my @lines = grep /[^#]/, split /[\x0D\x0A]+/, &main::__get_database('RefererSiteName');    my @lines = grep /[^#]/, split /[\x0D\x0A]+/, $main::database{RefererSiteName};
1028    my @item;    my @item;
1029    for (@lines) {    for (@lines) {
1030      next if /^#/;      next if /^#/;
# Line 1536  sub __decode ($) { Line 1069  sub __decode ($) {
1069  }  }
1070    
1071  package wiki::useragent;  package wiki::useragent;
1072    our $UseLog;
1073    
1074  sub add ($) {  sub add ($) {
1075    my $s = shift;    my $s = shift;
1076    return unless length $s;    return unless length $s;
1077      return unless $UseLog;
1078    $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;    $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1079    my %ua;    my %ua;
1080    for (split /\n/, &main::__get_database('WikiUserAgentList')) {    for (split /\n/, $main::database{$main::PageName{UserAgentList}}) {
1081      if (/^-\[(\d+)\] (.+)$/) {      if (/^-\[(\d+)\] (.+)$/) {
1082        my ($t, $n) = ($1, $2);        my ($t, $n) = ($1, $2);
1083        $n =~ tr/\x0A\x0D//d;        $n =~ tr/\x0A\x0D//d;
# Line 1554  sub add ($) { Line 1089  sub add ($) {
1089    for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {    for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1090      $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;      $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1091    }    }
1092    &main::__set_database ('WikiUserAgentList' => $s);    $main::database->STORE ($main::PageName{UserAgentList} => $s, -touch => 0);
1093  }  }
1094    
1095  package wiki::suikawikiconst;  package wiki::suikawikiconst;
# Line 1564  sub to_hash ($;$) { Line 1099  sub to_hash ($;$) {
1099    my $h = shift || {};    my $h = shift || {};
1100    my $val;    my $val;
1101    for my $line (split /\n/, $page) {    for my $line (split /\n/, $page) {
1102        next if $line =~ /^#/;
1103      $line =~ tr/\x0A\x0D//d;      $line =~ tr/\x0A\x0D//d;
1104      if ($val && $line =~ s/^\s+//) {      if ($val && $line =~ s/^\s+//) {
1105        $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;        $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
# Line 1574  sub to_hash ($;$) { Line 1110  sub to_hash ($;$) {
1110    $h;    $h;
1111  }  }
1112    
1113    package wiki::dummy;
1114    sub mtime (@) {undef}
1115    sub meta (@) {undef}
1116    sub Yuki::YukiWikiDB2::meta (@) {undef}
1117    
1118  package SuikaWiki::Plugin;  package SuikaWiki::Plugin;
1119    our $plugin_directory;  # defined in top of this file.    our ($plugin_directory, %List, %Index, %Cache);
1120    our %List;    push @main::INC, $plugin_directory.'/../..';
1121    
1122  sub escape ($$) { main::escape ($_[1]) }  sub escape ($$) { main::escape ($_[1]) }
1123  sub unescape ($$) { main::unescape ($_[1]) }  sub unescape ($$) { main::unescape ($_[1]) }
# Line 1585  sub decode ($$) { main::decode ($_[1]) } Line 1126  sub decode ($$) { main::decode ($_[1]) }
1126  sub __get_datetime ($) { main::get_now () }  sub __get_datetime ($) { main::get_now () }
1127  sub resource ($$;%) { shift; &main::Resource (@_) }  sub resource ($$;%) { shift; &main::Resource (@_) }
1128  sub uri ($$) { $main::uri{$_[1]} }  sub uri ($$) { $main::uri{$_[1]} }
1129    sub new_index ($$) { ++$Index{$_[1]} }
1130    sub user_agent_names ($) { $main::UA }
1131    sub magic_and_content ($$) {
1132      my ($magic, $page) = ('', $_[1]);
1133      $magic = $1 if $page =~ s!^((?:\#\?|/\*|<\?)[^\x02\x0A\x0D]+)[\x02\x0A\x0D]+!!s;
1134      ($magic, $page);
1135    }
1136    sub formatter ($$) {
1137      &main::load_formatter ($_[1]);
1138      $main::fmt{$_[1]};
1139    }
1140    sub format_converter ($$$) {
1141      &main::load_formatter ('format');
1142      $main::fmt{format}->{($_[1]=~/([A-Za-z0-9]\S+)/?$1:'SuikaWiki/0.9').'_to_'.$_[2]}
1143      || $main::fmt{format}->{($_[1]=~/([A-Za-z0-9](?:(?!\/)\S)+)/?$1:'SuikaWiki').'_to_'.$_[2]};
1144    }
1145    sub cache ($$) {
1146      my $name = $_[1];
1147      unless (ref $Cache{$name}) {
1148        my %cache;
1149        tie (%cache, 'Yuki::YukiWikiCache', -file => $main::PathTo{CachePrefix}.$name);
1150        $Cache{$name} = \%cache;
1151      }
1152      $Cache{$name};
1153    }
1154    
1155  sub regist ($@) {  sub regist ($@) {
1156      my $pack = shift;      my $pack = shift;
# Line 1611  package wiki::conneg; Line 1177  package wiki::conneg;
1177  sub get_accept_lang (;$) {  sub get_accept_lang (;$) {
1178    my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};    my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1179    my %alang = (ja => 0.0002, en => 0.0001);    my %alang = (ja => 0.0002, en => 0.0001);
1180      if ($UA =~ m#Mozilla/0\.#) {
1181        $alang{ja} = 0.00001;
1182      }
1183    my $i = 0.1;    my $i = 0.1;
1184    for (split /\s*,\s*/, $alang) {    for (split /\s*,\s*/, $alang) {
1185      tr/\x09\x0A\x0D\x20//d;      tr/\x09\x0A\x0D\x20//d;
# Line 1634  sub get ($;\%) { Line 1203  sub get ($;\%) {
1203    for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {    for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1204      while (length $lang) {      while (length $lang) {
1205        unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {        unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1206          $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash (&main::__get_database('WikiResource:'.$lang));          $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash ($main::database{'WikiResource:'.$lang});
1207          $v = $option->{resource}->{$lang}->{$resname};          $v = $option->{resource}->{$lang}->{$resname};
1208          last if defined $v;          last if defined $v;
1209        }        }
# Line 1645  sub get ($;\%) { Line 1214  sub get ($;\%) {
1214    defined $v ? $v : $resname;    defined $v ? $v : $resname;
1215  }  }
1216    
 package wiki::map;  
   
 sub make_list ($;%) {  
   my ($page, %option) = @_;  
   $option{level} ||= 3;  
   my %weight;  
   my $content = &main::__get_database ($page);  
   $content =~ s{^\#\?([^\x0A\x0D]+)}{  
     if ($1 =~ /import="([^"]+)"/) {  
       for (split /\s*,\s*/, $1) {  
         $weight{$_} += 2;  
       }  
     }  
     $&;  
   }ges;  
   ## Bug: this code does not support content type.  
   $content =~ s{\[\[((?!\#)[^]]+)\](?:>>\d+)?\]}{  
     $weight{$1}++; $&;  
   }ge;  
   delete $weight{$page};        ## Delete myself  
   for my $page (keys %weight) {  
     my $w = ($content =~ s/\Q$page\E/$&/g);  
     $weight{$page} += $w + $weight{$page}; ## Weight of [[name]] is x2.  
     ($weight{$page} *= 0.1, $option{not_exist}->{$page} = 1) unless &main::is_exist_page ($page);  
   }  
   $option{weight_list}->{$page} = \%weight;  
   if (--$option{level}) {  
     for my $page (keys %weight) {  
       &make_list ($page, %option) unless $option{weight_list}->{$page};  
     }  
   }  
   $option{weight_list};  
 }  
   
 sub list_to_html ($$;%) {  
   my ($Page, $wlist, %option) = @_;  
   my $r = '';  
   $option{outputed}->{$Page} = 1;  
   for my $page (sort {$wlist->{$Page}->{$b} <=> $wlist->{$Page}->{$a}} keys %{$wlist->{$Page}}) {  
     $r .= qq(<li><span class="weight">[@{[0+$wlist->{$Page}->{$page}]}]</span> <a href="$main::url_cgi?@{[&main::encode($page)]}" class="wiki@{[$option{not_exist}->{$page}?' not-exist':'']}">@{[&main::escape ($page).($option{not_exist}->{$page}?qq(<span class="mark">@{[&main::Resource('JumpAndEditWikiPageMark',escape=>1)]}</span>):'')]}</a> <a href="$main::url_cgi?mycmd=map;mypage=@{[&main::encode($page)]}" class="wiki-cmd map-from-here" title="@{[&main::escape($option{map_from_here_description})]}">@{[&main::escape($option{map_from_here})]}</a> <span class="summary">@{[&main::escape(&main::get_subjectline($page))]}</span>);  
     unless ($option{outputed}->{$page}) {  
       $r .= &list_to_html ($page, $wlist, %option);  
     }  
     $r .= "</li>\n";  
   }  
   $r ? qq(<ul class="map">$r</ul>) : '';  
 }  
   
1217  package main;  package main;
1218  &main;  &main;
1219  exit 0;  exit 0;
# Line 1701  exit 0; Line 1222  exit 0;
1222  __END__  __END__
1223  =head1 NAME  =head1 NAME
1224    
1225  wiki.cgi - This is YukiWiki, yet another Wiki clone.  wiki.cgi --- SuikaWiki: Yet yet another WikiEngine
 walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.  
1226    
1227  =head1 DESCRIPTION  =head1 SEE ALSO
1228    
1229  YukiWiki is yet another Wiki clone.  <IW:SuikaWiki:SuikaWiki>
1230    
1231  YukiWiki can treat Japanese WikiNames (enclosed with [[ and ]]).  =head1 AUTHORS
 YukiWiki provides 'InterWiki' feature, RDF Site Summary (RSS),  
 and some embedded commands (such as [[#comment]] to add comments).  
1232    
1233  Read F<readme_en.txt> (English) or F<readme_ja.txt> (Japanese) in more detail.  Hiroshi Yuki <hyuki@hyuki.com> <http://www.hyuki.com/yukiwiki/>
1234    
1235  =head1 AUTHOR  Makio Tsukamoto <http://digit.que.ne.jp/>
1236    
1237  Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/  Wakaba <w@suika.fam.cx>
1238    
1239  =head1 LICENSE  =head1 LICENSE
1240    
1241  Copyright (C) 2000-2002 by Hiroshi Yuki.  Copyright (C) 2000-2003 AUTHORS
1242    
1243  This program is free software; you can redistribute it and/or  This program is free software; you can redistribute it and/or
1244  modify it under the same terms as Perl itself.  modify it under the same terms as Perl itself.

Legend:
Removed from v.1.44  
changed lines
  Added in v.1.51

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24