/[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.28 by wakaba, Thu Oct 17 07:56:58 2002 UTC revision 1.50 by w, Sun Jan 12 09:15:06 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);  binmode STDOUT; binmode STDIN;
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 = "SuikaWiki $walversion";  
 my $modifier_rss_link = 'http://suika.fam.cx/~wakaba/-temp/wiki2/wiki'; # Blank is not allowed.  
 my $modifier_rss_description = 'This is SuikaWiki';  
 ##############################  
 #  
 # You MAY modify following variables.  
 #  
 my $file_touch = "$modifier_dir_data/touched.txt";  
 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 = '/~wakaba/-temp/wiki/wiki';       ## MUST be started from '/'  
 my $url_stylesheet = $url_cgi.'?mycmd=TEXT_CSS;mypage=WikiHTMLStyle';  
 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 $NAME_OF_WikiPageLicense = 'WikiPageLicense';  
 my $AdminSpecialPage = 'Admin Special Page'; # must include spaces.  
14  ##############################  ##############################
15  # my $wiki_name = '\b([A-Z][a-z]+([A-Z][a-z]+)+)\b';        # Walrus del (2)  our %fmt;       ## formatter objects
16  my $wiki_name   = '\b([A-Z][a-z]+([A-Z][a-z]*)+)\b';        # Walrus add (2)  our %embed_command = (
 my $bracket_name = '\[\[(\S+?)\]\]';  
 my $embedded_name = '\[\[(#\S+?)\]\]';  
 my $interwiki_definition = '\[\[(\S+?)\ (\S+?)\]\]';  
 my $interwiki_name = 'i:([^:]+):([^:].*)';  
 ##############################  
 my $embed_comment = '[[#comment]]';  
 my $embed_rcomment = '[[#rcomment]]';  
 my $embed_comment_Name_Prompt = '名前:';  
 my $DEFAULT_embed_comment_name = '名無しさん';  
 my $embed_interwiki = '^\[\[#(box|text|password):(\S+)\]\]$';    # Walrus add (5)  
 my %embed_command = (  
17          searched        => '^\[\[#searched:([^\]]+)\]\]$',          searched        => '^\[\[#searched:([^\]]+)\]\]$',
18            form    => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
19  );  );
20    our ($modifier_dbtype,$url_cgi,%uri,%PathTo,$use_exists);
21    our (%PageName,$kanjicode,$lang,%ViewDefinition);
22    
23  ##############################  ##############################
 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,  
 );  
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  ##############################  ##############################
 my %page_command = (  
     $IndexPage => 'index',  
     $SearchPage => 'searchform',  
     $CreatePage => 'create',  
     $RssPage => 'rss',  
     $AdminChangePassword => 'adminchangepasswordform',  
     #$FrontPage => 'FrontPage',  
 );  
