/[pub]/suikawiki/script/lib/suikawiki.pl
Suika

Contents of /suikawiki/script/lib/suikawiki.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.2 - (hide annotations) (download)
Thu Mar 27 07:18:51 2003 UTC (21 years, 8 months ago) by wakaba
Branch: MAIN
Changes since 1.1: +36 -4 lines
File MIME type: text/plain
namespace support

1 wakaba 1.1 # -*- perl -*-
2     use strict;
3    
4     package main;
5     binmode STDOUT; binmode STDIN;
6     require Yuki::YukiWikiCache;
7     use Fcntl;
8     require SuikaWiki::Plugin;
9     our %fmt; ## formatter objects
10     our %embed_command = (
11     searched => '^\[\[#searched:([^\]]+)\]\]$',
12     form => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
13     );
14     our ($modifier_dbtype,$url_cgi,%uri,%PathTo);
15     our (%PageName,$kanjicode,$lang,%ViewDefinition);
16    
17     my %form;
18     our %database;
19     our $database = bless {}, 'wiki::dummy';
20     my %interwiki;
21     my %command_do = (
22     default => \&do_view,
23     adminchangepassword => \&do_adminchangepassword,
24     write => \&do_write,
25     searchform => \&do_searchform,
26     comment => \&do_comment,
27     RandomJump => \&do_random_jump,
28     wikiform => \&do_wikiform,
29     );
30     our $UA = ''; ## User agent name
31     $| = 1;
32    
33     sub main {
34     $UA = $main::ENV{HTTP_USER_AGENT};
35     &open_db;
36     &init_form;
37     if ($command_do{$form{mycmd}}) {
38     &{$command_do{$form{mycmd}}};
39     } else {
40     &{$command_do{default}};
41     }
42     &close_db;
43     }
44    
45     sub do_view {
46     my $content = $database{$form{mypage}};
47     my $lm = $database->mtime ($form{mypage});
48     wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
49     wiki::useragent::add ($ENV{HTTP_USER_AGENT});
50     &load_formatter ('view');
51     my $view = $form{mycmd};
52     if ($view eq 'edit') {
53     $view = 'adminedit' if $form{admin};
54     } elsif ($view =~ /[^0-9A-Za-z_]/) {
55     $view = 'default'
56     }
57     if ($view eq 'default' || !$view) {
58     ## BUG: this code is not strict
59     if ($main::ENV{HTTP_COOKIE} =~ /SelectedMode=([0-9A-Za-z]+)/) {
60     $view = $1;
61     } else {
62     $view = 'read';
63     }
64     }
65     my ($magic, $content) = &SuikaWiki::Plugin::magic_and_content (undef, $content);
66     $magic ||= '#?SuikaWiki/0.9';
67     my $o = bless {param => \%form, page => $form{mypage}, toc => [],
68     magic => $magic, content => $content,
69     formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin';
70     if (!ref $ViewDefinition{$view} || !&{$ViewDefinition{$view}->{check}} ($o)) {
71     print "Status: 406 Unsupported Media Type\n";
72     $view = '-UnsupportedMediaType';
73     }
74     my $media = $ViewDefinition{$view}->{media};
75     if ($ViewDefinition{$view}->{xmedia} && $UA =~ /Gecko/) {
76     $media = $ViewDefinition{$view}->{xmedia};
77     $o->{media} = $media;
78     } elsif ($UA =~ m#Mozilla/0\..+Windows#) {
79     $kanjicode = 'shift_jis';
80     }
81     if ($magic =~ m!^\#\?SuikaWiki/0.9!) {
82     &print_header ($form{mypage}, -last_modified => ($magic =~ /interactive="yes"/ ? time : $lm),
83     -expires => ($magic =~ /interactive="yes"/ ? 1 : undef), o => $o,
84     -media => $media, -magic => $magic, content => $content);
85     } else {
86     &print_header($form{mypage}, -media => $media,
87     -magic => $magic, -last_modified => $lm, o => $o);
88     }
89     if ($kanjicode ne 'euc') {
90     my $s = $fmt{view}->replace ($ViewDefinition{$view}->{template} => $o);
91     print &code_convert (\$s => $kanjicode);
92     } else {
93     print $fmt{view}->replace ($ViewDefinition{$view}->{template} => $o);
94     }
95     }
96    
97     sub _do_view_msg (%) {
98     my %option = @_;
99     &load_formatter ('view');
100     my $o = bless {param => \%form, page => $option{-page}, toc => [], condition => \%option,
101     formatter => $fmt{view}, &_compatible_options ()}, 'SuikaWiki::Plugin';
102     unless (&{$ViewDefinition{$option{-view}}->{check}} ($o)) {
103     print "Status: 406 Unsupported Media Type\n";
104     $option{-view} = '-UnsupportedMediaType';
105     }
106     my $media = $ViewDefinition{$option{-view}}->{media};
107     if ($ViewDefinition{$option{-view}}->{xmedia} && $UA =~ /Gecko/) {
108     $media = $ViewDefinition{$option{-view}}->{xmedia};
109     $o->{media} = $media;
110     }
111     &print_header($option{-page}, -media => $media, o => $o, -goto => $option{-goto});
112     print $fmt{view}->replace ($ViewDefinition{$option{-view}}->{template} => $o);
113     }
114    
115     sub id_and_name ($) {
116     my $name = shift;
117     if ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer#) {
118     qq{id="$name"><a name="$name"></a};
119     } else {
120     qq{id="$name"};
121     }
122     }
123    
124     sub do_adminchangepassword {
125     if ($form{mynewpassword} ne $form{mynewpassword2}) {
126     &_do_view_msg (-view => '-error', -page => $form{mypage},
127     error_message => &Resource ('Error:PasswordMismatch'));
128     return;
129     }
130     my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
131     if ($validpassword_crypt) {
132     if (not &valid_password($form{myoldpassword})) {
133     &_do_view_msg (-view => '-error', -page => $form{mypage},
134     error_message => &Resource ('Error:PasswordIsIncorrect'));
135     return;
136     }
137     }
138     my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
139     my (@token) = ('0'..'9', 'A'..'Z', 'a'..'z');
140     my $salt1 = $token[(time | $$) % scalar(@token)];
141     my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
142     my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
143     $database->meta (AdminPassword => $PageName{AdminSpecialPage} => $crypted);
144    
145     &_do_view_msg (-view => '-wrote', -page => $form{mypage});
146     }
147    
148     sub valid_password ($) {
149     my ($validpassword_crypt) = $database->meta (AdminPassword => $PageName{AdminSpecialPage});
150     return crypt (shift, $validpassword_crypt) eq $validpassword_crypt ? 1 : 0;
151     }
152    
153     sub do_write {
154     if (&frozen_reject()) {
155     return;
156     }
157    
158     if (not &is_editable($form{mypage})) {
159     &_do_view_msg (-view => '-error', -page => $form{mypage},
160     error_message => &Resource ('Error:ThisPageIsUneditable'));
161     return;
162     }
163    
164     ## Check confliction
165     if ($form{myLastModified} ne $database->mtime ($form{mypage})) {
166     &_do_view_msg (-view => '-conflict', -page => $form{mypage});
167     return;
168     }
169    
170     if ($form{mymsg}) {
171     if ($form{mytouch} || !ref $database) {
172     $database{$form{mypage}} = $form{mymsg};
173     } else {
174     $database->STORE ($form{mypage} => $form{mymsg}, -touch => 0);
175     }
176     $database->meta (IsFrozen => $form{mypage} => 0 + $form{myfrozen});
177     my $fragment = '';
178     $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
179     if ($form{__comment_anchor_index}) {
180     $fragment .= qq(#anchor-$form{__comment_anchor_index});
181     } elsif ($form{__wikiform_anchor_index}) {
182     $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
183     }
184     &_do_view_msg (-view => '-wrote', -page => $form{mypage}, -goto => $url_cgi.'?mycmd='.&encode($form{after_edit_cmd}||'default').';mypage='.&encode($form{mypage}).qq(;x-param=@{[time.[0..9]->[rand 10]]}$fragment));
185     } else {
186     delete $database{$form{mypage}};
187     &_do_view_msg (-view => '-deleted', -page => $form{mypage});
188     }
189     }
190    
191     sub _compatible_options () {
192     (use_anchor_name => ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer# ? 1 : 0));
193     }
194    
195     sub get_search_result ($;%) {
196     my $word = lc shift;
197     my $SearchResult = SuikaWiki::Plugin->cache ('search');
198     my %option = @_;
199     my @r;
200     unless (defined $SearchResult->{$word}) {
201     for my $page (keys %database) {
202     next if !$option{-match_myself} && ($page eq $word);
203     my $content = lc $database{$page};
204     $content =~ s/^[^\x0A\x0D]+[\x0D\x0A]+//s;
205     if (index (lc $page, $word) > -1) {
206     my $c = $content =~ s/\Q$word\E//g;
207     push @r, [$page, $c+20];
208     } elsif (index ($word, lc $page) > -1) {
209     my $c = $content =~ s/\Q$word\E//g;
210     push @r, [$page, $c+10];
211     } elsif (my $c = $content =~ s/\Q$word\E//g) {
212     push @r, [$page, $c];
213     }
214     }
215     @r = sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]} @r;
216     $SearchResult->{$word} = join "\x1E", map {$_->[0]."\x1F".$_->[1]} @r;
217     } else {
218     @r = map {[split /\x1F/, $_, 2]} split /\x1E/, $SearchResult->{$word};
219     }
220     #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
221     my $r = join "\n", map {qq(<li>[$_->[1]] <a href ="$url_cgi?@{[&encode($_->[0])]}" class="wiki">@{[&escape($_->[0])]}</a> <span class="wikipage-summary">@{[&escape(&get_subjectline($_->[0]))]}</span></li>)} @r;
222     $r = qq|<ul class="search-result">$r</ul>| if $r;
223     wantarray? ($r, scalar @r): $r;
224     }
225    
226     sub do_random_jump {
227     my @list = keys %database;
228     my $name = &encode ($list[rand @list]);
229     print "Location: $uri{wiki}?$name\n";
230     print "\n";
231     }
232    
233     sub print_header ($;%) {
234     my ($page, %option) = @_;
235     my @head;
236     $option{o}->{-header}->{class} = &is_frozen($page) ? 'frozen' : '';
237     $option{o}->{-header}->{class} .= " wiki-page-obsoleted" if $option{-magic} =~ /obsoleted="yes"/;
238     if ($option{-goto}) {
239     if ($UA =~ m#Opera|MSIE 2\.#) {
240     ## WARNING: This code may output unsafe HTML document if
241     ## $option{-goto} is not clean.
242     $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
243     print qq{Refresh: 0; url=$option{-goto}\n};
244     push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
245     } elsif ($UA =~ /Gecko/) {
246     print qq{Refresh: 0; url="$option{-goto}"\n};
247     push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;" />);
248     } else {
249     $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
250     print qq{Refresh: 0; url="$option{-goto}"\n};
251     push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;">);
252     }
253     }
254     print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
255     if ($option{-expires} != -1) {
256     if (defined $option{-expires}) { ## TODO: Don't use asctime
257     print qq{Expires: @{[scalar gmtime (time + $option{-expires})]}\n};
258     } elsif ($option{-media}->{expires} != -1) {
259     print qq{Expires: @{[scalar gmtime (time + $option{-media}->{expires})]}\n};
260     }
261     }
262     if ($option{-media}->{charset} && $UA =~ m#Mozilla/[12]\.#) {
263     my $ct = qq{$option{-media}->{type}; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
264     print qq{Content-Type: $ct\n};
265     $option{o}->{-header}->{meta_ct} = qq{<meta http-equiv="content-type" content="$ct">\n};
266     } elsif (!$option{-media}->{charset} || $UA =~ m#Infomosaic|Mozilla/0\.#) {
267     print qq{Content-Type: $option{-media}->{type}\n};
268     $option{o}->{-header}->{meta_ct} = qq{<meta http-equiv="content-type" content="$option{-media}->{type}; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}">\n};
269     } else {
270     my $type = $option{-media}->{type};
271     $type = 'application/xml' if $type eq 'application/rss+xml';
272     print qq{Content-Type: $type; charset=@{[&get_charset_name($kanjicode)]}\n};
273     }
274     print <<"EOD"; ## TODO:
275     Content-Language: $lang
276     Content-Style-Type: text/css
277    
278     EOD
279     $option{o}->{-header}->{links} = join "\n", (@head);
280     }
281    
282     sub get_charset_name ($;%) {
283     my ($charset, %option) = (lc shift, @_);
284     if ($charset =~ 'euc') {
285     $charset = $option{compatible} ? 'x-euc-jp' : 'euc-jp';
286     } elsif ($charset =~ 'sjis' || $charset =~ 'shift') {
287     $charset = $option{compatible} ? 'x-sjis' : 'shift_jis';
288     } elsif ($charset =~ 'jis') {
289     $charset = 'iso-2022-jp';
290     }
291     $charset;
292     }
293    
294     sub escape {
295     my $s = shift;
296     $s =~ s|\x0D\x0A|\x0A|g;
297     $s =~ s|&|&amp;|g;
298     $s =~ s|<|&lt;|g;
299     $s =~ s|>|&gt;|g;
300     $s =~ s|"|&quot;|g;
301     return $s;
302     }
303    
304     sub unescape {
305     my $s = shift;
306     # $s =~ s|\n|\r\n|g;
307     $s =~ s|&lt;|<|g;
308     $s =~ s|&gt;|>|g;
309     $s =~ s|&quot;|"|g;
310     $s =~ s|&amp;|&|g;
311     return $s;
312     }
313    
314     sub convert_format ($$$;%) {
315     my ($content, $d => $t, %option) = @_;
316     my $f = SuikaWiki::Plugin->format_converter ($d => $t);
317     if (ref $f) {
318     $option{content} = $content;
319     $option{from} = $d;
320     $option{to} = $t;
321     &$f ({}, bless (\%option, 'SuikaWiki::Plugin'));
322     } elsif ($option{-error_no_return}) {
323     return undef;
324     } elsif ($t =~ /HTML|xml/) {
325     length $content ? '<pre>'.&escape($content).'</pre>' : '';
326     } else {
327     $content;
328     }
329     }
330    
331     sub text_to_html {
332     my ($txt, %option) = @_;
333     my $toc = $option{-toc} || (ref $option{toc} ? $option{toc} : []);
334     my $tocnum = 0;
335    
336     ## Load constants
337     my %const;
338     if ($option{magic} =~ /import="([^"]+)"/) {
339     for (split /\s*,\s*/, $1) {
340     my $wp = $database{$_};
341     if ($wp =~ m!^\#\?SuikaWikiConst/(?:0.9|1.0)!) {
342     wiki::suikawikiconst::to_hash ($wp => \%const);
343     }
344     }
345     }
346    
347     $txt =~ s{__&&([^&]+)&&__}{defined $const{$1}?$const{$1}:qq(__&&$1&&__)}ge;
348     my (@txt) = split(/\n/, $txt);
349     my (@saved, @result);
350     unshift(@saved, "</p>");
351     push(@result, "<p>");
352     foreach (@txt) {
353     chomp;
354     if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
355     push @$toc, [5, "i$tocnum" => ($1 || $tocnum)];
356     push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h6>');
357     $tocnum++;
358     } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
359     push @$toc, [4, "i$tocnum" => ($1 || $tocnum)];
360     push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h5>');
361     $tocnum++;
362     } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
363     push @$toc, [3, "i$tocnum" => ($1 || $tocnum)];
364     push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h4>');
365     $tocnum++;
366     } elsif (/^\*\*([^\x0D\x0A]*)/) {
367     # if (/^\*\*(.*)/) {
368     # Walrus mod (6) end
369     push @$toc, [2, "i$tocnum" => ($1 || $tocnum)];
370     push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h3>');
371     $tocnum++;
372     } elsif (/^\*([^\x0D\x0A]*)/) {
373     push @$toc, [1, "i$tocnum" => ($1 || $tocnum)];
374     push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, %option, const => \%const) . '</h2>');
375     $tocnum++;
376     } elsif (/^(={1,6})(.*)/) {
377     &back_push('ol', length($1), \@saved, \@result);
378     push(@result, '<li>' . &inline($2, %option, const => \%const) . '</li>');
379     } elsif (/^(-{1,6})(.*)/) {
380     &back_push('ul', length($1), \@saved, \@result);
381     my ($pf, $l) = ('', $2);
382     if (!$main::_EMBEDED && $l =~ s/^\s*\[([0-9]+)\]//) {
383     my $num = 0+$1;
384     $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
385     }
386     push(@result, '<li>' . $pf . &inline ($l, %option, const => \%const) . '</li>');
387     } elsif (/^:([^:]+):(.*)/) {
388     &back_push('dl', 1, \@saved, \@result);
389     push(@result, '<dt>' . &inline($1, %option, const => \%const) . '</dt>', '<dd>' . &inline($2, %option, const => \%const) . '</dd>');
390     } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
391     &back_push('blockquote', length($1), \@saved, \@result);
392     push @result, "<p>";
393     push(@result, &inline($2, %option, const => \%const));
394     unshift @saved, "</p>";
395     } elsif (/^\s*$/) {
396     push(@result, splice(@saved));
397     push(@result, "<p>");
398     unshift(@saved, "</p>");
399     } elsif (/^(\s+.*)$/) {
400     &back_push('pre', 1, \@saved, \@result);
401     push(@result, &inline($1, %option, const => \%const));
402     } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
403     &back_push('table', 1, \@saved, \@result);
404     #######
405     # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.
406     # XXXXX
407     my $tmp = "$1,";
408     my @value = map {/^"(.*)"$/ ? scalar($_ = $1, s/""/"/g, $_) : $_} ($tmp =~ /("[^"]*(?:""[^"]*)*"|[^,]*),/g);
409     my @align = map {(s/^\s+//) ? ((s/\s+$//) ? ' align="center"' : ' align="right"') : ''} @value;
410     my @colspan = map {($_ eq '==') ? 0 : 1} @value;
411     for (my $i = 0; $i < @value; $i++) {
412     if ($colspan[$i]) {
413     while ($i + $colspan[$i] < @value and $value[$i + $colspan[$i]] eq '==') {
414     $colspan[$i]++;
415     }
416     $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
417     $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], %option, const => \%const));
418     } else {
419     $value[$i] = '';
420     }
421     }
422     push(@result, join('', '<tr>', @value, '</tr>'));
423     # XXXXX
424     #######
425     } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
426     push @result, splice (@saved), '<'.lc($1).'>';
427     unshift @saved, "</p>";
428     push @result, "<p>";
429     } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
430     push @result, splice (@saved), '</'.lc($1).'>';
431     } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
432     my $num = 0+$1;
433     push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
434     push @result, &inline ($2, %option, const => \%const);
435     } else {
436     push(@result, &inline($_, %option, const => \%const));
437     }
438     }
439     push(@result, splice(@saved));
440    
441     my $r = join("\n", @result);
442     $r =~ s#<p>\x0D?\x0A</p>##g;
443     $r =~ s#[\x0D\x0A]+</#</#g;
444     $r =~ s#<pre>\x0D?\x0A#<pre>#g;
445     $r;
446     }
447    
448     sub back_push {
449     my ($tag, $level, $savedref, $resultref, $attr) = @_;
450     while (@$savedref > $level) {
451     push(@$resultref, shift(@$savedref));
452     }
453     if ($savedref->[0] ne "</$tag>") {
454     push(@$resultref, splice(@$savedref));
455     }
456     while (@$savedref < $level) {
457     unshift(@$savedref, "</$tag>");
458     push(@$resultref, "<$tag$attr>");
459     }
460     }
461    
462     sub inline ($;%) {
463     my ($line, %option) = @_;
464     $line = &escape($line);
465     $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4, \%option)}ge;
466     $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;
467     $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
468     $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
469     $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;
470     $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
471     $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;
472     $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
473     $line =~ s|''([^']+)''|<em>$1</em>|g;
474     $line =~ s{
475     (\[\[(\#\S+?)\]\])
476     |\[\[([^[]+?)](?:&gt;&gt;([0-9]+))?]
477     |&gt;&gt;([0-9]+)
478     |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
479     }{
480     my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
481     if ($l) {
482     &embedded_to_html($1);
483     } elsif (defined $page) {
484 wakaba 1.2 &make_wikilink (&unescape ($page), anchor => 0+$anchor, base => $option{page});
485 wakaba 1.1 } elsif ($anum) {
486     qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
487     } elsif ($uri) {
488     &make_urilink ($uri);
489     }
490     }gex;
491     return $line;
492     }
493    
494     sub make_wikilink ($%) {
495     my ($name, %option) = @_;
496     my $ename = &escape (length $option{label} ? $option{label} : $name);
497     $option{latest} = $option{latest} ? qq(mycmd=default;x-param=@{[time.[0..9]->[rand 10]]};mypage=) : '';
498 wakaba 1.2
499     ## Namespace
500     if ($wiki::page::ns::delimiter && ($name =~ m#\Q$wiki::page::ns::delimiter\E#
501     || $name eq $wiki::page::ns::parent
502     || $name eq $wiki::page::ns::self)) {
503     my @name = split m#\Q$wiki::page::ns::delimiter\E#, $name;
504     my @base = split m#\Q$wiki::page::ns::delimiter\E#, $option{base};
505     if ($name[0] eq $wiki::page::ns::self) { ## .//Foo//Bar
506     @name = (@base, @name[1..$#name]);
507     } elsif ($name[0] eq $wiki::page::ns::parent) { ## ..//Foo//Bar
508     @base = grep {$_} @base; $#base--;
509     @name = (@base, @name[1..$#name]);
510     }
511     $name = join $wiki::page::ns::delimiter, grep {$_} @name;
512     }
513     $name ||= $PageName{FrontPage};
514    
515 wakaba 1.1 if ($database{$name}) {
516 wakaba 1.2 my $subject = &escape ($name.&get_subjectline ($name));
517 wakaba 1.1 if ($option{anchor}) {
518     return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
519     } else {
520     return qq(<a title="$subject" href="$uri{wiki}?$option{latest}@{[&encode($name)]}" class="wiki">$ename</a>);
521     }
522     } else {
523 wakaba 1.2 return qq(<a title="@{[&escape($name).&Resource('Title-Summary Delimiter',escape=>1).&Resource('JumpAndEditWikiPage',escape=>1)]}" href="$uri{wiki}?$option{latest}@{[&encode($name)]}" class="wiki not-exist">$ename<span class="mark">@{[&Resource('JumpAndEditWikiPageMark',escape=>1)]}</span></a>);
524 wakaba 1.1 }
525     }
526    
527     sub make_urilink ($;%) {
528     require URI;
529     my $uri = shift;
530     if ($uri =~ s/^IW://) { ## InterWiki (not URI)
531     $uri = &unescape ($uri);
532     if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
533     my ($site, $name) = ($1, $2);
534     for ($site, $name) {
535     if (s/^"//) { s/"$//; s/\\(.)/$1/g }
536     }
537     &init_InterWikiName () unless $interwiki{'[[]]'};
538     if ($interwiki{$site}) {
539     &load_formatter ('interwiki');
540     my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
541     $site = &escape ($site); $name = &escape ($name);
542     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;);
543     } else {
544     qq(&lt;@{[&Resource('Error:UnknownInterWikiName=',escape=>1)]}@{[&escape ($site)]}&gt;);
545     }
546     } else {
547     qq(&lt;@{[&Resource('Error:InvalidInterWiki=',escape=>1)]}@{[&escape($uri)]}&gt;);
548     }
549     } elsif ($uri =~ /^urn:/) { ## URN
550     my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
551     qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
552     } elsif ($uri =~ s/^MAIL://) { ## mail address (not URI)
553     my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
554     qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
555     } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) { ## image (not URI itself)
556     my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
557     qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
558     } else { ## misc. URI
559     CGI::Carp::warningsToBrowser (0);
560     my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
561     CGI::Carp::warningsToBrowser (1);
562     qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
563     }
564     }
565    
566     {my %FormIndex;
567     sub make_custom_form ($$$$%) {
568     my ($wfname, $definition, $template, $foption, $option) = @_;
569     ## $template is currently not used in this procedure.
570     #unless ($main::_EMBEDED) {
571     $FormIndex{$option->{page}}++;
572     if (length $definition) {
573     my $param = bless {depth=>10}, 'SuikaWiki::Plugin';
574     my $lastmodified = $database->mtime ($option->{page});
575     &load_formatter (qw/form_input form_option/);
576     $definition = &unescape ($definition);
577     $definition =~ s/\\(['\\])/$1/g;
578     $foption = &unescape ($foption);
579     $foption =~ s/\\(['\\])/$1/g;
580     $fmt{form_option}->replace ($foption, $param);
581     $param->{output}->{form} = 1 unless defined $param->{output}->{form};
582     $param->{output}->{form} = 0 if $main::_EMBEDED;
583     $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
584     $param->{output}->{page} ||= $option->{page};
585     $param->{form_disabled} = 1 if $database->meta (IsFrozen => $option->{page});
586     my $target_form = $param->{output}->{id};
587     my $r = '';
588     $r = <<EOH if $param->{output}->{form};
589     <form method="post" action="$url_cgi" id="wikiform-$FormIndex{$option->{page}}" class="wikiform">
590     <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'default':'wikiform']}" />
591     <input type="hidden" name="mypage" value="@{[&escape($param->{output}->{page})]}" />
592     <input type="hidden" name="myLastModified" value="$lastmodified" />
593     <input type="hidden" name="mytouch" value="on" />
594     <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex{$option->{page}})]}" />
595     EOH
596     $r .= qq(<a name="wikiform-$FormIndex{$option->{page}}"></a>) if $UA =~ m#Mozilla/[12]\.#;
597     $r .= $fmt{form_input}->replace ($definition, $param);
598     $r .= "</form>\n" if $param->{output}->{form};
599     $r;
600     } else { ## No input-interface WikiForm
601     qq(<a id="wikiform-$FormIndex{$option->{page}}" name="wikiform-$FormIndex{$option->{page}}"><!-- #form --></a>);
602     }
603     #} else {
604     # qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
605     #}
606     }}
607    
608     sub init_form {
609     ## TODO: Support multipart/form-data
610     my $query = '';
611     if (uc $main::ENV{REQUEST_METHOD} eq 'POST') {
612     read STDIN, $query, $main::ENV{CONTENT_LENGTH};
613     }
614     $query .= ($query ? ';' : '') . $main::ENV{QUERY_STRING};
615     if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
616     my $query = &decode($main::ENV{QUERY_STRING});
617     $query = &code_convert(\$query, $kanjicode);
618     $form{mypage} = $query;
619     $form{mycmd} = 'default';
620     } else {
621     for (split /[;&]/, $query) {
622     if (my ($n, $v) = split /=/, $_, 2) {
623     for ($n, $v) {tr/+/ /; s/%([0-9A-Fa-f][0-9A-Fa-f])/pack 'C', hex $1/ge};
624     $form{$n} = $v;
625     }
626     }
627     unless (defined $form{mypage}) {
628     $form{mypage} = $form{epage};
629     $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;
630     }
631     $form{mypage} = &code_convert (\$form{mypage}, $kanjicode);
632     }
633     $form{mypage} ||= $PageName{FrontPage};
634     $form{mypage} =~ tr/\x00-\x1F\x7F//d;
635     $form{mycmd} ||= 'default';
636    
637     # mypreview_edit -> do_edit, with preview.
638     # mypreview_adminedit -> do_adminedit, with preview.
639     # mypreview_write -> do_write, without preview.
640     foreach (keys %form) {
641     if (/^mypreview_(.*)$/) {
642     $form{mycmd} = $1;
643     $form{mypreview} = 1;
644     }
645     }
646    
647     #
648     # $form{mycmd} is frozen here.
649     #
650    
651     for (grep /^wikiform__/, keys %form) {
652     $form{$_} = &code_convert (\$form{$_}, $kanjicode);
653     }
654     $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
655     $form{myname} = &code_convert(\$form{myname}, $kanjicode);
656     }
657    
658     sub get_subjectline {
659     my ($page, %option) = @_;
660     my $SubjectLine = SuikaWiki::Plugin->cache ('headline');
661     unless (defined $SubjectLine->{$page}) {
662     if (not &is_editable($page)) {
663     $SubjectLine->{$page} = "";
664     } else {
665     $SubjectLine->{$page} = do {
666     my $s=$database{$page};
667     $s =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
668     $s =~ s/\x0D?\x0A.*//s;
669     $s =~ s/^[-=]*\s*\[\d+\]\s*//;
670     $s =~ s/'''?//g;
671     $s =~ s/\[[A-Z]+(?:\([^)]+\))?\[([^]]+)\](?:\s\[([^]]+)\])?\]/$1$2/g;
672     $s =~ s/\[\[([^]]+)\]\]/$1/g;
673     $s};
674     }
675     }
676     if (length $SubjectLine->{$page}) {
677     $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
678     $option{delimiter}.$SubjectLine->{$page}.$option{tail};
679     } else {
680     '';
681     }
682     }
683    
684     sub open_db {
685     if ($modifier_dbtype eq 'dbmopen') {
686     dbmopen(%database, $PathTo{WikiDataBase}, 0666) or die "(dbmopen) $PathTo{WikiDataBase}";
687     } elsif ($modifier_dbtype eq 'AnyDBM_File') {
688     eval q{use AnyDBM_File};
689     tie(%database, "AnyDBM_File", $PathTo{WikiDataBase}, O_RDWR|O_CREAT, 0666) or die ("(tie AnyDBM_File) $PathTo{WikiDataBase}");
690     } elsif ($modifier_dbtype eq 'Yuki::YukiWikiDB') {
691     eval q{use Yuki::YukiWikiDB};
692     tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or die ("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");
693     } else { ## Yuki::YukiWikiDB || Yuki::YukiWikiDBMeta
694     eval qq{use $modifier_dbtype};
695     $database = tie(%database, $modifier_dbtype => $PathTo{WikiDataBase}, -lock => 2, -backup => $wiki::diff::UseDiff) or die ("(tie $modifier_dbtype) $PathTo{WikiDataBase}");
696     }
697     }
698    
699     sub close_db {
700     if ($modifier_dbtype eq 'dbmopen') {
701     dbmclose(%database);
702     } else {
703     untie(%database);
704     }
705     }
706    
707     sub editform (@) {
708     my %option = @_;
709     my $frozen = &is_frozen ($option{page});
710     $option{content} = $database{$option{page}} unless defined $option{content};
711     $option{content} = $database{NewPageTemplate} unless length $option{content};
712     $option{last_modified} = $database->mtime ($option{page}) unless defined $option{last_modified};
713     my $f = '';
714     my $magic = '';
715     $magic = $1 if $option{content} =~ m/^([^\x0A\x0D]+)/s;
716    
717     my $selected = 'default';
718     if ($form{after_edit_cmd}) {
719     $selected = $form{after_edit_cmd};
720     } elsif ($magic =~ /Const|Config|CSS/) {
721     $selected = 'edit';
722     }
723     my $afteredit = <<EOH;
724     <select name="after_edit_cmd">
725     <option value="default" label="@{[&Resource('Edit:SaveAndDefault',escape=>1)]}"@{[$selected eq 'default' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndDefault',escape=>1)]}</option>
726     <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
727     <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
728     </select>
729     EOH
730     $f .= <<"EOD";
731     <form action="$uri{wiki}" method="post">
732     @{[ $option{conflict} ? '' : qq(<label><input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" /><kbd>S</kbd></label>) ]}
733     @{[ $option{admin} ? qq(<label>@{[&Resource('Edit:Password=',escape=>1)]}<input type="password" name="mypassword" value="" size="10" /></label>) : "" ]} [@{[&get_new_anchor_index($option{content})]}]<br />
734     <input type="hidden" name="myLastModified" value="$option{last_modified}" />
735     <input type="hidden" name="mypage" value="@{[&escape($form{mypage})]}" />
736     <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">@{[&escape($option{content})]}</textarea><br />
737     @{[
738     $option{admin} ?
739     qq(
740     <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]} />@{[&Resource('Edit:Freeze',escape=>1)]}</label>
741     <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]} />@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br />)
742     : ""
743     ]}
744     @{[
745     $option{conflict} ? "" :
746     qq(
747     <label><input type="checkbox" name="mytouch" value="on" checked="checked" />@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}</label><br />
748     <label><input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S" /><kbd>S</kbd></label>
749     $afteredit
750     )
751     ]}
752     </form>
753     EOD
754     $f;
755     }
756    
757     sub is_editable {
758     my ($page) = @_;
759 wakaba 1.2 if ($page =~ /[\x00-\x20\x7F]/) {
760     return 0;
761     } elsif ($wiki::page::ns::delimiter) { ## Use namespace
762     if ($page eq $wiki::page::ns::delimiter
763     || $page eq $wiki::page::ns::self
764     || $page eq $wiki::page::ns::parent) {
765     return 0;
766     } elsif ($page =~ /\Q$wiki::page::ns::delimiter\E(?:\Q$wiki::page::ns::self\E|\Q$wiki::page::ns::parent\E)\Q$wiki::page::ns::delimiter\E/) {
767     return 0;
768     } elsif ($page =~ /^(?:\Q$wiki::page::ns::self\E|\Q$wiki::page::ns::parent\E)\Q$wiki::page::ns::delimiter\E/) {
769     return 0;
770     } elsif ($page =~ /\Q$wiki::page::ns::delimiter\E(?:\Q$wiki::page::ns::self\E|\Q$wiki::page::ns::parent\E)$/) {
771     return 0;
772     }
773     }
774     1;
775 wakaba 1.1 }
776    
777     sub decode {
778     my ($s) = @_;
779     $s =~ tr/+/ /;
780     $s =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;
781     return $s;
782     }
783    
784     sub encode {
785     my $s = shift;
786     $s =~ s/([^0-9A-Za-z_-])/sprintf '%%%02X', ord $1/ge;
787     $s;
788     }
789    
790     sub get_now {
791     my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
792     $year += 1900;
793     $mon++;
794     $mon = "0$mon" if $mon < 10;
795     $day = "0$day" if $day < 10;
796     $hour = "0$hour" if $hour < 10;
797     $min = "0$min" if $min < 10;
798     #$sec = "0$sec" if $sec < 10;
799     return "$year-$mon-$day $hour:$min";
800     }
801    
802     sub init_InterWikiName {
803     my @content = split /\n/, $database{InterWikiName};
804     for (@content) {
805     if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
806     $interwiki{$1} = $2;
807     }
808     }
809     $interwiki{'[[]]'} = 1; ## dummy
810     }
811    
812     sub frozen_reject {
813     my ($isfrozen) = $database->meta (IsFrozen => $form{mypage});
814     my ($willbefrozen) = $form{myfrozen};
815     if (not $isfrozen and not $willbefrozen) {
816     # You need no check.
817     return 0;
818     } elsif (valid_password($form{mypassword})) {
819     # You are admin.
820     return 0;
821     } else {
822     &_do_view_msg (-view => '-error', -page => $form{mypage},
823     error_message => &Resource ('Error:PasswordIsIncorrect'));
824     exit;
825     }
826     }
827    
828     sub is_frozen ($) { $database->meta (IsFrozen => $_[0]) ? 1 : 0 }
829    
830     sub do_comment {
831     my ($content) = $database{$form{mypage}};
832     my $default_name; ## this code is not strict.
833     $default_name = $1 if $content =~ /default-name="([^"]+)"/;
834     my $datestr = '[WEAK['.&get_now.']]';
835     my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
836     ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
837     if ($namestr =~ /^(?:>>)?[0-9]/) {
838     $namestr = qq( ''$namestr'': );
839     } elsif (length $namestr) {
840     $namestr = qq( ''[[$namestr]]'': );
841     }
842     my $anchor = &get_new_anchor_index ($content);
843     my $i = 1; my $o = 0;
844     $content =~ s{(\[\[\#r?comment\]\])}{
845     my $embed = $1;
846     if ($i == $form{comment_index}) {
847     if ($embed ne '[[#rcomment]]') {
848     $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed"; $o = 1;
849     } else {
850     $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}"; $o = 1;
851     }
852     }
853     $i++; $embed;
854     }ge;
855     unless ($o) {
856     $content = "#?SuikaWiki/0.9\n\n" unless $content;
857     $content .= "\n" unless $content =~ /\n$/s;
858     $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
859     }
860     $form{__comment_anchor_index} = $anchor;
861     if ($form{mymsg} || $form{myname}) {
862     $form{mymsg} = $content;
863     $form{mytouch} = 'on';
864     &do_write;
865     } else { ## Don't write
866     $form{mycmd} = 'default';
867     &do_view;
868     }
869     }
870    
871     sub get_new_anchor_index ($) {
872     my $content = shift;
873     my $anchor = 0;
874     $content =~ s/^(?:[-=]+\s*)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
875     $anchor + 1;
876     }
877    
878     my $CommentIndex = 0;
879     sub embedded_to_html {
880     my ($embedded) = @_;
881     if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
882     unless ($main::_EMBEDED) {
883     my $lastmodified = $database->mtime ($form{mypage});
884     return <<"EOD";
885     <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
886     <input type="hidden" name="mycmd" value="comment" />
887     <input type="hidden" name="mypage" value="$form{mypage}" />
888     <input type="hidden" name="myLastModified" value="$lastmodified" />
889     <input type="hidden" name="mytouch" value="on" />
890     <input type="hidden" name="comment_index" value="$CommentIndex" />
891     @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
892     <input type="text" name="myname" value="" size="10" class="comment-name" />
893     <input type="text" name="mymsg" value="" size="60" class="comment-msg" />
894     <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit" />
895     </p></form>
896     EOD
897     } else {
898     return <<"EOD";
899     <del><form action="$url_cgi" method="get">
900     <input type="hidden" name="mycmd" value="default" />
901     <input type="hidden" name="mypage" value="$form{mypage}" />
902     @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
903     <input type="text" name="myname" value="" size="10" disabled="disabled" />
904     <input type="text" name="mymsg" value="" size="60" disabled="disabled" />
905     </form></del>
906     EOD
907     }
908     } elsif ($embedded =~ /$embed_command{searched}/) {
909     return get_search_result ($1, -match_myself => 1);
910     } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
911     my ($name, $r) = ($1, '');
912     if ($name =~ s/^IMG://) {
913     my ($magic, $content) = SuikaWiki::Plugin->magic_and_content ($database{$name});
914     $r = &convert_format ($content, $magic => 'HTML_fragment', page => $name, magic => $magic, -error_no_return => 1);
915     if (defined $r) {
916     return $r;
917     } else {
918     return '<span class="error-embed-image">'.&Resource ('Embed:ImageNotSupported', escape=>1).'</span>';
919     }
920     } else {
921     if ($main::_EMBEDED != 1) {
922     my ($cf, $content) = SuikaWiki::Plugin->magic_and_content ($database{$name});
923     $cf ||= '#?SuikaWiki/0.9';
924     if ($cf =~ m!^#\?SuikaWiki/0.9(?:$|\s)!) {
925     $main::_EMBEDED = 1;
926     $r = &text_to_html ($content, magic => $cf, page => $name);
927     $main::_EMBEDED = 0;
928     } elsif (length $content) {
929     $r = "<pre>@{[&escape ($content)]}</pre>";
930     } else {
931     $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", magic => '#?SuikaWiki/0.9');
932     }
933     } else { ## nested #EMBED
934     $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", magic => '#?SuikaWiki/0.9');
935     }
936     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>);
937     }
938     } else {
939     return $embedded;
940     }
941     }
942    
943     sub load_formatter (@) {
944     for my $t (@_) {
945     unless ($fmt{$t}) {
946     require Message::Util::Formatter;
947     $fmt{$t} = Message::Util::Formatter->new;
948     for (@{$SuikaWiki::Plugin::List{'wiki'.$t}||[]}) {
949     $_->load_formatter ($fmt{$t}, type => 'wiki'.$t);
950     }
951     }
952     }
953     }
954    
955     sub do_wikiform {
956     my $content = $database{$form{mypage}};
957     my $anchor = &get_new_anchor_index ($content);
958     &load_formatter (qw/form_template form_option/);
959     my $write = 0;
960     my $i = 1;
961     $content =~ s{$embed_command{form}}{
962     my ($embed, $wfname, $template, $option) = ($&, $1, $3, $4);
963     if (($wfname && $wfname eq $form{wikiform_targetform})
964     || $i == $form{wikiform_index}) {
965     $template =~ s/\\([\\'])/$1/g;
966     $option =~ s/\\([\\'])/$1/g;
967     my $param = bless {depth=>10}, 'SuikaWiki::Plugin';
968     $param->{page} = $form{mypage};
969     $param->{form_index} = $i;
970     $param->{form_name} = $wfname;
971     $param->{anchor_index} = $anchor;
972     $param->{argv} = \%form;
973     $param->{default_name} = $1 if $content =~ /default-name="([^"]+)"/;
974     $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
975     $fmt{form_option}->replace ($option, $param);
976     my $t = 1;
977     for (keys %{$param->{require}||{}}) {
978     (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
979     }
980     $t = $fmt{form_template}->replace ($template, $param) if $t;
981     if (length $t) {
982     if ($param->{output}->{reverse}) {
983     $embed .= "\n" . $t;
984     } else {
985     $embed = $t . "\n" . $embed;
986     }
987     $write = 1;
988     $form{__comment_anchor_index} = $anchor
989     if $param->{anchor_index_}; ## $anchor is used!
990     }
991     $form{__wikiform_anchor_index} = $i;
992     undef $form{wikiform_targetform}; ## Make sure never to match
993     undef $form{wikiform_index}; ## with WikiForm in rest of page!
994     }
995     $i++; $embed;
996     }ge;
997     unless ($write) {
998     #$content = "#?SuikaWiki/0.9\n\n" unless $content;
999     #$content .= "\n" unless $content =~ /\n$/s;
1000     #
1001     }
1002     if ($write) {
1003     $form{mymsg} = $content;
1004     $form{mytouch} = 'on';
1005     &do_write;
1006     } else { ## Don't write!
1007     $form{mycmd} = 'default';
1008     &do_view;
1009     }
1010     }
1011    
1012     sub code_convert {
1013     require Jcode;
1014     my ($contentref, $code) = (shift, shift || $kanjicode);
1015     if ($code =~ /euc/) { $code = 'euc' }
1016     elsif ($code =~ /iso/) { $code = 'jis' }
1017     elsif ($code =~ /shi/) { $code = 'sjis' }
1018     elsif ($code =~ /utf/) { $code = 'utf8' }
1019     $$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;
1020     return $$contentref;
1021     }
1022    
1023     sub _rfc3339_date ($) {
1024     my @time = gmtime (shift);
1025     sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
1026     }
1027    
1028     my %_Resource;
1029     sub Resource ($;%) {
1030     my ($s, %o) = @_;
1031     unless (defined $_Resource{$s}) {
1032     $_Resource{$_[0]} = &wiki::resource::get ($s, $_Resource{__option});
1033     }
1034     $o{escape} ? &escape ($_Resource{$s}) : $_Resource{$s};
1035     }
1036    
1037     package wiki::referer;
1038     sub add ($$) {
1039     my $page = shift;
1040     my $uri = shift;
1041     unless (ref $uri) {
1042     require URI;
1043     $uri = URI->new ($uri);
1044     ## Some schemes do not have query part.
1045     eval q{ $uri->query (undef) if $uri->query =~ /^[0-9]{6,8}$/ };
1046     $uri->fragment (undef);
1047     }
1048     $uri = $uri->canonical;
1049     return unless $uri;
1050     for my $regex (&get_dont_record) {
1051     return if $uri =~ /$regex/;
1052     }
1053     my %list = get ($page);
1054     $list{ $uri }++;
1055     set ($page, \%list);
1056     }
1057     sub get ($) { split /"/, $main::database->meta (Referer => $_[0]) }
1058     sub set ($%) {
1059     my $page = shift;
1060     my $list = shift;
1061     $main::database->meta (Referer => $page => join '"', %$list);
1062     }
1063    
1064     sub get_dont_record () {
1065     map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1066     grep !/^#/,
1067     split /[\x0D\x0A]+/, $main::database{RefererDontRecord};
1068     }
1069     sub get_site_name () {
1070     my @lines = grep /[^#]/, split /[\x0D\x0A]+/, $main::database{RefererSiteName};
1071     my @item;
1072     for (@lines) {
1073     next if /^#/;
1074     my ($uri, $name) = split /\s+/, $_, 2;
1075     $uri =~ s/\$/\\\$/g; $uri =~ s/\@/\\\@/g; $uri =~ s/\//\\\//g;
1076     $name =~ s!([()/\\])!\\$1!g; $name =~ s/\$([0-9]+)/).__decode (\${$1}).q(/g;
1077     push @item, [$uri, qq(q($name))];
1078     }
1079     @item;
1080     }
1081    
1082     sub list_html ($) {
1083     my $page = shift;
1084     my %list = get ($page);
1085     my $r = '';
1086     my @name = get_site_name ();
1087     for my $uri (sort {$list{$b}<=>$list{$a}||$a cmp $b} keys %list) {
1088     my $title;
1089     for my $item (@name) {
1090     if ($uri =~ /$item->[0]/) {
1091     $title = $uri;
1092     eval qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e}
1093     or die $@ ;#. qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e};
1094     last;
1095     }
1096     }
1097     my $euri = main::escape ($uri);
1098     if ($title) {
1099     $r .= qq(<li>{$list{$uri}} <a href="$euri" title="URI: &lt;$euri&gt;">@{[main::escape ($title)]}</a></li>\n);
1100     } else {
1101     $r .= qq(<li>{$list{$uri}} &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1102     }
1103     }
1104     $r ? qq(<ul>$r</ul>\n) : '';
1105     }
1106    
1107     sub __decode ($) {
1108     my $s = shift;
1109     $s =~ tr/+/ /;
1110     $s =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/chr hex $1/ge;
1111     main::code_convert (\$s);
1112     }
1113    
1114     package wiki::useragent;
1115     our $UseLog;
1116    
1117     sub add ($) {
1118     my $s = shift;
1119     return unless length $s;
1120     return unless $UseLog;
1121     $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1122     my %ua;
1123     for (split /\n/, $main::database{$main::PageName{UserAgentList}}) {
1124     if (/^-\[(\d+)\] (.+)$/) {
1125     my ($t, $n) = ($1, $2);
1126     $n =~ tr/\x0A\x0D//d;
1127     $ua{$n} = $t;
1128     }
1129     }
1130     $ua{$s}++;
1131     my $s = qq(#?SuikaWiki/0.9\n);
1132     for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1133     $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1134     }
1135     $main::database->STORE ($main::PageName{UserAgentList} => $s, -touch => 0);
1136     }
1137    
1138     package wiki::suikawikiconst;
1139    
1140     sub to_hash ($;$) {
1141     my $page = shift;
1142     my $h = shift || {};
1143     my $val;
1144     for my $line (split /\n/, $page) {
1145     next if $line =~ /^#/;
1146     $line =~ tr/\x0A\x0D//d;
1147     if ($val && $line =~ s/^\s+\\?//) {
1148     $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
1149     } elsif ($line =~ /^(.+):/) {
1150     $val = $1; $h->{$val} = '';
1151     }
1152     }
1153     $h;
1154     }
1155    
1156     package wiki::dummy;
1157     sub mtime (@) {undef}
1158     sub meta (@) {undef}
1159     sub Yuki::YukiWikiDB2::meta (@) {undef}
1160    
1161     package SuikaWiki::Plugin;
1162     sub escape ($$) { main::escape ($_[1]) }
1163     sub unescape ($$) { main::unescape ($_[1]) }
1164     sub encode ($$) { main::encode ($_[1]) }
1165     sub decode ($$) { main::decode ($_[1]) }
1166     sub __get_datetime ($) { main::get_now () }
1167     sub resource ($$;%) { shift; &main::Resource (@_) }
1168     sub uri ($$) { $main::uri{$_[1]} }
1169     sub user_agent_names ($) { $main::UA }
1170     sub formatter ($$) {
1171     &main::load_formatter ($_[1]);
1172     $main::fmt{$_[1]};
1173     }
1174     sub format_converter ($$$) {
1175     &main::load_formatter ('format');
1176     $main::fmt{format}->{($_[1]=~/([A-Za-z0-9]\S+)/?$1:'SuikaWiki/0.9').'_to_'.$_[2]}
1177     || $main::fmt{format}->{($_[1]=~/([A-Za-z0-9](?:(?!\/)\S)+)/?$1:'SuikaWiki').'_to_'.$_[2]};
1178     }
1179     sub cache ($$) {
1180     our %Cache;
1181     my (undef, $name, %option) = @_;
1182     unless (ref $Cache{$name}) {
1183     my %cache;
1184     tie (%cache, 'Yuki::YukiWikiCache', -file => $main::PathTo{CachePrefix}.$name, %option);
1185     $Cache{$name} = \%cache;
1186     }
1187     $Cache{$name};
1188     }
1189     sub _database ($) { $main::database }
1190     sub _database_exist ($$) { exists $main::database{$_[1]} }
1191     sub _html_wikilink ($$%) { shift; &main::make_wikilink (@_) }
1192     sub _uri_wiki_page ($$%) {
1193     my (undef, $page, %option) = @_;
1194     $option{mode} ||= 'read';
1195     length $page ? undef : ($page = $main::PageName{FrontPage});
1196     $option{href} = $main::uri{wiki}.'?';
1197     if ($option{up_to_date} || $option{mode} ne 'read' || $option{add_param}) {
1198     $option{href} .= qq(mypage=@{[&main::encode($page)]};mycmd=@{[&main::encode($option{mode})]});
1199     $option{href} .= ';'.$option{add_param} if $option{add_param};
1200     $option{href} .= ';x-d='.time if $option{up_to_date};
1201     $option{href} .= ';x-lm='.($main::database->mtime ($page)||0) if $option{with_lm};
1202     } else {
1203     $option{href} .= &main::encode ($page);
1204     }
1205     $option{href};
1206     }
1207    
1208    
1209     package wiki::conneg;
1210    
1211     ## BUG: this parser isn't strict.
1212     sub get_accept_lang (;$) {
1213     my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1214     my %alang = (ja => 0.0002, en => 0.0001);
1215     if ($main::UA =~ m#Mozilla/0\.#) {
1216     $alang{ja} = 0.00001;
1217     }
1218     my $i = 0.1;
1219     for (split /\s*,\s*/, $alang) {
1220     tr/\x09\x0A\x0D\x20//d;
1221     if (/((?:(?!;q=).)+)(?:;q="?([0-9.]+)"?)?/) {
1222     my $l = lc $1; $l =~ tr/\x22\x5C//d;
1223     $alang{$l} = (defined $2 ? $2 : 1.000)*1000;
1224     $alang{$l} += $i unless $alang{$l} == 0;
1225     $i -= 0.001;
1226     }
1227     }
1228     \%alang;
1229     }
1230    
1231     package wiki::resource;
1232    
1233     sub get ($;\%) {
1234     my ($resname, $option) = @_;
1235     $option->{accept_language} ||= &wiki::conneg::get_accept_lang ();
1236     $option->{resource} ||= {};
1237     my $v;
1238     for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1239     while (length $lang) {
1240     unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1241     $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash ($main::database{'WikiResource:'.$lang});
1242     $v = $option->{resource}->{$lang}->{$resname};
1243     last if defined $v;
1244     }
1245     $lang =~ s/[^+-]*$//; $lang =~ s/[+-]$//;
1246     }
1247     last if defined $v;
1248     }
1249     defined $v ? $v : $resname;
1250     }
1251    
1252     package main;
1253     &SuikaWiki::Plugin::import_plugins ();
1254     &main ();
1255    
1256     =head1 NAME
1257    
1258     lib/suikawiki.pl --- SuikaWiki
1259    
1260     =head1 AUTHOR
1261    
1262     Hiroshi Yuki <hyuki@hyuki.com> <http://www.hyuki.com/yukiwiki/>
1263    
1264     Makio Tsukamoto <http://digit.que.ne.jp/>
1265    
1266     Wakaba <w@suika.fam.cx>
1267    
1268     =head1 LICENSE
1269    
1270     Copyright (C) 2000-2003 AUTHORS
1271    
1272     This program is free software; you can redistribute it and/or
1273     modify it under the same terms as Perl itself.
1274    
1275     =cut
1276    
1277     1; # $Date: $

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24