/[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.21 by wakaba, Sun Jun 2 07:15:20 2002 UTC revision 1.49 by w, Sat Jan 4 03:32:55 2003 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl  #!/usr/bin/perl
 #!perl  
 #  
2  # wiki.cgi - This is YukiWiki, yet another Wiki clone.  # wiki.cgi - This is YukiWiki, yet another Wiki clone.
3  #  #
 # Copyright (C) 2000-2002 by Hiroshi Yuki.  
 # <hyuki@hyuki.com>  
 # http://www.hyuki.com/yukiwiki/  
 #  
4  # This program is free software; you can redistribute it and/or  # This program is free software; you can redistribute it and/or
5  # modify it under the same terms as Perl itself.  # modify it under the same terms as Perl itself.
 #  
 ##############################  
 #  
 # walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.  
 #  
 # WalWikiの現バージョンは、YukiWiki 2.0.beta1をベースにしています。  
 #  
 # * 更新内容  
 #  
 # 2.0.beta1.wal.1 on 2002/05/19,22:32:19  
 # (1) Footerの変更  
 # (2) WikiNameの拡張 : PerlCEも包含、PPMInstallは含まない  
 # (3) 別名リンク([別名 URL])に対応。  
 # (4) ISBNをアマゾン.jpのAsociateプログラムリンクに変換。  
 # (5) [[#box:InterWikiName]]でInterWikiなテキストボックス生成  
 # (6) HTMLモード対応。  
 #  
 # 旧2.0.alpha0.wal.3版までの修正の内、以下に変更があります。  
 # ・以下はYukiWiki2に実装されたため、独自コードはなくなりました。  
 #   - インラインの画像変換  
 #   - YukiWikiDB対応  
 #   - テーブル  
 #   - DB関連モジュールuseのeval化  
 #   - BracketNameによるキーからブラケットを排除  
 # ・ISBN番号への対応はWalWiki2.0より、InterWikiへのAdd-Onになりました。  
 #   [[ISBN http://www.amazon.co.jp/exec/obidos/ASIN/isbn($1)/walrdigi-22]]のように登録。  
 #  
 #=======================================  
   
 # Walrus add (debug) start  
 my $walrus_log;  
 my $walrus_debugging = 0;  
 # Walrus add (debug) end  
6    
 # Libraries.  
7  use strict;  use strict;
8  use lib qw(./WalWiki/lib);  use lib qw(./lib);
 use CGI qw(:standard);  
9  use CGI::Carp qw(fatalsToBrowser);  use CGI::Carp qw(fatalsToBrowser);
10  use Yuki::RSS;  our $VERSION = do{my @r=(q$Revision$=~/\d+/g);sprintf "%d."."%02d" x $#r,@r};
11  use Yuki::DiffText qw(difftext);  
12  use Yuki::YukiWikiDB;  require 'wikidata/suikawiki-config.ph';
 use AnyDBM_File;  
 require 'jcode.pl';  
 # use Jcode;  
13  use Fcntl;  use Fcntl;
 my $version = '2.0.beta1.2002-05-29';  
 my $walversion;  
 ##############################  
 #  
 # You MUST modify following '$modifier_...' variables.  
 #  
 my $modifier_mail = 'w@suika.fam.cx';   # Your mail address, like 'walrus@digit.que.ne.jp'.  
 my $modifier_url  = 'http://suika.fam.cx/~wakaba/';     # Your web page, like 'http://digit.que.ne.jp/work/'.  
 my $modifier_name = '和';       # Your name, like 'Makio Tsukamoto'.  
 # my $modifier_dbtype = 'AnyDBM_File';  # Fast, not available on some server, page size limited.  
 # my $modifier_dbtype = 'dbmopen';      # Fast, not available on some server, page size limited.  
 my $modifier_dbtype = 'YukiWikiDB';     # Slow, available on all environment.  
 # my $modifier_sendmail = '/usr/sbin/sendmail -t -n'; # Your sendmail.  
 my $modifier_sendmail = ''; # If you don't need mail notification.  
 my $modifier_dir_data = './wikidata'; # Your data directory.  
 my $modifier_rss_title = "WalWiki $walversion";  
 my $modifier_rss_link = 'http://suika.fam.cx/~wakaba/-temp/wiki2/wiki'; # Blank is not allowed.  
 my $modifier_rss_description = 'This is WalWiki, yet another Wiki clone based on YukiWiki';  
14  ##############################  ##############################
15  #  our %fmt;       ## formatter objects
16  # You MAY modify following variables.  my %embed_command = (
17  #          searched        => '^\[\[#searched:([^\]]+)\]\]$',
18  my $file_touch = "$modifier_dir_data/touched.txt";          form    => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
 my $file_resource = "$modifier_dir_data/resource.txt";  
 my $file_FrontPage = "$modifier_dir_data/frontpage.txt";  
 my $file_conflict = "$modifier_dir_data/conflict.txt";  
 my $file_format = "$modifier_dir_data/format.txt";  
 my $url_cgi = 'wiki';  
 my $url_stylesheet = 'wiki-style.css';  
 my $icontag = '<img src="/icons/folder" alt="*" width="40" height="40" />';  
 my $maxrecent = 50;  
 my $cols = 80;  
 my $rows = 20;  
 ##############################  
 #  
 # You MAY, but do NOT NEED modify following variables.  
 #  
 my $dataname = "$modifier_dir_data/wiki";  
 my $infoname = "$modifier_dir_data/info";  
 my $diffname = "$modifier_dir_data/diff";  
 my $editchar = '?';  
 my $subject_delimiter = ' - ';  
 my $use_autoimg = 1; # automatically convert image URL into <img> tag.  
 my $use_exists = 0; # If you can use 'exists' method for your DB.  
 ##############################  
 my $InterWikiName = 'InterWikiName';  
 my $RecentChanges = 'RecentChanges';  
 my $AdminChangePassword = 'AdminChangePassword';  
 my $CompletedSuccessfully = 'CompletedSuccessfully';  
 my $FrontPage = 'HomePage';  
 my $IndexPage = 'IndexPage';  
 my $SearchPage = 'SearchPage';  
 my $CreatePage = 'CreatePage';  
 my $ErrorPage = 'ErrorPage';  
 my $RssPage = 'RssPage';  
 my $AdminSpecialPage = 'Admin Special Page'; # must include spaces.  
 ##############################  
 # my $wiki_name = '\b([A-Z][a-z]+([A-Z][a-z]+)+)\b';        # Walrus del (2)  
 my $wiki_name   = '\b([A-Z][a-z]+([A-Z][a-z]*)+)\b';        # Walrus add (2)  
 my $bracket_name = '\[\[(\S+?)\]\]';  
 my $embedded_name = '\[\[(#\S+?)\]\]';  
 my $interwiki_definition = '\[\[(\S+?)\ (\S+?)\]\]';  
 my $interwiki_name = '([^:]+):([^:].*)';  
 ##############################  
 my $embed_comment = '[[#comment]]';  
 my $embed_rcomment = '[[#rcomment]]';  
 my $embed_interwiki = '^\[\[#(box|text|password):(\S+)\]\]$';    # Walrus add (5)  
 ##############################  
 my $info_LastModified = 'LastModified';  
 my $info_IsFrozen = 'IsFrozen';  
 my $info_AdminPassword = 'AdminPassword';  
 ##############################  
 my $kanjicode = 'euc';  
 my $charset = 'EUC-JP';  
 my $lang = 'ja';  
 my %fixedpage = (  
     $IndexPage => 1,  
     $CreatePage => 1,  
     $ErrorPage => 1,  
     $RssPage => 1,  
     $RecentChanges => 1,  
     $SearchPage => 1,  
     $AdminChangePassword => 1,  
     $CompletedSuccessfully => 1,  
     #$FrontPage => 1,  
19  );  );
20    our ($modifier_dbtype,$url_cgi,%uri,%PathTo,$use_exists);
21    our (%PageName,$kanjicode,$lang,%ViewDefinition);
22    
23    ##############################
24  my %form;  my %form;
25  my %database;  our %database;
26  my %infobase;  our $database = bless {}, 'wiki::dummy';
 my %diffbase;  
 my %resource;  
27  my %interwiki;  my %interwiki;
28  ##############################  ##############################
29  my %page_command = (  my %page_command = (
30      $IndexPage => 'index',      $PageName{RssPage} => 'rss',
     $SearchPage => 'searchform',  
     $CreatePage => 'create',  
     $RssPage => 'rss',  
     $AdminChangePassword => 'adminchangepasswordform',  
     #$FrontPage => 'FrontPage',  
31  );  );
32  my %command_do = (  my %command_do = (
33      read => \&do_read,      read => \&do_read,
34      edit => \&do_edit,      TEXT_CSS => \&do_output_css,
35      adminedit => \&do_adminedit,      edit => \&do_view,
     adminchangepasswordform => \&do_adminchangepasswordform,  
36      adminchangepassword => \&do_adminchangepassword,      adminchangepassword => \&do_adminchangepassword,
37      write => \&do_write,      write => \&do_write,
     index => \&do_index,  
38      searchform => \&do_searchform,      searchform => \&do_searchform,
     search => \&do_search,  
     create => \&do_create,  
     createresult => \&do_createresult,  
     FrontPage => \&do_FrontPage,  
39      comment => \&do_comment,      comment => \&do_comment,
40        RandomJump  => \&do_random_jump,
41      rss => \&do_rss,      rss => \&do_rss,
42      diff => \&do_diff,      diff => \&do_view,
43      interwikibox => \&do_interwiki_box, # Walrus add (5)      wikiform    => \&do_wikiform,
44        map => \&do_view,
45  );  );
46  ##############################  my $UA = '';  ## User agent name
47  my @ignore_html_page = ('FrontPage');        # Walrus add (6)  $| = 1;
 my @ignore_html_tags = ('a', 'br', 'img');   # Walrus add (6)  
 my $walversion = '2.0.beta1.wal.1';          # Walrus add (1)  
 ##############################  
 # &test_convert;  
 &main;  
 exit(0);  
48  ##############################  ##############################
49    
50  sub main {  sub main {
51      &init_resource;      $UA = $main::ENV{HTTP_USER_AGENT};
52      &open_db;      &open_db;
53      &init_form;      &init_form;
     &init_InterWikiName;  
54      if ($command_do{$form{mycmd}}) {      if ($command_do{$form{mycmd}}) {
55          &{$command_do{$form{mycmd}}};          &{$command_do{$form{mycmd}}};
56      } else {      } else {
57          &do_FrontPage;          &{$command_do{read}};
58      }      }
59      &close_db;      &close_db;
60  }  }
61    
62  sub do_read {  sub do_read {
63      &print_header($form{mypage});    my $content = $database{$form{mypage}};
64      &print_content($database{$form{mypage}});    my $lm = $database->mtime ($form{mypage});
65      &print_footer($form{mypage});    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
66  }    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
67      my @toc;
68  sub do_edit {      my ($magic, $content) = &SuikaWiki::Plugin::magic_and_content (undef, $content);
69      my ($page) = &unarmor_name(&armor_name($form{mypage}));      $magic ||= '#?SuikaWiki/0.9';
70      &print_header($page);      if ($magic =~ m!^\#\?SuikaWiki/0.9!) {
71      if (not &is_editable($page)) {        my $expires = time;
72          &print_message($resource{cantchange});        if ($magic =~ /interactive="yes"/) {
73      } elsif (&is_frozen($page)) {          $lm = $expires;
74          &print_message($resource{cantchange});        } else {
75            $expires += 120;
76          }
77          &print_header ($form{mypage}, -last_modified => $lm, -expires => $expires,
78            -content_format => $magic, -noindex => ($magic =~ /obsoleted="yes"/ ? 1 : 0));
79      } else {      } else {
80          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);        &print_header($form{mypage}, -expires => time + 120, -content_format => $magic, -last_modified => $lm);
81      }      }
82      &print_footer($page);      &load_formatter ('view');
83        print $fmt{view}->replace ($ViewDefinition{read} => bless {param => \%form, page => $form{mypage}, toc => \@toc, formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin');
84  }  }
85    
86  sub do_adminedit {  sub do_output_css {
87      my ($page) = &unarmor_name(&armor_name($form{mypage}));    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
88      &print_header($page);    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
89      if (not &is_editable($page)) {    my $content = $database{$form{mypage}};
90          &print_message($resource{cantchange});    if ($content =~ m#^\s*/\*\s*W3C-CSS#) {
91      } else {      my $lm = gmtime $database->mtime ($form{mypage});
92          &print_message($resource{passwordneeded});      print "Content-Type: text/css; charset=@{[&get_charset_name($kanjicode)]}\n";
93          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);      print "Last-Modified: $lm\n";
94        print "Expires: @{[scalar gmtime time+3600]}\n";    ## TODO: don't use asctime
95        print "\n";
96        print $content;
97      } else {
98        print "Status: 406 Unsupported Media Type\n";
99        &print_header('WikiPageIsNotCSS', -noindex => 1);
100        &load_formatter ('view');
101        print $fmt{view}->replace ($ViewDefinition{read} => bless {param => \%form, page => 'WikiPageIsNotCSS', toc => [], formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin');
102      }
103    }
104    
105    sub id_and_name ($) {
106        my $name = shift;
107        if ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer#) {
108          qq{id="$name"><a name="$name"></a};
109        } else {
110            qq{id="$name"};
111      }      }
     &print_footer($page);  
112  }  }
113    
114  sub do_adminchangepasswordform {  sub do_view {
115      &print_header($AdminChangePassword);      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
116      &print_passwordform;      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
117      &print_footer($AdminChangePassword);      &print_header($form{mypage}, -noindex => 1, -expires => time+60);
118        &load_formatter ('view');
119        my $view = $form{mycmd};
120        if ($view eq 'edit') {
121          $view = 'adminedit' if $form{admin};
122        } elsif ($view =~ /[^0-9A-Za-z]/) {
123          $view = 'view'
124        }
125        print $fmt{view}->replace ($ViewDefinition{$view} => bless {param => \%form, page => $form{mypage}, toc => [], formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin');
126  }  }
127    
128  sub do_adminchangepassword {  sub do_adminchangepassword {
129      if ($form{mynewpassword} ne $form{mynewpassword2}) {      if ($form{mynewpassword} ne $form{mynewpassword2}) {
130          &print_error($resource{passwordmismatcherror});          &print_error(&Resource('Error:PasswordMismatch'));
131      }      }
132      my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_AdminPassword);      my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
133      if ($validpassword_crypt) {      if ($validpassword_crypt) {
134          if (not &valid_password($form{myoldpassword})) {          if (not &valid_password($form{myoldpassword})) {
135              &send_mail_to_admin(<<"EOD", "AdminChangePassword");              &print_error(&Resource('Error:PasswordIsIncorrect'));
 myoldpassword=$form{myoldpassword}  
 mynewpassword=$form{mynewpassword}  
 mynewpassword2=$form{mynewpassword2}  
 EOD  
             &print_error($resource{passworderror});  
136          }          }
137      }      }
138      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
# Line 254  EOD Line 140  EOD
140      my $salt1 = $token[(time | $$) % scalar(@token)];      my $salt1 = $token[(time | $$) % scalar(@token)];
141      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
142      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
143      &set_info($AdminSpecialPage, $info_AdminPassword, $crypted);      $database->meta (AdminPassword => $PageName{AdminSpecialPage} => $crypted);
144    
145      &print_header($CompletedSuccessfully);      &print_header('CompletedSuccessfully', -noindex => 1);
146      &print_message($resource{passwordchanged});      &print_message(&Resource('Error:PasswordIsChanged'));
     &print_footer($CompletedSuccessfully);  
147  }  }
148    
149  sub do_index {  sub valid_password ($) {
150      &print_header($IndexPage);      my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
151      print qq(<ul>);      return crypt (shift, $validpassword_crypt) eq $validpassword_crypt ? 1 : 0;
     foreach my $page (sort keys %database) {  
         if (&is_editable($page)) {  
             print qq(<li><a href="$url_cgi?@{[&encode($page)]}">$page</a>@{[&escape(&get_subjectline($page))]}</li>);  
             # print qq(<li>@{[&get_info($page, $info_IsFrozen)]}</li>);  
             # print qq(<li>@{[0 + &is_frozen($page)]}</li>);  
         }  
     }  
     print qq(</ul>);  
     &print_footer($IndexPage);  
152  }  }
153    
154  sub do_write {  sub do_write {
# Line 281  sub do_write { Line 157  sub do_write {
157      }      }
158    
159      if (not &is_editable($form{mypage})) {      if (not &is_editable($form{mypage})) {
160          &print_header($form{mypage});          &print_header($form{mypage}, -noindex => 1);
161          &print_message($resource{cantchange});          &print_message(&Resource('Error:ThisPageIsUneditable'));
         &print_footer($form{mypage});  
         return;  
     }  
   
     if (&conflict($form{mypage}, $form{mymsg})) {  
162          return;          return;
163      }      }
164    
165      # Making diff      ## Check confliction
166      {      if ($form{myLastModified} ne $database->mtime ($form{mypage})) {
167          &open_diff;        &print_header($form{mypage}, -noindex => 1);
168          my @msg1 = split(/\n/, $database{$form{mypage}});        &load_formatter ('view');
169          my @msg2 = split(/\n/, $form{mymsg});        print $fmt{view}->replace ($ViewDefinition{-conflict} => bless {param => \%form, page => $form{mypage}, toc => [], formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin');
170          $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);        return;
         &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, '' . localtime);            $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          &print_header($CompletedSuccessfully);          my $fragment = '';
181          &print_message($resource{saved});          $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
182          &print_content("$resource{continuereading} @{[&armor_name($form{mypage})]}");          if ($form{__comment_anchor_index}) {
183          &print_footer($CompletedSuccessfully);              $fragment .= qq(#anchor-$form{__comment_anchor_index});
184            } elsif ($form{__wikiform_anchor_index}) {
185                $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
186            }
187            &print_header($form{mypage}, -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));
188            &load_formatter ('view');
189            print $fmt{view}->replace ($ViewDefinition{-wrote} => bless {param => \%form, page => $form{mypage}, formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin');
190      } else {      } else {
         &send_mail_to_admin($form{mypage}, "Delete");  
191          delete $database{$form{mypage}};          delete $database{$form{mypage}};
192          delete $infobase{$form{mypage}};          &print_header($form{mypage}, -noindex => 1);
193          if ($form{mytouch}) {          &load_formatter ('view');
194              &update_recent_changes;          print $fmt{view}->replace ($ViewDefinition{-deleted} => bless {param => \%form, page => $form{mypage}, formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin');
         }  
         &print_header($form{mypage});  
         &print_message($resource{deleted});  
         &print_footer($form{mypage});  
195      }      }
196  }  }
197    
198  sub do_searchform {  sub _compatible_options () {
199      &print_header($SearchPage);    (use_anchor_name => ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer# ? 1 : 0));
200      &print_searchform("");  }
201      &print_footer($SearchPage);  
202  }  sub get_search_result ($;%) {
203      my $word = lc shift;
204  sub do_search {    my %option = @_;
205      my $word = &escape($form{mymsg});    my @r;
206      &print_header($SearchPage);    foreach my $page (keys %database) {
207      &print_searchform($word);      next if !$option{-match_myself} && ($page eq $word);
208      my $counter = 0;      my $content = lc $database{$page};
209      foreach my $page (sort keys %database) {      if (index (lc $page, $word) > -1) {
210          next if $page =~ /^$RecentChanges$/;        my $c = $content =~ s/\Q$word\E//g;
211          if ($database{$page} =~ /\Q$form{mymsg}\E/ or $page =~ /\Q$form{mymsg}\E/) {        push @r, [$page, $c+20];
212              if ($counter == 0) {      } elsif (index ($word, lc $page) > -1) {
213                  print qq|<ul>|;        my $c = $content =~ s/\Q$word\E//g;
214              }        push @r, [$page, $c+10];
215              print qq(<li><a href ="$url_cgi?@{[&encode($page)]}">$page</a>@{[&escape(&get_subjectline($page))]}</li>);      } elsif (my $c = $content =~ s/\Q$word\E//g) {
216              $counter++;        push @r, [$page, $c];
217          }      }
218      }    }
219      if ($counter == 0) {    #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
220          &print_message($resource{notfound});    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;
221      } else {    $r = qq|<ul class="search-result">$r</ul>| if $r;
222          print qq|</ul>|;    wantarray? ($r, scalar @r): $r;
223      }  }
224      &print_footer($SearchPage);  
225  }  sub do_random_jump {
226      my @list = keys %database;
227  sub do_create {    my $name = &encode ($list[rand @list]);
228      &print_header($CreatePage);    my $scheme = 'http';
229      print <<"EOD";    $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
230  <form action="$url_cgi" method="post">    print "Location: $scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi?$name\n";
231      <input type="hidden" name="mycmd" value="edit">    print "\n";
     <strong>$resource{newpagename}</strong><br>  
     <input type="text" name="mypage" value="" size="20">  
     <input type="submit" value="$resource{createbutton}"><br>  
 </form>  
 EOD  
     &print_footer($CreatePage);  
 }  
   
 sub do_FrontPage {  
     open(FILE, $file_FrontPage) or &print_error("($file_FrontPage)");  
     my $content = join('', <FILE>);  
     &code_convert(\$content, $kanjicode);  
     close(FILE);  
     &print_header($FrontPage);  
     &print_content($content);  
     &print_footer($FrontPage);  
232  }  }
233    
234  sub print_error {  sub print_error {
235      my ($msg) = @_;      my ($msg) = @_;
236      &print_header($ErrorPage);      &print_header($PageName{ErrorPage}, -noindex => 1);
237      print qq(<p><strong class="error">$msg</strong></p>);      print qq(<p><strong class="error">$msg</strong></p>);
     &print_footer($ErrorPage);  
238      exit(0);      exit(0);
239  }  }
240    
241  sub print_header {  sub print_header ($;%) {
242      my ($page) = @_;      my ($page, %option) = @_;
243      my $bodyclass = "normal";      my @head;
244      my $editable = 0;      $option{body_class} = &is_frozen($page) ? 'frozen' : 'normal';
245      my $admineditable = 0;      $option{body_class} .= " wiki-page-obsoleted" if $option{-content_format} =~ /obsoleted="yes"/;
246      if (&is_frozen($page) and $form{mycmd} =~ /^(read|write)$/) {      if ($option{-goto}) {
247          $editable = 0;        if ($UA =~ m#Opera|MSIE 2\.#) {
248          $admineditable = 1;            ## WARNING: This code may output unsafe HTML document if
249          $bodyclass = "frozen";            ##          $option{-goto} is not clean.
250      } elsif (&is_editable($page) and $form{mycmd} =~ /^(read|write)$/) {            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
251          $admineditable = 1;            print qq{Refresh: 0; url=$option{-goto}\n};
252          $editable = 1;            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
253      } else {        } else {
254          $editable = 0;            $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
255              print qq{Refresh: 0; url="$option{-goto}"\n};
256              push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;">);
257          }
258      }      }
259      my $cookedpage = &encode($page);      print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
260        if ($option{-expires}) {
261          print qq{Expires: @{[scalar gmtime $option{-expires}]}\n};
262        }
263        if ($UA =~ m#Mozilla/2#) {
264            my $ct = qq{text/html; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
265            print qq{Content-Type: $ct\n};
266            push @head, qq{<meta http-equiv="content-type" content="$ct">};
267        } elsif ($UA =~ m#Infomosaic#) {
268            print qq{Content-Type: text/html\n};
269        } else {
270            print qq{Content-Type: text/html; charset=@{[&get_charset_name($kanjicode)]}\n};
271        }
272        push @head, qq(<title>@{[&escape($page)]}</title>);
273        if ($UA !~ m#Mozilla/[1-4]\.# || $UA =~ m#MSIE (?:[4-9]\.|\d\d)#) {
274          push @head, qq(<link rel="stylesheet" type="text/css").
275                      qq( href="@{[&escape($uri{wiki}.'?mycmd=TEXT_CSS;mypage='.&encode($PageName{DefaultStyleForHTML}).';x-lm='.$database->mtime ($PageName{DefaultStyleForHTML}))]}");
276        }
277        push @head, q(<meta name="ROBOTS" content="NOINDEX">) if $option{-noindex};
278        my ($Links, $links) = &make_navigate_links ($page);
279        #print $Links;      ## Link: fields
280        $links = join "\n", (@head, $links);
281      print <<"EOD";      print <<"EOD";
 Content-type: text/html; charset=$charset  
282  Content-Language: $lang  Content-Language: $lang
283  Content-Style-Type: text/css  Content-Style-Type: text/css
284    
285  <!DOCTYPE html  <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
286      PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->
287      "http://www.w3.org/TR/html4/loose.dtd">  <html lang="$lang" class="$option{body_class}">
288  <html lang="$lang">  <head profile="http://suika.fam.cx/~wakaba/-temp/wiki/wiki?WikiHTMLMetaProfile">
289  <head>  $links
     <title>$page @{[&escape(&get_subjectline($page))]}</title>  
     <link rel="index" href="$url_cgi?$IndexPage">  
     <link rev="made" href="mailto:$modifier_mail">  
     <link rel="stylesheet" type="text/css" href="$url_stylesheet">  
290  </head>  </head>
 <body class="$bodyclass">  
 <div class="tools">  
     @{[ $admineditable  
         ? qq(<a title="$resource{admineditthispage}" href="$url_cgi?mycmd=adminedit;mypage=$cookedpage">$resource{admineditbutton}</a> | )  
         : qq()  
     ]}  
     @{[ $editable  
         ? qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=$cookedpage">$resource{editbutton}</a> | )  
         : qq()  
     ]}  
     @{[ $admineditable  
         ? qq(<a href="$url_cgi?mycmd=diff;mypage=$cookedpage">$resource{diffbutton}</a> | )  
         : qq()  
     ]}  
     <a href="$url_cgi?$CreatePage">$resource{createbutton}</a> |  
     <a href="$url_cgi?$IndexPage">$resource{indexbutton}</a> |  
     <a href="$url_cgi?$RssPage">$resource{rssbutton}</a> |  
     <a href="$url_cgi?$FrontPage">$FrontPage</a> |  
     <a href="$url_cgi?$SearchPage">$resource{searchbutton}</a> |  
     <a href="$url_cgi?$RecentChanges">$resource{recentchangesbutton}</a>  
 </div>  
 <h1 class="header"><a  
     title="$resource{searchthispage}"  
     href="$url_cgi?mycmd=search;mymsg=$cookedpage">$page</a>@{[&escape(&get_subjectline($page))]}</h1>  
291  EOD  EOD
292  }  }
293    
294  sub print_footer {  sub get_charset_name ($;%) {
295      my ($page) = @_;      my ($charset, %option) = (lc shift, @_);
296      $walrus_log = ($walrus_debugging) ? &text_to_html("----\n$walrus_log") : '';    # Walrus add (debug)      if ($charset =~ 'euc') {
297      # Walrus mod (1) start          $charset = $option{compatible} ? 'x-euc-jp' : 'euc-jp';
298  my $cvslog = '$Revision$ $Date$';      } elsif ($charset =~ 'sjis' || $charset =~ 'shift') {
299      print <<"EOD";          $charset = $option{compatible} ? 'x-sjis' : 'shift_jis';
300  <div class="footer">      } elsif ($charset =~ 'jis') {
301  <p>          $charset = 'iso-2022-jp';
302  <a href="http://digit.que.ne.jp/work/">WalWiki</a> $walversion &copy; 2000-2002 by <a href="http://digit.que.ne.jp/">Makio Tsukamoto</a>.<br />      }
303  based on <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version &copy; 2000-2002 by <a href="http://www.hyuki.com/">Hiroshi Yuki</a>.<br />      $charset;
304  <a href="/gate/cvs/wakaba/wiki/" title="CVS Repository">  }
305  $cvslog  
306  </a>  sub _navigate_links (@) {
307  </p>    my ($page) = @_;
308  <div class="navigation">    my $editable = (&is_editable($page) && !&is_frozen($page)) ? 1 : 0;
309  [<a href="/" title="このサーバーの首頁">/</a>    my $cookedpage = &encode($page);
310  <a href="/map" title="このサーバーの案内">地図</a>    <<EOH;
311  <a href="/search/" title="このサーバーの検索">検索</a>]      @{[ $editable
312  </div>          ? qq(<a title="@{[&Resource('EditThisPageLong',escape=>1)]}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E" class="wiki-cmd">@{[&Resource('EditThisPage',escape=>1)]}</a> | )
313  </div>          : qq()
314  $walrus_log      ]}
315  </body>      <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> |
316  </html>      <a href="$url_cgi?mycmd=map;mypage=$cookedpage" class="wiki-cmd" title="@{[&Resource('ShowMapOfThisPageLong',escape=>1)]}">@{[&Resource('ShowMapOfThisPage',escape=>1)]}</a> |
317  EOD      <a href="$url_cgi?$PageName{CreatePage}" class="wiki" title="@{[&Resource('GoToCreatePageLong',escape=>1)]}">@{[&Resource('GoToCreatePage',escape=>1)]}</a> |
318  #       print <<"EOD";      <a href="$url_cgi?$PageName{IndexPage}" class="wiki" title="@{[&Resource('GoToIndexPageLong',escape=>1)]}">@{[&Resource('GoToIndexPage',escape=>1)]}</a> |
319  #   <hr>      <a href="$url_cgi?$PageName{FrontPage}" class="wiki" title="@{[&Resource('GoToHomePageLong',escape=>1)]}">@{[&Resource('GoToHomePage',escape=>1)]}</a> |
320  #   <address class="footer">      <a href="$url_cgi?$PageName{SearchPage}" class="wiki" title="@{[&Resource('GoToSearchPageLong',escape=>1)]}">@{[&Resource('GoToSearchPage',escape=>1)]}</a> |
321  #       <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version      <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> |
322  #       &copy; 2000-2002 by <a href="http://www.hyuki.com/">Hiroshi Yuki</a>.<br />      <a href="$url_cgi?$PageName{RecentChanges}" class="wiki" title="@{[&Resource('GoToRecentChangesLong',escape=>1)]}">@{[&Resource('GoToRecentChanges',escape=>1)]}</a>
323  #       Modified by <a href="$modifier_url">$modifier_name</a>.  EOH
324  #   </address>  }
325  #   <p class="footer">  
326  #       <a href="http://www.hyuki.com/yukiwiki/">$icontag</a>  sub make_navigate_links ($) {
327  #   </p>      my $page = shift;
328  #   </body>      my @link;
329  #   </html>      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);
330  #   EOD      push @link, {rel=>'edit', href=>"$url_cgi?mycmd=edit;admin=1;mypage=@{[&encode($page)]}", class=>"wiki-command", title=>&Resource('AdminEditThisPageLink')} if &is_editable ($page) || &is_frozen ($page);
331      # Walrus mod (1) end      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')};
332        push @link, {rel=>'myself', href=>"$url_cgi?@{[&encode($page)]}", class=>'wiki', title=>&Resource('GoToMyselfLink')};
333        push @link, {rel=>'index', href=>"$url_cgi?$PageName{IndexPage}", class=>'wiki', title=>&Resource('GoToIndexPageLink')};
334        push @link, {rel=>'home', href=>"$url_cgi?$PageName{FrontPage}", class=>'wiki', title=>&Resource('GoToHomePageLink')};
335        push @link, {rel=>'News', href=>"$url_cgi?WikiNews", class=>'wiki', title=>&Resource('GoToWikiNewsLink')};
336        push @link, {rel=>'News', href=>"$url_cgi?$PageName{RecentChanges}", class=>"wiki", title=>&Resource('GoToRecentChangesLink')};
337        push @link, {rel=>'News', href=>"$url_cgi?$PageName{RssPage}", class=>"wiki", title=>&Resource('GoToRssPageLink'), type=>'application/xml'};
338        push @link, {rel=>'search', href=>"$url_cgi?$PageName{SearchPage}", class=>'wiki', title=>&Resource('GoToSearchPageLink')};
339        push @link, {rel=>'help', href=>"$url_cgi?WikiHelp", class=>'wiki', title=>&Resource('GoToWikiHelpLink')};
340        push @link, {rel=>'copyright', href=>"$url_cgi?WikiPageLicense", class=>'wiki', title=>&Resource('GoToWikiPageLicenseLink')};
341        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')};
342        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')};
343        push @link, {rel=>'lucky', href=>"$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}", class=>'wiki randomlink', title=>&Resource('GoSomewhereLink')};
344        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};
345        push @link, {rel=>'history', href=>"$url_cgi?mycmd=diff;mypage=@{[&encode($page)]}", title=>&Resource('ViewDiffOfThisPageLink'), class=>'wiki-command'} if $wiki::diff::UseDiff;
346        push @link, {rel=>'contents', href=>"$url_cgi?mycmd=map;mypage=@{[&encode($page)]}", title=>&Resource('ShowMapOfThisPageLink'), class=>'wiki-command'};
347        my ($Links, $links) = ('', '');
348        for my $e (@link) {
349            $links .= qq(<link);
350            $Links .= qq(Link: <$e->{href}>);
351            for my $attr (qw/rel rev href title class type hreflang charset/) {
352                $links .= qq( $attr="@{[&escape($e->{$attr})]}") if $e->{$attr};
353            }
354            for my $attr (qw/rel rev title/) {
355                $Links .= qq(; $attr="@{[do{$e->{$attr} =~ s/([\\\"])/\\$1/g; $e->{$attr}}]}") if $e->{$attr};
356            }
357            $links .= qq(>\n);
358            $Links .= qq(\n);
359        }
360        wantarray ? ($Links, $links) : $Links;
361  }  }
362    
363  sub escape {  sub escape {
364      my $s = shift;      my $s = shift;
365      $s =~ s|\r\n|\n|g;      $s =~ s|\x0D\x0A|\x0A|g;
366      $s =~ s|\&|&amp;|g;      $s =~ s|&|&amp;|g;
367      $s =~ s|<|&lt;|g;      $s =~ s|<|&lt;|g;
368      $s =~ s|>|&gt;|g;      $s =~ s|>|&gt;|g;
369      $s =~ s|"|&quot;|g;      $s =~ s|"|&quot;|g;
# Line 496  sub escape { Line 373  sub escape {
373  sub unescape {  sub unescape {
374      my $s = shift;      my $s = shift;
375      # $s =~ s|\n|\r\n|g;      # $s =~ s|\n|\r\n|g;
376      $s =~ s|\&amp;|\&|g;      $s =~ s|&lt;|<|g;
377      $s =~ s|\&lt;|\<|g;      $s =~ s|&gt;|>|g;
378      $s =~ s|\&gt;|\>|g;      $s =~ s|&quot;|"|g;
379      $s =~ s|\&quot;|\"|g;      $s =~ s|&amp;|&|g;
380      return $s;      return $s;
381  }  }
382    
383  sub print_content {  sub convert_format ($$$;%) {
384      my ($rawcontent) = @_;    my ($content, $d => $t, %option) = @_;
385      print &text_to_html($rawcontent, toc=>1);    &load_formatter ('format');
386      my $f = $fmt{format}->{$d.'_to_'.$t};
387      if (ref $f) {
388        $option{content} = $content;
389        &$f ({}, bless (\%option, 'SuikaWiki::Plugin'));
390      } elsif ($t =~ /HTML|xml/) {
391        length $content ? '<pre>'.&escape($content).'</pre>' : '';
392      } else {
393        $content;
394      }
395  }  }
396    
397  sub text_to_html {  sub text_to_html {
398      my ($txt, %option) = @_;      my ($txt, %option) = @_;
399      my (@txt) = split(/\n/, $txt);      my $toc = $option{-toc} || (ref $option{toc} ? $option{toc} : []);
     my (@toc);  
400      my $tocnum = 0;      my $tocnum = 0;
401        
402        ## Load constants
403        my %const;
404        if ($option{content_format} =~ /import="([^"]+)"/) {
405          for (split /\s*,\s*/, $1) {
406            my $wp = $database{$_};
407            if ($wp =~ m!^\#\?SuikaWikiConst/1.0!) {
408              wiki::suikawikiconst::to_hash ($wp => \%const);
409            }
410          }
411        }
412        
413        $txt =~ s{__&&([^&]+)&&__}{defined $const{$1}?$const{$1}:qq(__&&$1&&__)}ge;
414        my (@txt) = split(/\n/, $txt);
415      my (@saved, @result);      my (@saved, @result);
416      unshift(@saved, "</p>");      unshift(@saved, "</p>");
417      push(@result, "<p>");      push(@result, "<p>");
418      foreach (@txt) {      foreach (@txt) {
419          chomp;          chomp;
420          # Walrus mod (6) start          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
421          #if ($saved[0] eq '</html>') {              push @$toc, [5, "i$tocnum" => ($1 || $tocnum)];
422          #    if (/<\/html>/i) { splice(@saved); }              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h6>');
         #    else { push (@result, &html_to_ignored_html($_)); }  
         #} elsif (/^<html>/i and &is_ignore_html($form{mypage})) {  
         #    push(@result, splice(@saved));  
         #    push(@saved, '</html>');  
         #} els  
         if (/^\*\*\*\*\*(.*)/) {  
             push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));  
             push(@result, splice(@saved), qq(<h6 id="i$tocnum">) . &inline($1) . '</h6>');  
423              $tocnum++;              $tocnum++;
424          } elsif (/^\*\*\*\*(.*)/) {          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
425              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));              push @$toc, [4, "i$tocnum" => ($1 || $tocnum)];
426              push(@result, splice(@saved), qq(<h5 id="i$tocnum">) . &inline($1) . '</h5>');              push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h5>');
427              $tocnum++;              $tocnum++;
428          } elsif (/^\*\*\*(.*)/) {          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
429              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));              push @$toc, [3, "i$tocnum" => ($1 || $tocnum)];
430              push(@result, splice(@saved), qq(<h4 id="i$tocnum">) . &inline($1) . '</h4>');              push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h4>');
431              $tocnum++;              $tocnum++;
432          } elsif (/^\*\*(.*)/) {          } elsif (/^\*\*([^\x0D\x0A]*)/) {
433          # if (/^\*\*(.*)/) {          # if (/^\*\*(.*)/) {
434          # Walrus mod (6) end          # Walrus mod (6) end
435              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));              push @$toc, [2, "i$tocnum" => ($1 || $tocnum)];
436              push(@result, splice(@saved), qq(<h3><a name="i$tocnum"> </a>) . &inline($1) . '</h3>');              push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h3>');
437              $tocnum++;              $tocnum++;
438          } elsif (/^\*(.*)/) {          } elsif (/^\*([^\x0D\x0A]*)/) {
439              push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));              push @$toc, [1, "i$tocnum" => ($1 || $tocnum)];
440              push(@result, splice(@saved), qq(<h2><a name="i$tocnum"> </a>) . &inline($1) . '</h2>');              push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h2>');
441              $tocnum++;              $tocnum++;
442          #} elsif (/^----/) {          } elsif (/^(={1,6})(.*)/) {
         #    push(@result, splice(@saved), '<hr>');  
         } elsif (/^(={1,5})(.*)/) {  
443              &back_push('ol', length($1), \@saved, \@result);              &back_push('ol', length($1), \@saved, \@result);
444              push(@result, '<li>' . &inline($2) . '</li>');              push(@result, '<li>' . &inline($2, const => \%const) . '</li>');
445          } elsif (/^(-{1,5})(.*)/) {          } elsif (/^(-{1,6})(.*)/) {
446              &back_push('ul', length($1), \@saved, \@result);            &back_push('ul', length($1), \@saved, \@result);
447              push(@result, '<li>' . &inline($2) . '</li>');            my ($pf, $l) = ('', $2);
448              if (!$main::_EMBEDED && $l =~ s/^\s*\[([0-9]+)\]//) {
449                my $num = 0+$1;
450                $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
451              }
452              push(@result, '<li>' . $pf . &inline ($l, const => \%const) . '</li>');
453          } elsif (/^:([^:]+):(.*)/) {          } elsif (/^:([^:]+):(.*)/) {
454              &back_push('dl', 1, \@saved, \@result);              &back_push('dl', 1, \@saved, \@result);
455              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');              push(@result, '<dt>' . &inline($1, const => \%const) . '</dt>', '<dd>' . &inline($2, const => \%const) . '</dd>');
456          } elsif (/^(>{1,5})(.*)/) {          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
457              &back_push('blockquote', length($1), \@saved, \@result);              &back_push('blockquote', length($1), \@saved, \@result);
458              push(@result, &inline($2));              push @result, "<p>";
459                push(@result, &inline($2, const => \%const));
460                unshift @saved, "</p>";
461          } elsif (/^\s*$/) {          } elsif (/^\s*$/) {
462              push(@result, splice(@saved));              push(@result, splice(@saved));
             unshift(@saved, "</p>");  
463              push(@result, "<p>");              push(@result, "<p>");
464                unshift(@saved, "</p>");
465          } elsif (/^(\s+.*)$/) {          } elsif (/^(\s+.*)$/) {
466              &back_push('pre', 1, \@saved, \@result);              &back_push('pre', 1, \@saved, \@result);
467              #push(@result, &escape($1)); # Not &inline, but &escape              push(@result, &inline($1, const => \%const));
468              push(@result, &inline($1)); # Not &inline, but &escape          } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
469  #       } elsif (/^\,(.*)$/) {             # Walrus del (BF)              &back_push('table', 1, \@saved, \@result);
         } elsif (/^\,(.*?)[\x0D\x0A]*$/) { # Walrus add (BF)  
             &back_push('table', 1, \@saved, \@result, ' border="1"');  
470              #######              #######
471              # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.              # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.
472              # XXXXX              # XXXXX
# Line 586  sub text_to_html { Line 480  sub text_to_html {
480                          $colspan[$i]++;                          $colspan[$i]++;
481                      }                      }
482                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
483                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i]));                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], const => \%const));
484                  } else {                  } else {
485                      $value[$i] = '';                      $value[$i] = '';
486                  }                  }
# Line 594  sub text_to_html { Line 488  sub text_to_html {
488              push(@result, join('', '<tr>', @value, '</tr>'));              push(@result, join('', '<tr>', @value, '</tr>'));
489              # XXXXX              # XXXXX
490              #######              #######
491            } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
492                push @result, splice (@saved), '<'.lc($1).'>';
493                unshift @saved, "</p>";
494                push @result, "<p>";
495            } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
496                push @result, splice (@saved), '</'.lc($1).'>';
497            } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
498              my $num = 0+$1;
499              push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
500              push @result, &inline ($2, const => \%const);
501          } else {          } else {
502              push(@result, &inline($_));              push(@result, &inline($_, const => \%const));
503          }          }
504      }      }
505      push(@result, splice(@saved));      push(@result, splice(@saved));
506        
507      if ($option{toc}) {      my $r = join("\n", @result);
508          # Convert @toc (table of contents) to HTML.      $r =~ s#<p>\x0D?\x0A</p>##g;
509          # This part is taken from Makio Tsukamoto's WalWiki.      $r =~ s#[\x0D\x0A]+</#</#g;
510          my (@tocsaved, @tocresult);      $r =~ s#<pre>\x0D?\x0A#<pre>#g;
511          foreach (@toc) {      $r;
             if (/^(-{1,3})(.*)/) {  
                 &back_push('ul', length($1), \@tocsaved, \@tocresult);  
                 push(@tocresult, '<li>' . $2 . '</li>');  
             }  
         }  
         push(@tocresult, splice(@tocsaved));  
         return join("\n", @tocresult, @result);  
     } else {  
         return join("\n", @result);  
     }  