29  my %command_do = (  my %command_do = (
30      read => \&do_read,      read => \&do_view,
     TEXT_CSS => \&do_output_css,  
     edit => \&do_edit,  
     adminedit => \&do_adminedit,  
     adminchangepasswordform => \&do_adminchangepasswordform,  
31      adminchangepassword => \&do_adminchangepassword,      adminchangepassword => \&do_adminchangepassword,
32      write => \&do_write,      write => \&do_write,
     index => \&do_index,  
33      searchform => \&do_searchform,      searchform => \&do_searchform,
     search => \&do_search,  
     create => \&do_create,  
     createresult => \&do_createresult,  
     FrontPage => \&do_FrontPage,  
34      comment => \&do_comment,      comment => \&do_comment,
35      RandomJump  => \&do_random_jump,      RandomJump  => \&do_random_jump,
36      rss => \&do_rss,      wikiform    => \&do_wikiform,
     diff => \&do_diff,  
     interwikibox => \&do_interwiki_box, # Walrus add (5)  
37  );  );
38  ##############################  my $UA = '';  ## User agent name
39  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);  
40  ##############################  ##############################
41    
42  sub main {  sub main {
43      &init_resource;      $UA = $main::ENV{HTTP_USER_AGENT};
44      &open_db;      &open_db;
45      &init_form;      &init_form;
     &init_InterWikiName;  
46      if ($command_do{$form{mycmd}}) {      if ($command_do{$form{mycmd}}) {
47          &{$command_do{$form{mycmd}}};          &{$command_do{$form{mycmd}}};
48      } else {      } else {
49          &do_FrontPage;          &{$command_do{read}};
50      }      }
51      &close_db;      &close_db;
52  }  }
53    
54  sub do_read {  sub do_view {
55    my $content = $database{$form{mypage}};    my $content = $database{$form{mypage}};
56    my $lm = &get_info($form{mypage}, $info_LastModified);    my $lm = $database->mtime ($form{mypage});
   &print_header($form{mypage}, -last_modified => $lm);  
57    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
58      my $cf = 'SuikaWiki/0.9';    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
59      ## Should be support at least:    &load_formatter ('view');
60      ## - 'SuikaWiki/0.9' CRLF      my $view = $form{mycmd};
61      ## - 'H2H/' ("0.9" / "1.0" / "1.1") CRLF      if ($view eq 'edit') {
62      ## - "/*" WSP* 'W3C-CSS/' ("1.0" / "2.0") "*/" CRLF        $view = 'adminedit' if $form{admin};
63      $cf = $1 if $content =~ s#^(?:/\*\s*|[\#<]\?)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+##s;      } elsif ($view =~ /[^0-9A-Za-z]/) {
64      if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {        $view = 'view'
65        &print_content($content, content_format => $cf, last_modified => $lm);      }
66        print &text_to_html (q([[#comment]]));    my ($magic, $content) = &SuikaWiki::Plugin::magic_and_content (undef, $content);
67      $magic ||= '#?SuikaWiki/0.9';
68      my $o = bless {param => \%form, page => $form{mypage}, toc => [],
69                     magic => $magic, content => $content,
70                     formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin';
71      if (!ref $ViewDefinition{$view} || !&{$ViewDefinition{$view}->{check}} ($o)) {
72        print "Status: 406 Unsupported Media Type\n";
73        $view = '-UnsupportedMediaType';
74      }
75      my $media = $ViewDefinition{$view}->{media};
76      if ($ViewDefinition{$view}->{xmedia} && $UA =~ /Gecko/) {
77        $media = $ViewDefinition{$view}->{xmedia};
78        $o->{media} = $media;
79      }
80        if ($magic =~ m!^\#\?SuikaWiki/0.9!) {
81          &print_header ($form{mypage}, -last_modified => ($magic =~ /interactive="yes"/ ? $lm : time),
82            -expires => ($magic =~ /interactive="yes"/ ? 1 : undef), o => $o,
83            -media => $media, -magic => $magic,  content => $content);
84      } else {      } else {
85        print "<pre>@{[&escape($content)]}</pre>";        &print_header($form{mypage}, -media => $media,
86      }                                     -magic => $magic, -last_modified => $lm, o => $o);
   my ($r, $c) = get_search_result ($form{mypage});  
     if ($c) {  
       print q{<h2 id="SEE-ALSO">See also</h2>};  
       print $r;  
     }  
   my $r = wiki::referer::list_html ($form{mypage});  
     if ($r) {  
       print qq(<div id="wikipage-referer"><h2>参照元</h2>\n$r</div>\n);  
87      }      }
88    &print_footer($form{mypage}, $lm);      print $fmt{view}->replace ($ViewDefinition{$view}->{template} => $o);
89  }  }
90    
91  sub do_output_css {  sub _do_view_msg (%) {
92    my $content = $database{$form{mypage}};    my %option = @_;
93    if ($content =~ m#^\s*/\*\s*W3C-CSS#) {    &load_formatter ('view');
94      print "Content-Type: text/css; charset=$charset\n";    my $o = bless {param => \%form, page => $option{-page}, toc => [], condition => \%option,
95      print "\n";                   formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin';
96      print $content;    unless (&{$ViewDefinition{$option{-view}}->{check}} ($o)) {
   } else {  
97      print "Status: 406 Unsupported Media Type\n";      print "Status: 406 Unsupported Media Type\n";
98      &print_header('WikiPageIsNotCSS');      $option{-view} = '-UnsupportedMediaType';
     &print_content($database{WikiPageIsNotCSS});  
     &print_footer('WikiPageIsNotCSS');  
99    }    }
100      my $media = $ViewDefinition{$option{-view}}->{media};
101      if ($ViewDefinition{$option{-view}}->{xmedia} && $UA =~ /Gecko/) {
102        $media = $ViewDefinition{$option{-view}}->{xmedia};
103        $o->{media} = $media;
104      }
105      &print_header($option{-page}, -media => $media, o => $o, -goto => $option{-goto});
106      print $fmt{view}->replace ($ViewDefinition{$option{-view}}->{template} => $o);
107  }  }
108    
109  sub do_edit {  sub id_and_name ($) {
110      my ($page) = &unarmor_name(&armor_name($form{mypage}));      my $name = shift;
111      &print_header($page);      if ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer#) {
112      if (not &is_editable($page)) {        qq{id="$name"><a name="$name"></a};
         &print_message($resource{cantchange});  
     } elsif (&is_frozen($page)) {  
         &print_message($resource{cantchange});  
     } else {  
         &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);  
     }  
     &print_footer($page);  
 }  
   
 sub do_adminedit {  
     my ($page) = &unarmor_name(&armor_name($form{mypage}));  
     &print_header($page);  
     if (not &is_editable($page)) {  
         &print_message($resource{cantchange});  
113      } else {      } else {
114          &print_message($resource{passwordneeded});          qq{id="$name"};
         &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);  
115      }      }
     &print_footer($page);  
 }  
   
 sub do_adminchangepasswordform {  
     &print_header($AdminChangePassword);  
     &print_passwordform;  
     &print_footer($AdminChangePassword);  
116  }  }
117    
118  sub do_adminchangepassword {  sub do_adminchangepassword {
119      if ($form{mynewpassword} ne $form{mynewpassword2}) {      if ($form{mynewpassword} ne $form{mynewpassword2}) {
120          &print_error($resource{passwordmismatcherror});          &_do_view_msg (-view => '-error', -page => $form{mypage},
121                           error_message => &Resource ('Error:PasswordMismatch'));
122            return;
123      }      }
124      my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_AdminPassword);      my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
125      if ($validpassword_crypt) {      if ($validpassword_crypt) {
126          if (not &valid_password($form{myoldpassword})) {          if (not &valid_password($form{myoldpassword})) {
127              &send_mail_to_admin(<<"EOD", "AdminChangePassword");              &_do_view_msg (-view => '-error', -page => $form{mypage},
128  myoldpassword=$form{myoldpassword}                             error_message => &Resource ('Error:PasswordIsIncorrect'));
129  mynewpassword=$form{mynewpassword}              return;
 mynewpassword2=$form{mynewpassword2}  
 EOD  
             &print_error($resource{passworderror});  
130          }          }
131      }      }
132      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
# Line 299  EOD Line 134  EOD
134      my $salt1 = $token[(time | $$) % scalar(@token)];      my $salt1 = $token[(time | $$) % scalar(@token)];
135      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
136      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
137      &set_info($AdminSpecialPage, $info_AdminPassword, $crypted);      $database->meta (AdminPassword => $PageName{AdminSpecialPage} => $crypted);
138        
139      &print_header($CompletedSuccessfully);      &_do_view_msg (-view => '-wrote', -page => $form{mypage});
     &print_message($resource{passwordchanged});  
     &print_footer($CompletedSuccessfully);  
140  }  }
141    
142  sub do_index {  sub valid_password ($) {
143      &print_header($IndexPage);      my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
144      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)]}">@{[&escape($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);  
145  }  }
146    
147  sub do_write {  sub do_write {
# Line 326  sub do_write { Line 150  sub do_write {
150      }      }
151    
152      if (not &is_editable($form{mypage})) {      if (not &is_editable($form{mypage})) {
153          &print_header($form{mypage});          &_do_view_msg (-view => '-error', -page => $form{mypage},
154          &print_message($resource{cantchange});                         error_message => &Resource ('Error:ThisPageIsUneditable'));
         &print_footer($form{mypage});  
155          return;          return;
156      }      }
157    
158      if (&conflict($form{mypage}, $form{mymsg})) {      ## Check confliction
159          return;      if ($form{myLastModified} ne $database->mtime ($form{mypage})) {
160      }        &_do_view_msg (-view => '-conflict', -page => $form{mypage});
161          return;
     # Making diff  
     {  
         &open_diff;  
         my @msg1 = split(/\n/, $database{$form{mypage}});  
         my @msg2 = split(/\n/, $form{mymsg});  
         $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);  
         &close_diff;  
162      }      }
163    
164      if ($form{mymsg}) {      if ($form{mymsg}) {
165          $database{$form{mypage}} = $form{mymsg};          if ($form{mytouch} || !ref $database) {
166          &send_mail_to_admin($form{mypage}, "Modify");            $database{$form{mypage}} = $form{mymsg};
167          if ($form{mytouch}) {          } else {
168              &set_info($form{mypage}, $info_LastModified, '' . localtime);            $database->STORE ($form{mypage} => $form{mymsg}, -touch => 0);
             &update_recent_changes;  
169          }          }
170          &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});          $database->meta (IsFrozen => $form{mypage} => 0 + $form{myfrozen});
171          &print_header($CompletedSuccessfully, -goto => $url_cgi.'?'.&encode($form{mypage}).($form{comment_index}?"#x-comment-$form{comment_index}":''));          my $fragment = '';
172          &print_message($resource{saved});          $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
173          &print_content("$resource{continuereading} @{[&armor_name($form{mypage})]}");          if ($form{__comment_anchor_index}) {
174          &print_footer($CompletedSuccessfully);              $fragment .= qq(#anchor-$form{__comment_anchor_index});
175            } elsif ($form{__wikiform_anchor_index}) {
176                $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
177            }
178            &_do_view_msg (-view => '-wrote', -page => $form{mypage}, -goto => $url_cgi.'?mycmd='.&encode($form{after_edit_cmd}||'read').';mypage='.&encode($form{mypage}).qq(;x-param=@{[time.[0..9]->[rand 10]]}$fragment));
179      } else {      } else {
         &send_mail_to_admin($form{mypage}, "Delete");  
180          delete $database{$form{mypage}};          delete $database{$form{mypage}};
181          delete $infobase{$form{mypage}};          &_do_view_msg (-view => '-deleted', -page => $form{mypage});
         if ($form{mytouch}) {  
             &update_recent_changes;  
         }  
         &print_header($form{mypage});  
         &print_message($resource{deleted});  
         &print_footer($form{mypage});  
182      }      }
183  }  }
184    
185  sub do_searchform {  sub _compatible_options () {
186      &print_header($SearchPage);    (use_anchor_name => ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer# ? 1 : 0));
     &print_searchform("");  
     &print_footer($SearchPage);  
 }  
   
 sub do_search {  
     my $word = $form{mymsg};  
     &print_header($SearchPage);  
     &print_searchform(&escape($word));  
     print scalar get_search_result ($word, -output_not_found => 1);  
     &print_footer($SearchPage);  
187  }  }
188    
189  sub get_search_result ($;%) {  sub get_search_result ($;%) {
190    my $word = shift;    my $word = lc shift;
191    my %option = @_;    my %option = @_;
192    my $counter = 0;    my @r;
193    my $r = '';    foreach my $page (keys %database) {
194    foreach my $page (sort keys %database) {      next if !$option{-match_myself} && ($page eq $word);
195      next if $page eq $RecentChanges;      my $content = lc $database{$page};
196      my $content = $database{$page};      if (index (lc $page, $word) > -1) {
197      $content =~ s/^\#\?[^\x0A\x0D]+//s;        my $c = $content =~ s/\Q$word\E//g;
198      if (   index ($content, $word) > 0        push @r, [$page, $c+20];
199          || index ($page, $word) > 0      } elsif (index ($word, lc $page) > -1) {
200          || index ($word, $page) > 0        my $c = $content =~ s/\Q$word\E//g;
201         ) {        push @r, [$page, $c+10];
202        $r .= qq(<li><a href ="$url_cgi?@{[&encode($page)]}" class="wiki">@{[&escape($page)]}</a> <span class="wikipage-summary">@{[&escape(&get_subjectline($page))]}</span></li>);      } elsif (my $c = $content =~ s/\Q$word\E//g) {
203        $counter++;        push @r, [$page, $c];
204      }      }
205    }    }
206    $r = qq|<ul>$r</ul>| if $r;    #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
207    get_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;
208      if $counter == 0 && $option{-output_not_found};    $r = qq|<ul class="search-result">$r</ul>| if $r;
209    wantarray? ($r, $counter): $r;    wantarray? ($r, scalar @r): $r;
 }  
   
 sub do_create {  
     &print_header($CreatePage);  
     print <<"EOD";  
 <form action="$url_cgi" method="post">  
     <input type="hidden" name="mycmd" value="edit">  
     <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);  
210  }  }
211    
212  sub do_random_jump {  sub do_random_jump {
213    my @list = keys %database;    my @list = keys %database;
214    my $name = &encode ($list[rand @list]);    my $name = &encode ($list[rand @list]);
215    print "Location: $url_cgi?$name\n";    print "Location: $uri{wiki}?$name\n";
216    print "\n";    print "\n";
217  }  }
218    
 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);  
 }  
   
 sub print_error {  
     my ($msg) = @_;  
     &print_header($ErrorPage);  
     print qq(<p><strong class="error">$msg</strong></p>);  
     &print_footer($ErrorPage);  
     exit(0);  
 }  
   
