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

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

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24