512  }  }
513    
514  sub back_push {  sub back_push {
# Line 631  sub back_push { Line 525  sub back_push {
525      }      }
526  }  }
527    
528  sub inline {  sub inline ($;%) {
529      my ($line) = @_;      my ($line, %option) = @_;
530      $line = &escape($line);      $line = &escape($line);
531      $line =~ s|'''([^']+?)'''|<strong>$1</strong>|g;      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4)}ge;
532      $line =~ s|''([^']+?)''|<em>$1</em>|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;
533      $line =~ s|(\d\d\d\d-\d\d-\d\d \(\w\w\w\) \d\d:\d\d:\d\d)|<span class="date">$1</span>|g;   # Date      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
534      $line =~ s!      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
535        (      $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;
536          (?:&lt;(?:mailto|http|https|ftp|urn):[\x21-\x7E]*)&gt;      $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
537        |      $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;
538          ($bracket_name) # [[likethis]], [[#comment]], [[Friend:remotelink]]      $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
539        |      $line =~ s|''([^']+)''|<em>$1</em>|g;
540          ($interwiki_definition) # [[Friend http://somewhere/?q=sjis($1)]]      $line =~ s{
541        #|        (\[\[(\#\S+?)\]\])
542        #  ($wiki_name)        |\[\[([^[]+?)](?:&gt;&gt;([0-9]+))?]
543        )        |&gt;&gt;([0-9]+)
544              !        |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
545                  &make_link($1)      }{
546              !gex;        my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
547          if ($l) {
548            &embedded_to_html($1);
549          } elsif (defined $page) {
550            &make_wikilink ($page, anchor => 0+$anchor);
551          } elsif ($anum) {
552            qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
553          } elsif ($uri) {
554            &make_urilink ($uri);
555          }
556        }gex;
557      return $line;      return $line;
558  }  }
559    
560  sub make_link {  sub make_wikilink ($%) {
561      my $chunk = shift;    my ($ename, %option) = @_;
562      # Walrus add (3) start    my $name = &unescape ($ename);
563      $chunk =~ s/^&lt;(.*)&gt;$/$1/;    $option{latest} = $option{latest} ? qq(mycmd=read;x-param=@{[time.[0..9]->[rand 10]]};mypage=) : '';
564      my $name  = $chunk;    if ($database{$name}) {
565      if ($chunk =~ /^\[\[([^ ]+?) ([^ ]+?)\]\]$/ and $form{mypage} ne $InterWikiName) {      my $subject = &escape (&get_subjectline ($name, delimiter => ''));
566          ($name, $chunk) = ($1, $2);      if ($option{anchor}) {
567      } elsif ($chunk =~ /^mailto:(.*)$/) {        return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
568          $name = $1;      } else {
569      }        return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}" class="wiki">$ename</a>);
570      if ($use_autoimg and $name =~ /^(http|https|ftp|):.+\.(png|gif|jpe?g)/) {      }
571          $name = qq(<img src="$name">) ;    } else {
572      }      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>);
573      $name = &unarmor_name($name);    }
574      # Walrus add (3) end  }
575      if ($chunk =~ /^(http|https|ftp):/) {  
576          # Walrus mod (3) start  sub make_urilink ($;%) {
577  #       if ($use_autoimg and $chunk =~ /\.(gif|png|jpeg|jpg)$/) {    require URI;
578  #           return qq(<a href="$chunk"><img src="$chunk"></a>);    my $uri = shift;
579  #       } else {    if ($uri =~ s/^IW://) {       ## InterWiki (not URI)
580  #           return qq(<a href="$chunk">$chunk</a>);      $uri = &unescape ($uri);
581  #       }      if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
582          return qq(&lt;<a href="$chunk">$name</a>&gt;);        my ($site, $name) = ($1, $2);
583          # Walrus mod (3) end        for ($site, $name) {
584      } elsif ($chunk =~ m#^urn:[0-9A-Za-z_:;/.-]+#) {          if (s/^"//) { s/"$//; s/\\(.)/$1/g }
585          return qq|&lt;<a href="/uri-res/N2L?${name}">$name</a>&gt;|;        }
586      } elsif ($chunk =~ /^mailto:(.*)/) {        &init_InterWikiName () unless $interwiki{'[[]]'};
587  #       return qq(<a href="$chunk">$2</a>);                 # Walrus del (3)        if ($interwiki{$site}) {
588          return qq(&lt;<a href="$chunk">$name</a>&gt;);              # Walrus add (3)          &load_formatter ('interwiki');
589      } elsif ($chunk =~ /^$interwiki_definition$/) {          my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
590  #       return qq(<span class="InterWiki">$chunk</span>);   # Walrus del (3)          $site = &escape ($site); $name = &escape ($name);
591          return qq(<span class="InterWiki">$name</span>);    # Walrus add (3)          qq(&lt;<a href="$uri" class="out-of-wiki interwiki" title="$name ($site); URI: &lt;$uri&gt;"><span class="interwiki-site">$site:</span><span class="interwiki-name">$name</span></a>&gt;);
592      } elsif ($chunk =~ /^$embedded_name$/) {        } else {
593          return &embedded_to_html($chunk);          qq(&lt;@{[&Resource('Error:UnknownInterWikiName=',escape=>1)]}@{[&escape ($site)]}&gt;);
594          }
595      } else {      } else {
596          $chunk = &unarmor_name($chunk);        qq(&lt;@{[&Resource('Error:InvalidInterWiki=',escape=>1)]}@{[&escape($uri)]}&gt;);
         $chunk = &unescape($chunk); # To treat '&' or '>' or '<' correctly.  
         my $cookedchunk = &encode($chunk);  
         if ($chunk =~ /^$interwiki_name$/) {  
             my ($intername, $localname) = ($1, $2);  
             my $remoteurl = $interwiki{$intername};  
             if ($remoteurl) {  
 #               $remoteurl =~ s/\b(euc|sjis|ykwk|asis)\(\$1\)/&interwiki_convert($1, $localname)/e;      # Walrus del (4)  
                 $remoteurl =~ s/\b(euc|sjis|ykwk|asis|isbn)\(\$1\)/&interwiki_convert($1, $localname)/e; # Walrus add (4)  
 #               return qq(<a href="$remoteurl">$chunk</a>); # Walrus del (3)  
                 return qq(<a href="$remoteurl">$name</a>);  # Walrus add (3)  
             } else {  
 #               return $chunk;                              # Walrus del (3)  
                 return $name;                               # Walrus add (3)  
             }  
         } elsif ($database{$chunk}) {  
             my $subject = &escape(&get_subjectline($chunk, delimiter => ''));  
 #           return qq(<a title="$subject" href="$url_cgi?$cookedchunk">$chunk</a>);  # Walrus del (3)  
             return qq(<a title="$subject" href="$url_cgi?$cookedchunk">$name</a>);   # Walrus add (3)  
         } elsif ($page_command{$chunk}) {  
 #           return qq(<a title="$chunk" href="$url_cgi?$cookedchunk">$chunk</a>);    # Walrus del (3)  
             return qq(<a title="$chunk" href="$url_cgi?$cookedchunk" class="wiki">$name</a>);     # Walrus add (3)  
         } else {  
             return qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=$cookedchunk" class="wiki">$name<span class="mark">$editchar</span></a>);  
         }  
597      }      }
598  }    } elsif ($uri =~ /^urn:/) {   ## URN
599        my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
600  # Walrus add (6) start      qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
601  sub is_ignore_html {    } elsif ($uri =~ s/^MAIL://) {        ## mail address (not URI)
602      my ($pagename) = @_;      my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
603      foreach (@ignore_html_page) {      qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
604          return 1 if ($pagename eq $_);    } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) {   ## image (not URI itself)
605      }      my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
606      return 0;      qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
607  }    } else {      ## misc. URI
608  # Walrus add (6) end      CGI::Carp::warningsToBrowser (0);
609        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
610  # Walrus add (6) start      CGI::Carp::warningsToBrowser (1);
611  sub html_to_ignored_html {      qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
612      my $str = shift(@_);    }
613      my $text_regex        = q{[^<]*};  }
614      my $tag_regex_        = q{[^"'<>]*(?:"[^"]*"[^"'<>]*|'[^']*'[^"'<>]*)*(?:>|(?=<)|$(?!\n))}; #'}}}}  
615      my $comment_tag_regex = '<!(?:--[^-]*-(?:[^-]+-)*?-(?:[^>-]*(?:-[^>-]+)*?)??)*(?:>|$(?!\n)|--.*$)';  {my $FormIndex = 0;
616      my $tag_regex         = qq{$comment_tag_regex|<$tag_regex_};  sub make_custom_form ($$$$) {
617      my $ignored           = join('|', @ignore_html_tags);      my ($wfname, $definition, $template, $option) = @_;
618      my $result = '';      ## $template and $option is currently not used in this procedure.
619      while ($str =~ /($text_regex)($tag_regex)?/gso) {      unless ($main::_EMBEDED) {
620        last if $1 eq '' and $2 eq '';          $FormIndex++;
621        $result .= $1;          if (length $definition) {
622        my $tag_tmp = $2;              my $param = bless {}, 'SuikaWiki::Plugin';
623        $result .= ($tag_tmp =~ /^<\/?($ignored)(?![0-9A-Za-z])/i) ? $tag_tmp : &escape($tag_tmp);              my $lastmodified = $database->mtime ($form{mypage});
624        if ($tag_tmp =~ /^<(XMP|PLAINTEXT|SCRIPT)(?![0-9A-Za-z])/i) {              &load_formatter (qw/form_input form_option/);
625          $str =~ /(.*?)(?:<\/$1(?![0-9A-Za-z])$tag_regex_|$)/gsi;              $definition = &unescape ($definition);
626          $result .= &escape($1);              $definition =~ s/\\(.)/$1/g;
627        }              $option = &unescape ($option);
628                $option =~ s/\\(.)/$1/g;
629                $fmt{form_option}->replace ($option, $param);
630                $param->{output}->{form} = 1 unless defined $param->{output}->{form};
631                $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
632                my $target_page = $param->{output}->{page} || $form{mypage};
633                $param->{form_disabled} = 1 if $database->meta (IsFrozen => $form{mypage});
634                my $target_form = $param->{output}->{id};
635                my $r = '';
636                $r = <<EOH if $param->{output}->{form};
637    <form method="post" action="$url_cgi" id="wikiform-$FormIndex" class="wikiform">
638      <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'read':'wikiform']}">
639      <input type="hidden" name="mypage" value="@{[&escape($target_page)]}">
640      <input type="hidden" name="myLastModified" value="$lastmodified">
641      <input type="hidden" name="mytouch" value="on">
642      <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex)]}">
643    EOH
644                $r .= qq(<a name="wikiform-$FormIndex"></a>) if $UA =~ m#Mozilla/[12]\.#;
645                $r .= $fmt{form_input}->replace ($definition, $param);
646                $r .= "</form>\n" if $param->{output}->{form};
647                $r;
648           } else {  ## No input-interface WikiForm
649               qq(<a id="wikiform-$FormIndex" name="wikiform-$FormIndex"><!-- #form --></a>);
650           }
651        } else {
652            qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
653      }      }
654      return $result;  }}
 }  
 # Walrus add (6) end  