219  sub print_header ($;%) {  sub print_header ($;%) {
220      my ($page, %option) = @_;      my ($page, %option) = @_;
221      my $bodyclass = "normal";      my @head;
222      if (&is_frozen($page) and $form{mycmd} =~ /^(read|write)$/) {      $option{o}->{-header}->{class} = &is_frozen($page) ? 'frozen' : '';
223          $bodyclass = "frozen";      $option{o}->{-header}->{class} .= " wiki-page-obsoleted" if $option{-magic} =~ /obsoleted="yes"/;
224      }      if ($option{-goto}) {
225      print qq{Refresh: 0; url="$option{-goto}"\n} if $option{-goto};        if ($UA =~ m#Opera|MSIE 2\.#) {
226      print qq{Last-Modified: $option{-last_modified}\n} if $option{-last_modified};            ## WARNING: This code may output unsafe HTML document if
227      my $cookedpage = &encode($page);            ##          $option{-goto} is not clean.
228      my $escapedpage = &escape($page);            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
229      print <<"EOD";            print qq{Refresh: 0; url=$option{-goto}\n};
230  Content-type: text/html; charset=$charset            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
231          } elsif ($UA =~ /Gecko/) {
232              print qq{Refresh: 0; url="$option{-goto}"\n};
233              push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;" />);
234          } else {
235              $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
236              print qq{Refresh: 0; url="$option{-goto}"\n};
237              push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;">);
238          }
239        }
240        print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
241        if ($option{-expires} != -1) {
242          if (defined $option{-expires}) {  ## TODO: Don't use asctime
243            print qq{Expires: @{[scalar gmtime (time + $option{-expires})]}\n};
244          } elsif ($option{-media}->{expires} != -1) {
245            print qq{Expires: @{[scalar gmtime (time + $option{-media}->{expires})]}\n};
246          }
247        }
248        if ($option{-media}->{charset} && $UA =~ m#Mozilla/2#) {
249            my $ct = qq{$option{-media}->{type}; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
250            print qq{Content-Type: $ct\n};
251            $option{o}->{-header}->{meta_ct} = qq{<meta http-equiv="content-type" content="$ct">\n};
252        } elsif (!$option{-media}->{charset} || $UA =~ m#Infomosaic#) {
253            print qq{Content-Type: $option{-media}->{type}\n};
254        } else {
255            my $type = $option{-media}->{type};
256            $type = 'application/xml' if $type eq 'application/rss+xml';
257            print qq{Content-Type: $type; charset=@{[&get_charset_name($kanjicode)]}\n};
258        }
259        print <<"EOD";      ## TODO:
260  Content-Language: $lang  Content-Language: $lang
261  Content-Style-Type: text/css  Content-Style-Type: text/css
262    
 <!--  
 <!DOCTYPE html  
     PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
     "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->  
 <html lang="$lang">  
 <head>  
     <title>$escapedpage @{[&escape(&get_subjectline($page))]}</title>  
     <link rel="index" href="$url_cgi?$IndexPage">  
     <link rel="copyright" href="$url_cgi?$NAME_OF_WikiPageLicense">  
     <link rev="made" href="mailto:@{[&escape($modifier_mail)]}">  
     <link rel="stylesheet" type="text/css" href="@{[&escape($url_stylesheet)]}">  
 </head>  
 <body class="$bodyclass">  
 EOD  
   &print_navigate_links ($page);  
   print <<EOD;  
 <h1 class="header">@{[&escape($page)]}  
   <span class="wikipage-summary">@{[&escape(&get_subjectline($page))]}</span></h1>  
263  EOD  EOD
264      $option{o}->{-header}->{links} = join "\n", (@head);
265  }  }
266    
267  sub print_navigate_links (@) {  sub get_charset_name ($;%) {
268    my ($page) = @_;      my ($charset, %option) = (lc shift, @_);
269      my $editable = 0;      if ($charset =~ 'euc') {
270      my $admineditable = 0;          $charset = $option{compatible} ? 'x-euc-jp' : 'euc-jp';
271      if (&is_frozen($page) and $form{mycmd} =~ /^(read|write)$/) {      } elsif ($charset =~ 'sjis' || $charset =~ 'shift') {
272          $editable = 0;          $charset = $option{compatible} ? 'x-sjis' : 'shift_jis';
273          $admineditable = 1;      } elsif ($charset =~ 'jis') {
274      } elsif (&is_editable($page) and $form{mycmd} =~ /^(read|write)$/) {          $charset = 'iso-2022-jp';
         $admineditable = 1;  
         $editable = 1;  
     } else {  
         $editable = 0;  
275      }      }
276      my $cookedpage = &encode($page);      $charset;
   print <<EOH;  
 <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" accesskey="E">$resource{editbutton} <kbd>E</kbd></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>  
 EOH  
 }  
   
 sub print_footer {  
     my ($page, $lm) = @_;  
     $walrus_log = ($walrus_debugging) ? &text_to_html("----\n$walrus_log") : '';    # Walrus add (debug)  
     # Walrus mod (1) start  
   my $cvslog = '$Revision$ $Date$';  
   print_navigate_links ($page);  
   print <<"EOD";  
 @{[ $lm ? qq(<div id="wikipage-last-modified">Last modified: $lm</div>) : '' ]}  
 <div class="footer">  
 <p>  
 <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 />  
 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 />  
 <a href="/gate/cvs/wakaba/wiki/" title="CVS Repository">  
 $cvslog  
 </a>  
 </p>  
 <div class="navigation">  
 [<a href="/" title="このサーバーの首頁">/</a>  
 <a href="/map" title="このサーバーの案内">地図</a>  
 <a href="/search/" title="このサーバーの検索">検索</a>]  
 </div>  
 </div>  
 $walrus_log  
 </body>  
 </html>  
 EOD  
 #       print <<"EOD";  
 #   <hr>  
 #   <address class="footer">  
 #       <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version  
 #       &copy; 2000-2002 by <a href="http://www.hyuki.com/">Hiroshi Yuki</a>.<br />  
 #       Modified by <a href="$modifier_url">$modifier_name</a>.  
 #   </address>  
 #   <p class="footer">  
 #       <a href="http://www.hyuki.com/yukiwiki/">$icontag</a>  
 #   </p>  
 #   </body>  
 #   </html>  
 #   EOD  
     # Walrus mod (1) end  
277  }  }
278    
279  sub escape {  sub escape {
280      my $s = shift;      my $s = shift;
281      $s =~ s|\r\n|\n|g;      $s =~ s|\x0D\x0A|\x0A|g;
282      $s =~ s|&|&amp;|g;      $s =~ s|&|&amp;|g;
283      $s =~ s|<|&lt;|g;      $s =~ s|<|&lt;|g;
284      $s =~ s|>|&gt;|g;      $s =~ s|>|&gt;|g;
# Line 581  sub unescape { Line 296  sub unescape {
296      return $s;      return $s;
297  }  }
298    
299  sub print_content ($;$) {  sub convert_format ($$$;%) {
300      my ($rawcontent, %option) = @_;    my ($content, $d => $t, %option) = @_;
301      print &text_to_html($rawcontent, toc=>1);    &load_formatter ('format');
302      my $f = SuikaWiki::Plugin->format_converter ($d => $t);
303      if (ref $f) {
304        $option{content} = $content;
305        $option{from} = $d;
306        $option{to} = $t;
307        &$f ({}, bless (\%option, 'SuikaWiki::Plugin'));
308      } elsif ($t =~ /HTML|xml/) {
309        length $content ? '<pre>'.&escape($content).'</pre>' : '';
310      } else {
311        $content;
312      }
313  }  }
314    
315  sub text_to_html {  sub text_to_html {
316      my ($txt, %option) = @_;      my ($txt, %option) = @_;
317      my (@txt) = split(/\n/, $txt);      my $toc = $option{-toc} || (ref $option{toc} ? $option{toc} : []);
     my (@toc);  
318      my $tocnum = 0;      my $tocnum = 0;
319        
320        ## Load constants
321        my %const;
322        if ($option{content_format} =~ /import="([^"]+)"/) {
323          for (split /\s*,\s*/, $1) {
324            my $wp = $database{$_};
325            if ($wp =~ m!^\#\?SuikaWikiConst/1.0!) {
326              wiki::suikawikiconst::to_hash ($wp => \%const);
327            }
328          }
329        }
330        
331        $txt =~ s{__&&([^&]+)&&__}{defined $const{$1}?$const{$1}:qq(__&&$1&&__)}ge;
332        my (@txt) = split(/\n/, $txt);
333      my (@saved, @result);      my (@saved, @result);
334      unshift(@saved, "</p>");      unshift(@saved, "</p>");
335      push(@result, "<p>");      push(@result, "<p>");
336      foreach (@txt) {      foreach (@txt) {
337          chomp;          chomp;
338          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
339              push(@toc, qq(----- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [5, "i$tocnum" => ($1 || $tocnum)];
340              push(@result, splice(@saved), qq(<h6 id="i$tocnum">) . &inline($1) . '</h6>');              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h6>');
341              $tocnum++;              $tocnum++;
342          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
343              push(@toc, qq(---- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [4, "i$tocnum" => ($1 || $tocnum)];
344              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>');
345              $tocnum++;              $tocnum++;
346          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
347              push(@toc, qq(--- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [3, "i$tocnum" => ($1 || $tocnum)];
348              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>');
349              $tocnum++;              $tocnum++;
350          } elsif (/^\*\*([^\x0D\x0A]*)/) {          } elsif (/^\*\*([^\x0D\x0A]*)/) {
351          # if (/^\*\*(.*)/) {          # if (/^\*\*(.*)/) {
352          # Walrus mod (6) end          # Walrus mod (6) end
353              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [2, "i$tocnum" => ($1 || $tocnum)];
354              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>');
355              $tocnum++;              $tocnum++;
356          } elsif (/^\*([^\x0D\x0A]*)/) {          } elsif (/^\*([^\x0D\x0A]*)/) {
357              push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));              push @$toc, [1, "i$tocnum" => ($1 || $tocnum)];
358              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>');
359              $tocnum++;              $tocnum++;
360          } elsif (/^(={1,6})(.*)/) {          } elsif (/^(={1,6})(.*)/) {
361              &back_push('ol', length($1), \@saved, \@result);              &back_push('ol', length($1), \@saved, \@result);
362              push(@result, '<li>' . &inline($2) . '</li>');              push(@result, '<li>' . &inline($2, const => \%const) . '</li>');
363          } elsif (/^(-{1,6})(.*)/) {          } elsif (/^(-{1,6})(.*)/) {
364            &back_push('ul', length($1), \@saved, \@result);            &back_push('ul', length($1), \@saved, \@result);
365            my ($pf, $l) = ('', $2);            my ($pf, $l) = ('', $2);
# Line 628  sub text_to_html { Line 367  sub text_to_html {
367              my $num = 0+$1;              my $num = 0+$1;
368              $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);              $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
369            }            }
370            push(@result, '<li>' . $pf . &inline ($l) . '</li>');            push(@result, '<li>' . $pf . &inline ($l, const => \%const) . '</li>');
371          } elsif (/^:([^:]+):(.*)/) {          } elsif (/^:([^:]+):(.*)/) {
372              &back_push('dl', 1, \@saved, \@result);              &back_push('dl', 1, \@saved, \@result);
373              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');              push(@result, '<dt>' . &inline($1, const => \%const) . '</dt>', '<dd>' . &inline($2, const => \%const) . '</dd>');
374          } elsif (/^(>{1,5})(.*)/) {          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
375              &back_push('blockquote', length($1), \@saved, \@result);              &back_push('blockquote', length($1), \@saved, \@result);
376              push(@result, &inline($2));              push @result, "<p>";
377                push(@result, &inline($2, const => \%const));
378                unshift @saved, "</p>";
379          } elsif (/^\s*$/) {          } elsif (/^\s*$/) {
380              push(@result, splice(@saved));              push(@result, splice(@saved));
             unshift(@saved, "</p>");  
381              push(@result, "<p>");              push(@result, "<p>");
382                unshift(@saved, "</p>");
383          } elsif (/^(\s+.*)$/) {          } elsif (/^(\s+.*)$/) {
384              &back_push('pre', 1, \@saved, \@result);              &back_push('pre', 1, \@saved, \@result);
385              #push(@result, &escape($1)); # Not &inline, but &escape              push(@result, &inline($1, const => \%const));
386              push(@result, &inline($1));          } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
387  #       } elsif (/^\,(.*)$/) {             # Walrus del (BF)              &back_push('table', 1, \@saved, \@result);
         } elsif (/^\,(.*?)[\x0D\x0A]*$/) { # Walrus add (BF)  
             &back_push('table', 1, \@saved, \@result, ' border="1"');  
388              #######              #######
389              # 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.
390              # XXXXX              # XXXXX
# Line 659  sub text_to_html { Line 398  sub text_to_html {
398                          $colspan[$i]++;                          $colspan[$i]++;
399                      }                      }
400                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
401                      $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));
402                  } else {                  } else {
403                      $value[$i] = '';                      $value[$i] = '';
404                  }                  }
# Line 667  sub text_to_html { Line 406  sub text_to_html {
406              push(@result, join('', '<tr>', @value, '</tr>'));              push(@result, join('', '<tr>', @value, '</tr>'));
407              # XXXXX              # XXXXX
408              #######              #######
409          } elsif (/^\[(INS|DEL|PRE)\[/) {          } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
410              push @result, splice (@saved), '<'.lc($1).'>';              push @result, splice (@saved), '<'.lc($1).'>';
411              unshift @saved, "</p>";              unshift @saved, "</p>";
412              push @result, "<p>";              push @result, "<p>";
413          } elsif (/^\](INS|DEL|PRE)\]/) {          } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
414              push @result, splice (@saved), '</'.lc($1).'>';              push @result, splice (@saved), '</'.lc($1).'>';
415          } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {          } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
416            my $num = 0+$1;            my $num = 0+$1;
417            push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);            push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
418            push @result, &inline ($2);            push @result, &inline ($2, const => \%const);
419          } else {          } else {
420              push(@result, &inline($_));              push(@result, &inline($_, const => \%const));
421          }          }
422      }      }
423      push(@result, splice(@saved));      push(@result, splice(@saved));
424            
425      my $toc = '';      my $r = join("\n", @result);
426      if ($option{toc}) {      $r =~ s#<p>\x0D?\x0A</p>##g;
427          # Convert @toc (table of contents) to HTML.      $r =~ s#[\x0D\x0A]+</#</#g;
428          # This part is taken from Makio Tsukamoto's WalWiki.      $r =~ s#<pre>\x0D?\x0A#<pre>#g;
429          my (@tocsaved, @tocresult);      $r;
         foreach (@toc) {  
             if (/^(-{1,6})(.*)$/) {  
                 &back_push('ul', length($1), \@tocsaved, \@tocresult);  
                 push(@tocresult, '<li>' . $2 . '</li>');  
             }  
         }  
         push(@tocresult, splice(@tocsaved));  
         $toc = join("\n", @tocresult);  
         $toc = $toc ? qq(<div id="wikipage-toc">$toc</div>) : '';  
     }  
     return $toc . join("\n", @result);  
