/[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 by wakaba, Mon Feb 4 13:19:08 2002 UTC revision 1.44 by w, Wed Jan 1 12:30:24 2003 UTC
# Line 1  Line 1 
1  #!/usr/local/bin/perl  #!/usr/bin/perl
2  use lib "../lib";  # wiki.cgi - This is YukiWiki, yet another Wiki clone.
3  use CGI::Carp 'fatalsToBrowser';  #
4  use Algorithm::Diff qw(traverse_sequences);  # This program is free software; you can redistribute it and/or
5  # use strict;  # modify it under the same terms as Perl itself.
6  #  
7  # yukiwiki.cgi - Yet another WikiWikiWeb clone.  use strict;
8  #  use lib qw(./lib);
9  # Copyright (C) 2000,2001 by Hiroshi Yuki.  use CGI::Carp qw(fatalsToBrowser);
10  # <hyuki@hyuki.com>  
11  # http://www.hyuki.com/yukiwiki/  require 'wikidata/suikawiki-config.ph';
12  #  use Yuki::DiffText qw(difftext);
13  # This program is free software; you can redistribute it and/or modify  use Fcntl;
14  # it under the terms of the GNU General Public License as published by  ##############################
15  # the Free Software Foundation; either version 2 of the License, or  my %fmt;        ## formatter objects
16  # (at your option) any later version.  my %embed_command = (
17  #          searched        => '^\[\[#searched:([^\]]+)\]\]$',
18  # This program is distributed in the hope that it will be useful,          form    => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
19  # but WITHOUT ANY WARRANTY; without even the implied warranty of  );
20  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  our ($modifier_dbtype,$url_cgi,%uri,%PathTo,$use_exists);
21  # GNU General Public License for more details.  our (%PageName,$kanjicode,$lang,%fixedpage);
22  #  
23  # $Id$  ##############################
24  ##############################  my $info_LastModified = 'LastModified';
25  my $version = "1.6.6";  my $info_IsFrozen = 'IsFrozen';
26  ##############################  ##############################
27  # 単独テストのときには 1 にする。  my %form;
28  my $testing = 0;  my %database;
29  ##############################  my %infobase;
30  # 漢字ライブラリ  my %diffbase;
31  my $jcodelib = 'jcode.pl';  my %interwiki;
32  ##############################  ##############################
33  # 保存・表示の漢字コード  my %page_command = (
34  my $kanjicode = 'sjis';     # 'sjis' 'euc'      $PageName{IndexPage} => 'index',
35  my $charset = 'Shift_JIS';  # 'Shift_JIS' 'EUC-JP'      $PageName{RssPage} => 'rss',
36  ##############################      AdminChangePassword => 'adminchangepasswordform',
37  # dbmopenが使えるなら1、使えないなら0  );
38  my $dbmopen = 0;  my %command_do = (
39  ##############################      read => \&do_read,
40  # データベース名(.pag, .dir, .dbなどは不要)      TEXT_CSS => \&do_output_css,
41  # $dbmopen = 1のときはデータベース名、      edit => \&do_edit,
42  # $dbmopen = 0のときはディレクトリ名になる。      adminedit => \&do_adminedit,
43  my $dbname = './yukiwiki';      adminchangepasswordform => \&do_adminchangepasswordform,
44  my $diffdbname = './yukidiff';      adminchangepassword => \&do_adminchangepassword,
45  ##############################      write => \&do_write,
46  # 修正者の氏名(自由に変更してください)      index => \&do_index,
47  my $modifier = 'Hiroshi Yuki';      searchform => \&do_searchform,
48  ##############################      comment => \&do_comment,
49  # 修正者のWebページ(自由に変更してください)      RandomJump  => \&do_random_jump,
50  my $modifierlink = 'http://www.hyuki.com/';      rss => \&do_rss,
51  ##############################      diff => \&do_diff,
52  # このページのURL      wikiform    => \&do_wikiform,
53  my $thisurl = 'yukiwiki.cgi';      map => \&do_map,
54  ##############################  );
55  # 開始ページ名  my $UA = '';  ## User agent name
56  my $toppage = 'FrontPage';  $| = 1;
57  ##############################  ##############################
58  # 最終更新ページ名  
59  my $whatsnew = 'RecentChanges';  sub main {
60  ##############################      $UA = $main::ENV{HTTP_USER_AGENT};
61  # 最終更新に掲載するページ数      &open_db;
62  my $maxnew = 50;      &init_form;
63  ##############################      if ($command_do{$form{mycmd}}) {
64  # アイコンファイル名(カラー版)          &{$command_do{$form{mycmd}}};
65  my $iconfile = 'yukiwiki.gif';      } else {
66  ##############################          &{$command_do{read}};
67  # アイコンファイル名(モノクロ版)      }
68  # my $iconfile = 'yukimono.gif';      &close_db;
69  ##############################  }
70  # ページを変更したときにtouchするファイル(''なら何もしない)  
71  my $touchfile = 'touch.txt';  sub do_read {
72  ##############################    my $content = $database{$form{mypage}};
73  # プレビュー用の背景色    #print "content-type:text/plain;charset=euc-jp\n\n".gmtime."Get Lastmodified\n";
74  my $preview_color = '#FFCCCC';    my $lm = &get_info($form{mypage}, $info_LastModified);
75  ##############################    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
76  # 全ページのスタイル    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
77  my $style = <<'EOD';    #print gmtime."Search...\n";
78  pre, dl, ul, ol, p, blockquote { line-height:120%; }    my ($r, $c) = get_search_result ($form{mypage});
79  a { text-decoration: none; }    my $rl = wiki::referer::list_html ($form{mypage});
80  a:link { color: #0000FF; background-color: #FFFFFF; }    my @toc;
81  a:visited { color: #9900CC; background-color: #FFFFFF; }    push @toc, qq(-<a href="#wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</a>) if $c;
82  a:hover { text-decoration: underline; }    push @toc, qq(-<a href="#wikipage-referer">@{[&Resource('Referers',escape=>1)]}</a>) if $rl;
83  EOD      my $cf = 'SuikaWiki/0.9';
84  ##############################      ## Should be support at least:
85  # テキスト入力部分の大きさ      ## - 'SuikaWiki/0.9' CRLF
86  my $cols = 80;      ## - 'H2H/' ("0.9" / "1.0" / "1.1") CRLF
87  my $rows = 20;      ## - "/*" WSP* 'W3C-CSS/' ("1.0" / "2.0") "*/" CRLF
88  ##############################      $cf = $1 if $content =~ s#^(?:/\*\s*|[\#<]\?)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+##s;
89  my %form = ();      if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
90  my %database = ();      #print gmtime."Header...\n";
91  my %diffbase = ();        &print_header ($form{mypage}, -last_modified => $lm, -expires => time + 120,
92  my $diff_text = '';          -content_format => $cf, -noindex => ($cf =~ /obsoleted="yes"/ ? 1 : 0));
93  my @diff_added = ();          #print "\n". gmtime."Body...\n";
94  my @diff_deleted = ();        &print_content ($content, content_format => $cf, last_modified => $lm,
95  my $msgrefA;          -toc => \@toc);
96  my $msgrefB;        print &text_to_html (q([[#comment]])) if $cf !~ /obsoleted="yes"/ && !$fixedpage{$form{mypage}};
97  ##############################      } else {
98  # 編集不可ページ名一覧        &print_header($form{mypage}, -expires => time + 120, -last_modified => $lm);
99  my @uneditable = ( $whatsnew );        print "<pre>@{[&escape($content)]}</pre>";
100  ##############################      }
101  # リンク用の正規表現      if ($c) {
102  # YukiWikiのリンクは2種類ある。        print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};
103  #        print $r;
104  # (1) WikiName (RecentChangesとかFrontPageのようなもの)      }
105  # (2) BracketName ([[結城浩]]とか[[トラブルシュート]]のようなもの)      if ($rl) {
106  #        print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
107  # ※シフトJISの2バイト目には ']' が来うるので、      }
108  # 文字']'を1つ多くとるようにしている。          #print "\n". gmtime."Footer...\n";
109  #    &print_footer($form{mypage}, $lm);
110  my $WikiName = '([A-Z][a-z]+([A-Z][a-z]+)+)';          #print "\n". gmtime."Fin...\n";
111  my $BracketName = '\[\[([^>\s]+?\]?)\]\]';  }
112    
113  # アイコン部分のタグ  sub do_output_css {
114  my $IconTag = <<"EOD";    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
115  <a href="http://www.hyuki.com/yukiwiki/"><img src="$iconfile"    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
116   border="0" width="80" height="80" alt="[YukiWiki]" /></a>    my $content = $database{$form{mypage}};
117  EOD    if ($content =~ m#^\s*/\*\s*W3C-CSS#) {
118        my $lm = gmtime &get_info($form{mypage}, $info_LastModified);
119  require "$jcodelib";      print "Content-Type: text/css; charset=@{[&get_charset_name($kanjicode)]}\n";
120        print "Last-Modified: $lm\n";
121  &init_form($kanjicode);      print "Expires: @{[scalar gmtime time+3600]}\n";    ## TODO: don't use asctime
122        print "\n";
123  if ($testing) {      print $content;
124      %form = (    } else {
125          # 'mycmd' => 'write',      print "Status: 406 Unsupported Media Type\n";
126          'mycmd' => 'read',      &print_header('WikiPageIsNotCSS', -noindex => 1);
127          #'mycmd' => 'search',      &print_content($database{WikiPageIsNotCSS});
128          #'mycmd' => 'edit',      &print_footer('WikiPageIsNotCSS');
129          'mymsg' => <<"EOD",    }
130  はじめまして。  }
131  これからいろいろ書き込みますね。  
132  LinkPageも見てください。  sub id_and_name ($) {
133  TestPageはどうでしょうか。      my $name = shift;
134  どうぞよろしく。      if ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer#) {
135  http://www.hyuki.com/        qq{id="$name"><a name="$name"></a};
136  [[結城浩]]      } else {
137  EOD          qq{id="$name"};
138          'mypage' => '<結城浩>',      }
139          'myword' => '結',  }
140          # '3C8C8B8FE98D5F3E' => '',  
141          # 'TestPage' => '',  sub do_edit {
142      );      my ($page) = &unarmor_name(&armor_name($form{mypage}));
143  }      if (not &is_editable($page)) {
144  &main;          &print_header($page, -noindex => 1);
145  exit(0);          &print_message(&Resource('Error:ThisPageIsUneditable'));
146        } elsif (&is_frozen($page)) {
147  # メイン          &print_header($page, -noindex => 1);
148  sub main {          &print_message(&Resource('Error:ThisPageIsUneditable'));
149      &normalize_form;      } else {
150      if ($dbmopen) {          &print_header($page, -noindex => 1, -expires => time+60);
151          if (!dbmopen(%database, $dbname, 0666)) {          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);
152              &print_error("(dbmopen) $dbname が作れません。");      }
153          }      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
154      } else {      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
155          if (!tie(%database, "YukiWikiDB", $dbname)) {      my ($r, $c) = get_search_result ($form{mypage});
156              &print_error("(tie error)");      my $rl = wiki::referer::list_html ($form{mypage});
157          }      if ($c) {
158      }        print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};
159          print $r;
160      # myspecial対応      }
161      foreach (keys %form) {      if ($rl) {
162          if (/^myspecial_(.*)/) {        print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
163              $form{mycmd} = $1;      }
164              last;      &print_footer($page);
165          }  }
166      }  
167    sub do_adminedit {
168      if ($form{mycmd} eq 'read') {      my ($page) = &unarmor_name(&armor_name($form{mypage}));
169          &do_read;      &print_header($page, -noindex => 1);
170      } elsif ($form{mycmd} eq 'preview') {      if (not &is_editable($page)) {
171          &do_preview;          &print_message(&Resource('Error:ThisPageIsUneditable'));
172      } elsif ($form{mycmd} eq 'write') {      } else {
173          &do_write;          &print_message(&Resource('Error:PasswordIsNotSpecified'));
174      } elsif ($form{mycmd} eq 'edit') {          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);
175          &do_edit;      }
176      } elsif ($form{mycmd} eq 'reedit') {      &print_footer($page);
177          &do_reedit;  }
178      } elsif ($form{mycmd} eq 'search') {  
179          &do_search;  sub do_adminchangepasswordform {
180      } elsif ($form{mycmd} eq 'list') {      &print_header('AdminChangePassword', -noindex => 1);
181          &do_list;      &print_passwordform;
182      } elsif ($form{mycmd} eq 'diff') {      &print_footer('AdminChangePassword');
183          &do_diff;  }
184      } else {  
185          $form{mypage} = $toppage;  sub do_adminchangepassword {
186          &do_read;      if ($form{mynewpassword} ne $form{mynewpassword2}) {
187      }          &print_error(&Resource('Error:PasswordMismatch'));
188      if ($dbmopen) {      }
189          dbmclose(%database);      my ($validpassword_crypt) = &get_info($PageName{AdminSpecialPage}, 'AdminPassword');
190      } else {      if ($validpassword_crypt) {
191          untie(%database);          if (not &valid_password($form{myoldpassword})) {
192      }  #            &send_mail_to_admin(<<"EOD", "AdminChangePassword");
193  }  #myoldpassword=$form{myoldpassword}
194    #mynewpassword=$form{mynewpassword}
195  # ページの表示  #mynewpassword2=$form{mynewpassword2}
196  sub do_read {  #EOD
197      my $page_name = $form{mypage};              &print_error(&Resource('Error:PasswordIsIncorrect'));
198      my $percent_name = &encode_percent($page_name);          }
199      &print_header($page_name);      }
200      print qq|<h1>$IconTag<a href="$thisurl?mycmd=search&myword=$percent_name">$page_name</a></h1>\n|;      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
201      &print_toolbar($page_name);      my (@token) = ('0'..'9', 'A'..'Z', 'a'..'z');
202      print &convert_html(&get_page($page_name));      my $salt1 = $token[(time | $$) % scalar(@token)];
203      &print_footer;      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
204  }      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
205        &set_info($PageName{AdminSpecialPage}, 'AdminPassword', $crypted);
206  # ページの編集  
207  sub do_edit {      &print_header('CompletedSuccessfully', -noindex => 1);
208      if (not &is_editable($form{mypage})) {      &print_message(&Resource('Error:PasswordIsChanged'));
209          # 編集不可ページは表示のみ      &print_footer('CompletedSuccessfully');
210          &do_read;  }
211          return;  
212      }  sub do_index {
213      &editpage(&get_page($form{mypage}));    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
214  }    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
215        &print_header($PageName{IndexPage});
216  # ページの再編集      print qq(<ul>);
217  sub do_reedit {      foreach my $page (sort keys %database) {
218      if (not &is_editable($form{mypage})) {          if (&is_editable($page)) {
219          # 編集不可ページは表示のみ              print qq(<li><a href="$url_cgi?@{[&encode($page)]}">@{[&escape($page)]}</a>@{[&escape(&get_subjectline($page))]}</li>);
220          &do_read;          }
221      } else {      }
222          &editpage($form{mymsg});      print qq(</ul>);
223      }      my ($r, $c) = get_search_result ($form{mypage});
224  }      if ($c) {
225          print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};
226  sub editpage {        print $r;
227      my $page_msg = shift;      }
228      my $page_name = $form{mypage};      my $rl = wiki::referer::list_html ($form{mypage});
229      my $digest = &calc_message_digest($page_msg);      if ($rl) {
230      &print_header($page_name);          print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
231      print qq|<h1>$IconTag${page_name}の編集</h1>\n|;      }
232      &print_toolbar($page_name);      &print_footer($PageName{IndexPage});
233      $page_msg = &escape($page_msg);  }
234      print <<"EOD";  
235  <form action="$thisurl" method="post">  sub do_write {
236  <input type="hidden" name="mycmd" value="preview">      if (&frozen_reject()) {
237  <input type="hidden" name="mypage" value="$page_name">          return;
238  <input type="hidden" name="mydigest" value="$digest">      }
239  <textarea cols="$cols" rows="$rows" name="mymsg" wrap="virtual">$page_msg</textarea><br>  
240  <input type="submit" value="プレビュー">      if (not &is_editable($form{mypage})) {
241  </form>          &print_header($form{mypage}, -noindex => 1);
242  <hr>          &print_message(&Resource('Error:ThisPageIsUneditable'));
243  <h3>テキスト整形のルール</h3>          &print_footer($form{mypage});
244            return;
245  <p>通常は入力した文字がそのまま出力されますが、      }
246  以下のルールに従ってテキスト整形を行うことができます。</p>  
247        if (&conflict($form{mypage}, $form{mymsg})) {
248  <ul>          return;
249  <li>      }
250  空行は段落の区切りとなります。  
251        # Making diff
252  <li>      {
253  HTMLのタグは書けません。          &open_diff;
254            my @msg1 = split(/\n/, $database{$form{mypage}});
255  <li>          my @msg2 = split(/\n/, $form{mymsg});
256  ''ボールド''のようにシングルクォート二つではさむと、ボールドになります。          $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);
257            &close_diff;
258  <li>      }
259  '''イタリック'''のようにシングルクォート三つではさむと、イタリックになります。  
260        if ($form{mymsg}) {
261  <li>          $database{$form{mypage}} = $form{mymsg};
262  ----のようにマイナス4つがあると、水平線になります。          #&send_mail_to_admin($form{mypage}, "Modify");
263            if ($form{mytouch}) {
264  <li>              &set_info($form{mypage}, $info_LastModified, time);
265  *を行頭に書くと大見出しになります。              &update_recent_changes;
266            }
267  <li>          &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});
268  **を行頭に書くと小見出しになります。          my $fragment = '';
269            $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
270  <li>          if ($form{__comment_anchor_index}) {
271  -を行頭に書くと箇条書きになります。- -- --- の3レベルがあります。              $fragment .= qq(#anchor-$form{__comment_anchor_index});
272            } elsif ($form{__wikiform_anchor_index}) {
273  <li>              $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
274  :を行頭に書くと用語と解説文が作れます。          }
275            &print_header('CompletedSuccessfully', -noindex => 1, -goto => $url_cgi.'?mycmd='.&encode($form{after_edit_cmd}||'read').';mypage='.&encode($form{mypage}).qq(;x-param=@{[time.[0..9]->[rand 10]]}$fragment));
276  <pre>          &print_message(&Resource('Error:SavedSuccessfully'));
277      :用語1:いろいろ書いた解説文1          &print_content(&Resource('Error:ContinueReading')." @{[&armor_name($form{mypage})]}");
278      :用語2:いろいろ書いた解説文2          &print_footer('CompletedSuccessfully');
279      :用語3:いろいろ書いた解説文3      } else {
280  </pre>          #&send_mail_to_admin($form{mypage}, "Delete");
281            delete $database{$form{mypage}};
282  <li>          delete $infobase{$form{mypage}};
283  http://www.hyuki.com/ のようなURLは自動的にリンクになります。          if ($form{mytouch}) {
284                &update_recent_changes;
285  <li>          }
286  YukiWikiのように大文字小文字を混ぜた英文字列を書くと、          &print_header($form{mypage}, -noindex => 1);
287  YukiWikiのページ名になります。          &print_message(&Resource('Error:PageIsDeletedSuccessfully'));
288            &print_footer($form{mypage});
289  <li>      }
290  [[結城浩]]のように二重の大かっこ[[ ]]でくくった文字列を書くと、  }
291  YukiWikiのページ名になります。  
292  大かっこの中にはスペースを含めてはいけません。  sub get_search_result ($;%) {
293  日本語も使えます。    my $word = lc shift;
294      my %option = @_;
295  <li>    my @r;
296  行頭がスペースで始まっていると、    foreach my $page (keys %database) {
297  その段落は整形済み扱われます。      next if !$option{-match_myself} && ($page eq $word);
298  プログラムを書き込むときに使うと便利です。      my $content = lc $database{$page};
299        if (index (lc $page, $word) > -1) {
300  <li>        my $c = $content =~ s/\Q$word\E//g;
301  > を行頭に書くと、        push @r, [$page, $c+20];
302  引用文が書けます。      } elsif (index ($word, lc $page) > -1) {
303  >の数が多いとインデントが深くなります(3レベルまで)。        my $c = $content =~ s/\Q$word\E//g;
304          push @r, [$page, $c+10];
305  </ul>      } elsif (my $c = $content =~ s/\Q$word\E//g) {
306  EOD        push @r, [$page, $c];
307      &print_footer;      }
308  }    }
309      #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
310  # ページの検索    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;
311  sub do_search {    $r = qq|<ul class="search-result">$r</ul>| if $r;
312      if ($form{myword}) {    wantarray? ($r, scalar @r): $r;
313          &print_header('検索結果');  }
314          print qq|<h1>$IconTag$form{myword}の検索結果</h1>\n|;  
315          &print_toolbar();  sub do_random_jump {
316          print qq|<ul>\n|;    my @list = keys %database;
317          my $count = 0;    my $name = &encode ($list[rand @list]);
318          foreach my $page_name (sort keys %database) {    # sortするのは無謀かな    my $scheme = 'http';
319              if ($database{$page_name} =~ /\Q$form{'myword'}\E/) {    $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
320                  my $encoded = &encode_percent($page_name);    print "Location: $scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi?$name\n";
321                  print qq|<li><a href="$thisurl?mycmd=read&mypage=$encoded">$page_name</a>\n|;    print "\n";
322                  $count++;  }
323              }  
324          }  sub print_error {
325          print qq|</ul>\n|;      my ($msg) = @_;
326          if ($count > 0) {      &print_header($PageName{ErrorPage}, -noindex => 1);
327              print qq|<p><b>$form{myword}</b>を含むページは、上に示す<b>$count</b>ページです。</p>\n|;      print qq(<p><strong class="error">$msg</strong></p>);
328          } else {      &print_footer($PageName{ErrorPage});
329              print qq|<p><b>$form{myword}</b>を含むページは見つかりません。</p>\n|;      exit(0);
330          }  }
331      } else {  
332          &print_header('単語検索');  sub print_header ($;%) {
333          print qq|<h1>$IconTag単語検索</h1>\n|;      my ($page, %option) = @_;
334          &print_toolbar();      my @head;
335      }      $option{body_class} = &is_frozen($page) ? 'frozen' : 'normal';
336      print <<"EOD";      $option{body_class} .= " wiki-page-obsoleted" if $option{-content_format} =~ /obsoleted="yes"/;
337  <p>      if ($option{-goto}) {
338  <form action="$thisurl" method="post">        if ($UA =~ m#Opera|MSIE 2\.#) {
339  <input type="hidden" name="mycmd" value="search">            ## WARNING: This code may output unsafe HTML document if
340  <input type="text" name="myword" size="20" value="$form{myword}">            ##          $option{-goto} is not clean.
341  <input type="submit" value="単語検索">            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
342  </form>            print qq{Refresh: 0; url=$option{-goto}\n};
343  </p>            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
344  EOD        } else {
345      &print_footer;            $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
346  }            print qq{Refresh: 0; url="$option{-goto}"\n};
347              push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;">);
348  # ページの一覧        }
349  sub do_list {      }
350      &print_header('ページ一覧');      print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
351      print qq|<h1>$IconTag ページ一覧</h1>\n|;      if ($option{-expires}) {
352      &print_toolbar();        print qq{Expires: @{[scalar gmtime $option{-expires}]}\n};
353      print qq|<ul>\n|;      }
354      foreach my $page_name (sort keys %database) {    # sortするのは無謀かな      if ($UA =~ m#Mozilla/2#) {
355          my $encoded = &encode_percent($page_name);          my $ct = qq{text/html; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
356          print qq|<li><a href="$thisurl?mycmd=read&mypage=$encoded">$page_name</a>\n|          print qq{Content-Type: $ct\n};
357      }          push @head, qq{<meta http-equiv="content-type" content="$ct">};
358      print qq|</ul>\n|;      } elsif ($UA =~ m#Infomosaic#) {
359      &print_footer;          print qq{Content-Type: text/html\n};
360  }      } else {
361            print qq{Content-Type: text/html; charset=@{[&get_charset_name($kanjicode)]}\n};
362  # プレビュー      }
363  sub do_preview {      push @head, qq(<title>@{[&escape($page)]}</title>);
364      my $page_name = $form{mypage};      if ($UA !~ m#Mozilla/[1-4]\.# || $UA =~ m#MSIE (?:[4-9]\.|\d\d)#) {
365      my $escapedmsg = &escape($form{mymsg});        push @head, qq(<link rel="stylesheet" type="text/css" href="@{[&escape($uri{wiki}.'?mycmd=TEXT_CSS;mypage='.&encode($PageName{DefaultStyleForHTML}).';x-lm='.&get_info($PageName{DefaultStyleForHTML}, $info_LastModified))]}");
366      &print_header($page_name);      }
367      print qq|<h1>$IconTag${page_name}のプレビュー</h1>\n|;      push @head, q(<meta name="ROBOTS" content="NOINDEX">) if $option{-noindex};
368      &print_toolbar($page_name);      my ($Links, $links) = &make_navigate_links ($page);
369      # local $percent_name = &encode_percent($page_name);      #print $Links;      ## Link: fields
370      print qq|<p>以下のプレビューを確認して、よければページ下部のボタンで更新してください。</p>\n|;      $links = join "\n", (@head, $links);
371      if ($form{mymsg}) {      print <<"EOD";
372          print qq|<table width="100%" bgcolor="$preview_color" ><tr><td>\n|;  Content-Language: $lang
373          # print &convert_html($escapedmsg);  Content-Style-Type: text/css
374          print &convert_html($form{mymsg});  
375          print qq|</td></tr></table>\n|;  <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
376      } else {  "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->
377          print qq|<p>(ページの内容は空です。更新するとこのページは<b>削除</b>されます。)</p>\n|;  <html lang="$lang" class="$option{body_class}">
378      }  <head profile="http://suika.fam.cx/~wakaba/-temp/wiki/wiki?WikiHTMLMetaProfile">
379      &print_preview_buttons($page_name, $escapedmsg, $form{mydigest});  $links
380      &print_footer;  </head>
381  }  <body class="$option{body_class}">
382    EOD
383  sub print_preview_buttons {      &print_navigate_links ($page);
384      my ($page_name, $escapedmsg, $digest) = @_;      print <<EOD;
385      print <<"EOD";  <h1 class="header">@{[&escape($page)]}</h1>
386      <form action="$thisurl" method="post">  EOD
387      <textarea cols="$cols" rows="$rows" name="mymsg" wrap="virtual">$escapedmsg</textarea>  }
388      <br />  
389      <input type="hidden" name="mypage" value="$page_name">  sub get_charset_name ($;%) {
390      <input type="hidden" name="mydigest" value="$digest">      my ($charset, %option) = (lc shift, @_);
391      <input type="submit" name="myspecial_preview" value="再度プレビュー">      if ($charset =~ 'euc') {
392      <input type="submit" name="myspecial_write" value="ページの更新">          $charset = $option{compatible} ? 'x-euc-jp' : 'euc-jp';
393      </form>      } elsif ($charset =~ 'sjis' || $charset =~ 'shift') {
394  EOD          $charset = $option{compatible} ? 'x-sjis' : 'shift_jis';
395  }      } elsif ($charset =~ 'jis') {
396            $charset = 'iso-2022-jp';
397  # 書き込む      }
398  sub do_write {      $charset;
399      if (not &is_editable($form{mypage})) {  }
400          # 編集不可ページは表示のみ  
401          &do_read;  sub print_navigate_links (@) {
402          return;    my ($page) = @_;
403      }    my $editable = (&is_editable($page) && !&is_frozen($page)) ? 1 : 0;
404      my $cookedpage = &encode($page);
405      my $page_name = $form{mypage};    print <<EOH;
406    <div class="tools">
407      # digestを使って、更新の衝突チェック      @{[ $editable
408      my $original_digest = &calc_message_digest(&get_page($page_name));          ? qq(<a title="@{[&Resource('EditThisPageLong',escape=>1)]}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E" class="wiki-cmd">@{[&Resource('EditThisPage',escape=>1)]}</a> | )
409      if ($form{mydigest} ne $original_digest) {          : qq()
410          &print_header($page_name);      ]}
411          print qq|<h1>$IconTag${page_name}で【更新の衝突】が起きました</h1>\n|;      <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> |
412          print <<"EOD";      <a href="$url_cgi?mycmd=map;mypage=$cookedpage" class="wiki-cmd" title="@{[&Resource('ShowMapOfThisPageLong',escape=>1)]}">@{[&Resource('ShowMapOfThisPage',escape=>1)]}</a> |
413  <p>あなたがこのページを編集している間に、      <a href="$url_cgi?$PageName{CreatePage}" class="wiki" title="@{[&Resource('GoToCreatePageLong',escape=>1)]}">@{[&Resource('GoToCreatePage',escape=>1)]}</a> |
414  他の人が同じページを更新してしまったようです。      <a href="$url_cgi?$PageName{IndexPage}" class="wiki" title="@{[&Resource('GoToIndexPageLong',escape=>1)]}">@{[&Resource('GoToIndexPage',escape=>1)]}</a> |
415  </p><p>      <a href="$url_cgi?$PageName{FrontPage}" class="wiki" title="@{[&Resource('GoToHomePageLong',escape=>1)]}">@{[&Resource('GoToHomePage',escape=>1)]}</a> |
416  以下に、あなたの編集したテキストがありますので、      <a href="$url_cgi?$PageName{SearchPage}" class="wiki" title="@{[&Resource('GoToSearchPageLong',escape=>1)]}">@{[&Resource('GoToSearchPage',escape=>1)]}</a> |
417  あなたの編集内容が失われないように、      <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> |
418  いますぐ、メモ帳などにコピー&ペーストしてください。      <a href="$url_cgi?RecentChanges" class="wiki" title="@{[&Resource('GoToRecentChangesLong',escape=>1)]}">@{[&Resource('GoToRecentChanges',escape=>1)]}</a>
419  </p><p>  </div>
420  コピー&ペーストが済んでから、  EOH
421  最新の内容を見て再度編集し直してください。  }
422  最新の内容は  
423  <a target="_blank" href="$thisurl?mycmd=read&mypage=$form{mypage}">$form{mypage}</a>  sub make_navigate_links ($) {
424  で見ることができます。      my $page = shift;
425  </p>      my @link;
426  EOD      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);
427          # &print_toolbar($page_name);      push @link, {rel=>'edit', href=>"$url_cgi?mycmd=adminedit;mypage=@{[&encode($page)]}", class=>"wiki-command", title=>&Resource('AdminEditThisPageLink')} if &is_editable ($page) || &is_frozen ($page);
428          &print_preview_buttons($page_name, &escape($form{mymsg}), $form{mydigest});      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')};
429          &print_footer;      push @link, {rel=>'myself', href=>"$url_cgi?@{[&encode($page)]}", class=>'wiki', title=>&Resource('GoToMyselfLink')};
430          return;      push @link, {rel=>'index', href=>"$url_cgi?$PageName{IndexPage}", class=>'wiki', title=>&Resource('GoToIndexPageLink')};
431      }      push @link, {rel=>'home', href=>"$url_cgi?$PageName{FrontPage}", class=>'wiki', title=>&Resource('GoToHomePageLink')};
432        push @link, {rel=>'News', href=>"$url_cgi?WikiNews", class=>'wiki', title=>&Resource('GoToWikiNewsLink')};
433      # diff生成      push @link, {rel=>'News', href=>"$url_cgi?RecentChanges", class=>"wiki", title=>&Resource('GoToRecentChangesLink')};
434      {      push @link, {rel=>'News', href=>"$url_cgi?$PageName{RssPage}", class=>"wiki", title=>&Resource('GoToRssPageLink'), type=>'application/xml'};
435          &opendiff;      push @link, {rel=>'search', href=>"$url_cgi?$PageName{SearchPage}", class=>'wiki', title=>&Resource('GoToSearchPageLink')};
436          my @msg1 = split(/\n/, &get_page($page_name));      push @link, {rel=>'help', href=>"$url_cgi?WikiHelp", class=>'wiki', title=>&Resource('GoToWikiHelpLink')};
437          my @msg2 = split(/\n/, $form{mymsg});      push @link, {rel=>'copyright', href=>"$url_cgi?WikiPageLicense", class=>'wiki', title=>&Resource('GoToWikiPageLicenseLink')};
438          $msgrefA = \@msg1;      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')};
439          $msgrefB = \@msg2;      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')};
440          &diff_check;      push @link, {rel=>'lucky', href=>"$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}", class=>'wiki randomlink', title=>&Resource('GoSomewhereLink')};
441          $diffbase{$form{mypage}} = $diff_text;      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};
442          $diff_text = '';      push @link, {rel=>'history', href=>"$url_cgi?mycmd=diff;mypage=@{[&encode($page)]}", title=>&Resource('ViewDiffOfThisPageLink'), class=>'wiki-command'};
443          &closediff;      push @link, {rel=>'contents', href=>"$url_cgi?mycmd=map;mypage=@{[&encode($page)]}", title=>&Resource('ShowMapOfThisPageLink'), class=>'wiki-command'};
444      }      my ($Links, $links) = ('', '');
445        for my $e (@link) {
446      &print_header($page_name);          $links .= qq(<link);
447      &set_page($page_name, $form{mymsg});          $Links .= qq(Link: <$e->{href}>);
448      if ($form{mymsg}) {          for my $attr (qw/rel rev href title class type hreflang charset/) {
449          print qq|<h1>$IconTag${page_name}を更新しました</h1>\n|;              $links .= qq( $attr="@{[&escape($e->{$attr})]}") if $e->{$attr};
450          &print_toolbar($page_name);          }
451          print &convert_html(&get_page($page_name));          for my $attr (qw/rel rev title/) {
452      } else {              $Links .= qq(; $attr="@{[do{$e->{$attr} =~ s/([\\\"])/\\$1/g; $e->{$attr}}]}") if $e->{$attr};
453          print qq|<h1>$IconTag${page_name}を削除しました</h1>\n|;          }
454          &print_toolbar($page_name);          $links .= qq(>\n);
455          print qq|<p>${page_name}を削除しました。</p>\n|;          $Links .= qq(\n);
456      }      }
457      &print_footer;      wantarray ? ($Links, $links) : $Links;
458      # 更新されたのでタッチしておく。  }
459      if ($touchfile) {  
460          open(FILE, "> $touchfile");  sub print_footer {
461          print FILE "\n";      my ($page, $lm) = @_;
462          close(FILE);      my $epage = &encode ($page);
463      }    my $cvslog1 = q$Revision$;
464  }    my $cvslog2 = q$Date$;
465      print_navigate_links ($page);
466  # ページの変更点    print <<"EOD";
467  sub do_diff {  @{[ $lm ? qq(<div id="wikipage-last-modified">@{[&Resource('LastModified=',escape=>1)]}@{[&_rfc3339_date ($lm)]}</div>) : '' ]}
468      if (not &is_editable($form{mypage})) {  <div class="footer">
469          # 編集不可ページは表示のみ  <a href="http://www.hyuki.com/yukiwiki/" title="YukiWiki 2.0.beta1.2002-05-29 &copy; 2000-2002 by Hiroshi Yuki">@{[&Resource('About:Name:YukiWiki',escape=>1)]}</a> <a href="http://digit.que.ne.jp/work/" title="WalWiki 2.0.beta1.wal.1 &copy; 2000-2002 by Makio Tsukamoto">@{[&Resource('About:Name:WalWiki',escape=>1)]}</a>
470          &do_read;  <a href="/gate/cvs/wakaba/wiki/" title="@{[&Resource('About:SuikaWiki:JumpToCVS',escape=>1)]} ($cvslog2)">@{[&Resource('About:Name:SuikaWiki',escape=>1)]} $cvslog1</a>
471          return;  </div>
472      }  </body>
473      &opendiff;  </html>
474      &print_header($form{mypage} . 'の変更点');  EOD
475      print qq|<h1>$IconTag <a href="$thisurl?mycmd=read&mypage=$form{mypage}">$form{mypage}</a>の変更点</h1>\n|;  }
476      &print_toolbar();  
477      $_ = &escape($diffbase{$form{mypage}});  sub escape {
478      print <<"EOD";      my $s = shift;
479  <ul>      $s =~ s|\r\n|\n|g;
480  <li>追加された行は<font color="blue">青色</font>です。      $s =~ s|&|&amp;|g;
481  <li>削除された行は<font color="red">赤色</font>です。      $s =~ s|<|&lt;|g;
482  <li><a href="$thisurl?mycmd=read&mypage=$form{mypage}">$form{mypage}</a>へ行く。      $s =~ s|>|&gt;|g;
483  </ul>      $s =~ s|"|&quot;|g;
484  <hr />      return $s;
485  EOD  }
486      print qq|<pre>\n|;  
487      foreach (split(/\n/, $_)) {  sub unescape {
488          if (/^\+(.*)/) {      my $s = shift;
489              print qq|<font color="blue">$1</font>\n|;      # $s =~ s|\n|\r\n|g;
490          } elsif (/^\-(.*)/) {      $s =~ s|&lt;|<|g;
491              print qq|<font color="red">$1</font>\n|;      $s =~ s|&gt;|>|g;
492          } elsif (/^\=(.*)/) {      $s =~ s|&quot;|"|g;
493              print qq|$1\n|;      $s =~ s|&amp;|&|g;
494          } else {      return $s;
495              print qq|??? $_\n|;  }
496          }  
497      }  sub print_content ($;$) {
498      print qq|</pre>\n|;      my ($rawcontent, %option) = @_;
499      &print_footer;      print &text_to_html($rawcontent, toc=>1, %option);
500      &closediff;  }
501  }  
502    sub text_to_html {
503  sub opendiff {      my ($txt, %option) = @_;
504      if ($dbmopen) {      my @toc;
505          if (!dbmopen(%diffbase, $diffdbname, 0666)) {      my @toc2 = @{$option{-toc}||[]};
506              &print_error("(dbmopen) $diffdbname が作れません。");      my $tocnum = 0;
507          }      
508      } else {      ## Load constants
509          if (!tie(%diffbase, "YukiWikiDB", $diffdbname)) {      my %const;
510              &print_error("(tie error)");      if ($option{content_format} =~ /import="([^"]+)"/) {
511          }        for (split /\s*,\s*/, $1) {
512      }          my $wp = $database{$_};
513  }          if ($wp =~ m!^\#\?SuikaWikiConst/1.0!) {
514              wiki::suikawikiconst::to_hash ($wp => \%const);
515  sub closediff {          }
516      if ($dbmopen) {        }
517          dbmclose(%diffbase);      }
518      } else {      
519          untie(%diffbase);      $txt =~ s{__&&([^&]+)&&__}{defined $const{$1}?$const{$1}:qq(__&&$1&&__)}ge;
520      }      my (@txt) = split(/\n/, $txt);
521  }      my (@saved, @result);
522        unshift(@saved, "</p>");
523  # フォームからの情報を連想配列 %form に入れる      push(@result, "<p>");
524  # &init_form('euc');      foreach (@txt) {
525  sub init_form {          chomp;
526      my ($charcode) = @_;          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
527      my $query;              push(@toc, qq(----- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
528      if ($ENV{REQUEST_METHOD} =~ /^post$/i) {              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h6>');
529          read(STDIN, $query, $ENV{CONTENT_LENGTH});              $tocnum++;
530      } else {          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
531          $query = $ENV{QUERY_STRING};              push(@toc, qq(---- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
532      }              push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h5>');
533      my @assocarray = split(/&/, $query);              $tocnum++;
534      foreach my $assoc (@assocarray) {          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
535          my ($property, $value) = split(/=/, $assoc);              push(@toc, qq(--- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
536          $value =~ tr/+/ /;              push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h4>');
537          $value =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;              $tocnum++;
538          &jcode::convert(\$value, $charcode);          } elsif (/^\*\*([^\x0D\x0A]*)/) {
539          $form{$property} = $value;          # if (/^\*\*(.*)/) {
540      }          # Walrus mod (6) end
541  }              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
542                push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h3>');
543  # エラーページを出力する              $tocnum++;
544  sub print_error {          } elsif (/^\*([^\x0D\x0A]*)/) {
545      my ($msg) = @_;              push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
546      &print_header('Error');              push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h2>');
547      print "<h1>$IconTag$msg</h1></body></html>";              $tocnum++;
548      exit(0);          } elsif (/^(={1,6})(.*)/) {
549  }              &back_push('ol', length($1), \@saved, \@result);
550                push(@result, '<li>' . &inline($2, const => \%const) . '</li>');
551  sub escape {          } elsif (/^(-{1,6})(.*)/) {
552      my ($line) = shift;            &back_push('ul', length($1), \@saved, \@result);
553      $line =~ s|<|&lt;|g;            my ($pf, $l) = ('', $2);
554      $line =~ s|>|&gt;|g;            if (!$main::_EMBEDED && $l =~ s/^\s*\[([0-9]+)\]//) {
555      $line =~ s|"|&quot;|g;              my $num = 0+$1;
556      # $line =~ s|\&|&amp;|g;              $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
557      return $line;            }
558  }            push(@result, '<li>' . $pf . &inline ($l, const => \%const) . '</li>');
559            } elsif (/^:([^:]+):(.*)/) {
560  sub inline {              &back_push('dl', 1, \@saved, \@result);
561      my ($line) = shift;              push(@result, '<dt>' . &inline($1, const => \%const) . '</dt>', '<dd>' . &inline($2, const => \%const) . '</dd>');
562      $line = &escape($line);          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
563      $line =~ s|'''([^']+?)'''|<i>$1</i>|g;              # Italic              &back_push('blockquote', length($1), \@saved, \@result);
564      $line =~ s|''([^']+?)''|<b>$1</b>|g;                # Bold              push @result, "<p>";
565      $line =~ s!              push(@result, &inline($2, const => \%const));
566                  (              unshift @saved, "</p>";
567                      ((mailto|http|https|ftp):[\x21-\x7E]*) # Direct http://...          } elsif (/^\s*$/) {
568                          |              push(@result, splice(@saved));
569                      ($WikiName)                         # LocalLinkLikeThis              push(@result, "<p>");
570                          |              unshift(@saved, "</p>");
571                      ($BracketName)                      # [[日本語リンク]]          } elsif (/^(\s+.*)$/) {
572                  )              &back_push('pre', 1, \@saved, \@result);
573              !              push(@result, &inline($1, const => \%const));
574                  &make_link($1)          } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
575              !gex;              &back_push('table', 1, \@saved, \@result);
576      return $line;              #######
577  }              # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.
578                # XXXXX
579  # ページのタイトルからページの内容を得る              my $tmp = "$1,";
580  sub get_page {              my @value = map {/^"(.*)"$/ ? scalar($_ = $1, s/""/"/g, $_) : $_} ($tmp =~ /("[^"]*(?:""[^"]*)*"|[^,]*),/g);
581      my $page_name = shift;              my @align = map {(s/^\s+//) ? ((s/\s+$//) ? ' align="center"' : ' align="right"') : ''} @value;
582      return $database{$page_name};              my @colspan = map {($_ eq '==') ? 0 : 1} @value;
583  }              for (my $i = 0; $i < @value; $i++) {
584                    if ($colspan[$i]) {
585  # ページの内容を与える                      while ($i + $colspan[$i] < @value and $value[$i + $colspan[$i]] eq '==') {
586  # &set_page($title, $txt)                          $colspan[$i]++;
587  sub set_page {                      }
588      # ページを更新する                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
589      my $title = $_[0];                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], const => \%const));
590      $database{$title} = $_[1];                  } else {
591      # 空ページなら削除する                      $value[$i] = '';
592      unless ($database{$title}) {                  }
593          delete $database{$title};              }
594      }              push(@result, join('', '<tr>', @value, '</tr>'));
595      # RecentChangesを更新する              # XXXXX
596      my $delim = ' - ';              #######
597      my @pages = split(/\n/, $database{$whatsnew});          } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
598      my $datestr = &get_current_datestr;              push @result, splice (@saved), '<'.lc($1).'>';
599      unshift(@pages, qq|-$datestr$delim$title|);              unshift @saved, "</p>";
600      # 同一ページの更新は最新のもののみにし、              push @result, "<p>";
601      # 存在しないページはスキップする。          } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
602      my %count;              push @result, splice (@saved), '</'.lc($1).'>';
603      my @newpages;          } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
604      foreach my $line (@pages) {            my $num = 0+$1;
605          my ($prefix, $title) = split(/$delim/, $line);            push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
606          $count{$title}++;            push @result, &inline ($2, const => \%const);
607          if ($count{$title} == 1 and exists($database{$title})) {          } else {
608              push(@newpages, qq|$prefix - $title|);              push(@result, &inline($_, const => \%const));
609          }          }
610      }      }
611      # ここで本当に更新      push(@result, splice(@saved));
612      $database{$whatsnew} = join("\n", splice(@newpages, 0, $maxnew));      
613  }      my $toc = '';
614        if ($option{toc}) {
615  # ページのヘッダを出力          # Convert @toc (table of contents) to HTML.
616  sub print_header {          # This part is taken from Makio Tsukamoto's WalWiki.
617      my $title = shift;          my (@tocsaved, @tocresult);
618      print <<"EOD";          foreach (@toc,@toc2) {
619  Content-type: text/html              if (/^(-{1,6})(.*)$/) {
620                    &back_push('ul', length($1), \@tocsaved, \@tocresult);
621  <html><head>                  push(@tocresult, '<li>' . $2 . '</li>');
622  <title>$title</title>              }
623  <style type="text/css">          }
624  <!--          push(@tocresult, splice(@tocsaved));
625  $style          $toc = join("\n", @tocresult);
626  -->          $toc = $toc ? qq(<div id="wikipage-toc">$toc</div>) : '';
627  </style>      }
628  </head>      $toc .= join("\n", @result);
629  <body bgcolor="white">      $toc =~ s#<p>\n</p>##g;
630  EOD      $toc =~ s#[\x0D\x0A]+</#</#g;
631  }      $toc =~ s#<pre>\n#<pre>#g;
632        $toc;
633  # ツールバーを出力  }
634  sub print_toolbar {  
635      my $page_name = shift;  sub back_push {
636      my $percent_name = &encode_percent($page_name);      my ($tag, $level, $savedref, $resultref, $attr) = @_;
637      my $editlink = '';      while (@$savedref > $level) {
638      if ($page_name ne '' and &is_editable($page_name)) {          push(@$resultref, shift(@$savedref));
639          $editlink = <<"EOD";      }
640  <a href="$thisurl?mycmd=edit&mypage=$percent_name">編集</a> |      if ($savedref->[0] ne "</$tag>") {
641  <a href="$thisurl?mycmd=diff&mypage=$percent_name">差分</a> |          push(@$resultref, splice(@$savedref));
642  EOD      }
643      }      while (@$savedref < $level) {
644      print <<"EOD";          unshift(@$savedref, "</$tag>");
645  <p>          push(@$resultref, "<$tag$attr>");
646   [      }
647  <a href="$thisurl?mycmd=read&mypage=$toppage">トップ</a> |  }
648  <a href="$thisurl?mycmd=list">一覧</a> |  
649  $editlink  sub inline ($;%) {
650  <a href="$thisurl?mycmd=search">単語検索</a> |      my ($line, %option) = @_;
651  <a href="$thisurl?mycmd=read&mypage=$whatsnew">最終更新</a>      $line = &escape($line);
652   ]      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4)}ge;
653  </p>      $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;
654  EOD      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
655  }      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
656        $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;
657  # ページのフッタを出力      $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
658  sub print_footer {      $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;
659      print <<"EOD";      $line =~ s%\[Q\[([^]]+)\](?: \[&lt;([\x21-\x5A\x5E-\x7E]+)&gt;\])?\]%。ヨ<q@{[$2?qq( cite="$2"):'']}>$1</q>。ラ%g;
660  <hr>      $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
661  <p>      $line =~ s|''([^']+)''|<em>$1</em>|g;
662  <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version Copyright (C) 2000,2001 by <a href="http://www.hyuki.com/">Hiroshi Yuki.</a><br />      $line =~ s{
663  Modified by <a href="$modifierlink">$modifier</a>.<br/>        (\[\[(\#\S+?)\]\])
664  </p>        |\[\[([^[]+?)](?:&gt;&gt;([0-9]+))?]
665  </body></html>        |&gt;&gt;([0-9]+)
666  EOD        |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
667  }      }{
668          my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
669  # URLやページの名前からリンクを作る        if ($l) {
670  sub make_link {          return &embedded_to_html($1);
671      my $name = shift;        } elsif (defined $page) {
672      if ($name =~ /^(http|https|ftp).*?(\.gif|\.png|\.jpeg|\.jpg)?$/) {          &make_wikilink ($page, anchor => 0+$anchor);
673          if ($2) {        } elsif ($anum) {
674              return qq|<a href="$name"><img border="0" src="$name" /></a>|;          qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
675          } else {        } elsif ($uri) {
676              return qq|<a href="$name">$name</a>|;          &make_urilink ($uri);
677          }        }
678      } elsif ($name =~ /^mailto:(.*)/) {      }gex;
679          my $address = $1;      return $line;
680          return qq|<a href="$name">$address</a>|;  }
681      } elsif ($database{$name}) {  
682          my $percent_name = &encode_percent($name);  sub make_wikilink ($%) {
683          return qq|<a href="$thisurl?mycmd=read&mypage=$percent_name">$name</a>|;    my ($ename, %option) = @_;
684      } else {    my $name = &unescape ($ename);
685          my $percent_name = &encode_percent($name);    if ($database{$name}) {
686          return qq|$name<a href="$thisurl?mycmd=edit&mypage=$percent_name">?</a>|;      my $subject = &escape (&get_subjectline ($name, delimiter => ''));
687      }      if ($option{anchor}) {
688  }        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
689        } else {
690  # %xx の形式にエンコードする        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}" class="wiki">$ename</a>);
691  # これは、      }
692  # http://www.hyuki.com/yukiwiki/yukiwiki.cgi?mycmd=read&mypage=%3C%8C%8B%8F%E9%8D_%3E    } else {
693  # という形式のために使われる。      return qq(<a title="@{[&Resource('JumpAndEditWikiPage',escape=>1)]}" href="$url_cgi?@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">@{[&Resource('JumpAndEditWikiPageMark',escape=>1)]}</span></a>);
694  # '<結城浩>' → '%3C%8C%8B%8F%E9%8D_%3E'    }
695  sub encode_percent {  }
696      my $name = shift;  
697      my $encoded = '';  sub make_urilink ($;%) {
698      foreach my $ch (split(//, $name)) {    require URI;
699          if ($ch =~ /[A-Za-z0-9_]/) {    my $uri = shift;
700              $encoded .= $ch;    if ($uri =~ s/^IW://) {       ## InterWiki (not URI)
701          } else {      $uri = &unescape ($uri);
702              $encoded .= '%' . sprintf("%02X", ord($ch));      if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
703          }        my ($site, $name) = ($1, $2);
704      }        for ($site, $name) {
705      return $encoded;          if (s/^"//) { s/"$//; s/\\(.)/$1/g }
706  }        }
707          &init_InterWikiName () unless $interwiki{'[[]]'};
708  # テキスト本体をHTMLに変換する        if ($interwiki{$site}) {
709  sub convert_html {          &load_formatter ('interwiki');
710      my ($txt) = shift;          my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
711      my (@txt) = split(/\n/, $txt);          $site = &escape ($site); $name = &escape ($name);
712      foreach (@txt) {          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;);
713          chomp;        } else {
714          if (/^\*\*(.*)/) {          qq(&lt;@{[&Resource('Error:UnknownInterWikiName=',escape=>1)]}@{[&escape ($site)]}&gt;);
715              push(@result, splice(@saved), '<h3>' . &inline($1) . '</h3>');        }
716          } elsif (/^\*(.*)/) {      } else {
717              push(@result, splice(@saved), '<h2>' . &inline($1) . '</h2>');        qq(&lt;@{[&Resource('Error:InvalidInterWiki=',escape=>1)]}@{[&escape($uri)]}&gt;);
718          } elsif (/^----/) {      }
719              push(@result, splice(@saved), '<hr>');    } elsif ($uri =~ /^urn:/) {   ## URN
720          } elsif (/^(-{1,3})(.*)/) {      my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
721              &back_push('ul', length($1));      qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
722              push(@result, '<li>' . &inline($2) . '</li>');    } elsif ($uri =~ s/^MAIL://) {        ## mail address (not URI)
723          } elsif (/^:([^:]+):(.*)/) {      my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
724              &back_push('dl', 1);      qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
725              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');    } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) {   ## image (not URI itself)
726          } elsif (/^(>{1,3})(.*)/) {      my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
727              &back_push('blockquote', length($1));      qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
728              push(@result, &inline($2));    } else {      ## misc. URI
729          } elsif (/^\s*$/) {      CGI::Carp::warningsToBrowser (0);
730              push(@result, splice(@saved));      my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
731              unshift(@saved, "</p>");      CGI::Carp::warningsToBrowser (1);
732              push(@result, "<p>");      qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
733          } elsif (/^(\s+.*)$/) {    }
734              &back_push('pre', 1);  }
735              push(@result, &escape($1)); # Not &inline, but &escape  
736          } else {  {my $FormIndex = 0;
737              push(@result, &inline($_));  sub make_custom_form ($$$$) {
738          }      my ($wfname, $definition, $template, $option) = @_;
739      }      ## $template and $option is currently not used in this procedure.
740      push(@result, splice(@saved));      unless ($main::_EMBEDED) {
741      return join("\n", @result);          $FormIndex++;
742  }          if (length $definition) {
743                my $param = bless {}, 'SuikaWiki::Plugin';
744  # &back_push($tag, $count)              my $lastmodified = &get_info($form{mypage}, $info_LastModified);
745  # $tagのタグを$levelレベルまで詰める。              &load_formatter (qw/form_input form_option/);
746  sub back_push {              $definition = &unescape ($definition);
747      my ($tag, $level) = @_;              $definition =~ s/\\(.)/$1/g;
748      while (@saved > $level) {              $option = &unescape ($option);
749          push(@result, shift(@saved));              $option =~ s/\\(.)/$1/g;
750      }              $fmt{form_option}->replace ($option, $param);
751      if ($saved[0] ne "</$tag>") {              $param->{output}->{form} = 1 unless defined $param->{output}->{form};
752          push(@result, splice(@saved));              $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
753      }              my $target_page = $param->{output}->{page} || $form{mypage};
754      while (@saved < $level) {              $param->{form_disabled} = 1 if $fixedpage{$target_page};
755          unshift(@saved, "</$tag>");              my $target_form = $param->{output}->{id};
756          push(@result, "<$tag>");              my $r = '';
757      }              $r = <<EOH if $param->{output}->{form};
758  }  <form method="post" action="$url_cgi" id="wikiform-$FormIndex" class="wikiform">
759      <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'read':'wikiform']}">
760  # 編集可能ページか?    <input type="hidden" name="mypage" value="@{[&escape($target_page)]}">
761  sub is_editable {    <input type="hidden" name="myLastModified" value="$lastmodified">
762      my ($pagename) = @_;    <input type="hidden" name="mytouch" value="on">
763      foreach (@uneditable) {    <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex)]}">
764          if ($pagename eq $_) {  EOH
765              return 0;              $r .= qq(<a name="wikiform-$FormIndex"></a>) if $UA =~ m#Mozilla/[12]\.#;
766          }              $r .= $fmt{form_input}->replace ($definition, $param);
767      }              $r .= "</form>\n" if $param->{output}->{form};
768      if (&is_valid_name($pagename)) {              $r;
769          return 1;         } else {  ## No input-interface WikiForm
770      }             qq(<a id="wikiform-$FormIndex" name="wikiform-$FormIndex"><!-- #form --></a>);
771      return 0;         }
772  }      } else {
773            qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
774  # Validな名前か?      }
775  sub is_valid_name {  }}
776      my ($pagename) = @_;  
777      if ($pagename =~ /^$WikiName$/) {  sub print_message {
778          return 1;      my ($msg) = @_;
779      } elsif ($pagename =~ /^$BracketName$/) {      print qq(<p><strong>@{[&escape($msg)]}</strong></p>);
780          return 1;  }
781      } else {  
782          return 0;  sub init_form {
783      }      ## TODO: Support multipart/form-data
784  }      my $query = '';
785        if (uc $main::ENV{REQUEST_METHOD} eq 'POST') {
786  # 現在時刻の文字列を得る        read STDIN, $query, $main::ENV{CONTENT_LENGTH};
787  sub get_current_datestr {      }
788      my (@wdays) = ( "日", "月", "火", "水", "木", "金", "土" );      $query .= ($query ? ';' : '') . $main::ENV{QUERY_STRING};
789      my ($sec, $min, $hour, $mday, $mon, $year, $wday) = localtime(time);      if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
790      return sprintf("%4d-%02d-%02d (%s) %02d:%02d:%02d",        my $query = &decode($main::ENV{QUERY_STRING});
791          $year + 1900, $mon + 1, $mday, $wdays[$wday], $hour, $min, $sec);        $query = &code_convert(\$query, $kanjicode);
792  }        if ($page_command{$query}) {
793            $form{mycmd} = $page_command{$query};
794  # URL?SomePageや、          $form{mypage} = $query;
795  # URL?[[結城浩]]の形式だった場合、(not yet)        } else {
796  # 強制的にmycmdをreadにして$formの内容を設定する。          $form{mypage} = $query;
797  sub normalize_form {          $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';
798      foreach my $key (keys %form) {        }
799          if ($key =~ /^$WikiName$/) {      } else {
800              $form{mycmd} = 'read';        for (split /[;&]/, $query) {
801              $form{mypage} = $1;          if (my ($n, $v) = split /=/, $_, 2) {
802              last;            for ($n, $v) {tr/+/ /; s/%([0-9A-Fa-f][0-9A-Fa-f])/pack 'C', hex $1/ge};
803          } elsif ($key =~ /^$BracketName$/) {            $form{$n} = $v;
804              $form{mycmd} = 'read';          }
805              $form{mypage} = $1;        }
806              last;        unless (defined $form{mypage}) {
807          }          $form{mypage} = $form{epage};
808      }          $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;
809  }        }
810          if ($page_command{$form{mypage}} && $form{mycmd} eq 'read') {
811  # 変換テストを行なうときのサンプル          $form{mypage} = &code_convert(\$form{mypage}, $kanjicode);
812  sub print_sample {          $form{mycmd} = $page_command{$form{mypage}};
813      my $txt = &convert_html(<<"EOD");        }
814  *大見出し1      }
815  **小見出し1-1      $form{mypage} ||= 'HomePage';
816  -項目1      $form{mycmd} ||= 'read';
817  -項目2  
818  -項目3      # mypreview_edit        -> do_edit, with preview.
819  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      # mypreview_adminedit   -> do_adminedit, with preview.
820  段落1段落1段落1段落1段落1段落''強調''1段落1段落1段落1段落1段落1      # mypreview_write       -> do_write, without preview.
821  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      foreach (keys %form) {
822            if (/^mypreview_(.*)$/) {
823  段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2              $form{mycmd} = $1;
824  段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2              $form{mypreview} = 1;
825  段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2          }
826  **小見出し1-2      }
827  :用語1:いろいろ書いた解説文1と''強調単語''  
828  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      #
829  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      # $form{mycmd} is frozen here.
830  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      #
831  :用語2:いろいろ書いた解説文2  
832  :用語3:いろいろ書いた解説文3      for (grep /^wikiform__/, keys %form) {
833  ----          $form{$_} = &code_convert (\$form{$_}, $kanjicode);
834  *大見出し2      }
835  **小見出し2-1      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
836  http://www.hyuki.com/      $form{myname} = &code_convert(\$form{myname}, $kanjicode);
837  **小見出し2-2  }
838    
839  [[結城浩]]  sub update_recent_changes {
840        my $update = "- @{[&get_now]} [[$form{mypage}]] @{[&get_subjectline($form{mypage})]}";
841  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      my @oldupdates = split(/\x0D?\x0A/, $database{RecentChanges});
842  段落1段落1段落1段落'''イタリック'''1段落1段落1段落1段落1段落1段落1段落1      shift @oldupdates; ## '#?' magic line
843  段落1段落1段落1段落'''''イタボールド'''''1段落1段落1段落1段落1段落1段落1段落1段落1      my @updates;
844  >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2      foreach (@oldupdates) {
845  >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2          /^\- \d\d\d\d\-\d\d\-\d\d \d\d:\d\d \[\[([^]]+)\]\]/;
846  >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2          my $name = $1;
847            if ($name ne $form{mypage}) {
848  レベル0レベル0レベル0レベル0レベル0レベル0              push @updates, $_;
849            }
850  >レベル1      }
851  >レベル1      if (&is_exist_page($form{mypage})) {
852  >レベル1        unshift @updates, $update;
853  >>レベル2      }
854  >>レベル2      splice @updates, (&Resource ('RecentChanges:Max') || 50) + 1;
855  >>レベル2      $database{RecentChanges} = "#?SuikaWiki/0.9\n" . join("\n", @updates);
856  >>>レベル3      if ($PathTo{TouchFile}) {
857  -はろ1          open(FILE, "> ".$PathTo{TouchFile});
858  --はろ2          print FILE localtime() . "\n";
859  ろろろろ2          close(FILE);
860  ---はろ3      }
861  --はろ2  }
862  ---はろ3  
863  --はろ2  {my %SubjectLine;
864  ---はろ3  sub get_subjectline {
865  >>>レベル3      my ($page, %option) = @_;
866  >>>レベル3      unless (defined $SubjectLine{$page}) {
867  >>>レベル3        if (not &is_editable($page)) {
868  EOD          $SubjectLine{$page} = "";
869      print $txt;        } else {
870      exit;          $SubjectLine{$page} = $database{$page};
871  }          $SubjectLine{$page} =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
872            $SubjectLine{$page} =~ s/\x0D?\x0A.*//s;
873  sub diff_check {        }
874      traverse_sequences(      }
875              $msgrefA, $msgrefB,      if (length $SubjectLine{$page}) {
876              {        $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
877                  MATCH => \&df_match,        $option{delimiter}.$SubjectLine{$page}.$option{tail};
878                  DISCARD_A => \&df_delete,      } else {
879                  DISCARD_B => \&df_add,        '';
880              }      }
881      );  }}
882      &diff_flush;  
883  }  sub open_db {
884        if ($modifier_dbtype eq 'dbmopen') {
885  sub diff_flush {          dbmopen(%database, $PathTo{WikiDataBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDataBase}");
886      $diff_text .= join('', map { "-$_\n" } splice(@diff_deleted));          dbmopen(%infobase, $PathTo{WikiInfoBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiInfoBase}");
887      $diff_text .= join('', map { "+$_\n" } splice(@diff_added));      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
888  }          eval q{use AnyDBM_File};
889            tie(%database, "AnyDBM_File", $PathTo{WikiDataBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDataBase}");
890  sub df_match {          tie(%infobase, "AnyDBM_File", $PathTo{WikiInfoBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiInfoBase}");
891      my ($a, $b) = @_;      } else {
892      &diff_flush;          eval q{use Yuki::YukiWikiDB};
893      $diff_text .= "=$msgrefA->[$a]\n";          tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");
894  }          tie(%infobase, "Yuki::YukiWikiDB", $PathTo{WikiInfoBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiInfoBase}");
895        }
896  sub df_delete {  }
897      my ($a, $b) = @_;  
898      push(@diff_deleted, $msgrefA->[$a]);  sub close_db {
899  }      if ($modifier_dbtype eq 'dbmopen') {
900            dbmclose(%database);
901  sub df_add {          dbmclose(%infobase);
902      my ($a, $b) = @_;      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
903      push(@diff_added, $msgrefB->[$b]);          untie(%database);
904  }          untie(%infobase);
905        } else {
906  sub calc_message_digest {   # You have to use MD5...          untie(%database);
907      my $text = shift;          untie(%infobase);
908      my @text = split(//, $text);      }
909      my $len = length($text);  }
910      my $checksum = 0;  
911      foreach (@text) {  sub open_diff {
912          $checksum += ord($_);      if ($modifier_dbtype eq 'dbmopen') {
913          $checksum = ($checksum * 2) % 65536 + (($checksum & 32768) ? 1 : 0); # 16bit rotate          dbmopen(%diffbase, $PathTo{WikiDiffBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDiffBase}");
914      }      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
915      return "$len:$checksum";          tie(%diffbase, "AnyDBM_File", $PathTo{WikiDiffBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDiffBase}");
916  }      } else {
917            tie(%diffbase, "Yuki::YukiWikiDB", $PathTo{WikiDiffBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDiffBase}");
918  # Definition of YukiWikiDB      }
919  package YukiWikiDB;  }
920    
921  my $debug = 1;  sub close_diff {
922        if ($modifier_dbtype eq 'dbmopen') {
923  # Constructor          dbmclose(%diffbase);
924  sub new {      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
925      return shift->TIEHASH(@_);          untie(%diffbase);
926  }      } else {
927            untie(%diffbase);
928  # tying      }
929  sub TIEHASH {  }
930      my ($class, $dbname) = @_;  
931      my $self = {  sub print_editform {
932          dir => $dbname,      my ($mymsg, $lastmodified, %mode) = @_;
933          keys => [],      my $frozen = &is_frozen($form{mypage});
934      };  
935      if (not -d $self->{dir}) {      if ($form{mypreview}) {
936          if (!mkdir($self->{dir}, 0777)) {          if ($form{mymsg}) {
937              print "mkdir(" . $self->{dir} . ") fail\n" if ($debug);              unless ($mode{conflict}) {
938              return undef;                  print qq(<h3>@{[&Resource('Preview:Title',escape=>1)]}</h3>\n);
939          }                  print qq(<p>@{[&Resource('Preview:Notice',escape=>1)]}</p>\n);
940      }                  print qq(<div class="preview">\n);
941      return bless($self, $class);                  &print_content($form{mymsg});
942  }                  print qq(</div>\n);
943                }
944  # Store          } else {
945  sub STORE {              print @{[&Resource('Preview:Empty',escape=>1)]};
946      my ($self, $key, $val) = @_;          }
947      my $file = &make_filename($self, $key);          $mymsg = &escape($form{mymsg});
948      if (open(FILE,"> $file")) {      } else {
949          binmode(FILE);          $mymsg = &escape($mymsg || $database{NewPageTemplate});
950          print FILE $val;      }
951          close(FILE);      my $magic = '';
952          return $self->{$key} = $val;      $magic = $1 if $mymsg =~ m/^([^\x0A\x0D]+)/s;
953      } else {  
954          print "$file create error.";      my $edit = $mode{admin} ? 'adminedit' : 'edit';
955      }      my $escapedmypage = &escape($form{mypage});
956  }      my $escapedmypassword = &escape($form{mypassword});
957        my $selected = 'read';
958  # Fetch      if ($form{after_edit_cmd}) {
959  sub FETCH {          $selected = $form{after_edit_cmd};
960      my ($self, $key) = @_;      } elsif ($magic =~ /Const|Config|CSS/) {
961      my $file = &make_filename($self, $key);          $selected = 'edit';
962      if (open(FILE, $file)) {      }
963          local $/;      my $afteredit = <<EOH;
964          $self->{$key} = <FILE>;  <select name="after_edit_cmd">
965          close(FILE);  <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
966      }  <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
967      return $self->{$key};  </select>
968  }  EOH
969    
970  # Exists      print <<"EOD";
971  sub EXISTS {  <form action="$url_cgi" method="post">
972      my ($self, $key) = @_;  <h2>@{[&Resource('Edit:Title',escape=>1)]}</h2>
973      my $file = &make_filename($self, $key);      @{[ $mode{conflict} ? '' : qq(<input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}"><kbd>S</kbd>) ]}
974      return -e($file);      @{[ $mode{admin} ? qq(<label>@{[&Resource('Edit:Password=',escape=>1)]}<input type="password" name="mypassword" value="$escapedmypassword" size="10"></label>) : "" ]} [@{[do {my $n = 0;
975  }                 $mymsg =~ s/(?:-+\s)?\[([0-9]+)\]/$n = $1 if $1 > $n; $&/mge;
976                   ++$n}]}]<br>
977  # Delete      <input type="hidden" name="myLastModified" value="$lastmodified">
978  sub DELETE {      <input type="hidden" name="mypage" value="$escapedmypage">
979      my ($self, $key) = @_;      <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">$mymsg</textarea><br>
980      my $file = &make_filename($self, $key);  @{[
981      unlink $file;      $mode{admin} ?
982      return delete $self->{$key};      qq(
983  }      <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>@{[&Resource('Edit:Freeze',escape=>1)]}</label>
984        <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br>)
985  sub FIRSTKEY {      : ""
986      my ($self) = @_;  ]}
987      opendir(DIR, $self->{dir}) or die $self->{dir};  @{[
988      @{$self->{keys}} = grep /\.txt$/, readdir(DIR);      $mode{conflict} ? "" :
989      foreach my $name (@{$self->{keys}}) {      qq(
990          $name =~ s/\.txt$//;          <input type="checkbox" name="mytouch" value="on" checked="checked">@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}<br>
991          $name =~ s/[0-9A-F][0-9A-F]/pack("C", hex($&))/eg;          <input type="submit" name="mypreview_$edit" value="@{[&Resource('Edit:Preview',escape=>1)]}">
992      }          <input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S"><kbd>S</kbd>
993      return shift @{$self->{keys}};         $afteredit
994  }         <br>
995        )
996  sub NEXTKEY {  ]}
997      my ($self) = @_;  </form>
998      return shift @{$self->{keys}};  EOD
999  }      unless ($mode{conflict}) {
1000            ## Show help text
1001  sub make_filename {          my $help = $database{WikiEditHelp};
1002      my ($self, $key) = @_;          $help =~ s!^\#\?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1003      my $enkey = '';          print &text_to_html ($help, toc => 0);
1004      foreach my $ch (split(//, $key)) {      }
1005          $enkey .= sprintf("%02X", ord($ch));  }
1006      }  
1007      return $self->{dir} . "/$enkey.txt";  sub print_passwordform {
1008  }          print <<"EOD";
1009  __END__  <form action="$url_cgi" method="post">
1010        <input type="hidden" name="mycmd" value="adminchangepassword">
1011  =head1 NAME      <label>@{[&Resource('Password:Old=',escape=>1)]}<input type="password" name="myoldpassword" size="10"></label><br>
1012        <label>@{[&Resource('Password:New1=',escape=>1)]}<input type="password" name="mynewpassword" size="10"></label><br>
1013  YukiWiki - 自由にページを追加・削除・編集できるWebページ構築CGI      <label>@{[&Resource('Password:New2=',escape=>1)]}<input type="password" name="mynewpassword2" size="10"></label><br>
1014        <input type="submit" value="@{[&Resource('WikiForm:Change',escape=>1)]}"><br>
1015      Copyright (C) 2000,2001 by Hiroshi Yuki.  </form>
1016      結城浩 <hyuki@hyuki.com>  EOD
1017      http://www.hyuki.com/  }
1018      http://www.hyuki.com/yukiwiki/  
1019    sub is_editable {
1020  =head1 SYNOPSIS      my ($page) = @_;
1021        if ($fixedpage{$page} || $page =~ /\s/ || $page =~ /^\#/) {
1022      http://www.hyuki.com/yukiwiki/yukiwiki.cgi          return 0;
1023        } else {
1024  =head1 DESCRIPTION          return 1;
1025        }
1026  YukiWiki(結城ウィキィ)は参加者が自由にページを追加・削除・編集できる  }
1027  不思議なWebページ群を作るCGIです。  
1028  Webで動作する掲示板とちょっと似ていますが、  # armor_name:
1029  Web掲示板が単にメッセージを追加するだけなのに対して、  #   WikiName -> WikiName
1030  YukiWikiは、Webページ全体を自由に変更することができます。  #   not_wiki_name -> [[not_wiki_name]]
1031    sub armor_name { qq([[$_[0]]]) }
1032  YukiWikiは、Cunningham & CunninghamのWikiWikiWebの  
1033  仕様を参考にして独自に作られました。  # unarmor_name:
1034    #   [[bracket_name]] -> bracket_name
1035  YukiWikiはPerlで書かれたCGIスクリプトとして実現されていますので、  #   WikiName -> WikiName
1036  Perlが動作するWebサーバならば比較的容易に設置できます。  sub unarmor_name {
1037        my ($name) = @_;
1038  あとはdbmopenが使える環境ならば設置できます(Version 1.5.0以降ならdbmopenが使えなくても設置できます)。      if ($name =~ /^\[\[(\S+?)\]\]$/) {
1039            return $1;
1040        } else {
1041  YukiWikiはフリーソフトです。          return $name;
1042  ご自由にお使いください。      }
1043    }
1044  =head1 設置方法  
1045    sub decode {
1046  =head2 入手      my ($s) = @_;
1047        $s =~ tr/+/ /;
1048  YukiWikiの最新版は、      $s =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;
1049  http://www.hyuki.com/yukiwiki/      return $s;
1050  から入手できます。  }
1051    
1052  =head2 ファイル一覧  sub encode {
1053        my ($s) = @_;
1054      readme.txt      ドキュメント      my $encoded = '';
1055      yukiwiki.cgi    YukiWiki本体      foreach my $ch (split(//, $s)) {
1056      yukiwiki.gif    ロゴ(カラー版)          if ($ch =~ /[A-Za-z0-9_]/) {
1057      yukimono.gif    ロゴ(モノクロ版)              $encoded .= $ch;
1058      jcode.pl        漢字コードライブラリ          } else {
1059                $encoded .= '%' . sprintf("%02X", ord($ch));
1060  =head2 インストール          }
1061        }
1062  =over 4      return $encoded;
1063    }
1064  =item 1.  
1065    sub conflict {
1066  アーカイブを解く。      my ($page, $rawmsg) = @_;
1067        if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {
1068  =item 2.          return 0;
1069        }
1070  yukiwiki.cgiのはじめの方にある設定を確認します。      &print_header($page, -noindex => 1);
1071  通常は何もしなくてよいが、      &print_content(&Resource('Error:Conflict'));
1072  はじめは$touchfileを''にした方がよいでしょう。      &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);
1073        &print_footer($page);
1074  =item 3.      return 1;
1075    }
1076  yukiwiki.cgiとjcode.plを同じところに設置します。  
1077    sub get_now {
1078  =item 4.      my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
1079        $year += 1900;
1080  サイズ0のyukiwiki.dbというファイルを設置します。      $mon++;
1081  (Perlシステムによってはyukiwiki.pag, yukiwiki.dir)      $mon = "0$mon" if $mon < 10;
1082        $day = "0$day" if $day < 10;
1083  =item 5.      $hour = "0$hour" if $hour < 10;
1084        $min = "0$min" if $min < 10;
1085  yukiwiki.cgiにブラウザからアクセスします。      #$sec = "0$sec" if $sec < 10;
1086        return "$year-$mon-$day $hour:$min";
1087  =back  }
1088    
1089  =head2 パーミッション  sub init_InterWikiName {
1090      my @content = split /\n/, $database{InterWikiName};
1091          ファイル        パーミッション      転送モード    for (@content) {
1092          yukiwiki.cgi    755                 ASCII      if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
1093          yukiwiki.gif    644                 BINARY        $interwiki{$1} = $2;
1094          yukimono.gif    644                 BINARY      }
1095          jcode.pl        644                 ASCII    }
1096      $interwiki{'[[]]'} = 1;       ## dummy
1097      $dbmopen = 1; にした場合:  }
1098          yukiwiki.db     666                 BINARY  
1099          (yukiwiki.pag, yukiwiki.dirの場合もあり)  
1100    sub get_info {
1101      $dbmopen = 0; にした場合: (カレントディレクトリを777にしておく)      my ($page, $key) = @_;
1102          .               777                 (転送しない)      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1103        return $info{$key};
1104  =head1 データのバックアップ方法  }
1105    
1106  $dbmopen = 1;の場合は、  sub set_info {
1107  データはすべてyukiwiki.db(.dir, .pag)に入る。      my ($page, $key, $value) = @_;
1108  これをバックアップすればよい。      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1109        $info{$key} = $value;
1110  $dbmopen = 0;の場合は、      my $s = '';
1111  yukiwikiというディレクトリができるので、      for (keys %info) {
1112  これ以下をバックアップすればよい。          $s .= "$_=$info{$_}\n";
1113        }
1114  =head1 新しいページの作り方      $infobase{$page} = $s;
1115    }
1116  =over 4  
1117    sub frozen_reject {
1118  =item 1.      my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);
1119        my ($willbefrozen) = $form{myfrozen};
1120  まず、適当なページ(例えばFrontPage)を選び、      if (not $isfrozen and not $willbefrozen) {
1121  ページの下にある「編集」リンクをたどります。          # You need no check.
1122            return 0;
1123  =item 2.      } elsif (valid_password($form{mypassword})) {
1124            # You are admin.
1125  するとテキスト入力ができる状態になるので、          return 0;
1126  そこにNewPageのような単語      } else {
1127  (大文字小文字混在している英文字列)          &print_error(&Resource('Error:PasswordIsIncorrect'));
1128  を書いて「保存」します。          return 1;
1129        }
1130  =item 3.  }
1131    
1132  保存すると、FrontPageのページが書き換わり、  sub valid_password {
1133  あなたが書いたNewPageという文字列の後ろに ? というリンクが表示されます。      my ($givenpassword) = @_;
1134  この ? はそのページがまだ存在しないことを示す印です。      my ($validpassword_crypt) = &get_info($PageName{AdminSpecialPage}, 'AdminPassword');
1135        if (crypt($givenpassword, $validpassword_crypt) eq $validpassword_crypt) {
1136  =item 4.          return 1;
1137        } else {
1138  その ? をクリックすると新しいページNewPageができますので、          return 0;
1139  あなたの好きな文章をその新しいページに書いて保存します。      }
1140    }
1141  =item 5.  
1142    sub is_frozen {
1143  NewPageページができるとFrontPageの ? は消えて、リンクとなります。      my ($page) = @_;
1144        if (&get_info($page, $info_IsFrozen)) {
1145  =back          return 1;
1146        } else {
1147  =head1 テキスト整形のルール          return 0;
1148        }
1149  =over 4  }
1150    
1151  =item *  sub do_comment {
1152        my ($content) = $database{$form{mypage}};
1153  連続した複数行はフィルされて表示されます。      my $default_name;   ## this code does not strict.
1154        $default_name = $1 if $content =~ /default-name="([^"]+)"/;
1155  =item *      my $datestr = '[WEAK['.&get_now.']]';
1156        my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
1157  空行は段落C<< <p> >>の区切りとなります。      ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
1158        if ($namestr =~ /^(?:>>)?[0-9]/) {
1159  =item *        $namestr = qq( ''$namestr'': );
1160        } elsif (length $namestr) {
1161  HTMLのタグは書けません。        $namestr = qq( ''[[$namestr]]'': );
1162        }
1163  =item *      my $anchor = &get_new_anchor_index ($content);
1164        my $i = 1;  my $o = 0;
1165  B<''ボールド''>のようにシングルクォート二つではさむと、      $content =~ s{(\[\[\#r?comment\]\])}{
1166  ボールドC<< <b> >>になります。        my $embed = $1;
1167          if ($i == $form{comment_index}) {
1168  =item *          if ($embed ne '[[#rcomment]]') {
1169              $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;
1170  B<'''イタリック'''>のようにシングルクォート三つではさむと、          } else {
1171  イタリックC<< <i> >>になります。            $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;
1172            }
1173  =item *        }
1174          $i++; $embed;
1175  B<---->のようにマイナス4つがあると、      }ge;
1176  水平線C<< <hr> >>になります。      unless ($o) {
1177          $content = "#?SuikaWiki/0.9\n\n" unless $content;
1178  =item *        $content .= "\n" unless $content =~ /\n$/s;
1179          $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
1180  行をB<*>ではじめると、      }
1181  大見出しC<< <h2> >>になります。      $form{__comment_anchor_index} = $anchor;
1182        if ($form{mymsg} || $form{myname}) {
1183  =item *          $form{mymsg} = $content;
1184            $form{mytouch} = 'on';
1185  行をB<**>ではじめると、          &do_write;
1186  小見出しC<< <h3> >>になります。      } else {
1187            $form{mycmd} = 'read';
1188  =item *          &do_read;
1189        }
1190  行をマイナス-ではじめると、  }
1191  箇条書きC<< <ul> >>になります。  
1192  マイナスの数が増えるとレベルが下がります(3レベルまで)  sub get_new_anchor_index ($) {
1193        my $content = shift;
1194      -項目1      my $anchor = 0;
1195      --項目1-1      $content =~ s/^(?:[-=]+\s*)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
1196      --項目1-2      $anchor + 1;
1197      -項目2  }
1198      -項目3  
1199      --項目3-1  my $CommentIndex = 0;
1200      ---項目3-1-1  sub embedded_to_html {
1201      ---項目3-1-2      my ($embedded) = @_;
1202      --項目3-2      if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
1203          unless ($main::_EMBEDED) {
1204  =item *          my $lastmodified = &get_info($form{mypage}, $info_LastModified);
1205            return <<"EOD";
1206  コロンを使うと、  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
1207  用語と解説文のリストC<< <dl> >>が書けます。      <input type="hidden" name="mycmd" value="comment">
1208        <input type="hidden" name="mypage" value="$form{mypage}">
1209      :用語1:いろいろ書いた解説文1      <input type="hidden" name="myLastModified" value="$lastmodified">
1210      :用語2:いろいろ書いた解説文2      <input type="hidden" name="mytouch" value="on">
1211      :用語3:いろいろ書いた解説文3      <input type="hidden" name="comment_index" value="$CommentIndex">
1212        @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
1213  =item *      <input type="text" name="myname" value="" size="10" class="comment-name">
1214        <input type="text" name="mymsg" value="" size="60" class="comment-msg">
1215  リンク      <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit">
1216    </p></form>
1217  =over 4  EOD
1218         } else {
1219  =item *          return <<"EOD";
1220    <del><form action="$url_cgi" method="get">
1221  LinkToSomePageやFrontPageのように、      <input type="hidden" name="mycmd" value="read">
1222  英単語の最初の一文字を大文字にしたものが      <input type="hidden" name="mypage" value="$form{mypage}">
1223  二つ以上連続したものはYukiWikiのページ名となり、      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
1224  それが文章中に含まれるとリンクになります。      <input type="text" name="myname" value="" size="10" disabled="disabled">
1225        <input type="text" name="mymsg" value="" size="60" disabled="disabled">
1226  =item *  </form></del>
1227    EOD
1228  http://www.hyuki.com/ のようなURLは自動的にリンクになります。      }
1229      } elsif ($embedded =~ /$embed_command{searched}/) {
1230  =item *      return get_search_result ($1, -match_myself => 1);
1231      } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
1232  二重の大かっこ[[ ]]でくくった文字列も、      my ($name, $r) = ($1, '');
1233  YukiWikiのページ名になります。      if ($main::_EMBEDED != 1) {
1234  大かっこの中にはスペースを含めてはいけません。        my ($content, $cf) = ($database{$name}, 'SuikaWiki/0.9');
1235  日本語も使えます。        $cf = $1 if $content =~ s!^(?:[\#<]\?|/\*\s*)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1236          if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
1237  =back          $main::_EMBEDED = 1;
1238            $r = &text_to_html ($content, content_format => $cf);
1239  =item *          $main::_EMBEDED = 0;
1240          } elsif (length $content) {
1241  行頭がスペースやタブで始まっていると、          $r = "<pre>@{[&escape ($content)]}</pre>";
1242  それは整形済みの段落C<< <pre> >>として扱われます。        } else {
1243  プログラムの表示などに使うと便利です。          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
1244          }
1245        } else {    ## nested #EMBED
1246  =item *        $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
1247        }
1248  行を > ではじめると、      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>);
1249  引用文C<< <blockquote> >>が書けます。    } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
1250  >の数が多いとインデントが深くなります(3レベルまで)。      return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);
1251      } else {
1252      >文章      return $embedded;
1253      >文章    }
1254      >>さらなる引用  }
1255      >文章  
1256    sub load_formatter (@) {
1257  =back      for my $t (@_) {
1258            unless ($fmt{$t}) {
1259  =head1 更新履歴              require Message::Util::Formatter;
1260                $fmt{$t} = Message::Util::Formatter->new;
1261  =over 4              for (@{$SuikaWiki::Plugin::List{'wiki'.$t}||[]}) {
1262                    $_->load_formatter ($fmt{$t}, type => 'wiki'.$t);
1263  =item *              }
1264            }
1265  2001年10月20日、Version 1.6.6。      }
1266    }
1267  更新の衝突対策。  
1268  元ページの簡単なチェックサムを取っておき、  sub do_wikiform {
1269  更新前にチェックサムを比較する。      my $content = $database{$form{mypage}};
1270  修正個所はdigestという文字列を検索すれば分かる。      my $anchor = &get_new_anchor_index ($content);
1271  本来はMD5などでちゃんとやった方がいいのだけれど。      &load_formatter (qw/form_template form_option/);
1272        my $write = 0;
1273  衝突時に表示されるメッセージなどは「極悪」さんのページを参考にした。      my $i = 1;
1274        $content =~ s{$embed_command{form}}{
1275  =item *          my ($embed, $wfname, $template, $option) = ($&, $1, $3, $4);
1276            if (($wfname && $wfname eq $form{wikiform_targetform})
1277  2001年10月17日、Version 1.6.5。              || $i == $form{wikiform_index}) {
1278                $template =~ s/\\(.)/$1/g;
1279  プレビュー画面で、更新ボタンを押したときに送信される              $option =~ s/\\(.)/$1/g;
1280  メッセージの内容をinput要素のtype="hidden"を使って埋め込むのをやめる。              my $param = bless {}, 'SuikaWiki::Plugin';
1281  代わりに、textarea要素を使う。              $param->{page} = $form{mypage};
1282  再プレビュー用にmyspecial_を導入。でもきれいな対策ではない。              $param->{form_index} = $i;
1283                $param->{form_name} = $wfname;
1284  =item *              $param->{anchor_index} = $anchor;
1285                $param->{argv} = \%form;
1286  2001年8月30日、Version 1.6.4。              $param->{default_name} = $1 if $content =~ /default-name="([^"]+)"/;
1287                $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
1288  URLでダイレクトにページ名を指定しても、              $fmt{form_option}->replace ($option, $param);
1289  $WikiNameと$BracketName以外のページを作れないようにした。              my $t = 1;
1290  (is_valid_nameとis_editable参照)。              for (@{$param->{require}||[]}) {
1291                    (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
1292  =item *              }
1293                $t = $fmt{form_template}->replace ($template, $param) if $t;
1294  2001年8月30日、Version 1.6.3。              if (length $t) {
1295                    if ($param->{output}->{reverse}) {
1296  RecentChangesを編集・再編集不可とした。                      $embed .= "\n" . $t;
1297  編集不可ページは@uneditableにページ名を入れる。                  } else {
1298                        $embed = $t . "\n" . $embed;
1299  =item *                  }
1300                    $write = 1;
1301  2001年2月25日、Version 1.6.1, 1.6.2。                  $form{__comment_anchor_index} = $anchor
1302                      if $param->{anchor_index_};  ## $anchor is used!
1303  差分機能のバグ修正。              }
1304  do_previewで'>'が扱えないバグを修正              $form{__wikiform_anchor_index} = $i;
1305  (ユーザからの指摘)。              undef $form{wikiform_targetform};  ## make sure never to match
1306                undef $form{wikiform_index};       ## with WikiForm in rest of page
1307  =item *          }
1308            $i++; $embed;
1309  2001年2月22日、Version 1.6.0。      }ge;
1310  差分機能を実装した。      unless ($write) {
1311          #$content = "#?SuikaWiki/0.9\n\n" unless $content;
1312  =item *        #$content .= "\n" unless $content =~ /\n$/s;
1313          #
1314  2001年2月19日、Version 1.5.4。      }
1315  画像ファイルへのリンクは画像にしてみた。      if ($write) {
1316            $form{mymsg} = $content;
1317  =item *          $form{mytouch} = 'on';
1318            &do_write;
1319  2001年2月19日、Version 1.5.3。      } else {
1320  RecentChangesの中に削除したページがあるのをやめた。          $form{mycmd} = 'read';
1321  use strict;で引っかかる部分を少し整理(完全ではない)。          &do_read;
1322        }
1323  =item *  }
1324    
1325  2001年2月16日、Version 1.5.2。  sub code_convert {
1326  textareaに表示およびプレビューする前に < や > を &lt; や &gt; に変換した    require Jcode;
1327  (do_preview, editpage, print_preview_buttons)。      my ($contentref, $code) = (shift, shift || $kanjicode);
1328        $code = 'jis' if $code =~ /iso/;
1329  =item *      $code = 'euc' if $code =~ /euc/;
1330        $code = 'sjis' if $code =~ /shift/;
1331  2000年12月27日、Version 1.5.1。      $code = 'utf8' if $code =~ /utf/;
1332  プレビュー画面を整理した。      #&Jcode::convert($contentref, $code);       # for Jcode.pm
1333    #    &jcode::convert($contentref, $code);       # for jcode.pl
1334  =item *      #&Jcode::tr ($contentref, "\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA\xA1\xF5\xA1\xA4\xA1\xA5\xA1\xA7\xA1\xA8\xA1\xA9\xA1\xAA\xA1\xAE\xA1\xB0\xA1\xB2\xA1\xBF\xA1\xC3\xA1\xCA\xA1\xCB\xA1\xCE\xA1\xCF\xA1\xD0\xA1\xD1\xA1\xDC\xA1\xF0\xA1\xF3\xA1\xF4\xA1\xF6\xA1\xF7\xA1\xE1\xA2\xAF\xA2\xB0\xA2\xB2\xA2\xB1\xA1\xE4\xA1\xE3\xA1\xC0\xA1\xA1" => q(0-9A-Za-z&,.:;?!`^_/|()[]{}+$%#*@='"~-><\ )) if $code eq 'euc';
1335        $$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;
1336  2000年12月22日、Version 1.5.0。      return $$contentref;
1337  全体的にずいぶん書き直した。  }
1338  一覧を別途作成するようにした(do_list)。  
1339  書き込む前に確認画面を出すようにした(do_preview)。  sub do_diff {
1340  テキストの書き方を編集画面に入れた(do_edit, do_reedit)。      if (not &is_editable($form{mypage})) {
1341  WhatsNew→RecentChanges、TopPage→FrontPageに変更した。          &do_read;
1342            return;
1343  =item *      }
1344        &open_diff;
1345  2000年12月20日、Version 1.1.0。      my $title = $form{mypage};
1346  tieを利用して、dbmopenが使えない場合でも動作するように修正。      &print_header($title, -noindex => 1);
1347  利用者の1人である「極悪」さんから      $_ = &escape($diffbase{$form{mypage}});
1348  送っていただいたコードを元にしています。      &close_diff;
1349        print qq(<h3>@{[&Resource('Diff:Title',escape=>1)]}</h3>);
1350  =item *      print qq(<p>@{[&Resource('Diff:Notice',escape=>1)]}</p>);
1351        print qq(<pre class="diff">);
1352  2000年9月5日、Version 1.0.2。      foreach (split(/\n/, $_)) {
1353   <body color=...> → <body bgcolor=...>          if (/^\+(.*)/) {
1354  利用者からの指摘による。感謝。              print qq(<ins class="added">$1</ins>\n);
1355            } elsif (/^\-(.*)/) {
1356  =item *              print qq(<del class="deleted">$1</del>\n);
1357            } elsif (/^\=(.*)/) {
1358  2000年8月6日、Version 1.0.1を公開。              print qq(<span class="same">$1</span>\n);
1359  C MAGAZINE(ソフトバンクパブリッシング)          } else {
1360  2000年10月号連載記事向け公開版。              print qq|??? $_\n|;
1361  [[ ]] の最後が「望」のようにシフトJISで          }
1362  0x5Dになる場合の回避を行なった。      }
1363        print qq(</pre>);
1364  =item *      &print_footer($title);
1365    }
1366  2000年8月5日、Version 1.0.0を公開。  
1367    sub do_rss {
1368  =item *      eval q{use Yuki::RSS};
1369        my $rss = new Yuki::RSS(
1370  2000年7月23日、Version 0.82を公開。          version => '1.0',
1371  編集時のリンクミス。          encoding => &get_charset_name ($kanjicode),
1372  <textarea>の属性変更。      );
1373        my $scheme = 'http';
1374  =item *      $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
1375        my $myuri = "$scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi";
1376  2000年7月22日、Version 0.81を公開。      $rss->stylesheet (
1377  ロゴを組み込む。        href      => $myuri . "?mycmd=TEXT_CSS;mypage=WikiStyle:RSS",
1378          type      => 'text/css',
1379  =item *      );
1380        $rss->channel(
1381  2000年7月21日、Version 0.80を公開。          title   => &Resource ('RSS:WikiTitle'),
1382  PODをCGI中に書き込む。          link    => $myuri,
1383            description     => &Resource ('RSS:WikiDescription'),
1384  =item *          'dc:language'   => $lang,
1385        );
1386  2000年7月19日、Version 0.70を公開。      my $recentchanges = $database{RecentChanges};
1387  '''イタリック'''や、--、---、>>、>>>などを実装。      my $count = 0;
1388        foreach (split(/\n/, $recentchanges)) {
1389  =item *          last if ($count >= 15);
1390            if (/\[\[([^]]+)\]\]/) {
1391  2000年7月18日、Version 0.60を公開。            my $title = $1;
1392  *太字*を''太字''に変更            $rss->add_item (
1393                title       => &escape($title),
1394  =item *              link        => $myuri . '?' . &encode($title),
1395                description => &escape(&get_subjectline($title,delimiter=>'')),
1396  2000年7月17日、Version 0.50を公開。              'dc:date'   => &get_info ($title, $info_LastModified),
1397              );
1398  =item *            $count++;
1399            }
1400  2000年7月17日、さらにいろいろ追加する。      }
1401        # print RSS information (as XML).
1402  =item *      print <<"EOD"
1403    Content-type: application/xml; charset=@{[&get_charset_name ($kanjicode)]}
1404  2000年7月16日、いろいろ追加。  
1405    @{[$rss->as_string]}
1406  =item *  EOD
1407    }
1408  2000年7月15日、公開。  
1409    sub _rfc3339_date ($) {
1410  =back    my @time = gmtime (shift);
1411      sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
1412  =head1 TODO  }
1413    
1414      - テキスト表示モード  sub is_exist_page {
1415      - Charsetを明示。      my ($name) = @_;
1416      - textarea中の閉じタグ対応      if ($use_exists) {
1417      - メニューの英語表記付記          return exists($database{$name});
1418      - プレビューのボタンで、mymsgをinputのvalueに入れているが、改行をそのままvalueにいれてはいけないのではないか。      } else {
1419      - 「再編集」の機能はブラウザの back で充分ではないか。プレビューはもっとシンプルに。          return $database{$name};
1420      - ページタイトル(Wikiname)が検索にかかるようにする。      }
1421      - InterWiki風の機能「URLを隠しつつ、リンクを張る」  }
1422    
1423  =head1 作者  sub __get_database ($) { $database{ $_[0] } }
1424    sub __set_database ($$) { $database{ $_[0] } = $_[1] }
1425      Copyright (C) 2000 by Hiroshi Yuki.  
1426      結城浩 <hyuki@hyuki.com>  sub do_map {
1427      http://www.hyuki.com/      my $page = $form{mypage};
1428      http://www.hyuki.com/yukiwiki/      &print_header ($page);
1429        wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
1430  質問、意見、バグ報告は hyuki@hyuki.com にメールしてください。      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
1431        my ($r, $c) = get_search_result ($form{mypage});
1432  =head1 配布条件      my $rl = wiki::referer::list_html ($form{mypage});
1433        print "<h2>@{[&Resource('Map:Title',escape=>1)]}</h2>\n<p>@{[&Resource('Map:Description',escape=>1)]}</p>\n";
1434  YukiWikiは、      my %option = (level => 0+&Resource('Map:Depth'), weight_list => {}, not_exist => {},
1435  GNU General Public Licenseにて公開します。        map_from_here => &Resource('Map:FromHere'),
1436          map_from_here_description => &Resource('Map:FromHereLong'));
1437  YukiWikiはフリーソフトです。      &wiki::map::make_list ($page, %option);
1438  ご自由にお使いください。      print &wiki::map::list_to_html ($page, $option{weight_list}, %option);
1439  自分好みのYukiWikiが作れるようにシンプルにしてあります。      if ($c) {
1440          print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};
1441  =head1 謝辞        print $r;
1442        }
1443  本家のWikiWikiを作ったCunningham & Cunningham, Inc.に      if ($rl) {
1444  感謝します。        print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
1445        }
1446  YukiWikiを楽しんで使ってくださる      &print_footer ($page);
1447  ネット上の方々に感謝します。  }
1448    
1449  YukiWikiのロゴをデザインしてくださった橋本礼奈さん  my %_Resource;
1450  http://city.hokkai.or.jp/~reina/  sub Resource ($;%) {
1451  に感謝します。    my ($s, %o) = @_;
1452      unless (defined $_Resource{$s}) {
1453  tieを使った版の元になるコードを送ってくださった      $_Resource{$_[0]} = &wiki::resource::get ($s, $_Resource{__option});
1454  「極悪」さんに感謝します。    }
1455      $o{escape} ? &escape ($_Resource{$s}) : $_Resource{$s};
1456  =head1 参照リンク  }
1457    
1458  =over 4  package wiki::referer;
1459    sub add ($$) {
1460  =item *    my $page = shift;
1461      my $uri = shift;
1462  YukiWikiホームページ    unless (ref $uri) {
1463  http://www.hyuki.com/yukiwiki/      require URI;
1464        $uri = URI->new ($uri);
1465  =item *      ## Some schemes do not have query part.
1466        eval q{ $uri->query (undef) if $uri->query =~ /^[0-9]{6,8}$/ };
1467  本家のWikiWiki      $uri->fragment (undef);
1468  http://c2.com/cgi/wiki?WikiWikiWeb    }
1469      $uri = $uri->canonical;
1470  =item *    return unless $uri;
1471      for my $regex (&get_dont_record) {
1472  本家のWikiWikiの作者(Cunningham & Cunningham, Inc.)      return if $uri =~ /$regex/;
1473  http://c2.com/    }
1474      my %list = get ($page);
1475  =item *    $list{ $uri }++;
1476      set ($page, \%list);
1477  YukiWikiのロゴデザインをしてくださった橋本礼奈さんのページ  }
1478  http://city.hokkai.or.jp/~reina/  sub get ($) {
1479      my $page = shift;
1480  =back    split /"/, main::get_info ($page, 'Referer');
1481    }
1482  =cut  sub set ($%) {
1483      my $page = shift;
1484      my $list = shift;
1485      main::set_info ($page, Referer => join '"', %$list);
1486    }
1487    
1488    sub get_dont_record () {
1489      map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1490      grep !/^#/,
1491      split /[\x0D\x0A]+/, &main::__get_database ('RefererDontRecord');
1492    }
1493    sub get_site_name () {
1494      my @lines = grep /[^#]/, split /[\x0D\x0A]+/, &main::__get_database('RefererSiteName');
1495      my @item;
1496      for (@lines) {
1497        next if /^#/;
1498        my ($uri, $name) = split /\s+/, $_, 2;
1499        $uri =~ s/\$/\\\$/g;  $uri =~ s/\@/\\\@/g;  $uri =~ s/\//\\\//g;
1500        $name =~ s!([()/\\])!\\$1!g;  $name =~ s/\$([0-9]+)/).__decode (\${$1}).q(/g;
1501        push @item, [$uri, qq(q($name))];
1502      }
1503      @item;
1504    }
1505    
1506    sub list_html ($) {
1507      my $page = shift;
1508      my %list = get ($page);
1509      my $r = '';
1510      my @name = get_site_name;
1511      for my $uri (sort keys %list) {
1512        my $title;
1513        for my $item (@name) {
1514          if ($uri =~ /$item->[0]/) {
1515            $title = $uri;
1516            eval qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e}
1517              or die $@ ;#. qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e};
1518            last;
1519          }
1520        }
1521        my $euri = main::escape ($uri);
1522        if ($title) {
1523          $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri&gt;">@{[main::escape ($title)]}</a></li>\n);
1524        } else {
1525          $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1526        }
1527      }
1528      $r ? qq(<ul>$r</ul>\n) : '';
1529    }
1530    
1531    sub __decode ($) {
1532      my $s = shift;
1533      $s =~ tr/+/ /;
1534      $s =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/chr hex $1/ge;
1535      main::code_convert (\$s);
1536    }
1537    
1538    package wiki::useragent;
1539    
1540    sub add ($) {
1541      my $s = shift;
1542      return unless length $s;
1543      $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1544      my %ua;
1545      for (split /\n/, &main::__get_database('WikiUserAgentList')) {
1546        if (/^-\[(\d+)\] (.+)$/) {
1547          my ($t, $n) = ($1, $2);
1548          $n =~ tr/\x0A\x0D//d;
1549          $ua{$n} = $t;
1550        }
1551      }
1552      $ua{$s}++;
1553      my $s = qq(#?SuikaWiki/0.9\n);
1554      for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1555        $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1556      }
1557      &main::__set_database ('WikiUserAgentList' => $s);
1558    }
1559    
1560    package wiki::suikawikiconst;
1561    
1562    sub to_hash ($;$) {
1563      my $page = shift;
1564      my $h = shift || {};
1565      my $val;
1566      for my $line (split /\n/, $page) {
1567        $line =~ tr/\x0A\x0D//d;
1568        if ($val && $line =~ s/^\s+//) {
1569          $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
1570        } elsif ($line =~ /^(.+):/) {
1571          $val = $1; $h->{$val} = '';
1572        }
1573      }
1574      $h;
1575    }
1576    
1577    package SuikaWiki::Plugin;
1578      our $plugin_directory;  # defined in top of this file.
1579      our %List;
1580    
1581    sub escape ($$) { main::escape ($_[1]) }
1582    sub unescape ($$) { main::unescape ($_[1]) }
1583    sub encode ($$) { main::encode ($_[1]) }
1584    sub decode ($$) { main::decode ($_[1]) }
1585    sub __get_datetime ($) { main::get_now () }
1586    sub resource ($$;%) { shift; &main::Resource (@_) }
1587    sub uri ($$) { $main::uri{$_[1]} }
1588    
1589    sub regist ($@) {
1590        my $pack = shift;
1591        for (@_) {
1592            push @{$List{$_}}, $pack;
1593        }
1594    }
1595    
1596    sub import_plugins () {
1597        opendir PDIR, $plugin_directory;
1598        my @plugin = grep {s/\.pm$//} readdir (PDIR);
1599        closedir PDIR;
1600        for (@plugin) {
1601            eval qq{ use SuikaWiki::Plugin::$_ } unless /[^A-Za-z0-9_]/;
1602            push @{$List{_all}}, qq(SuikaWiki::Plugin::$_);
1603        }
1604    }
1605    
1606    &import_plugins ();
1607    
1608    package wiki::conneg;
1609    
1610    ## BUG: this parser isn't strict.
1611    sub get_accept_lang (;$) {
1612      my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1613      my %alang = (ja => 0.0002, en => 0.0001);
1614      my $i = 0.1;
1615      for (split /\s*,\s*/, $alang) {
1616        tr/\x09\x0A\x0D\x20//d;
1617        if (/((?:(?!;q=).)+)(?:;q="?([0-9.]+)"?)?/) {
1618          my $l = lc $1; $l =~ tr/\x22\x5C//d;
1619          $alang{$l} = (defined $2 ? $2 : 1.000)*1000;
1620          $alang{$l} += $i unless $alang{$l} == 0;
1621          $i -= 0.001;
1622        }
1623      }
1624      \%alang;
1625    }
1626    
1627    package wiki::resource;
1628    
1629    sub get ($;\%) {
1630      my ($resname, $option) = @_;
1631      $option->{accept_language} ||= &wiki::conneg::get_accept_lang ();
1632      $option->{resource} ||= {};
1633      my $v;
1634      for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1635        while (length $lang) {
1636          unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1637            $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash (&main::__get_database('WikiResource:'.$lang));
1638            $v = $option->{resource}->{$lang}->{$resname};
1639            last if defined $v;
1640          }
1641          $lang =~ s/[^+-]*$//; $lang =~ s/[+-]$//;
1642        }
1643        last if defined $v;
1644      }
1645      defined $v ? $v : $resname;
1646    }
1647    
1648    package wiki::map;
1649    
1650    sub make_list ($;%) {
1651      my ($page, %option) = @_;
1652      $option{level} ||= 3;
1653      my %weight;
1654      my $content = &main::__get_database ($page);
1655      $content =~ s{^\#\?([^\x0A\x0D]+)}{
1656        if ($1 =~ /import="([^"]+)"/) {
1657          for (split /\s*,\s*/, $1) {
1658            $weight{$_} += 2;
1659          }
1660        }
1661        $&;
1662      }ges;
1663      ## Bug: this code does not support content type.
1664      $content =~ s{\[\[((?!\#)[^]]+)\](?:>>\d+)?\]}{
1665        $weight{$1}++; $&;
1666      }ge;
1667      delete $weight{$page};        ## Delete myself
1668      for my $page (keys %weight) {
1669        my $w = ($content =~ s/\Q$page\E/$&/g);
1670        $weight{$page} += $w + $weight{$page}; ## Weight of [[name]] is x2.
1671        ($weight{$page} *= 0.1, $option{not_exist}->{$page} = 1) unless &main::is_exist_page ($page);
1672      }
1673      $option{weight_list}->{$page} = \%weight;
1674      if (--$option{level}) {
1675        for my $page (keys %weight) {
1676          &make_list ($page, %option) unless $option{weight_list}->{$page};
1677        }
1678      }
1679      $option{weight_list};
1680    }
1681    
1682    sub list_to_html ($$;%) {
1683      my ($Page, $wlist, %option) = @_;
1684      my $r = '';
1685      $option{outputed}->{$Page} = 1;
1686      for my $page (sort {$wlist->{$Page}->{$b} <=> $wlist->{$Page}->{$a}} keys %{$wlist->{$Page}}) {
1687        $r .= qq(<li><span class="weight">[@{[0+$wlist->{$Page}->{$page}]}]</span> <a href="$main::url_cgi?@{[&main::encode($page)]}" class="wiki@{[$option{not_exist}->{$page}?' not-exist':'']}">@{[&main::escape ($page).($option{not_exist}->{$page}?qq(<span class="mark">@{[&main::Resource('JumpAndEditWikiPageMark',escape=>1)]}</span>):'')]}</a> <a href="$main::url_cgi?mycmd=map;mypage=@{[&main::encode($page)]}" class="wiki-cmd map-from-here" title="@{[&main::escape($option{map_from_here_description})]}">@{[&main::escape($option{map_from_here})]}</a> <span class="summary">@{[&main::escape(&main::get_subjectline($page))]}</span>);
1688        unless ($option{outputed}->{$page}) {
1689          $r .= &list_to_html ($page, $wlist, %option);
1690        }
1691        $r .= "</li>\n";
1692      }
1693      $r ? qq(<ul class="map">$r</ul>) : '';
1694    }
1695    
1696    package main;
1697    &main;
1698    exit 0;
1699    
1700    1;
1701    __END__
1702    =head1 NAME
1703    
1704    wiki.cgi - This is YukiWiki, yet another Wiki clone.
1705    walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.
1706    
1707    =head1 DESCRIPTION
1708    
1709    YukiWiki is yet another Wiki clone.
1710    
1711    YukiWiki can treat Japanese WikiNames (enclosed with [[ and ]]).
1712    YukiWiki provides 'InterWiki' feature, RDF Site Summary (RSS),
1713    and some embedded commands (such as [[#comment]] to add comments).
1714    
1715    Read F<readme_en.txt> (English) or F<readme_ja.txt> (Japanese) in more detail.
1716    
1717    =head1 AUTHOR
1718    
1719    Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/
1720    
1721    =head1 LICENSE
1722    
1723    Copyright (C) 2000-2002 by Hiroshi Yuki.
1724    
1725    This program is free software; you can redistribute it and/or
1726    modify it under the same terms as Perl itself.
1727    
1728    =cut

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

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24