655    
656  sub print_message {  sub print_message {
657      my ($msg) = @_;      my ($msg) = @_;
658      print qq(<p><strong>$msg</strong></p>);      print qq(<p><strong>@{[&escape($msg)]}</strong></p>);
659  }  }
660    
661  sub init_form {  sub init_form {
662      if (param()) {      ## TODO: Support multipart/form-data
663          foreach my $var (param()) {      my $query = '';
664              $form{$var} = param($var);      if (uc $main::ENV{REQUEST_METHOD} eq 'POST') {
665          }        read STDIN, $query, $main::ENV{CONTENT_LENGTH};
666      } else {      }
667          $ENV{QUERY_STRING} = $FrontPage;      $query .= ($query ? ';' : '') . $main::ENV{QUERY_STRING};
668      }      if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
669          my $query = &decode($main::ENV{QUERY_STRING});
670      my $query = &decode($ENV{QUERY_STRING});        $query = &code_convert(\$query, $kanjicode);
671      if ($page_command{$query}) {        if ($page_command{$query}) {
672          $form{mycmd} = $page_command{$query};          $form{mycmd} = $page_command{$query};
673          $form{mypage} = $query;          $form{mypage} = $query;
674      } elsif ($query =~ /^($wiki_name)$/) {        } else {
         $form{mycmd} = 'read';  
         $form{mypage} = $1;  
     } elsif ($database{$query}) {  
         $form{mycmd} = 'read';  
675          $form{mypage} = $query;          $form{mypage} = $query;
676            $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';
677          }
678        } else {
679          for (split /[;&]/, $query) {
680            if (my ($n, $v) = split /=/, $_, 2) {
681              for ($n, $v) {tr/+/ /; s/%([0-9A-Fa-f][0-9A-Fa-f])/pack 'C', hex $1/ge};
682              $form{$n} = $v;
683            }
684          }
685          unless (defined $form{mypage}) {
686            $form{mypage} = $form{epage};
687            $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;
688          }
689          if ($page_command{$form{mypage}} && $form{mycmd} eq 'read') {
690            $form{mypage} = &code_convert(\$form{mypage}, $kanjicode);
691            $form{mycmd} = $page_command{$form{mypage}};
692          }
693      }      }
694        $form{mypage} ||= 'HomePage';
695        $form{mypage} =~ tr/\x00-\x1F\x7F//d;
696        $form{mycmd} ||= 'read';
697    
698      # mypreview_edit        -> do_edit, with preview.      # mypreview_edit        -> do_edit, with preview.
699      # mypreview_adminedit   -> do_adminedit, with preview.      # mypreview_adminedit   -> do_adminedit, with preview.
# Line 785  sub init_form { Line 705  sub init_form {
705          }          }
706      }      }
707    
708      #      #
709      # $form{mycmd} is frozen here.      # $form{mycmd} is frozen here.
710      #      #
711    
712        for (grep /^wikiform__/, keys %form) {
713            $form{$_} = &code_convert (\$form{$_}, $kanjicode);
714        }
715      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
716      $form{myname} = &code_convert(\$form{myname}, $kanjicode);      $form{myname} = &code_convert(\$form{myname}, $kanjicode);
717  }  }
718    
719  sub update_recent_changes {  {my %SubjectLine;
     my $update = "- @{[&get_now]} @{[&armor_name($form{mypage})]} @{[&get_subjectline($form{mypage})]}";  
     my @oldupdates = split(/\r?\n/, $database{$RecentChanges});  
     my @updates;  
     foreach (@oldupdates) {  
         /^\- \d\d\d\d\-\d\d\-\d\d \(...\) \d\d:\d\d:\d\d (\S+)/;    # date format.  
         my $name = &unarmor_name($1);  
         if (&is_exist_page($name) and ($name ne $form{mypage})) {  
             push(@updates, $_);  
         }  
     }  
     if (&is_exist_page($form{mypage})) {  
         unshift(@updates, $update);  
     }  
     splice(@updates, $maxrecent + 1);  
     $database{$RecentChanges} = join("\n", @updates);  
     if ($file_touch) {  
         open(FILE, "> $file_touch");  
         print FILE localtime() . "\n";  
         close(FILE);  
     }  
 }  
   
720  sub get_subjectline {  sub get_subjectline {
721      my ($page, %option) = @_;      my ($page, %option) = @_;
722      if (not &is_editable($page)) {      unless (defined $SubjectLine{$page}) {
723          return "";        if (not &is_editable($page)) {
724            $SubjectLine{$page} = "";
725          } else {
726            $SubjectLine{$page} = $database{$page};
727            $SubjectLine{$page} =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
728            $SubjectLine{$page} =~ s/\x0D?\x0A.*//s;
729          }
730        }
731        if (length $SubjectLine{$page}) {
732          $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
733          $option{delimiter}.$SubjectLine{$page}.$option{tail};
734      } else {      } else {
735          # Delimiter check.        '';
         my $delim = $subject_delimiter;  
         if (defined($option{delimiter})) {  
             $delim = $option{delimiter};  
         }  
   
         # Get the subject of the page.  
         my $subject = $database{$page};  
         $subject =~ s/\r?\n.*//s;  
         return "$delim$subject";  
736      }      }
737  }  }}
   
 sub send_mail_to_admin {  
     my ($page, $mode) = @_;  
     return unless $modifier_sendmail;  
     my $message = <<"EOD";  
 To: $modifier_mail  
 From: $modifier_mail  
 Subject: [Wiki]  
 MIME-Version: 1.0  
 Content-Type: text/plain; charset=ISO-2022-JP  
 Content-Transfer-Encoding: 7bit  
   
 --------  
 MODE = $mode  
 REMOTE_ADDR = $ENV{REMOTE_ADDR}  
 REMOTE_HOST = $ENV{REMOTE_HOST}  
 --------  
 $page  
 --------  
 $database{$page}  
 --------  
 EOD  
     &code_convert(\$message, 'jis');  
     open(MAIL, "| $modifier_sendmail");  
     print MAIL $message;  
     close(MAIL);  
 }  