430  }  }
431    
432  sub back_push {  sub back_push {
# Line 715  sub back_push { Line 443  sub back_push {
443      }      }
444  }  }
445    
446  sub inline {  sub inline ($;%) {
447      my ($line) = @_;      my ($line, %option) = @_;
448      $line = &escape($line);      $line = &escape($line);
449      $line =~ s:\[(INS|DEL|SUP|SUB)\[(.+?)\]\]:<@{[lc $1]}>$2</@{[lc $1]}>:g;      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4)}ge;
450      $line =~ s:\[ABBR\[(.+?)\] \[(.+?)\]\]:<acronym title="$2">$1</acronym>: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;
451      $line =~ s:\[RUBY\[(.+?)\] \[(.+?)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
452      $line =~ s%\[Q\[(.+?)\](?: \[&lt;([\x21-\x5A\x5E-\x7E]+)&gt;\])?\]%「<q@{[$2?qq( cite="$2"):'']}>$1</q>」%g;      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
453      $line =~ s|'''([^']+?)'''|<strong>$1</strong>|g;      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><ruby class="rb"><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby><span class="rp"> (</span><span class="rt-below">$3</span><span class="rp">) </span></span>:g;
454      $line =~ s|''([^']+?)''|<em>$1</em>|g;      $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
455      $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:\[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;
456      $line =~ s!      $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
457        (      $line =~ s|''([^']+)''|<em>$1</em>|g;
458          (?:&lt;(?:mailto|http|https|ftp|urn|news):[\x21-\x7E]*)&gt;      $line =~ s{
459        |        (\[\[(\#\S+?)\]\])
460          (?:$bracket_name))      # [[likethis]], [[#comment]], [[Friend:remotelink]]        |\[\[([^[]+?)](?:&gt;&gt;([0-9]+))?]
       |\[\[([^[]+?)]&gt;&gt;([0-9]+)]  
461        |&gt;&gt;([0-9]+)        |&gt;&gt;([0-9]+)
462      !        |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
463        my ($l, $page,$anchor, $anum) = ($1, $3,$4, 0+$5);      }{
464          my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
465        if ($l) {        if ($l) {
466          &make_link($l)          &embedded_to_html($1);
467        } elsif (defined $page) {        } elsif (defined $page) {
468          &make_wikilink ($page, anchor => 0+$anchor);          &make_wikilink ($page, anchor => 0+$anchor);
469        } elsif ($anum) {        } elsif ($anum) {
470          qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);          qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
471          } elsif ($uri) {
472            &make_urilink ($uri);
473        }        }
474      !gex;      }gex;
475      return $line;      return $line;
476  }  }
477    
478  sub make_wikilink ($%) {  sub make_wikilink ($%) {
479    my ($ename, %option) = @_;    my ($ename, %option) = @_;
480    my $name = &unescape ($ename);    my $name = &unescape ($ename);
481      $option{latest} = $option{latest} ? qq(mycmd=read;x-param=@{[time.[0..9]->[rand 10]]};mypage=) : '';
482    if ($database{$name}) {    if ($database{$name}) {
483      my $subject = &escape (&get_subjectline ($name, delimiter => ''));      my $subject = &escape (&get_subjectline ($name, delimiter => ''));
484      if ($option{anchor}) {      if ($option{anchor}) {
485        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);        return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
486      } else {      } else {
487        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}" class="wiki">$ename</a>);        return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}" class="wiki">$ename</a>);
488      }      }
489    } else {    } else {
490      return qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">$editchar</span></a>);      return qq(<a title="@{[&Resource('JumpAndEditWikiPage',escape=>1)]}" href="$uri{wiki}?$option{latest}@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">@{[&Resource('JumpAndEditWikiPageMark',escape=>1)]}</span></a>);
491    }    }
492  }  }
493    
494  sub make_link {  sub make_urilink ($;%) {
495      my $chunk = shift;    require URI;
496      # Walrus add (3) start    my $uri = shift;
497      $chunk =~ s/^&lt;(.*)&gt;$/$1/;    if ($uri =~ s/^IW://) {       ## InterWiki (not URI)
498      my $name  = $chunk;      $uri = &unescape ($uri);
499      if ($chunk =~ /^\[\[([^ ]+?) ([^ ]+?)\]\]$/ and $form{mypage} ne $InterWikiName) {      if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
500          ($name, $chunk) = ($1, $2);        my ($site, $name) = ($1, $2);
501      } elsif ($chunk =~ /^mailto:(.*)$/) {        for ($site, $name) {
502          $name = $1;          if (s/^"//) { s/"$//; s/\\(.)/$1/g }
503      }        }
504      if ($use_autoimg and $name =~ /^(http|https|ftp):.+\.(png|gif|jpe?g)/) {        &init_InterWikiName () unless $interwiki{'[[]]'};
505          $name = qq(<img src="$name">) ;        if ($interwiki{$site}) {
506      }          &load_formatter ('interwiki');
507      $name = &unarmor_name($name);          my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
508      # Walrus add (3) end          $site = &escape ($site); $name = &escape ($name);
509      if ($chunk =~ /^(http|https|ftp|news):/) {          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;);
510          # Walrus mod (3) start        } else {
511  #       if ($use_autoimg and $chunk =~ /\.(gif|png|jpeg|jpg)$/) {          qq(&lt;@{[&Resource('Error:UnknownInterWikiName=',escape=>1)]}@{[&escape ($site)]}&gt;);
512  #           return qq(<a href="$chunk"><img src="$chunk"></a>);        }
 #       } else {  
 #           return qq(<a href="$chunk">$chunk</a>);  
 #       }  
         return qq(&lt;<a href="$chunk">$name</a>&gt;);  
         # Walrus mod (3) end  
     } elsif ($chunk =~ m#^urn:[0-9A-Za-z_:;/.-]+#) {  
         return qq|&lt;<a href="/uri-res/N2L?${name}">$name</a>&gt;|;  
     } elsif ($chunk =~ /^mailto:(.*)/) {  
 #       return qq(<a href="$chunk">$2</a>);                 # Walrus del (3)  
         return qq(&lt;<a href="$chunk">$name</a>&gt;);              # Walrus add (3)  
     } elsif ($chunk =~ /^$interwiki_definition$/) {  
 #       return qq(<span class="InterWiki">$chunk</span>);   # Walrus del (3)  
         return qq(<span class="InterWiki">$name</span>);    # Walrus add (3)  
     } elsif ($chunk =~ /^$embedded_name$/) {  
         return &embedded_to_html($chunk);  
513      } else {      } else {
514          $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">@{[&escape($name)]}</a>);  # Walrus add (3)  
             } else {  
 #               return $chunk;                              # Walrus del (3)  
                 return &escape($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" class="wiki">@{[&escape($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">@{[&escape($name)]}</a>);     # Walrus add (3)  
         } else {  
             return qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=$cookedchunk" class="wiki">@{[&escape($name)]}<span class="mark">$editchar</span></a>);  
         }  
515      }      }
516      } elsif ($uri =~ /^urn:/) {   ## URN
517        my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
518        qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
519      } elsif ($uri =~ s/^MAIL://) {        ## mail address (not URI)
520        my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
521        qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
522      } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) {   ## image (not URI itself)
523        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
524        qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
525      } else {      ## misc. URI
526        CGI::Carp::warningsToBrowser (0);
527        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
528        CGI::Carp::warningsToBrowser (1);
529        qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
530      }
531  }  }
532    
533  sub print_message {  {my $FormIndex = 0;
534      my ($msg) = @_;  sub make_custom_form ($$$$) {
535      print qq(<p><strong>$msg</strong></p>);      my ($wfname, $definition, $template, $option) = @_;
536  }      ## $template and $option is currently not used in this procedure.
537        unless ($main::_EMBEDED) {
538  sub get_message {          $FormIndex++;
539      my ($msg) = @_;          if (length $definition) {
540      qq(<p><strong>$msg</strong></p>);              my $param = bless {}, 'SuikaWiki::Plugin';
541  }              my $lastmodified = $database->mtime ($form{mypage});
542                &load_formatter (qw/form_input form_option/);
543  sub init_form {              $definition = &unescape ($definition);
544      if (param()) {              $definition =~ s/\\(.)/$1/g;
545          foreach my $var (param()) {              $option = &unescape ($option);
546              $form{$var} = param($var);              $option =~ s/\\(.)/$1/g;
547          }              $fmt{form_option}->replace ($option, $param);
548                $param->{output}->{form} = 1 unless defined $param->{output}->{form};
549                $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
550                $param->{output}->{page} ||= $form{mypage};
551                $param->{form_disabled} = 1 if $database->meta (IsFrozen => $form{mypage});
552                my $target_form = $param->{output}->{id};
553                my $r = '';
554                $r = <<EOH if $param->{output}->{form};
555    <form method="post" action="$url_cgi" id="wikiform-$FormIndex" class="wikiform">
556      <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'read':'wikiform']}" />
557      <input type="hidden" name="mypage" value="@{[&escape($param->{output}->{page})]}" />
558      <input type="hidden" name="myLastModified" value="$lastmodified" />
559      <input type="hidden" name="mytouch" value="on" />
560      <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex)]}" />
561    EOH
562                $r .= qq(<a name="wikiform-$FormIndex"></a>) if $UA =~ m#Mozilla/[12]\.#;
563                $r .= $fmt{form_input}->replace ($definition, $param);
564                $r .= "</form>\n" if $param->{output}->{form};
565                $r;
566           } else {  ## No input-interface WikiForm
567               qq(<a id="wikiform-$FormIndex" name="wikiform-$FormIndex"><!-- #form --></a>);
568           }
569      } else {      } else {
570          $ENV{QUERY_STRING} = $FrontPage;          qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
571      }      }
572    }}
573    
574      my $query = &decode($ENV{QUERY_STRING});  sub init_form {
575      if ($page_command{$query}) {      ## TODO: Support multipart/form-data
576          $form{mycmd} = $page_command{$query};      my $query = '';
577          $form{mypage} = $query;      if (uc $main::ENV{REQUEST_METHOD} eq 'POST') {
578      } elsif ($query =~ /^($wiki_name)$/) {        read STDIN, $query, $main::ENV{CONTENT_LENGTH};
579          $form{mycmd} = 'read';      }
580          $form{mypage} = $1;      $query .= ($query ? ';' : '') . $main::ENV{QUERY_STRING};
581      } elsif ($database{$query}) {      if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
582          $form{mycmd} = 'read';        my $query = &decode($main::ENV{QUERY_STRING});
583          $query = &code_convert(\$query, $kanjicode);
584          $form{mypage} = $query;          $form{mypage} = $query;
585            $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';
586        } else {
587          for (split /[;&]/, $query) {
588            if (my ($n, $v) = split /=/, $_, 2) {
589              for ($n, $v) {tr/+/ /; s/%([0-9A-Fa-f][0-9A-Fa-f])/pack 'C', hex $1/ge};
590              $form{$n} = $v;
591            }
592          }
593          unless (defined $form{mypage}) {
594            $form{mypage} = $form{epage};
595            $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;
596          }
597      }      }
598        $form{mypage} ||= $PageName{FrontPage};
599        $form{mypage} =~ tr/\x00-\x1F\x7F//d;
600        $form{mycmd} ||= 'read';
601    
602      # mypreview_edit        -> do_edit, with preview.      # mypreview_edit        -> do_edit, with preview.
603      # mypreview_adminedit   -> do_adminedit, with preview.      # mypreview_adminedit   -> do_adminedit, with preview.
# Line 864  sub init_form { Line 609  sub init_form {
609          }          }
610      }      }
611    
612      #      #
613      # $form{mycmd} is frozen here.      # $form{mycmd} is frozen here.
614      #      #
615    
616        for (grep /^wikiform__/, keys %form) {
617            $form{$_} = &code_convert (\$form{$_}, $kanjicode);
618        }
619      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
620      $form{myname} = &code_convert(\$form{myname}, $kanjicode);      $form{myname} = &code_convert(\$form{myname}, $kanjicode);
621  }  }
622    
623  sub update_recent_changes {  {my %SubjectLine;
     my $update = "- @{[&get_now]} [[@{[&escape($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 \[\[(\S+?)\]\]/;  
         my $name = $1;  
         if ($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);  
     }  
 }  
   
624  sub get_subjectline {  sub get_subjectline {
625      my ($page, %option) = @_;      my ($page, %option) = @_;
626      if (not &is_editable($page)) {      unless (defined $SubjectLine{$page}) {
627          return "";        if (not &is_editable($page)) {
628            $SubjectLine{$page} = "";
629          } else {
630            $SubjectLine{$page} = $database{$page};
631            $SubjectLine{$page} =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
632            $SubjectLine{$page} =~ s/\x0D?\x0A.*//s;
633          }
634        }
635        if (length $SubjectLine{$page}) {
636          $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
637          $option{delimiter}.$SubjectLine{$page}.$option{tail};
638      } else {      } else {
639          # 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#^(?:\#\?)?SuikaWiki/0.9[^\x0D\x0A]*[\x0D\x0A]+##s;  
         $subject =~ s/\r?\n.*//s;  
         return "$delim$subject".$option{tail};  
640      }      }
641  }  }}
   
 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);  
 }  
642    
643  sub open_db {  sub open_db {
644      if ($modifier_dbtype eq 'dbmopen') {      if ($modifier_dbtype eq 'dbmopen') {
645          dbmopen(%database, $dataname, 0666) or &print_error("(dbmopen) $dataname");          dbmopen(%database, $PathTo{WikiDataBase}, 0666) or die "(dbmopen) $PathTo{WikiDataBase}";
         dbmopen(%infobase, $infoname, 0666) or &print_error("(dbmopen) $infoname");  
646      } elsif ($modifier_dbtype eq 'AnyDBM_File') {      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
647          tie(%database, "AnyDBM_File", $dataname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $dataname");          eval q{use AnyDBM_File};
648          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 die ("(tie AnyDBM_File) $PathTo{WikiDataBase}");
649      } else {      } elsif ($modifier_dbtype eq 'Yuki::YukiWikiDB') {
650          tie(%database, "Yuki::YukiWikiDB", $dataname) or &print_error("(tie Yuki::YukiWikiDB) $dataname");          eval q{use Yuki::YukiWikiDB};
651          tie(%infobase, "Yuki::YukiWikiDB", $infoname) or &print_error("(tie Yuki::YukiWikiDB) $infoname");          tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or die ("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");
652        } else {    ## Yuki::YukiWikiDB || Yuki::YukiWikiDBMeta
653            eval qq{use $modifier_dbtype};
654            $database = tie(%database, $modifier_dbtype => $PathTo{WikiDataBase}, -lock => 2, -backup => $wiki::diff::UseDiff) or die ("(tie $modifier_dbtype) $PathTo{WikiDataBase}");
655      }      }
656  }  }
657    
658  sub close_db {  sub close_db {
659      if ($modifier_dbtype eq 'dbmopen') {      if ($modifier_dbtype eq 'dbmopen') {
660          dbmclose(%database);          dbmclose(%database);
         dbmclose(%infobase);  
     } elsif ($modifier_dbtype eq 'AnyDBM_File') {  
         untie(%database);  
         untie(%infobase);  
661      } else {      } else {
662          untie(%database);          untie(%database);
         untie(%infobase);  
663      }      }
664  }  }
665    
666  sub open_diff {  sub editform (@) {
667      if ($modifier_dbtype eq 'dbmopen') {    my %option = @_;
668          dbmopen(%diffbase, $diffname, 0666) or &print_error("(dbmopen) $diffname");    my $frozen = &is_frozen ($option{page});
669      } elsif ($modifier_dbtype eq 'AnyDBM_File') {    $option{content} = $database{$option{page}} unless defined $option{content};
670          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};
671      } else {    $option{last_modified} = $database->mtime ($option{page}) unless defined $option{last_modified};
672          tie(%diffbase, "Yuki::YukiWikiDB", $diffname) or &print_error("(tie Yuki::YukiWikiDB) $diffname");    my $f = '';
673      }    my $magic = '';
674  }    $magic = $1 if $option{content} =~ m/^([^\x0A\x0D]+)/s;
675      
676  sub close_diff {    my $selected = 'read';
677      if ($modifier_dbtype eq 'dbmopen') {    if ($form{after_edit_cmd}) {
678          dbmclose(%diffbase);      $selected = $form{after_edit_cmd};
679      } elsif ($modifier_dbtype eq 'AnyDBM_File') {    } elsif ($magic =~ /Const|Config|CSS/) {
680          untie(%diffbase);      $selected = 'edit';
681      } else {    }
682          untie(%diffbase);    my $afteredit = <<EOH;
683      }  <select name="after_edit_cmd">
684  }  <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
685    <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
686  sub print_searchform {  </select>
687      my ($word) = @_;  EOH
688      print <<"EOD";    $f .= <<"EOD";
689  <form action="$url_cgi" method="get">  <form action="$uri{wiki}" method="post">
690      <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>) ]}
691      <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 />
692      <input type="submit" value="$resource{searchbutton}">      <input type="hidden" name="myLastModified" value="$option{last_modified}" />
693  </form>      <input type="hidden" name="mypage" value="@{[&escape($form{mypage})]}" />
694  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 || $database{NewPageTemplate});  
     }  
   
     my $edit = $mode{admin} ? 'adminedit' : 'edit';  
     my $escapedmypage = &escape($form{mypage});  
     my $escapedmypassword = &escape($form{mypassword});  
   
     print <<"EOD";  
 <form action="$url_cgi" method="post">  
     @{[ $mode{admin} ? qq($resource{frozenpassword} <input type="password" name="mypassword" value="$escapedmypassword" size="10"><br>) : "" ]}  
     <input type="hidden" name="myLastModified" value="$lastmodified">  
     <input type="hidden" name="mypage" value="$escapedmypage">  
     <textarea cols="$cols" rows="$rows" name="mymsg" tabindex="1">$mymsg</textarea><br>  