738    
739  sub open_db {  sub open_db {
740      if ($modifier_dbtype eq 'dbmopen') {      if ($modifier_dbtype eq 'dbmopen') {
741          dbmopen(%database, $dataname, 0666) or &print_error("(dbmopen) $dataname");          dbmopen(%database, $PathTo{WikiDataBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDataBase}");
         dbmopen(%infobase, $infoname, 0666) or &print_error("(dbmopen) $infoname");  
742      } elsif ($modifier_dbtype eq 'AnyDBM_File') {      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
743          tie(%database, "AnyDBM_File", $dataname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $dataname");          eval q{use AnyDBM_File};
744          tie(%infobase, "AnyDBM_File", $infoname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $infoname");          tie(%database, "AnyDBM_File", $PathTo{WikiDataBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDataBase}");
745      } else {      } elsif ($modifier_dbtype eq 'Yuki::YukiWikiDB') {
746          tie(%database, "Yuki::YukiWikiDB", $dataname) or &print_error("(tie Yuki::YukiWikiDB) $dataname");          eval q{use Yuki::YukiWikiDB};
747          tie(%infobase, "Yuki::YukiWikiDB", $infoname) or &print_error("(tie Yuki::YukiWikiDB) $infoname");          tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");
748        } else {    ## Yuki::YukiWikiDB || Yuki::YukiWikiDBMeta
749            eval qq{use $modifier_dbtype};
750            $database = tie(%database, $modifier_dbtype => $PathTo{WikiDataBase}, -lock => 2, -backup => $wiki::diff::UseDiff) or &print_error("(tie $modifier_dbtype) $PathTo{WikiDataBase}");
751      }      }
752  }  }
753    
754  sub close_db {  sub close_db {
755      if ($modifier_dbtype eq 'dbmopen') {      if ($modifier_dbtype eq 'dbmopen') {
756          dbmclose(%database);          dbmclose(%database);
         dbmclose(%infobase);  
     } elsif ($modifier_dbtype eq 'AnyDBM_File') {  
         untie(%database);  
         untie(%infobase);  
757      } else {      } else {
758          untie(%database);          untie(%database);
         untie(%infobase);  
759      }      }
760  }  }
761    
762  sub open_diff {  sub editform (@) {
763      if ($modifier_dbtype eq 'dbmopen') {    my %option = @_;
764          dbmopen(%diffbase, $diffname, 0666) or &print_error("(dbmopen) $diffname");    my $frozen = &is_frozen ($option{page});
765      } elsif ($modifier_dbtype eq 'AnyDBM_File') {    $option{content} = $database{$option{page}} unless defined $option{content};
766          tie(%diffbase, "AnyDBM_File", $diffname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $diffname");    $option{content} = $database{NewPageTemplate} unless length $option{content};
767      } else {    $option{last_modified} = $database->mtime ($option{page}) unless defined $option{last_modified};
768          tie(%diffbase, "Yuki::YukiWikiDB", $diffname) or &print_error("(tie Yuki::YukiWikiDB) $diffname");    my $f = '';
769      }    my $magic = '';
770  }    $magic = $1 if $option{content} =~ m/^([^\x0A\x0D]+)/s;
771      
772  sub close_diff {    my $selected = 'read';
773      if ($modifier_dbtype eq 'dbmopen') {    if ($form{after_edit_cmd}) {
774          dbmclose(%diffbase);      $selected = $form{after_edit_cmd};
775      } elsif ($modifier_dbtype eq 'AnyDBM_File') {    } elsif ($magic =~ /Const|Config|CSS/) {
776          untie(%diffbase);      $selected = 'edit';
777      } else {    }
778          untie(%diffbase);    my $afteredit = <<EOH;
779      }  <select name="after_edit_cmd">
780  }  <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
781    <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
782  sub print_searchform {  </select>
783      my ($word) = @_;  EOH
784      print <<"EOD";    $f .= <<"EOD";
785  <form action="$url_cgi" method="get">  <form action="$uri{wiki}" method="post">
786      <input type="hidden" name="mycmd" value="search">      @{[ $option{conflict} ? '' : qq(<label><input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}"><kbd>S</kbd></label>) ]}
787      <input type="text" name="mymsg" value="$word" size="20">      @{[ $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>
788      <input type="submit" value="$resource{searchbutton}">      <input type="hidden" name="myLastModified" value="$option{last_modified}">
789  </form>      <input type="hidden" name="mypage" value="@{[&escape($form{mypage})]}">
790  EOD      <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">@{[&escape($option{content})]}</textarea><br>
 }  
   
 sub print_editform {  
     my ($mymsg, $lastmodified, %mode) = @_;  
     my $frozen = &is_frozen($form{mypage});  
   
     if ($form{mypreview}) {  
         if ($form{mymsg}) {  
             unless ($mode{conflict}) {  
                 print qq(<h3>$resource{previewtitle}</h3>\n);  
                 print qq($resource{previewnotice}\n);  
                 print qq(<div class="preview">\n);  
                 &print_content($form{mymsg});  
                 print qq(</div>\n);  
             }  
         } else {  
             print qq($resource{previewempty});  
         }  
         $mymsg = &escape($form{mymsg});  
     } else {  
         $mymsg = &escape($mymsg);  
     }  
   
     my $edit = $mode{admin} ? 'adminedit' : 'edit';  
   
     print <<"EOD";  
 <form action="$url_cgi" method="post">  
     @{[ $mode{admin} ? qq($resource{frozenpassword} <input type="password" name="mypassword" value="$form{mypassword}" size="10"><br>) : "" ]}  
     <input type="hidden" name="myLastModified" value="$lastmodified">  
     <input type="hidden" name="mypage" value="$form{mypage}">  
     <textarea cols="$cols" rows="$rows" name="mymsg" wrap="off">$mymsg</textarea><br>  
791  @{[  @{[
792      $mode{admin} ?      $option{admin} ?
793      qq(      qq(
794      <input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>$resource{frozenbutton}      <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>@{[&Resource('Edit:Freeze',escape=>1)]}</label>
795      <input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>$resource{notfrozenbutton}<br>)      <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br>)
796      : ""      : ""
797  ]}  ]}
798  @{[  @{[
799      $mode{conflict} ? "" :      $option{conflict} ? "" :
800      qq(      qq(
801          <input type="checkbox" name="mytouch" value="on" checked="checked">$resource{touch}<br>          <label><input type="checkbox" name="mytouch" value="on" checked="checked">@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}</label><br>
802          <input type="submit" name="mypreview_$edit" value="$resource{previewbutton}">          <label><input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S"><kbd>S</kbd></label>
803          <input type="submit" name="mypreview_write" value="$resource{savebutton}"><br>         $afteredit
804      )      )
805  ]}  ]}
806  </form>  </form>
807  EOD  EOD
808      unless ($mode{conflict}) {      $f;
         # Show the format rule.  
         open(FILE, $file_format) or &print_error("($file_format)");  
         my $content = join('', <FILE>);  
         &code_convert(\$content, $kanjicode);  
         close(FILE);  
         print &text_to_html($content, toc=>0);  
     }  
 }  
   
 sub print_passwordform {  
         print <<"EOD";  
 <form action="$url_cgi" method="post">  
     <input type="hidden" name="mycmd" value="adminchangepassword">  
     $resource{oldpassword} <input type="password" name="myoldpassword" size="10"><br>  
     $resource{newpassword} <input type="password" name="mynewpassword" size="10"><br>  
     $resource{newpassword2} <input type="password" name="mynewpassword2" size="10"><br>  
     <input type="submit" value="$resource{changepasswordbutton}"><br>  
 </form>  
 EOD  
809  }  }
810    
811  sub is_editable {  sub is_editable {
812      my ($page) = @_;      my ($page) = @_;
813      if (&is_bracket_name($page)) {      $page =~ /[\x00-\x1F\x7F]/ ? 0 : 1;
         return 0;  
     } elsif ($fixedpage{$page}) {  
         return 0;  
     } elsif ($page =~ /\s/) {  
         return 0;  
     } elsif ($page =~ /^\#/) {  
         return 0;  
     } elsif ($page =~ /^$interwiki_name$/) {  
         return 0;  
     } else {  
         return 1;  
     }  
 }  
   
 # armor_name:  
 #   WikiName -> WikiName  
 #   not_wiki_name -> [[not_wiki_name]]  
 sub armor_name {  
     my ($name) = @_;  
     if ($name =~ /^$wiki_name$/) {  
         return $name;  
     } else {  
         return "[[$name]]";  
     }  
 }  
   
 # unarmor_name:  
 #   [[bracket_name]] -> bracket_name  
 #   WikiName -> WikiName  
 sub unarmor_name {  
     my ($name) = @_;  
     if ($name =~ /^$bracket_name$/) {  
         return $1;  
     } else {  
         return $name;  
     }  
 }  
   
 sub is_bracket_name {  
     my ($name) = @_;  
     if ($name =~ /^$bracket_name$/) {  
         return 1;  
     } else {  
         return 0;  
     }  
814  }  }
815    
816  sub decode {  sub decode {
# Line 1044  sub decode { Line 821  sub decode {
821  }  }
822    
823  sub encode {  sub encode {
824      my ($s) = @_;    my $s = shift;
825      my $encoded = '';    $s =~ s/([^0-9A-Za-z_-])/sprintf '%%%02X', ord $1/g;
826      foreach my $ch (split(//, $s)) {    $s;
         if ($ch =~ /[A-Za-z0-9_]/) {  
             $encoded .= $ch;  
         } else {  
             $encoded .= '%' . sprintf("%02X", ord($ch));  
         }  
     }  
     return $encoded;  
 }  
   
 sub init_resource {  
     open(FILE, $file_resource) or &print_error("(resource)");  
     while (<FILE>) {  
         chomp;  
         next if /^#/;  
         my ($key, $value) = split(/=/, $_, 2);  
         $resource{$key} = &code_convert(\$value, $kanjicode);  
     }  
     close(FILE);  
 }  
   
 sub conflict {  
     my ($page, $rawmsg) = @_;  
     if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {  
         return 0;  
     }  
     open(FILE, $file_conflict) or &print_error("(conflict)");  
     my $content = join('', <FILE>);  
     &code_convert(\$content, $kanjicode);  
     close(FILE);  
     &print_header($page);  
     &print_content($content);  
     &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);  
     &print_footer($page);  
     return 1;  
827  }  }
828    
829  sub get_now {  sub get_now {
830      my (@week) = qw(Sun Mon Tue Wed Thu Fri Sat);      my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
     my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);  
831      $year += 1900;      $year += 1900;
832      $mon++;      $mon++;
833      $mon = "0$mon" if $mon < 10;      $mon = "0$mon" if $mon < 10;
834      $day = "0$day" if $day < 10;      $day = "0$day" if $day < 10;
835      $hour = "0$hour" if $hour < 10;      $hour = "0$hour" if $hour < 10;
836      $min = "0$min" if $min < 10;      $min = "0$min" if $min < 10;
837      $sec = "0$sec" if $sec < 10;      #$sec = "0$sec" if $sec < 10;
838      $weekday = $week[$weekday];      return "$year-$mon-$day $hour:$min";
     return "$year-$mon-$day ($weekday) $hour:$min:$sec";  
839  }  }
840    
 # [[YukiWiki http://www.hyuki.com/yukiwiki/wiki.cgi?euc($1)]]  
841  sub init_InterWikiName {  sub init_InterWikiName {
842      my $content = $database{$InterWikiName};    my @content = split /\n/, $database{InterWikiName};
843      while ($content =~ /\[\[(\S+) +(\S+)\]\]/g) {    for (@content) {
844          my ($name, $url) = ($1, $2);      if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
845          $interwiki{$name} = $url;        $interwiki{$1} = $2;
     }  
 }  
   
 sub interwiki_convert {  
     my ($type, $localname) = @_;  
     if ($type eq 'sjis' or $type eq 'euc') {  
         &code_convert(\$localname, $type);  
         return &encode($localname);  
     } elsif ($type eq 'ykwk') {  
         # for YukiWiki1  
         if ($localname =~ /^$wiki_name$/) {  
             return $localname;  
         } else {  
             &code_convert(\$localname, 'sjis');  
             return &encode("[[" . $localname . "]]");  
         }  
     } elsif ($type eq 'asis') {  
         return $localname;  
     # Walrus add (4) start  
     } elsif ($type eq 'isbn') {  
         $localname = join('', ($localname =~ /[0-9x]/g)) if ($localname =~ /^(\d-?){9}[\dx]$/);  
         return $localname;  
     # Walrus add (4) end  
     } else {  
         return $localname;  
846      }      }
847  }    }
848      $interwiki{'[[]]'} = 1;       ## dummy
 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;  
849  }  }
850    
851  sub frozen_reject {  sub frozen_reject {
852      my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);      my ($isfrozen) = $database->meta (IsFrozen => $form{mypage});
853      my ($willbefrozen) = $form{myfrozen};      my ($willbefrozen) = $form{myfrozen};
854      if (not $isfrozen and not $willbefrozen) {      if (not $isfrozen and not $willbefrozen) {
855          # You need no check.          # You need no check.
# Line 1158  sub frozen_reject { Line 858  sub frozen_reject {
858          # You are admin.          # You are admin.
859          return 0;          return 0;
860      } else {      } else {
861          &print_error($resource{passworderror});          &print_error(&Resource('Error:PasswordIsIncorrect'));
862          return 1;          return 1;
863      }      }
864  }  }
865    
866  sub valid_password {  sub is_frozen ($) { $database->meta (IsFrozen => $_[0]) ? 1 : 0 }
     my ($givenpassword) = @_;  
     my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_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;  
     }  
 }  
867    
868  sub do_comment {  sub do_comment {
869      my ($content) = $database{$form{mypage}};      my ($content) = $database{$form{mypage}};
870      my $datestr = &get_now;      my $default_name;   ## this code is not strict.
871      my $namestr = $form{myname} ? " ''[[$form{myname}]]'' : " : " ";      $default_name = $1 if $content =~ /default-name="([^"]+)"/;
872      if ($content =~ s/(\Q$embed_comment\E)/- $datestr$namestr$form{mymsg}\n$1/) {      my $datestr = '[WEAK['.&get_now.']]';
873          ;      my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
874      } else {      ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
875          $content =~ s/(\Q$embed_rcomment\E)/$1\n- $datestr$namestr$form{mymsg}/;      if ($namestr =~ /^(?:>>)?[0-9]/) {
876          $namestr = qq( ''$namestr'': );
877        } elsif (length $namestr) {
878          $namestr = qq( ''[[$namestr]]'': );
879        }
880        my $anchor = &get_new_anchor_index ($content);
881        my $i = 1;  my $o = 0;
882        $content =~ s{(\[\[\#r?comment\]\])}{
883          my $embed = $1;
884          if ($i == $form{comment_index}) {
885            if ($embed ne '[[#rcomment]]') {
886              $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;
887            } else {
888              $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;
889            }
890          }
891          $i++; $embed;
892        }ge;
893        unless ($o) {
894          $content = "#?SuikaWiki/0.9\n\n" unless $content;
895          $content .= "\n" unless $content =~ /\n$/s;
896          $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
897      }      }
898      if ($form{mymsg}) {      $form{__comment_anchor_index} = $anchor;
899        if ($form{mymsg} || $form{myname}) {
900          $form{mymsg} = $content;          $form{mymsg} = $content;
901          $form{mytouch} = 'on';          $form{mytouch} = 'on';
902          &do_write;          &do_write;
# Line 1201  sub do_comment { Line 906  sub do_comment {
906      }      }
907  }  }
908    
909    sub get_new_anchor_index ($) {
910        my $content = shift;
911        my $anchor = 0;
912        $content =~ s/^(?:[-=]+\s*)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
913        $anchor + 1;
914    }
915    
916    my $CommentIndex = 0;
917  sub embedded_to_html {  sub embedded_to_html {
918      my ($embedded) = @_;      my ($embedded) = @_;
919      if ($embedded eq $embed_comment or $embedded eq $embed_rcomment) {      if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
920          my $lastmodified = &get_info($form{mypage}, $info_LastModified);        unless ($main::_EMBEDED) {
921            my $lastmodified = $database->mtime ($form{mypage});
922          return <<"EOD";          return <<"EOD";
923  <form action="$url_cgi" method="post">  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
924      <input type="hidden" name="mycmd" value="comment">      <input type="hidden" name="mycmd" value="comment">
925      <input type="hidden" name="mypage" value="$form{mypage}">      <input type="hidden" name="mypage" value="$form{mypage}">
926      <input type="hidden" name="myLastModified" value="$lastmodified">      <input type="hidden" name="myLastModified" value="$lastmodified">
927      <input type="hidden" name="mytouch" value="on">      <input type="hidden" name="mytouch" value="on">
928      $resource{yourname}      <input type="hidden" name="comment_index" value="$CommentIndex">
929      <input type="text" name="myname" value="" size="10">      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
930      <input type="text" name="mymsg" value="" size="40">      <input type="text" name="myname" value="" size="10" class="comment-name">
931      <input type="submit" value="$resource{commentbutton}">      <input type="text" name="mymsg" value="" size="60" class="comment-msg">
932  </form>      <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit">
933    </p></form>
934    EOD
935         } else {
936            return <<"EOD";
937    <del><form action="$url_cgi" method="get">
938        <input type="hidden" name="mycmd" value="read">
939        <input type="hidden" name="mypage" value="$form{mypage}">
940        @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
941        <input type="text" name="myname" value="" size="10" disabled="disabled">
942        <input type="text" name="mymsg" value="" size="60" disabled="disabled">
943    </form></del>
944  EOD  EOD
945      # Walrus add (5) start      }
946      } elsif ($embedded =~ /$embed_interwiki/ and my $remoteurl = $interwiki{$2}) {    } elsif ($embedded =~ /$embed_command{searched}/) {
947          $_ = &make_interwiki_box($1, $2);      return get_search_result ($1, -match_myself => 1);
948          return ($_) ? $_ : $embedded;    } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
949      # Walrus add (5) end      my ($name, $r) = ($1, '');
950      } else {      if ($main::_EMBEDED != 1) {
951          return $embedded;        my ($content, $cf) = ($database{$name}, 'SuikaWiki/0.9');
952          $cf = $1 if $content =~ s!^(?:[\#<]\?|/\*\s*)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
953          if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
954            $main::_EMBEDED = 1;
955            $r = &text_to_html ($content, content_format => $cf);
956            $main::_EMBEDED = 0;
957          } elsif (length $content) {
958            $r = "<pre>@{[&escape ($content)]}</pre>";
959          } else {
960            $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
961          }
962        } else {    ## nested #EMBED
963          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
964        }
965        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>);
966      } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
967        return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);
968      } else {
969        return $embedded;
970      }
971    }
972    
973    sub load_formatter (@) {
974        for my $t (@_) {
975            unless ($fmt{$t}) {
976                require Message::Util::Formatter;
977                $fmt{$t} = Message::Util::Formatter->new;
978                for (@{$SuikaWiki::Plugin::List{'wiki'.$t}||[]}) {
979                    $_->load_formatter ($fmt{$t}, type => 'wiki'.$t);
980                }
981            }
982      }      }
983  }  }
984    
985  # Walrus add (5) start  sub do_wikiform {
986  sub do_interwiki_box {      my $content = $database{$form{mypage}};
987      my $remoteurl = $interwiki{$form{'myintername'}};      my $anchor = &get_new_anchor_index ($content);
988      if ($remoteurl) {      &load_formatter (qw/form_template form_option/);
989          $remoteurl =~ s/\b(euc|sjis|ykwk|asis|isbn)\(\$1\)/&interwiki_convert($1, $form{'mylocalname'})/e;      my $write = 0;
990          print "Location: $remoteurl\n\n";      my $i = 1;
991          exit(1);      $content =~ s{$embed_command{form}}{
992            my ($embed, $wfname, $template, $option) = ($&, $1, $3, $4);
993            if (($wfname && $wfname eq $form{wikiform_targetform})
994                || $i == $form{wikiform_index}) {
995                $template =~ s/\\(.)/$1/g;
996                $option =~ s/\\(.)/$1/g;
997                my $param = bless {}, 'SuikaWiki::Plugin';
998                $param->{page} = $form{mypage};
999                $param->{form_index} = $i;
1000                $param->{form_name} = $wfname;
1001                $param->{anchor_index} = $anchor;
1002                $param->{argv} = \%form;
1003                $param->{default_name} = $1 if $content =~ /default-name="([^"]+)"/;
1004                $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
1005                $fmt{form_option}->replace ($option, $param);
1006                my $t = 1;
1007                for (@{$param->{require}||[]}) {
1008                    (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
1009                }
1010                $t = $fmt{form_template}->replace ($template, $param) if $t;
1011                if (length $t) {
1012                    if ($param->{output}->{reverse}) {
1013                        $embed .= "\n" . $t;
1014                    } else {
1015                        $embed = $t . "\n" . $embed;
1016                    }
1017                    $write = 1;
1018                    $form{__comment_anchor_index} = $anchor
1019                      if $param->{anchor_index_};  ## $anchor is used!
1020                }
1021                $form{__wikiform_anchor_index} = $i;
1022                undef $form{wikiform_targetform};  ## make sure never to match
1023                undef $form{wikiform_index};       ## with WikiForm in rest of page
1024            }
1025            $i++; $embed;
1026        }ge;
1027        unless ($write) {
1028          #$content = "#?SuikaWiki/0.9\n\n" unless $content;
1029          #$content .= "\n" unless $content =~ /\n$/s;
1030          #
1031        }
1032        if ($write) {
1033            $form{mymsg} = $content;
1034            $form{mytouch} = 'on';
1035            &do_write;
1036      } else {      } else {
1037            $form{mycmd} = 'read';
1038          &do_read;          &do_read;
1039      }      }
1040  }  }
 # Walrus add (5) end  
   
 # Walrus add (5) start  
 sub make_interwiki_box {  
     my ($localname, $intername) = @_;  
     my %ignoretype = (  
         'box'      => 'text',  
         'text'     => 'text',  
         'pass'     => 'password',  
         'password' => 'password'  
     );  
     my $converted = ($ignoretype{$localname}) ? <<EOD : undef;  
 <form action="$url_cgi" method="post">  
     <input type="hidden" name="mycmd" value="interwikibox">  
     <input type="hidden" name="mypage" value="$form{mypage}">  
     <input type="hidden" name="myintername" value="$intername">  
     $intername:  
     <input type="$ignoretype{$localname}" name="mylocalname" value="" size="10">  
     <input type="submit" value="Submit">  
 </form>  
 EOD  
 }  
 # Walrus add (5) end  