695  @{[  @{[
696      $mode{admin} ?      $option{admin} ?
697      qq(      qq(
698      <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>
699      <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 />)
700      : ""      : ""
701  ]}  ]}
702  @{[  @{[
703      $mode{conflict} ? "" :      $option{conflict} ? "" :
704      qq(      qq(
705          <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 />
706          <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>
707          <input type="submit" name="mypreview_write" value="$resource{savebutton}" accesskey="S"><kbd>S</kbd><br>         $afteredit
708      )      )
709  ]}  ]}
710  </form>  </form>
711  EOD  EOD
712      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  
713  }  }
714    
715  sub is_editable {  sub is_editable {
716      my ($page) = @_;      my ($page) = @_;
717      if (&is_bracket_name($page)) {      $page =~ /[\x00-\x20\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;  
     }  
718  }  }
719    
720  sub decode {  sub decode {
# Line 1126  sub decode { Line 725  sub decode {
725  }  }
726    
727  sub encode {  sub encode {
728      my ($s) = @_;    my $s = shift;
729      my $encoded = '';    $s =~ s/([^0-9A-Za-z_-])/sprintf '%%%02X', ord $1/ge;
730      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;  
731  }  }
732    
733  sub get_now {  sub get_now {
734      my (@week) = qw(Sun Mon Tue Wed Thu Fri Sat);      my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
     my (@week) = qw(日 月 火 水 木 金 土);  
     my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);  
735      $year += 1900;      $year += 1900;
736      $mon++;      $mon++;
737      $mon = "0$mon" if $mon < 10;      $mon = "0$mon" if $mon < 10;
# Line 1176  sub get_now { Line 739  sub get_now {
739      $hour = "0$hour" if $hour < 10;      $hour = "0$hour" if $hour < 10;
740      $min = "0$min" if $min < 10;      $min = "0$min" if $min < 10;
741      #$sec = "0$sec" if $sec < 10;      #$sec = "0$sec" if $sec < 10;
742      $weekday = $week[$weekday];      return "$year-$mon-$day $hour:$min";
     return "$year-$mon-$day ($weekday) $hour:$min";  
743  }  }
744    
 # [[YukiWiki http://www.hyuki.com/yukiwiki/wiki.cgi?euc($1)]]  
745  sub init_InterWikiName {  sub init_InterWikiName {
746      my $content = $database{$InterWikiName};    my @content = split /\n/, $database{InterWikiName};
747      while ($content =~ /\[\[(\S+) +(\S+)\]\]/g) {    for (@content) {
748          my ($name, $url) = ($1, $2);      if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
749          $interwiki{$name} = $url;        $interwiki{$1} = $2;
750      }      }
751  }    }
752      $interwiki{'[[]]'} = 1;       ## dummy
 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;  
     }  
 }  
   
 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;  
753  }  }
754    
755  sub frozen_reject {  sub frozen_reject {
756      my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);      my ($isfrozen) = $database->meta (IsFrozen => $form{mypage});
757      my ($willbefrozen) = $form{myfrozen};      my ($willbefrozen) = $form{myfrozen};
758      if (not $isfrozen and not $willbefrozen) {      if (not $isfrozen and not $willbefrozen) {
759          # You need no check.          # You need no check.
# Line 1241  sub frozen_reject { Line 762  sub frozen_reject {
762          # You are admin.          # You are admin.
763          return 0;          return 0;
764      } else {      } else {
765          &print_error($resource{passworderror});          &_do_view_msg (-view => '-error', -page => $form{mypage},
766          return 1;                         error_message => &Resource ('Error:PasswordIsIncorrect'));
767            exit;
768      }      }
769  }  }
770    
771  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;  
     }  
 }  