1041    
1042  sub code_convert {  sub code_convert {
1043      my ($contentref, $kanjicode) = @_;    require Jcode;
1044  #   &Jcode::convert($contentref, $kanjicode);       # for Jcode.pm      my ($contentref, $code) = (shift, shift || $kanjicode);
1045      &jcode::convert($contentref, $kanjicode);       # for jcode.pl      if    ($code =~ /euc/) { $code = 'euc' }
1046        elsif ($code =~ /iso/) { $code = 'jis' }
1047        elsif ($code =~ /shi/) { $code = 'sjis' }
1048        elsif ($code =~ /utf/) { $code = 'utf8' }
1049        $$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;
1050      return $$contentref;      return $$contentref;
1051  }  }
1052    
 sub test_convert {  
     my $txt = &text_to_html(<<"EOD", toc=>1);  
 *HEADER1  
 **HEADER1-1  
 -ITEM1  
 -ITEM2  
 -ITEM3  
 PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 PAR1PAR1PAR1PAR1PAR1PAR1''BOLD''PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
   
 PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2  
 PAR2PAR2PAR2PAR2PAR2PAR2'''ITALIC'''PAR2PAR2PAR2PAR2PAR2PAR2PAR2  
 PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2  
 **HEADER1-2  
 :TERM1:DESCRIPTION1 AND ''BOLD''  
 PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 PAR1PAR1PAR1PAR1PAR1PAR1''BOLD''PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 :TERM2:DESCRIPTION2  
 :TERM3:DESCRIPTION3  
 ----  
 *HEADER2  
 **HEADER2-1  
 http://www.hyuki.com/  
 **HEADER2-2  
   
 [[YukiWiki2]]  
   
 PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 PAR1PAR1PAR1PAR1PAR1PAR1'''''BOLD ITALIC'''''PAR1PAR1PAR1PAR1PAR1  
 PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
 >PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2  
 >PAR2PAR2PAR2PAR2PAR2PAR2'''ITALIC'''PAR2PAR2PAR2PAR2PAR2PAR2PAR2  
 >PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2  
   
 LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0  
   
 >LEVEL1  
 >LEVEL1  
 >LEVEL1  
 >>LEVEL2  
 >>LEVEL2  
 >>LEVEL2  
 >>>LEVEL3  
 -HELLO-1  
 --HELLO-2  
 (HELLO-2, HELLO-2, HELLO-2)  
 ---HELLO-3  
 (HELLO-3, HELLO-3, HELLO-3)  
 --HELLO-2  
 ---HELLO-3  
 --HELLO-2  
 ---HELLO-3  
 >>>LEVEL3  
 >>>LEVEL3  
 >>>LEVEL3  
 >>>LEVEL3  
 EOD  
     print $txt;  
     exit;  
 }  
   
 sub do_diff {  
     if (not &is_editable($form{mypage})) {  
         &do_read;  
         return;  
     }  
     &open_diff;  
     my $title = $form{mypage};  
     &print_header($title);  
     $_ = &escape($diffbase{$form{mypage}});  
     &close_diff;  
     print qq(<h3>$resource{difftitle}</h3>);  
     print qq($resource{diffnotice});  
     print qq(<pre class="diff">);  
     foreach (split(/\n/, $_)) {  
         if (/^\+(.*)/) {  
             print qq(<b class="added">$1</b>\n);  
         } elsif (/^\-(.*)/) {  
             print qq(<s class="deleted">$1</s>\n);  
         } elsif (/^\=(.*)/) {  
             print qq(<span class="same">$1</span>\n);  
         } else {  
             print qq|??? $_\n|;  
         }  
     }  
     print qq(</pre>);  
     print qq(<hr>);  
     &print_footer($title);  
 }  
   
1053  sub do_rss {  sub do_rss {
1054        eval q{use Yuki::RSS};
1055      my $rss = new Yuki::RSS(      my $rss = new Yuki::RSS(
1056          version => '1.0',          version => '1.0',
1057          encoding => $charset,          encoding => &get_charset_name ($kanjicode),
1058        );
1059        my $scheme = 'http';
1060        $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
1061        my $myuri = "$scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi";
1062        $rss->stylesheet (
1063          href      => $myuri . "?mycmd=TEXT_CSS;mypage=WikiStyle:RSS",
1064          type      => 'text/css',
1065      );      );
1066      $rss->channel(      $rss->channel(
1067          title => $modifier_rss_title,          title   => &Resource ('RSS:WikiTitle'),
1068          link  => $modifier_rss_link,          link    => $myuri,
1069          description => $modifier_rss_description,          description     => &Resource ('RSS:WikiDescription'),
1070            'dc:language'   => $lang,
1071      );      );
1072      my $recentchanges = $database{$RecentChanges};      my $recentchanges = $database{RecentChanges};
1073      my $count = 0;      my $count = 0;
1074      foreach (split(/\n/, $recentchanges)) {      foreach (split(/\n/, $recentchanges)) {
1075          last if ($count >= 15);          last if ($count >= 15);
1076          /^\- \d\d\d\d\-\d\d\-\d\d \(...\) \d\d:\d\d:\d\d (\S+)/;    # date format.          if (/\[\[([^]]+)\]\]/) {
1077          my $title = &unarmor_name($1);            my $title = $1;
1078          my $escaped_title = &escape($title);            $rss->add_item (
1079          my $link = $modifier_rss_link . '?' . &encode($title);              title       => &escape($title),
1080          my $description = $escaped_title . &escape(&get_subjectline($title));              link        => $myuri . '?' . &encode($title),
1081          $rss->add_item(              description => &escape(&get_subjectline($title,delimiter=>'')),
1082              title => $escaped_title,              'dc:date'   => $database->mtime ($title),
1083              link  => $link,            );
1084              description => $description,            $count++;
1085          );          }
         $count++;  
1086      }      }
1087      # print RSS information (as XML).      # print RSS information (as XML).
1088      print <<"EOD"      print <<"EOD"
1089  Content-type: text/xml  Content-type: application/xml; charset=@{[&get_charset_name ($kanjicode)]}
1090    
1091  @{[$rss->as_string]}  @{[$rss->as_string]}
1092  EOD  EOD
1093  }  }
1094    
1095  sub is_exist_page {  sub _rfc3339_date ($) {
1096      my ($name) = @_;    my @time = gmtime (shift);
1097      if ($use_exists) {    sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
1098          return exists($database{$name});  }
1099      } else {  
1100          return $database{$name};  sub is_exist_page { $use_exists ? exists ($database{$_[0]}) : $database{$_[0]} }
1101    sub __get_database ($) { $database{ $_[0] } }
1102    
1103    my %_Resource;
1104    sub Resource ($;%) {
1105      my ($s, %o) = @_;
1106      unless (defined $_Resource{$s}) {
1107        $_Resource{$_[0]} = &wiki::resource::get ($s, $_Resource{__option});
1108      }
1109      $o{escape} ? &escape ($_Resource{$s}) : $_Resource{$s};
1110    }
1111    
1112    package wiki::referer;
1113    sub add ($$) {
1114      my $page = shift;
1115      my $uri = shift;
1116      unless (ref $uri) {
1117        require URI;
1118        $uri = URI->new ($uri);
1119        ## Some schemes do not have query part.
1120        eval q{ $uri->query (undef) if $uri->query =~ /^[0-9]{6,8}$/ };
1121        $uri->fragment (undef);
1122      }
1123      $uri = $uri->canonical;
1124      return unless $uri;
1125      for my $regex (&get_dont_record) {
1126        return if $uri =~ /$regex/;
1127      }
1128      my %list = get ($page);
1129      $list{ $uri }++;
1130      set ($page, \%list);
1131    }
1132    sub get ($) { split /"/, $main::database->meta (Referer => $_[0]) }
1133    sub set ($%) {
1134      my $page = shift;
1135      my $list = shift;
1136      $main::database->meta (Referer => $page => join '"', %$list);
1137    }
1138    
1139    sub get_dont_record () {
1140      map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1141      grep !/^#/,
1142      split /[\x0D\x0A]+/, $main::database{RefererDontRecord};
1143    }
1144    sub get_site_name () {
1145      my @lines = grep /[^#]/, split /[\x0D\x0A]+/, $main::database{RefererSiteName};
1146      my @item;
1147      for (@lines) {
1148        next if /^#/;
1149        my ($uri, $name) = split /\s+/, $_, 2;
1150        $uri =~ s/\$/\\\$/g;  $uri =~ s/\@/\\\@/g;  $uri =~ s/\//\\\//g;
1151        $name =~ s!([()/\\])!\\$1!g;  $name =~ s/\$([0-9]+)/).__decode (\${$1}).q(/g;
1152        push @item, [$uri, qq(q($name))];
1153      }
1154      @item;
1155    }
1156    
1157    sub list_html ($) {
1158      my $page = shift;
1159      my %list = get ($page);
1160      my $r = '';
1161      my @name = get_site_name;
1162      for my $uri (sort keys %list) {
1163        my $title;
1164        for my $item (@name) {
1165          if ($uri =~ /$item->[0]/) {
1166            $title = $uri;
1167            eval qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e}
1168              or die $@ ;#. qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e};
1169            last;
1170          }
1171      }      }
1172        my $euri = main::escape ($uri);
1173        if ($title) {
1174          $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri&gt;">@{[main::escape ($title)]}</a></li>\n);
1175        } else {
1176          $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1177        }
1178      }
1179      $r ? qq(<ul>$r</ul>\n) : '';
1180    }
1181    
1182    sub __decode ($) {
1183      my $s = shift;
1184      $s =~ tr/+/ /;
1185      $s =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/chr hex $1/ge;
1186      main::code_convert (\$s);
1187    }
1188    
1189    package wiki::useragent;
1190    our $UseLog;
1191    
1192    sub add ($) {
1193      my $s = shift;
1194      return unless length $s;
1195      return unless $UseLog;
1196      $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1197      my %ua;
1198      for (split /\n/, &main::__get_database($main::PageName{UserAgentList})) {
1199        if (/^-\[(\d+)\] (.+)$/) {
1200          my ($t, $n) = ($1, $2);
1201          $n =~ tr/\x0A\x0D//d;
1202          $ua{$n} = $t;
1203        }
1204      }
1205      $ua{$s}++;
1206      my $s = qq(#?SuikaWiki/0.9\n);
1207      for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1208        $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1209      }
1210      $main::database->STORE ($main::PageName{UserAgentList} => $s, -touch => 0);
1211    }
1212    
1213    package wiki::suikawikiconst;
1214    
1215    sub to_hash ($;$) {
1216      my $page = shift;
1217      my $h = shift || {};
1218      my $val;
1219      for my $line (split /\n/, $page) {
1220        $line =~ tr/\x0A\x0D//d;
1221        if ($val && $line =~ s/^\s+//) {
1222          $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
1223        } elsif ($line =~ /^(.+):/) {
1224          $val = $1; $h->{$val} = '';
1225        }
1226      }
1227      $h;
1228    }
1229    
1230    package wiki::dummy;
1231    sub mtime (@) {undef}
1232    sub meta (@) {undef}
1233    sub Yuki::YukiWikiDB2::meta (@) {undef}
1234    
1235    package SuikaWiki::Plugin;
1236      our $plugin_directory;
1237      our %List;
1238      our %Index;
1239    
1240    sub escape ($$) { main::escape ($_[1]) }
1241    sub unescape ($$) { main::unescape ($_[1]) }
1242    sub encode ($$) { main::encode ($_[1]) }
1243    sub decode ($$) { main::decode ($_[1]) }
1244    sub __get_datetime ($) { main::get_now () }
1245    sub resource ($$;%) { shift; &main::Resource (@_) }
1246    sub uri ($$) { $main::uri{$_[1]} }
1247    sub new_index ($$) { ++$Index{$_[1]} }
1248    sub magic_and_content ($$) {
1249      my $page = $_[1];
1250      $page =~ s!^((?:\#\?|/\*|<\?)[^\x02\x0A\x0D]+)[\x02\x0A\x0D]+!!s;
1251      ($1, $page);
1252    }
1253    sub formatter ($$) {
1254      &main::load_formatter ($_[1]);
1255      $main::fmt{$_[1]};
1256    }
1257    
1258    sub regist ($@) {
1259        my $pack = shift;
1260        for (@_) {
1261            push @{$List{$_}}, $pack;
1262        }
1263    }
1264    
1265    sub import_plugins () {
1266        opendir PDIR, $plugin_directory;
1267        my @plugin = grep {s/\.pm$//} readdir (PDIR);
1268        closedir PDIR;
1269        for (@plugin) {
1270            eval qq{ use SuikaWiki::Plugin::$_ } unless /[^A-Za-z0-9_]/;
1271            push @{$List{_all}}, qq(SuikaWiki::Plugin::$_);
1272        }
1273    }
1274    
1275    &import_plugins ();
1276    
1277    package wiki::conneg;
1278    
1279    ## BUG: this parser isn't strict.
1280    sub get_accept_lang (;$) {
1281      my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1282      my %alang = (ja => 0.0002, en => 0.0001);
1283      my $i = 0.1;
1284      for (split /\s*,\s*/, $alang) {
1285        tr/\x09\x0A\x0D\x20//d;
1286        if (/((?:(?!;q=).)+)(?:;q="?([0-9.]+)"?)?/) {
1287          my $l = lc $1; $l =~ tr/\x22\x5C//d;
1288          $alang{$l} = (defined $2 ? $2 : 1.000)*1000;
1289          $alang{$l} += $i unless $alang{$l} == 0;
1290          $i -= 0.001;
1291        }
1292      }
1293      \%alang;
1294    }
1295    
1296    package wiki::resource;
1297    
1298    sub get ($;\%) {
1299      my ($resname, $option) = @_;
1300      $option->{accept_language} ||= &wiki::conneg::get_accept_lang ();
1301      $option->{resource} ||= {};
1302      my $v;
1303      for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1304        while (length $lang) {
1305          unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1306            $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash ($main::database{'WikiResource:'.$lang});
1307            $v = $option->{resource}->{$lang}->{$resname};
1308            last if defined $v;
1309          }
1310          $lang =~ s/[^+-]*$//; $lang =~ s/[+-]$//;
1311        }
1312        last if defined $v;
1313      }
1314      defined $v ? $v : $resname;
1315  }  }
1316    
1317    package main;
1318    &main;
1319    exit 0;
1320    
1321  1;  1;
1322  __END__  __END__
1323  =head1 NAME  =head1 NAME
1324    
1325  wiki.cgi - This is YukiWiki, yet another Wiki clone.  wiki.cgi --- SuikaWiki: Yet yet another Wiki engine
1326    
1327  =head1 DESCRIPTION  =head1 SEE ALSO
1328    
1329  YukiWiki is yet another Wiki clone.  <IW:SuikaWiki:SuikaWiki>
1330    
1331  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).  
1332    
1333  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/>
1334    
1335  =head1 AUTHOR  Makio Tsukamoto <http://digit.que.ne.jp/>
1336    
1337  Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/  Wakaba <w@suika.fam.cx>
1338    
1339  =head1 LICENSE  =head1 LICENSE
1340    
1341  Copyright (C) 2000-2002 by Hiroshi Yuki.  Copyright (C) 2000-2003 AUTHORS
1342    
1343  This program is free software; you can redistribute it and/or  This program is free software; you can redistribute it and/or
1344  modify it under the same terms as Perl itself.  modify it under the same terms as Perl itself.

Legend:
Removed from v.1.21  
changed lines
  Added in v.1.49

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24