772    
773  sub do_comment {  sub do_comment {
774      my ($content) = $database{$form{mypage}};      my ($content) = $database{$form{mypage}};
775      my $datestr = &get_now;      my $default_name;   ## this code is not strict.
776      my $namestr = " ''[[@{[$form{myname}||$DEFAULT_embed_comment_name]}]]'': ";      $default_name = $1 if $content =~ /default-name="([^"]+)"/;
777      my $anchor = 0;      my $datestr = '[WEAK['.&get_now.']]';
778      $content =~ s/(?:-+\s)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;      my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
779      $anchor++;      ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
780        if ($namestr =~ /^(?:>>)?[0-9]/) {
781          $namestr = qq( ''$namestr'': );
782        } elsif (length $namestr) {
783          $namestr = qq( ''[[$namestr]]'': );
784        }
785        my $anchor = &get_new_anchor_index ($content);
786      my $i = 1;  my $o = 0;      my $i = 1;  my $o = 0;
787      $content =~ s{(\Q$embed_comment\E|\Q$embed_rcomment\E)}{      $content =~ s{(\[\[\#r?comment\]\])}{
788        my $embed = $1;        my $embed = $1;
789        if ($i == $form{comment_index}) {        if ($i == $form{comment_index}) {
790          if ($embed eq $embed_comment) {          if ($embed ne '[[#rcomment]]') {
791            $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;            $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;
792          } else {          } else {
793            $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;            $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;
# Line 1285  sub do_comment { Line 796  sub do_comment {
796        $i++; $embed;        $i++; $embed;
797      }ge;      }ge;
798      unless ($o) {      unless ($o) {
799          $content = "#?SuikaWiki/0.9\n\n" unless $content;
800          $content .= "\n" unless $content =~ /\n$/s;
801        $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";        $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
802      }      }
803      if ($form{mymsg}) {      $form{__comment_anchor_index} = $anchor;
804        if ($form{mymsg} || $form{myname}) {
805          $form{mymsg} = $content;          $form{mymsg} = $content;
806          $form{mytouch} = 'on';          $form{mytouch} = 'on';
807          &do_write;          &do_write;
# Line 1297  sub do_comment { Line 811  sub do_comment {
811      }      }
812  }  }
813    
814    sub get_new_anchor_index ($) {
815        my $content = shift;
816        my $anchor = 0;
817        $content =~ s/^(?:[-=]+\s*)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
818        $anchor + 1;
819    }
820    
821  my $CommentIndex = 0;  my $CommentIndex = 0;
822  sub embedded_to_html {  sub embedded_to_html {
823      my ($embedded) = @_;      my ($embedded) = @_;
824      if ($embedded eq $embed_comment or $embedded eq $embed_rcomment) {      if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
825        unless ($main::_EMBEDED) {        unless ($main::_EMBEDED) {
826          my $lastmodified = &get_info($form{mypage}, $info_LastModified);          my $lastmodified = $database->mtime ($form{mypage});
827          return <<"EOD";          return <<"EOD";
828  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}">  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
829      <input type="hidden" name="mycmd" value="comment">      <input type="hidden" name="mycmd" value="comment" />
830      <input type="hidden" name="mypage" value="$form{mypage}">      <input type="hidden" name="mypage" value="$form{mypage}" />
831      <input type="hidden" name="myLastModified" value="$lastmodified">      <input type="hidden" name="myLastModified" value="$lastmodified" />
832      <input type="hidden" name="mytouch" value="on">      <input type="hidden" name="mytouch" value="on" />
833      <input type="hidden" name="comment_index" value="$CommentIndex">      <input type="hidden" name="comment_index" value="$CommentIndex" />
834      $embed_comment_Name_Prompt      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
835      <input type="text" name="myname" value="" size="10">      <input type="text" name="myname" value="" size="10" class="comment-name" />
836      <input type="text" name="mymsg" value="" size="60">      <input type="text" name="mymsg" value="" size="60" class="comment-msg" />
837      <input type="submit" value="$resource{commentbutton}">      <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit" />
838  </form>  </p></form>
839  EOD  EOD
840       } else {       } else {
841          return <<"EOD";          return <<"EOD";
842  <del><form action="$url_cgi" method="get">  <del><form action="$url_cgi" method="get">
843      <input type="hidden" name="mycmd" value="read">      <input type="hidden" name="mycmd" value="read" />
844      <input type="hidden" name="mypage" value="$form{mypage}">      <input type="hidden" name="mypage" value="$form{mypage}" />
845      $embed_comment_Name_Prompt      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
846      <input type="text" name="myname" value="" size="10" disabled="disabled">      <input type="text" name="myname" value="" size="10" disabled="disabled" />
847      <input type="text" name="mymsg" value="" size="60" disabled="disabled">      <input type="text" name="mymsg" value="" size="60" disabled="disabled" />
     <input type="submit" value="$resource{commentbutton}" disabled="disabled">  
848  </form></del>  </form></del>
849  EOD  EOD
850      }      }
851    } elsif ($embedded =~ /$embed_command{searched}/) {    } elsif ($embedded =~ /$embed_command{searched}/) {
852      return get_search_result ($1);      return get_search_result ($1, -match_myself => 1);
     # Walrus add (5) start  
     } elsif ($embedded =~ /$embed_interwiki/ and my $remoteurl = $interwiki{$2}) {  
         $_ = &make_interwiki_box($1, $2);  
         return ($_) ? $_ : $embedded;  
     # Walrus add (5) end  
853    } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {    } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
854      my ($name, $r) = ($1, '');      my ($name, $r) = ($1, '');
855      if ($main::_EMBEDED != 1) {      if ($main::_EMBEDED != 1) {
# Line 1347  EOD Line 862  EOD
862        } elsif (length $content) {        } elsif (length $content) {
863          $r = "<pre>@{[&escape ($content)]}</pre>";          $r = "<pre>@{[&escape ($content)]}</pre>";
864        } else {        } else {
865          $r = &text_to_html ("[[$name]]", content_format => 'SuikaWiki/0.9');          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
866        }        }
867      } else {    ## nested #EMBED      } else {    ## nested #EMBED
868        $r = &text_to_html ("[INS[\n[[$name]] の埋め込みは (入り組んでいるので) 解決されませんでした。\n]INS]\n", content_format => 'SuikaWiki/0.9');        $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
869      }      }
870      return qq(<blockquote title="@{[&escape($name)]}">$r</blockquote>);      return qq(<blockquote title="@{[&escape($name)]}" class="wiki-embed">$r<div class="cite-note">『<cite><a href="$url_cgi?@{[&encode($name)]}" class="wiki">@{[&escape($name)]}</a></cite>』</div></blockquote>);
871    } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {    } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
872      return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);      return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);
873    } else {    } else {
# Line 1360  EOD Line 875  EOD
875    }    }
876  }  }
877    
878  # Walrus add (5) start  sub load_formatter (@) {
879  sub do_interwiki_box {      for my $t (@_) {
880      my $remoteurl = $interwiki{$form{'myintername'}};          unless ($fmt{$t}) {
881      if ($remoteurl) {              require Message::Util::Formatter;
882          $remoteurl =~ s/\b(euc|sjis|ykwk|asis|isbn)\(\$1\)/&interwiki_convert($1, $form{'mylocalname'})/e;              $fmt{$t} = Message::Util::Formatter->new;
883          print "Location: $remoteurl\n\n";              for (@{$SuikaWiki::Plugin::List{'wiki'.$t}||[]}) {
884          exit(1);                  $_->load_formatter ($fmt{$t}, type => 'wiki'.$t);
885      } else {              }
886          &do_read;          }
887      }      }
888  }  }
 # Walrus add (5) end  
889    
890  # Walrus add (5) start  sub do_wikiform {
891  sub make_interwiki_box {      my $content = $database{$form{mypage}};
892      my ($localname, $intername) = @_;      my $anchor = &get_new_anchor_index ($content);
893      my %ignoretype = (      &load_formatter (qw/form_template form_option/);
894          'box'      => 'text',      my $write = 0;
895          'text'     => 'text',      my $i = 1;
896          'pass'     => 'password',      $content =~ s{$embed_command{form}}{
897          'password' => 'password'          my ($embed, $wfname, $template, $option) = ($&, $1, $3, $4);
898      );          if (($wfname && $wfname eq $form{wikiform_targetform})
899      my $converted = ($ignoretype{$localname}) ? <<EOD : undef;              || $i == $form{wikiform_index}) {
900  <form action="$url_cgi" method="post">              $template =~ s/\\(.)/$1/g;
901      <input type="hidden" name="mycmd" value="interwikibox">              $option =~ s/\\(.)/$1/g;
902      <input type="hidden" name="mypage" value="$form{mypage}">              my $param = bless {}, 'SuikaWiki::Plugin';
903      <input type="hidden" name="myintername" value="$intername">              $param->{page} = $form{mypage};
904      $intername:              $param->{form_index} = $i;
905      <input type="$ignoretype{$localname}" name="mylocalname" value="" size="10">              $param->{form_name} = $wfname;
906      <input type="submit" value="Submit">              $param->{anchor_index} = $anchor;
907  </form>              $param->{argv} = \%form;
908  EOD              $param->{default_name} = $1 if $content =~ /default-name="([^"]+)"/;
909                $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
910                $fmt{form_option}->replace ($option, $param);
911                my $t = 1;
912                for (@{$param->{require}||[]}) {
913                    (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
914                }
915                $t = $fmt{form_template}->replace ($template, $param) if $t;
916                if (length $t) {
917                    if ($param->{output}->{reverse}) {
918                        $embed .= "\n" . $t;
919                    } else {
920                        $embed = $t . "\n" . $embed;
921                    }
922                    $write = 1;
923                    $form{__comment_anchor_index} = $anchor
924                      if $param->{anchor_index_};  ## $anchor is used!
925                }
926                $form{__wikiform_anchor_index} = $i;
927                undef $form{wikiform_targetform};  ## make sure never to match
928                undef $form{wikiform_index};       ## with WikiForm in rest of page
929            }
930            $i++; $embed;
931        }ge;
932        unless ($write) {
933          #$content = "#?SuikaWiki/0.9\n\n" unless $content;
934          #$content .= "\n" unless $content =~ /\n$/s;
935          #
936        }
937        if ($write) {
938            $form{mymsg} = $content;
939            $form{mytouch} = 'on';
940            &do_write;
941        } else {
942            $form{mycmd} = 'read';
943            &do_read;
944        }
945  }  }
 # Walrus add (5) end  
946    
947  sub code_convert {  sub code_convert {
948      require Jcode;
949      my ($contentref, $code) = (shift, shift || $kanjicode);      my ($contentref, $code) = (shift, shift || $kanjicode);
950  #   &Jcode::convert($contentref, $code);       # for Jcode.pm      if    ($code =~ /euc/) { $code = 'euc' }
951      &jcode::convert($contentref, $code);       # for jcode.pl      elsif ($code =~ /iso/) { $code = 'jis' }
952        elsif ($code =~ /shi/) { $code = 'sjis' }
953        elsif ($code =~ /utf/) { $code = 'utf8' }
954        $$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;
955      return $$contentref;      return $$contentref;
956  }  }
957    
958  sub test_convert {  sub _rfc3339_date ($) {
959      my $txt = &text_to_html(<<"EOD", toc=>1);    my @time = gmtime (shift);
960  *HEADER1    sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
 **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;  
961  }  }
962    
963  sub do_diff {  sub is_exist_page { $use_exists ? exists ($database{$_[0]}) : $database{$_[0]} }
964      if (not &is_editable($form{mypage})) {  sub __get_database ($) { $database{ $_[0] } }
         &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);  
 }  
   
 sub do_rss {  
     my $rss = new Yuki::RSS(  
         version => '1.0',  
         encoding => $charset,  
     );  
     $rss->channel(  
         title => $modifier_rss_title,  
         link  => $modifier_rss_link,  
         description => $modifier_rss_description,  
     );  
     my $recentchanges = $database{$RecentChanges};  
     my $count = 0;  
     foreach (split(/\n/, $recentchanges)) {  
         last if ($count >= 15);  
         /^\- \d\d\d\d\-\d\d\-\d\d \([^)]+\) \d\d:\d\d:\d\d (\S+)/;    # date format.  
         my $title = &unarmor_name($1);  
         my $escaped_title = &escape($title);  
         my $link = $modifier_rss_link . '?' . &encode($title);  
         my $description = $escaped_title . &escape(&get_subjectline($title));  
         $rss->add_item(  
             title => $escaped_title,  
             link  => $link,  
             description => $description,  
         );  
         $count++;  
     }  
     # print RSS information (as XML).  
     print <<"EOD"  
 Content-type: text/xml  
   
 @{[$rss->as_string]}  
 EOD  
 }  
965    
966  sub is_exist_page {  my %_Resource;
967      my ($name) = @_;  sub Resource ($;%) {
968      if ($use_exists) {    my ($s, %o) = @_;
969          return exists($database{$name});    unless (defined $_Resource{$s}) {
970      } else {      $_Resource{$_[0]} = &wiki::resource::get ($s, $_Resource{__option});
971          return $database{$name};    }
972      }    $o{escape} ? &escape ($_Resource{$s}) : $_Resource{$s};
973  }  }
974    
 sub __get_database ($) { $database{ $_[0] } }  
   
975  package wiki::referer;  package wiki::referer;
976  sub add ($$) {  sub add ($$) {
977    my $page = shift;    my $page = shift;
# Line 1559  sub add ($$) { Line 992  sub add ($$) {
992    $list{ $uri }++;    $list{ $uri }++;
993    set ($page, \%list);    set ($page, \%list);
994  }  }
995  sub get ($) {  sub get ($) { split /"/, $main::database->meta (Referer => $_[0]) }
   my $page = shift;  
   split /"/, main::get_info ($page, 'Referer');  
 }  
996  sub set ($%) {  sub set ($%) {
997    my $page = shift;    my $page = shift;
998    my $list = shift;    my $list = shift;
999    main::set_info ($page, Referer => join '"', %$list);    $main::database->meta (Referer => $page => join '"', %$list);
1000  }  }
1001    
1002  sub get_dont_record () {  sub get_dont_record () {
1003    map {s/\$/\\\$/g; s/\@/\\\@/g; $_}    map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1004    grep !/^#/,    grep !/^#/,
1005    split /[\x0D\x0A]+/, &main::__get_database ('RefererDontRecord');    split /[\x0D\x0A]+/, $main::database{RefererDontRecord};
1006  }  }
1007  sub get_site_name () {  sub get_site_name () {
1008    my @lines = grep /[^#]/, split /[\x0D\x0A]+/, &main::__get_database('RefererSiteName');    my @lines = grep /[^#]/, split /[\x0D\x0A]+/, $main::database{RefererSiteName};
1009    my @item;    my @item;
1010    for (@lines) {    for (@lines) {
1011      next if /^#/;      next if /^#/;
# Line 1604  sub list_html ($) { Line 1034  sub list_html ($) {
1034      }      }
1035      my $euri = main::escape ($uri);      my $euri = main::escape ($uri);
1036      if ($title) {      if ($title) {
1037        $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri>">@{[main::escape ($title)]}</a></li>\n);        $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri&gt;">@{[main::escape ($title)]}</a></li>\n);
1038      } else {      } else {
1039        $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);        $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1040      }      }
# Line 1619  sub __decode ($) { Line 1049  sub __decode ($) {
1049    main::code_convert (\$s);    main::code_convert (\$s);
1050  }  }
1051    
1052    package wiki::useragent;
1053    our $UseLog;
1054    
1055    sub add ($) {
1056      my $s = shift;
1057      return unless length $s;
1058      return unless $UseLog;
1059      $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1060      my %ua;
1061      for (split /\n/, &main::__get_database($main::PageName{UserAgentList})) {
1062        if (/^-\[(\d+)\] (.+)$/) {
1063          my ($t, $n) = ($1, $2);
1064          $n =~ tr/\x0A\x0D//d;
1065          $ua{$n} = $t;
1066        }
1067      }
1068      $ua{$s}++;
1069      my $s = qq(#?SuikaWiki/0.9\n);
1070      for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1071        $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1072      }
1073      $main::database->STORE ($main::PageName{UserAgentList} => $s, -touch => 0);
1074    }
1075    
1076    package wiki::suikawikiconst;
1077    
1078    sub to_hash ($;$) {
1079      my $page = shift;
1080      my $h = shift || {};
1081      my $val;
1082      for my $line (split /\n/, $page) {
1083        $line =~ tr/\x0A\x0D//d;
1084        if ($val && $line =~ s/^\s+//) {
1085          $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
1086        } elsif ($line =~ /^(.+):/) {
1087          $val = $1; $h->{$val} = '';
1088        }
1089      }
1090      $h;
1091    }
1092    
1093    package wiki::dummy;
1094    sub mtime (@) {undef}
1095    sub meta (@) {undef}
1096    sub Yuki::YukiWikiDB2::meta (@) {undef}
1097    
1098    package SuikaWiki::Plugin;
1099      our $plugin_directory;
1100      our %List;
1101      our %Index;
1102      push @main::INC, $plugin_directory.'/../..';
1103    
1104    sub escape ($$) { main::escape ($_[1]) }
1105    sub unescape ($$) { main::unescape ($_[1]) }
1106    sub encode ($$) { main::encode ($_[1]) }
1107    sub decode ($$) { main::decode ($_[1]) }
1108    sub __get_datetime ($) { main::get_now () }
1109    sub resource ($$;%) { shift; &main::Resource (@_) }
1110    sub uri ($$) { $main::uri{$_[1]} }
1111    sub new_index ($$) { ++$Index{$_[1]} }
1112    sub user_agent_names ($) { $main::UA }
1113    sub magic_and_content ($$) {
1114      my ($magic, $page) = ('', $_[1]);
1115      $magic = $1 if $page =~ s!^((?:\#\?|/\*|<\?)[^\x02\x0A\x0D]+)[\x02\x0A\x0D]+!!s;
1116      ($magic, $page);
1117    }
1118    sub formatter ($$) {
1119      &main::load_formatter ($_[1]);
1120      $main::fmt{$_[1]};
1121    }
1122    sub format_converter ($$$) {
1123      &main::load_formatter ('format');
1124      $main::fmt{format}->{($_[1]=~/([A-Za-z0-9]\S+)/?$1:'SuikaWiki/0.9').'_to_'.$_[2]}
1125      || $main::fmt{format}->{($_[1]=~/([A-Za-z0-9](?:(?!\/)\S)+)/?$1:'SuikaWiki').'_to_'.$_[2]};
1126    }
1127    
1128    sub regist ($@) {
1129        my $pack = shift;
1130        for (@_) {
1131            push @{$List{$_}}, $pack;
1132        }
1133    }
1134    
1135    sub import_plugins () {
1136        opendir PDIR, $plugin_directory;
1137        my @plugin = grep {s/\.pm$//} readdir (PDIR);
1138        closedir PDIR;
1139        for (@plugin) {
1140            eval qq{ use SuikaWiki::Plugin::$_ } unless /[^A-Za-z0-9_]/;
1141            push @{$List{_all}}, qq(SuikaWiki::Plugin::$_);
1142        }
1143    }
1144    
1145    &import_plugins ();
1146    
1147    package wiki::conneg;
1148    
1149    ## BUG: this parser isn't strict.
1150    sub get_accept_lang (;$) {
1151      my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1152      my %alang = (ja => 0.0002, en => 0.0001);
1153      my $i = 0.1;
1154      for (split /\s*,\s*/, $alang) {
1155        tr/\x09\x0A\x0D\x20//d;
1156        if (/((?:(?!;q=).)+)(?:;q="?([0-9.]+)"?)?/) {
1157          my $l = lc $1; $l =~ tr/\x22\x5C//d;
1158          $alang{$l} = (defined $2 ? $2 : 1.000)*1000;
1159          $alang{$l} += $i unless $alang{$l} == 0;
1160          $i -= 0.001;
1161        }
1162      }
1163      \%alang;
1164    }
1165    
1166    package wiki::resource;
1167    
1168    sub get ($;\%) {
1169      my ($resname, $option) = @_;
1170      $option->{accept_language} ||= &wiki::conneg::get_accept_lang ();
1171      $option->{resource} ||= {};
1172      my $v;
1173      for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1174        while (length $lang) {
1175          unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1176            $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash ($main::database{'WikiResource:'.$lang});
1177            $v = $option->{resource}->{$lang}->{$resname};
1178            last if defined $v;
1179          }
1180          $lang =~ s/[^+-]*$//; $lang =~ s/[+-]$//;
1181        }
1182        last if defined $v;
1183      }
1184      defined $v ? $v : $resname;
1185    }
1186    
1187    package main;
1188    &main;
1189    exit 0;
1190    
1191  1;  1;
1192  __END__  __END__
1193  =head1 NAME  =head1 NAME
1194    
1195  wiki.cgi - This is YukiWiki, yet another Wiki clone.  wiki.cgi --- SuikaWiki: Yet yet another Wiki engine
1196    
1197  =head1 DESCRIPTION  =head1 SEE ALSO
1198    
1199  YukiWiki is yet another Wiki clone.  <IW:SuikaWiki:SuikaWiki>
1200    
1201  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).  
1202    
1203  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/>
1204    
1205  =head1 AUTHOR  Makio Tsukamoto <http://digit.que.ne.jp/>
1206    
1207  Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/  Wakaba <w@suika.fam.cx>
1208    
1209  =head1 LICENSE  =head1 LICENSE
1210    
1211  Copyright (C) 2000-2002 by Hiroshi Yuki.  Copyright (C) 2000-2003 AUTHORS
1212    
1213  This program is free software; you can redistribute it and/or  This program is free software; you can redistribute it and/or
1214  modify it under the same terms as Perl itself.  modify it under the same terms as Perl itself.

Legend:
Removed from v.1.28  
changed lines
  Added in v.1.50

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24